branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>$(function() {
module("block");
test("toFunction", function () {
var block0 = $.ku4block(function(x){ return x + 1 }),
block1 = $.ku4block("function(x){ return x + 1 }"),
block2 = $.ku4block("^(x){ return x + 1 }");
expect(3);
ok($.isFunction(block0.toFunction()));
ok($.isFunction(block1.toFunction()));
ok($.isFunction(block2.toFunction()));
});
test("execute single argument", function () {
var block0 = $.ku4block(function(x){ return x + 1 }),
block1 = $.ku4block("function(x){ return x + 1 }"),
block2 = $.ku4block("^(x){ return x + 1 }");
expect(3);
equal(block0.execute(5), 6);
equal(block1.execute(5), 6);
equal(block2.execute(5), 6);
});
test("execute multiple argument", function () {
var block0 = $.ku4block(function(x, y, z, zzz){ return [x + 1, y, z, zzz]; }),
block1 = $.ku4block("function(x, y, z, zzz){ return [x + 1, y, z, zzz]; }"),
block2 = $.ku4block("^(x, y, z, zzz){ return [x + 1, y, z, zzz]; }"),
result0 = block0.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 }),
result1 = block1.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 }),
result2 = block2.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 });
expect(12);
equal(result0[0], 6);
equal(result1[0], 6);
equal(result2[0], 6);
equal(result1[1], "a");
equal(result1[1], "a");
equal(result2[1], "a");
deepEqual(result0[2], new Date(2014, 1, 1));
deepEqual(result1[2], new Date(2014, 1, 1));
deepEqual(result2[2], new Date(2014, 1, 1));
deepEqual(result0[3], { a:1, b:2, c:3 });
deepEqual(result1[3], { a:1, b:2, c:3 });
deepEqual(result2[3], { a:1, b:2, c:3 });
});
test("execute multiple argument tight", function () {
var block0 = $.ku4block(function(zz,z,zzzzz,zzz){ return [zzz,z,zz,zzzzz]; }),
block1 = $.ku4block("function(zz,z,zzzzz,zzz){ return [zzz,z,zz,zzzzz]; }"),
block2 = $.ku4block("^(zz,z,zzzzz,zzz){ return [zzz,z,zz,zzzzz]; }"),
result0 = block0.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 }),
result1 = block1.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 }),
result2 = block2.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 });
expect(12);
equal(result0[2], 5);
equal(result1[2], 5);
equal(result2[2], 5);
equal(result0[1], "a");
equal(result1[1], "a");
equal(result2[1], "a");
deepEqual(result0[3], new Date(2014, 1, 1));
deepEqual(result1[3], new Date(2014, 1, 1));
deepEqual(result2[3], new Date(2014, 1, 1));
deepEqual(result0[0], { a:1, b:2, c:3 });
deepEqual(result1[0], { a:1, b:2, c:3 });
deepEqual(result2[0], { a:1, b:2, c:3 });
});
test("execute multiple argument spaced", function () {
var block0 = $.ku4block(function (zz, z, zzzzz, zzz){ return [zzz,z,zz,zzzzz]; }),
block1 = $.ku4block("function (zz, z, zzzzz, zzz){ return [zzz,z,zz,zzzzz]; }"),
block2 = $.ku4block("^(zz, z, zzzzz, zzz){ return [zzz,z,zz,zzzzz]; }"),
result0 = block0.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 }),
result1 = block1.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 }),
result2 = block2.execute(5, "a", new Date(2014, 1, 1), { a:1, b:2, c:3 });
expect(12);
equal(result0[2], 5);
equal(result1[2], 5);
equal(result2[2], 5);
equal(result0[1], "a");
equal(result1[1], "a");
equal(result2[1], "a");
deepEqual(result0[3], new Date(2014, 1, 1));
deepEqual(result1[3], new Date(2014, 1, 1));
deepEqual(result2[3], new Date(2014, 1, 1));
deepEqual(result0[0], { a:1, b:2, c:3 });
deepEqual(result1[0], { a:1, b:2, c:3 });
deepEqual(result2[0], { a:1, b:2, c:3 });
});
test("execute complex function with simple arguments", function () {
var block0 = $.ku4block(function(x, y, z){ return $.money(x).add($.money(y)).value() / z; }),
block1 = $.ku4block("function(x, y, z){ return $.money(x).add($.money(y)).value() / z; }"),
block2 = $.ku4block("^(x, y, z){ return $.money(x).add($.money(y)).value() / z; }");
expect(3);
equal(block0.execute(5, 4, 3), 3);
equal(block1.execute(5, 4, 3), 3);
equal(block2.execute(5, 4, 3), 3);
});
test("execute complex function with simple arguments", function () {
var block0 = $.ku4block(function(xxxx, yyyy, zzzz){ return $.money(xxxx).add($.money(yyyy)).value() / zzzz * zzzz; }),
block1 = $.ku4block("function(xxxx, yyyy, zzzz){ return $.money(xxxx).add($.money(yyyy)).value() / zzzz * zzzz; }"),
block2 = $.ku4block("^(xxxx, yyyy, zzzz){ return $.money(xxxx).add($.money(yyyy)).value() / zzzz * zzzz; }");
expect(3);
equal(block0.execute(5, 4, 3), 9);
equal(block1.execute(5, 4, 3), 9);
equal(block2.execute(5, 4, 3), 9);
});
test("execute complex function with commonn name arguments", function () {
var block0 = $.ku4block(function(other, multiplier){ return $.money(4.15).add(other).multiply(multiplier); }),
block1 = $.ku4block("function(other, multiplier){ return $.money(4.15).add(other).multiply(multiplier); }"),
block2 = $.ku4block("^(other, multiplier){ return $.money(4.15).add(other).multiply(multiplier); }");
expect(3);
ok(block0.execute($.money(5), 4).equals($.money(36.60)));
ok(block1.execute($.money(5), 4).equals($.money(36.60)));
ok(block2.execute($.money(5), 4).equals($.money(36.60)));
});
test("execute complex function with no arguments", function () {
var block0 = $.ku4block(function(){ return 1; }),
block1 = $.ku4block("function(){ return 1; }"),
block2 = $.ku4block("^(){ return 1; }");
expect(3);
equal(block0.execute(), 1);
equal(block1.execute(), 1);
equal(block2.execute(), 1);
});
test("execute block with self executing function", function () {
var block0 = $.ku4block("function (){ return (function(x){ return x+1 })(1) }"),
block1 = $.ku4block("function (){ return (function(x){ return x+1 })(1) }"),
block2 = $.ku4block("^(){ return (function(x){ return x+1 })(1) }");
expect(3);
equal(block0.execute(), 2);
equal(block1.execute(), 2);
equal(block2.execute(), 2);
});
});<file_sep>$(function(){
module("class | call sync chain");
test("call sync", function() {
var value = $.ku4reflection.invoke("new Number", [1], [
"toString",
{"replace": ["1", "A"]}
]);
expect(1);
equal(value, "A");
});
test("call sync with args", function() {
var value = $.ku4reflection.invoke("$.money", [4.15], [
{"add": [$.money(1.15)]},
{"subtract": [$.money(.30)]},
"toString"
]);
expect(1);
equal(value, "$5.00");
});
test("call sync with invalid args", function() {
expect(1);
raises(function(){
$.ku4reflection.invoke("$.money", [4.15], [
{"add": $.money(1.15)},
{"subtract": $.money(.30)},
"toString"
]);
});
});
});<file_sep>#ku4js-reflection
kodmunki™ utilities for JavaScript reflection.
*(The following are the instructions from the build script found in the template at /_build/build.sh)*
####kodmunki™ build process
---
This build process is dependent upon yuicompressor and a specific directory structure:
* root
* _build (This build script and the yuicompressor)
* bin (The compiled scripts will appear here)
* src (All script files go here)
The following variables found in setup () are
expected to be changed by the developer running
this process:
* PROJNAME (The name of your project)
* STARTMSG (A message to echo at start of build)
* ENDMSG (A message to echo at end of build)
#Documentation
##$.ku4reflection
All reflection methods are called through the $.ku4reflection namespace.
###instantiate
| API | Return | Description |
| --- | --- | --- |
| instantiate(Class:_String_, constructors:_Array_ | Object | return an instance of Class constructed with constructors |
###execute
| API | Return | Description |
| --- | --- | --- |
| execute(func:_Function_) | Object | returns the result of executing func. |
| execute(func:_Function_, args:_Array_) | Object | returns the result of executing func passing applying args as the arguments |
| execute(instance:_Object_, method:_String_) | Object | returns the result of invoking method of instance. |
| execute(instance:_Object_, method:_Object_) | Object | returns the result of invoking method of instance having method name key and method args value, where the value of the method object is an array of arguments for the method. |
| execute(instance:_Object_, methods:_Array_) | Object | returns the result of invoking the chain of methods represented by an array of method objects. |
| execute(instance:_Object_, method:_String_, args:_Array_) | Object | returns the result of invoking method of instance with args |
| execute(instance:_Object_, method:_Object_, callback:_Function_) | void | invokes method of instance having method name key and method args value, where the value of the method object is an array of arguments for the method. The callback is inserted inserted for all instances of arg == "\_\_CALLBACK\_\_", and called with the result. |
| execute(instance:_Object_, methods:_Array_, callback_Function_) | void | invokes the chain of methods of instance represented by an array of method objects. The callback is called with the result. The callback is inserted inserted for all instances of arg == "\_\_CALLBACK\_\_", and called with the result. |
| execute(instance:_Object_, method:_String_, args:_Array_, callback:_Function_) | void | invokes method of instance with args. The callback is called with the result. The callback is inserted inserted for all instances of arg == "\_\_CALLBACK\_\_", and called with the result. |
####Examples:
Examples of these methods can be found in the unit tests for execute:
* [sync](https://github.com/kodmunki/ku4js-reflection/tree/master/tests/src/instance/sync)
* [async](https://github.com/kodmunki/ku4js-reflection/tree/master/tests/src/instance/async)
###invoke
| API | Return | Description |
| --- | --- | --- |
| invoke(Class:_String_, constructors:_Array_, method:_String_) | Object | returns the result of invoking method of Class constructed with constructors. |
| invoke(Class:_String_, constructors:_Array_, method:_Object_) | Object | returns the result of invoking method of Class constructed with constructors having method name key and method args value, where the value of the method object is an array of arguments for the method. |
| invoke(Class:_String_, constructors:_Array_, methods:_Array_) | Object | returns the result of invoking the chain of methods represented by an array of method objects. |
| invoke(Class:_String_, constructors:_Array_, method:_String_, args:_Array_) | Object | returns the result of invoking method of Class constructed with constructors with args |
| invoke(Class:_String_, constructors:_Array_, method:_Object_, callback:_Function_) | void | invokes method of Class constructed with constructors having method name key and method args value, where the value of the method object is an array of arguments for the method. The callback is inserted inserted for all Class constructed with constructorss of arg == "\_\_CALLBACK\_\_", and called with the result. |
| invoke(Class:_String_, constructors:_Array_, methods:_Array_, callback_Function_) | void | invokes the chain of methods of Class constructed with constructors represented by an array of method objects. The callback is called with the result. The callback is inserted inserted for all Class constructed with constructorss of arg == "\_\_CALLBACK\_\_", and called with the result. |
| invoke(Class:_String_, constructors:_Array_, method:_String_, args:_Array_, callback:_Function_) | void | invokes method of Class constructed with constructors with args. The callback is called with the result. The callback is inserted inserted for all Class constructed with constructorss of arg == "\_\_CALLBACK\_\_", and called with the result. |
####Examples:
Examples of these methods can be found in the unit tests for execute:
* [sync](https://github.com/kodmunki/ku4js-reflection/tree/master/tests/src/class/sync)
* [async](https://github.com/kodmunki/ku4js-reflection/tree/master/tests/src/class/async)
##Blocks
Blocks are an addition that came out of Apple's extension of C. Where blocks open the ability to implement closures in C.
Although JavaScript already includes this feature, the ability to pass functions across processes and threads may arise
in the implementation of async reflection calls. ku4js-reflection blocks allow the developer to pass functions across
threads as arguments to async reflection invocations and include "\_\_CALLBACK\_\_" replacements in withing the block.
| API | Return | Description |
| --- | --- | --- |
| isBlock(value:_String_) | Boolean | a class level method that returns true if value is a block. |
| execute(block:_String_) | Object? | executes the block returning any return value that the block returns. |
| toFunction(block:_String_) | Function | returns a function representation of the passed block. |
Blocks are strings that take the following form:
```javascript
'^([arg1[, arg2[, ...]]]) { /* implementation that may include __CALLBACK__ */ }'
```
Using this, we can see in the following example how a block may be used:
```javascript
$.ku4reflection.invoke("$.service", [], [
{"uri": ["./"]},
{"onSuccess": ['^(){ __CALLBACK__; }']},
{"onError": ['^(){ (function() { __CALLBACK__; })("ERROR"); }']},
"call"], function() { console.log(arguments); });
```
The above will attempt to call for the current document. If the call is made over http the callback result will be the
text of the document. If the call is made over the file system the browser will likely not allow the call.<file_sep>$(function(){
module("class | call sync object");
test("call object sync null args", function() {
var value = $.ku4reflection.invoke("$.money", [1114.15], {"toString": null});
expect(1);
equal(value, "$1,114.15");
});
test("call object sync undefined args", function() {
var value = $.ku4reflection.invoke("$.money", [1114.15], {"toString": undefined});
expect(1);
equal(value, "$1,114.15");
});
test("call object sync empty args", function() {
var value = $.ku4reflection.invoke("$.money", [1114.15], {"toString": []});
expect(1);
equal(value, "$1,114.15");
});
test("call object sync with invalid args", function() {
expect(1);
raises(function() { $.ku4reflection.invoke("$.money", [1114.15], {"toString": "."}); });
});
});<file_sep>$(function(){
module("instance | execute async");
asyncTest("execute object async null args", function() {
var instance = $.asyncStub();
expect(2);
function callback(err, arg) {
equal(err, null);
equal(arg, null);
start();
}
$.ku4reflection.execute(instance, {"callAsync": [null, "__CALLBACK__", null]}, callback);
});
asyncTest("execute object async undefined args", function() {
var instance = $.asyncStub();
expect(2);
function callback(err, arg) {
equal(err, null);
equal(arg, null);
start();
}
$.ku4reflection.execute(instance, {"callAsync": [undefined, "__CALLBACK__", undefined]}, callback);
});
test("execute object async empty args", function() {
expect(1);
raises(function() { $.ku4reflection.execute(instance, {"callAsync": []}, callback); });
});
test("execute object async with invalid args", function() {
expect(1);
raises(function() { $.ku4reflection.execute(instance, {"callAsync": "."}, callback); });
});
});<file_sep>$(function(){
module("class | call async");
asyncTest("call object async null args", function() {
expect(2);
function callback(err, arg) {
equal(err, null);
equal(arg, null);
start();
}
$.ku4reflection.invoke("$.asyncStub", [], {"callAsync": [null, "__CALLBACK__", null]}, callback);
});
asyncTest("call object async undefined args", function() {
expect(2);
function callback(err, arg) {
equal(err, null);
equal(arg, null);
start();
}
$.ku4reflection.invoke("$.asyncStub", [], {"callAsync": [undefined, "__CALLBACK__", undefined]}, callback);
});
test("call object async empty args", function() {
expect(1);
raises(function() { $.ku4reflection.invoke("$.asyncStub", [], {"callAsync": []}, callback); });
});
test("call object async with invalid args", function() {
expect(1);
raises(function() { $.ku4reflection.invoke("$.asyncStub", [], {"callAsync": "."}, callback); });
});
});<file_sep>$.ku4reflection = {
instantiate: function(Class, constructors) {
return ku4reflection_instantiate(Class, constructors);
},
execute: function() {
var arg0 = arguments[0],
args = ($.isArray(arg0)) ? arg0 : $.list.parseArguments(arguments).toArray(),
arity = args.length,
instance = args[0],
arg2 = args[1],
arg3 = args[2],
arg4 = args[3];
if(arity == 4) return ku4reflection_execute_async(instance, arg2, arg3, arg4);
if(arity == 3 && $.isArray(arg2) && $.isFunction(arg3)) return ku4reflection_execute_chain_async(instance, arg2, arg3);
if(arity == 3 && $.isObject(arg2) && $.isFunction(arg3)) return ku4reflection_execute_object_async(instance, arg2, arg3);
if(arity == 3 && $.isArray(arg3)) return ku4reflection_execute_sync(instance, arg2, arg3);
if(arity == 2 && $.isString(arg2)) return ku4reflection_execute_sync(instance, arg2, arg3);
if(arity == 2 && $.isObject(arg2)) return ku4reflection_execute_object_sync(instance, arg2);
if(arity == 2 && !$.isFunction(instance) && $.isArray(arg2)) return ku4reflection_execute_chain_sync(instance, arg2);
if((arity == 2 && $.isArray(arg2)) || arity == 1) return instance.apply(self, arg2);
throw $.ku4exception("Argument Exception", "Invalid reflection arguments: " + args);
},
invoke: function()
{
var arg0 = arguments[0],
args = ($.isArray(arg0)) ? arg0 : arguments,
arity = args.length - 1,
instance = ku4reflection_instantiate(args[0], args[1]),
arg3 = args[2],
arg4 = args[3],
arg5 = args[4];
if(arity == 4) return this.execute.call(this, instance, arg3, arg4, arg5);
if(arity == 3) return this.execute.call(this, instance, arg3, arg4);
if(arity == 2) return this.execute.call(this, instance, arg3);
if(arity == 1) return this.execute.call(this, instance);
return this.execute.call(this);
}
};<file_sep>$(function(){
module("instance | execute sync chain");
test("execute sync", function() {
var value = $.ku4reflection.execute(1, [
"toString",
{"replace": ["1", "A"]}
]);
expect(1);
equal(value, "A");
});
test("execute sync with args", function() {
var value = $.ku4reflection.execute($.money(4.15), [
{"add": [$.money(1.15)]},
{"subtract": [$.money(.30)]},
"toString"
]);
expect(1);
equal(value, "$5.00");
});
test("execute sync with invalid args", function() {
expect(1);
raises(function(){
$.ku4reflection.execute($.money(4.15), [
{"add": $.money(1.15)},
{"subtract": $.money(.30)},
"toString"
]);
});
});
});<file_sep>/* Synchronously executes method with args on Class with constructors
*/
function ku4reflection_execute_chain_sync(instance, methods)
{
$.list(methods).each(function(method) {
instance = ($.isString(method))
? ku4reflection_execute_sync(instance, method)
: ku4reflection_execute_object_sync(instance, method);
});
return instance;
}<file_sep>$(function(){
module("instance | execute async");
asyncTest("execute async", function() {
var instance = $.asyncStub();
expect(2);
function callback(err, arg) {
equal(err, null);
equal(arg, null);
start();
}
$.ku4reflection.execute(instance, "callAsync", [null, "__CALLBACK__", null], callback);
});
asyncTest("execute async with args", function() {
var instance = $.asyncStub();
expect(2);
function callback(err, arg) {
equal(err, false);
equal(arg, 1);
start();
}
$.ku4reflection.execute(instance, "callAsync", [false, "__CALLBACK__", 1], callback);
});
test("execute async with invalid args", function() {
var instance = $.asyncStub();
expect(1);
raises(function(){ $.ku4reflection.execute(instance, "callAsync", "__CALLBACK__", callback); });
});
test("execute async with no callback", function() {
var instance = $.asyncStub();
expect(1);
raises(function(){ $.ku4reflection.execute(instance, "callAsync", [false, "", 1], callback); });
});
asyncTest("execute async with continued processing", function () {
var instance = $.ku4indexedDbStore();
expect(2);
function callback(err, store) {
equal(err, null);
store.read("persons", function(err, collection) {
equal(collection.find({id:1})[0].name, "myName");
collection.remove();
start();
});
}
$.ku4reflection.execute(instance, {"read": ["persons",
"^(err, collection){ collection.insert({id:1, name:'myName'}).save(function(){ __CALLBACK__; }) }"
]}, callback);
});
});<file_sep>/* Executes the method of instance with args, and replaces all args passed
* as "__CALLBACK__" with the function passed as callback or default return function
*
* NOTE: Executes method of CLASS with callback
* ku4reflection_execute_async(new CLASS(), "method", ["arg", "__CALLBACK__"], function() { console.log("callback") });
*/
function ku4reflection_execute_async(instance, method, args, callback)
{
var _callback = callback || function() { return;},
format = "({0}).apply(null, arguments)",
regexp = /__CALLBACK__/g;
$.list(args).each(function(arg) {
var index = args.indexOf(arg);
if($.ku4block.isBlock(arg)) {
var block = arg.replace(regexp, $.str.format(format, _callback.toString()));
args[index] = $.ku4block(block).toFunction();
}
else if(regexp.test(arg)) args[index] = _callback;
});
return instance[method].apply(instance, args);
}<file_sep>(function(l){
function ku4block(block) {
var _block = ($.isFunction(block)) ? block.toString() : block;
if(!$.ku4block.isBlock(_block))
throw $.ku4exception("Argument Exception", "ku4blocks take the form ^( /*[arg[, arg]]*/ ){ /*code*/ }" +
"\n\nCOMMON REASONS FOR EXCEPTIONS:" +
"\n1) Parameters must be a CSV containing no more than one space between commas and the next parameter." +
"\n2) The block may not contain leading or trailing space." +
"\n3) The format of the block must contain: ^(){}");
this._block = _block.replace(/^\^/, "function");
}
ku4block.prototype = {
execute: function() {
return this.toFunction().apply(null, arguments);
},
toFunction: function() {
return eval("(" + this._block + ")");
}
};
$.ku4block = function(block) { return new ku4block(block); };
$.ku4block.isBlock = function(value) {
var _value = ($.isFunction(value)) ? value.toString() : value;
return /^(?:\^|function)\s?\((?:(?:\w+\,\s?)*\w+)?\)\s?\{[\s\S]*\}$/m.test(_value);
};
/* Instantiates a Class with the passed constructors
*
* NOTE: Returns an instance of money with value B4.13
* ku4reflection_instantiate("$.money", [4.13, 'B']);
*
* NOTE: Returns an instance of CLASS constructed with arguments 1, 2, and 3
* ku4reflection_instantiate("new CLASS", [1,2,3]);
*/
function ku4reflection_instantiate(Class, constructors) {
if(!$.isString(Class))
throw $.ku4exception("Argument Exception", $.str.format("Cannot instantiate non-string values. Class = {0}", Class));
var containsNew = /^new\s/.test(Class),
namespace = Class.split("."),
rootObject = (containsNew)
? $.str.format("{0}({1})", Class, $.json.serialize(constructors).replace(/^\[/, "").replace(/\]$/, ""))
: namespace.shift();
try {
var _class = eval("(" + rootObject + ")");
if (!containsNew) $.list(namespace).each(function (item) {
_class = _class[item];
});
return (containsNew || !$.exists(_class.apply)) ? _class : _class.apply(this, constructors);
}
catch(e) {
throw $.ku4exception("Argument Exception", $.str.format("Cannot instantiate Class = {0}. Is not defined.", Class));
}
}
/* Executes the method of instance with args, and replaces all args passed
* as "__CALLBACK__" with the function passed as callback or default return function
*
* NOTE: Executes method of CLASS with callback
* ku4reflection_execute_async(new CLASS(), "method", ["arg", "__CALLBACK__"], function() { console.log("callback") });
*/
function ku4reflection_execute_async(instance, method, args, callback)
{
var _callback = callback || function() { return;},
format = "({0}).apply(null, arguments)",
regexp = /__CALLBACK__/g;
$.list(args).each(function(arg) {
var index = args.indexOf(arg);
if($.ku4block.isBlock(arg)) {
var block = arg.replace(regexp, $.str.format(format, _callback.toString()));
args[index] = $.ku4block(block).toFunction();
}
else if(regexp.test(arg)) args[index] = _callback;
});
return instance[method].apply(instance, args);
}
/* Asynchronously executes method with args on Class with constructors
*/
function ku4reflection_execute_chain_async(instance, methods, callback)
{
$.list(methods).each(function(method) {
instance = ($.isString(method))
? ku4reflection_execute_async(instance, method, [], callback)
: ku4reflection_execute_object_async(instance, method, callback);
});
return instance;
}
/* Executes the method of instance with args, and replaces all args passed
* as "__CALLBACK__" with the function passed as callback or default return function
*
* NOTE: Executes method of CLASS with callback
* ku4reflection_execute_async(new CLASS(), "method", ["arg", "__CALLBACK__"], function() { console.log("callback") });
*/
function ku4reflection_execute_object_async(instance, method, callback)
{
var methodName = $.obj.keys(method)[0],
args = method[methodName];
return ku4reflection_execute_async(instance, methodName, args, callback);
}
/* Executes the method of instance with args
*
* NOTE: Executes toString with arguments "," and "."
* ku4reflection_execute_sync($.money(), "toString", [",","."]);
*/
function ku4reflection_execute_sync(instance, method, args)
{
return instance[method].apply(instance, args);
}
/* Synchronously executes method with args on Class with constructors
*/
function ku4reflection_execute_chain_sync(instance, methods)
{
$.list(methods).each(function(method) {
instance = ($.isString(method))
? ku4reflection_execute_sync(instance, method)
: ku4reflection_execute_object_sync(instance, method);
});
return instance;
}
/* Executes the method of instance with args
*
* NOTE: Executes toString with arguments "," and "."
* ku4reflection_execute_sync($.money(), "toString", [",","."]);
*/
function ku4reflection_execute_object_sync(instance, method)
{
var methodName = $.obj.keys(method)[0],
args = method[methodName];
return ku4reflection_execute_sync(instance, methodName, args);
}
$.ku4reflection = {
instantiate: function(Class, constructors) {
return ku4reflection_instantiate(Class, constructors);
},
execute: function() {
var arg0 = arguments[0],
args = ($.isArray(arg0)) ? arg0 : $.list.parseArguments(arguments).toArray(),
arity = args.length,
instance = args[0],
arg2 = args[1],
arg3 = args[2],
arg4 = args[3];
if(arity == 4) return ku4reflection_execute_async(instance, arg2, arg3, arg4);
if(arity == 3 && $.isArray(arg2) && $.isFunction(arg3)) return ku4reflection_execute_chain_async(instance, arg2, arg3);
if(arity == 3 && $.isObject(arg2) && $.isFunction(arg3)) return ku4reflection_execute_object_async(instance, arg2, arg3);
if(arity == 3 && $.isArray(arg3)) return ku4reflection_execute_sync(instance, arg2, arg3);
if(arity == 2 && $.isString(arg2)) return ku4reflection_execute_sync(instance, arg2, arg3);
if(arity == 2 && $.isObject(arg2)) return ku4reflection_execute_object_sync(instance, arg2);
if(arity == 2 && !$.isFunction(instance) && $.isArray(arg2)) return ku4reflection_execute_chain_sync(instance, arg2);
if((arity == 2 && $.isArray(arg2)) || arity == 1) return instance.apply(self, arg2);
throw $.ku4exception("Argument Exception", "Invalid reflection arguments: " + args);
},
invoke: function()
{
var arg0 = arguments[0],
args = ($.isArray(arg0)) ? arg0 : arguments,
arity = args.length - 1,
instance = ku4reflection_instantiate(args[0], args[1]),
arg3 = args[2],
arg4 = args[3],
arg5 = args[4];
if(arity == 4) return this.execute.call(this, instance, arg3, arg4, arg5);
if(arity == 3) return this.execute.call(this, instance, arg3, arg4);
if(arity == 2) return this.execute.call(this, instance, arg3);
if(arity == 1) return this.execute.call(this, instance);
return this.execute.call(this);
}
};
})();
<file_sep>$(function(){
module("instance | execute async chain");
asyncTest("execute async", function() {
var instance = $.asyncStub();
expect(2);
function callback(err, arg) {
equal(err, false);
equal(arg, null);
start();
}
$.ku4reflection.execute(instance, [
{"onSuccess":["__CALLBACK__"]},
{"callSuccess": []}], callback);
});
asyncTest("execute async with args", function() {
var instance = $.asyncStub();
expect(2);
function callback(err, arg) {
equal(err, false);
equal(arg, 5);
start();
}
$.ku4reflection.execute(instance, [
{"onSuccess":["__CALLBACK__"]},
{"callSuccess": [5]}], callback);
});
test("execute async with invalid args", function() {
var instance = $.asyncStub();
expect(1);
raises(function() { $.ku4reflection.execute(instance, [
{"onSuccess":"__CALLBACK__"},
{"callSuccess": "5"}], callback); });
});
});<file_sep>/* Asynchronously executes method with args on Class with constructors
*/
function ku4reflection_execute_chain_async(instance, methods, callback)
{
$.list(methods).each(function(method) {
instance = ($.isString(method))
? ku4reflection_execute_async(instance, method, [], callback)
: ku4reflection_execute_object_async(instance, method, callback);
});
return instance;
} | 100a0a923c1fc42e273b04ce7e67b20c8044757f | [
"JavaScript",
"Markdown"
] | 14 | JavaScript | kodmunki/ku4js-reflection | 95d536bcf6c36088cde938552b641a23118c13a2 | 300ff35abe07185daa0dc4dc3e2e50fa64a06cc1 |
refs/heads/master | <repo_name>liuhou/TestCoverage<file_sep>/Custom_Project_Test_Result/Clover/treemap-dash-json.js
var treeMapJson = {"id":"Clover database Thu Jun 1 2017 16:48:29 PDT0","name":"","data":{
"$area":125.0,"$color":78.4,"title":" 125 Elements, 78.4% Coverage"},
"children":[{"id":"CustomProjectMaven0","name":"CustomProjectMaven","data":
{"$area":125.0,"$color":78.4,"title":
"CustomProjectMaven 125 Elements, 78.4% Coverage"},"children":[]}]}
;
processTreeMapDashJson (treeMapJson);<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/DefaultConstructor.java
package CustomProjectMaven;
/**
* Created by arielxin on 5/18/17.
*/
public class DefaultConstructor {
}
<file_sep>/CustomProjectMaven/src/test/java/CustomProjectMaven/StaticInnerClassTest.java
package CustomProjectMaven;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Created by liyuanqi on 5/18/17.
*/
public class StaticInnerClassTest {
@Test
public void testStaticInnerClassMethod(){
assertTrue(StaticInnerClass.staticNestedClassAdd(1,1)==2);
}
}
<file_sep>/CustomProjectMaven/src/test/java/CustomProjectMaven/MultiplierEnumTest.java
package CustomProjectMaven;
import com.sun.org.apache.xpath.internal.operations.Mult;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by arielxin on 5/18/17.
*/
public class MultiplierEnumTest {
@Test
public void multiplierTest(){
assertEquals(MultiplierEnum.DOUBLE.applyMultiplier(1.0), 2.0, 0.1);
assertEquals(MultiplierEnum.TRIPLE.applyMultiplier(1.0), 3.0, 0.1);
}
}<file_sep>/Apache_Project_Test_Result/JMockit_Test/org/apache/commons/cli/AlreadySelectedException.html
<!DOCTYPE html>
<html>
<head>
<title>AlreadySelectedException.java</title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<link rel='stylesheet' type='text/css' href='../../../../coverage.css'/>
<link rel='shortcut icon' type='image/png' href='../../../../logo.png'/>
<script type='text/javascript' src='../../../../coverage.js'></script>
<script type='text/javascript' src='../../../../prettify.js'></script>
</head>
<body onload='prettyPrint()'>
<table cellpadding='0' cellspacing='1'>
<caption>commons-cli-1.4-src/src/main/java/org/apache/commons/cli/AlreadySelectedException.java</caption>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div>/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</div><span>/*...*/</span></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>18</td><td> </td>
<td><pre class='prettyprint'>package org.apache.commons.cli;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div>/**
* Thrown when more than one option in an option group
* has been provided.
*
* @version $Id: AlreadySelectedException.java 1443102 2013-02-06 18:12:16Z tn $
*/</div><span>/*...*/</span></td>
</tr>
<tr>
<td class='line'>26</td><td> </td>
<td><pre class='prettyprint'>public class AlreadySelectedException extends ParseException</pre></td>
</tr>
<tr>
<td class='line'>27</td><td> </td>
<td><pre class='prettyprint'>{</pre></td>
</tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* This exception {@code serialVersionUID}.
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>31</td><td> </td>
<td><pre class='prettyprint'> private static final long serialVersionUID = 3674381532418544760L;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>33</td><td> </td>
<td><pre class='comment'> /** The option group selected. */</pre></td>
</tr>
<tr>
<td class='line'>34</td><td> </td>
<td><pre class='prettyprint'> private OptionGroup group;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>36</td><td> </td>
<td><pre class='comment'> /** The option that triggered the exception. */</pre></td>
</tr>
<tr>
<td class='line'>37</td><td> </td>
<td><pre class='prettyprint'> private Option option;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Construct a new <code>AlreadySelectedException</code>
* with the specified detail message.
*
* @param message the detail message
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>45</td><td> </td>
<td><pre class='prettyprint'> public AlreadySelectedException(String message)</pre></td>
</tr>
<tr>
<td class='line'>46</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>47</td><td class='count'>2</td>
<td><pre class='prettyprint covered' id='l47s0'> super(message);</pre></td>
</tr>
<tr>
<td class='line'>48</td><td class='count'>2</td>
<td><pre class='prettyprint covered' id='l48s0'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Construct a new <code>AlreadySelectedException</code>
* for the specified option group.
*
* @param group the option group already selected
* @param option the option that triggered the exception
* @since 1.2
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>58</td><td> </td>
<td><pre class='prettyprint'> public AlreadySelectedException(OptionGroup group, Option option)</pre></td>
</tr>
<tr>
<td class='line'>59</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>60</td><td class='count'>4</td>
<td><pre class='prettyprint covered' id='l60s0'> this("The option '" + option.getKey() + "' was specified but an option from this group "</pre></td>
</tr>
<tr>
<td class='line'>61</td><td class='count'>2</td>
<td><pre class='prettyprint covered' id='l61s0'> + "has already been selected: '" + group.getSelected() + "'");</pre></td>
</tr>
<tr>
<td class='line'>62</td><td class='count'>2</td>
<td><pre class='prettyprint covered' id='l62s0'> this.group = group;</pre></td>
</tr>
<tr>
<td class='line'>63</td><td class='count'>2</td>
<td><pre class='prettyprint covered' id='l63s0'> this.option = option;</pre></td>
</tr>
<tr>
<td class='line'>64</td><td class='count'>2</td>
<td><pre class='prettyprint covered' id='l64s0'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Returns the option group where another option has been selected.
*
* @return the related option group
* @since 1.2
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>72</td><td> </td>
<td><pre class='prettyprint'> public OptionGroup getOptionGroup()</pre></td>
</tr>
<tr>
<td class='line'>73</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>74</td><td class='count'>4</td>
<td><pre class='prettyprint covered' id='l74s0'> return group;</pre></td>
</tr>
<tr>
<td class='line'>75</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Returns the option that was added to the group and triggered the exception.
*
* @return the related option
* @since 1.2
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>83</td><td> </td>
<td><pre class='prettyprint'> public Option getOption()</pre></td>
</tr>
<tr>
<td class='line'>84</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>85</td><td class='count'>2</td>
<td><pre class='prettyprint covered' id='l85s0'> return option;</pre></td>
</tr>
<tr>
<td class='line'>86</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr>
<td class='line'>87</td><td> </td>
<td><pre class='prettyprint'>}</pre></td>
</tr>
</table>
</body>
</html>
<file_sep>/Apache_Project_Test_Result/IntelliJ_Test_Report/org.apache.commons.cli/.classes/CommandLine.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html id="htmlId">
<head>
<title>Coverage Report :: CommandLine</title>
<style type="text/css">
@import "../../.css/coverage.css";
</style>
</head>
<body>
<div class="header"></div>
<div class="content">
<div class="breadCrumbs">
[ <a href="../../index.html">all classes</a> ]
[ <a href="../index.html">org.apache.commons.cli</a> ]
</div>
<h1>Coverage Summary for Class: CommandLine (org.apache.commons.cli)</h1>
<table class="coverageStats">
<tr>
<th class="name">Class</th>
<th class="coverageStat
">
Method, %
</th>
<th class="coverageStat
">
Line, %
</th>
</tr>
<tr>
<td class="name">CommandLine</td>
<td class="coverageStat">
<span class="percent">
100%
</span>
<span class="absValue">
(20/ 20)
</span>
</td>
<td class="coverageStat">
<span class="percent">
100%
</span>
<span class="absValue">
(59/ 59)
</span>
</td>
</tr>
<tr>
<td class="name">CommandLine$Builder</td>
<td class="coverageStat">
<span class="percent">
100%
</span>
<span class="absValue">
(4/ 4)
</span>
</td>
<td class="coverageStat">
<span class="percent">
100%
</span>
<span class="absValue">
(7/ 7)
</span>
</td>
</tr>
<tr>
<td class="name"><strong>total</strong></td>
<td class="coverageStat">
<span class="percent">
100%
</span>
<span class="absValue">
(24/ 24)
</span>
</td>
<td class="coverageStat">
<span class="percent">
100%
</span>
<span class="absValue">
(66/ 66)
</span>
</td>
</tr>
</table>
<br/>
<br/>
<div class="sourceCode"><i>1</i> /**
<i>2</i> * Licensed to the Apache Software Foundation (ASF) under one or more
<i>3</i> * contributor license agreements. See the NOTICE file distributed with
<i>4</i> * this work for additional information regarding copyright ownership.
<i>5</i> * The ASF licenses this file to You under the Apache License, Version 2.0
<i>6</i> * (the "License"); you may not use this file except in compliance with
<i>7</i> * the License. You may obtain a copy of the License at
<i>8</i> *
<i>9</i> * http://www.apache.org/licenses/LICENSE-2.0
<i>10</i> *
<i>11</i> * Unless required by applicable law or agreed to in writing, software
<i>12</i> * distributed under the License is distributed on an "AS IS" BASIS,
<i>13</i> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<i>14</i> * See the License for the specific language governing permissions and
<i>15</i> * limitations under the License.
<i>16</i> */
<i>17</i>
<i>18</i> package org.apache.commons.cli;
<i>19</i>
<i>20</i> import java.io.Serializable;
<i>21</i> import java.util.ArrayList;
<i>22</i> import java.util.Collection;
<i>23</i> import java.util.Iterator;
<i>24</i> import java.util.LinkedList;
<i>25</i> import java.util.List;
<i>26</i> import java.util.Properties;
<i>27</i>
<i>28</i> /**
<i>29</i> * Represents list of arguments parsed against a {@link Options} descriptor.
<i>30</i> * <p>
<i>31</i> * It allows querying of a boolean {@link #hasOption(String opt)},
<i>32</i> * in addition to retrieving the {@link #getOptionValue(String opt)}
<i>33</i> * for options requiring arguments.
<i>34</i> * <p>
<i>35</i> * Additionally, any left-over or unrecognized arguments,
<i>36</i> * are available for further processing.
<i>37</i> *
<i>38</i> * @version $Id: CommandLine.java 1786144 2017-03-09 11:34:57Z britter $
<i>39</i> */
<i>40</i> public class CommandLine implements Serializable
<i>41</i> {
<i>42</i> /** The serial version UID. */
<i>43</i> private static final long serialVersionUID = 1L;
<i>44</i>
<i>45</i> /** the unrecognized options/arguments */
<b class="fc"><i>46</i> private final List<String> args = new LinkedList<String>();</b>
<i>47</i>
<i>48</i> /** the processed options */
<b class="fc"><i>49</i> private final List<Option> options = new ArrayList<Option>();</b>
<i>50</i>
<i>51</i> /**
<i>52</i> * Creates a command line.
<i>53</i> */
<i>54</i> protected CommandLine()
<b class="fc"><i>55</i> {</b>
<i>56</i> // nothing to do
<b class="fc"><i>57</i> }</b>
<i>58</i>
<i>59</i> /**
<i>60</i> * Query to see if an option has been set.
<i>61</i> *
<i>62</i> * @param opt Short name of the option
<i>63</i> * @return true if set, false if not
<i>64</i> */
<i>65</i> public boolean hasOption(String opt)
<i>66</i> {
<b class="fc"><i>67</i> return options.contains(resolveOption(opt));</b>
<i>68</i> }
<i>69</i>
<i>70</i> /**
<i>71</i> * Query to see if an option has been set.
<i>72</i> *
<i>73</i> * @param opt character name of the option
<i>74</i> * @return true if set, false if not
<i>75</i> */
<i>76</i> public boolean hasOption(char opt)
<i>77</i> {
<b class="fc"><i>78</i> return hasOption(String.valueOf(opt));</b>
<i>79</i> }
<i>80</i>
<i>81</i> /**
<i>82</i> * Return the <code>Object</code> type of this <code>Option</code>.
<i>83</i> *
<i>84</i> * @param opt the name of the option
<i>85</i> * @return the type of this <code>Option</code>
<i>86</i> * @deprecated due to System.err message. Instead use getParsedOptionValue(String)
<i>87</i> */
<i>88</i> @Deprecated
<i>89</i> public Object getOptionObject(String opt)
<i>90</i> {
<i>91</i> try
<i>92</i> {
<b class="fc"><i>93</i> return getParsedOptionValue(opt);</b>
<i>94</i> }
<b class="fc"><i>95</i> catch (ParseException pe)</b>
<i>96</i> {
<b class="fc"><i>97</i> System.err.println("Exception found converting " + opt + " to desired type: " + pe.getMessage());</b>
<b class="fc"><i>98</i> return null;</b>
<i>99</i> }
<i>100</i> }
<i>101</i>
<i>102</i> /**
<i>103</i> * Return a version of this <code>Option</code> converted to a particular type.
<i>104</i> *
<i>105</i> * @param opt the name of the option
<i>106</i> * @return the value parsed into a particular object
<i>107</i> * @throws ParseException if there are problems turning the option value into the desired type
<i>108</i> * @see PatternOptionBuilder
<i>109</i> * @since 1.2
<i>110</i> */
<i>111</i> public Object getParsedOptionValue(String opt) throws ParseException
<i>112</i> {
<b class="fc"><i>113</i> String res = getOptionValue(opt);</b>
<b class="fc"><i>114</i> Option option = resolveOption(opt);</b>
<i>115</i>
<b class="fc"><i>116</i> if (option == null || res == null)</b>
<i>117</i> {
<b class="fc"><i>118</i> return null;</b>
<i>119</i> }
<i>120</i>
<b class="fc"><i>121</i> return TypeHandler.createValue(res, option.getType());</b>
<i>122</i> }
<i>123</i>
<i>124</i> /**
<i>125</i> * Return the <code>Object</code> type of this <code>Option</code>.
<i>126</i> *
<i>127</i> * @param opt the name of the option
<i>128</i> * @return the type of opt
<i>129</i> */
<i>130</i> public Object getOptionObject(char opt)
<i>131</i> {
<b class="fc"><i>132</i> return getOptionObject(String.valueOf(opt));</b>
<i>133</i> }
<i>134</i>
<i>135</i> /**
<i>136</i> * Retrieve the first argument, if any, of this option.
<i>137</i> *
<i>138</i> * @param opt the name of the option
<i>139</i> * @return Value of the argument if option is set, and has an argument,
<i>140</i> * otherwise null.
<i>141</i> */
<i>142</i> public String getOptionValue(String opt)
<i>143</i> {
<b class="fc"><i>144</i> String[] values = getOptionValues(opt);</b>
<i>145</i>
<b class="fc"><i>146</i> return (values == null) ? null : values[0];</b>
<i>147</i> }
<i>148</i>
<i>149</i> /**
<i>150</i> * Retrieve the first argument, if any, of this option.
<i>151</i> *
<i>152</i> * @param opt the character name of the option
<i>153</i> * @return Value of the argument if option is set, and has an argument,
<i>154</i> * otherwise null.
<i>155</i> */
<i>156</i> public String getOptionValue(char opt)
<i>157</i> {
<b class="fc"><i>158</i> return getOptionValue(String.valueOf(opt));</b>
<i>159</i> }
<i>160</i>
<i>161</i> /**
<i>162</i> * Retrieves the array of values, if any, of an option.
<i>163</i> *
<i>164</i> * @param opt string name of the option
<i>165</i> * @return Values of the argument if option is set, and has an argument,
<i>166</i> * otherwise null.
<i>167</i> */
<i>168</i> public String[] getOptionValues(String opt)
<i>169</i> {
<b class="fc"><i>170</i> List<String> values = new ArrayList<String>();</b>
<i>171</i>
<b class="fc"><i>172</i> for (Option option : options)</b>
<i>173</i> {
<b class="fc"><i>174</i> if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt()))</b>
<i>175</i> {
<b class="fc"><i>176</i> values.addAll(option.getValuesList());</b>
<i>177</i> }
<b class="fc"><i>178</i> }</b>
<i>179</i>
<b class="fc"><i>180</i> return values.isEmpty() ? null : values.toArray(new String[values.size()]);</b>
<i>181</i> }
<i>182</i>
<i>183</i> /**
<i>184</i> * Retrieves the option object given the long or short option as a String
<i>185</i> *
<i>186</i> * @param opt short or long name of the option
<i>187</i> * @return Canonicalized option
<i>188</i> */
<i>189</i> private Option resolveOption(String opt)
<i>190</i> {
<b class="fc"><i>191</i> opt = Util.stripLeadingHyphens(opt);</b>
<b class="fc"><i>192</i> for (Option option : options)</b>
<i>193</i> {
<b class="fc"><i>194</i> if (opt.equals(option.getOpt()))</b>
<i>195</i> {
<b class="fc"><i>196</i> return option;</b>
<i>197</i> }
<i>198</i>
<b class="fc"><i>199</i> if (opt.equals(option.getLongOpt()))</b>
<i>200</i> {
<b class="fc"><i>201</i> return option;</b>
<i>202</i> }
<i>203</i>
<b class="fc"><i>204</i> }</b>
<b class="fc"><i>205</i> return null;</b>
<i>206</i> }
<i>207</i>
<i>208</i> /**
<i>209</i> * Retrieves the array of values, if any, of an option.
<i>210</i> *
<i>211</i> * @param opt character name of the option
<i>212</i> * @return Values of the argument if option is set, and has an argument,
<i>213</i> * otherwise null.
<i>214</i> */
<i>215</i> public String[] getOptionValues(char opt)
<i>216</i> {
<b class="fc"><i>217</i> return getOptionValues(String.valueOf(opt));</b>
<i>218</i> }
<i>219</i>
<i>220</i> /**
<i>221</i> * Retrieve the first argument, if any, of an option.
<i>222</i> *
<i>223</i> * @param opt name of the option
<i>224</i> * @param defaultValue is the default value to be returned if the option
<i>225</i> * is not specified
<i>226</i> * @return Value of the argument if option is set, and has an argument,
<i>227</i> * otherwise <code>defaultValue</code>.
<i>228</i> */
<i>229</i> public String getOptionValue(String opt, String defaultValue)
<i>230</i> {
<b class="fc"><i>231</i> String answer = getOptionValue(opt);</b>
<i>232</i>
<b class="fc"><i>233</i> return (answer != null) ? answer : defaultValue;</b>
<i>234</i> }
<i>235</i>
<i>236</i> /**
<i>237</i> * Retrieve the argument, if any, of an option.
<i>238</i> *
<i>239</i> * @param opt character name of the option
<i>240</i> * @param defaultValue is the default value to be returned if the option
<i>241</i> * is not specified
<i>242</i> * @return Value of the argument if option is set, and has an argument,
<i>243</i> * otherwise <code>defaultValue</code>.
<i>244</i> */
<i>245</i> public String getOptionValue(char opt, String defaultValue)
<i>246</i> {
<b class="fc"><i>247</i> return getOptionValue(String.valueOf(opt), defaultValue);</b>
<i>248</i> }
<i>249</i>
<i>250</i> /**
<i>251</i> * Retrieve the map of values associated to the option. This is convenient
<i>252</i> * for options specifying Java properties like <tt>-Dparam1=value1
<i>253</i> * -Dparam2=value2</tt>. The first argument of the option is the key, and
<i>254</i> * the 2nd argument is the value. If the option has only one argument
<i>255</i> * (<tt>-Dfoo</tt>) it is considered as a boolean flag and the value is
<i>256</i> * <tt>"true"</tt>.
<i>257</i> *
<i>258</i> * @param opt name of the option
<i>259</i> * @return The Properties mapped by the option, never <tt>null</tt>
<i>260</i> * even if the option doesn't exists
<i>261</i> * @since 1.2
<i>262</i> */
<i>263</i> public Properties getOptionProperties(String opt)
<i>264</i> {
<b class="fc"><i>265</i> Properties props = new Properties();</b>
<i>266</i>
<b class="fc"><i>267</i> for (Option option : options)</b>
<i>268</i> {
<b class="fc"><i>269</i> if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt()))</b>
<i>270</i> {
<b class="fc"><i>271</i> List<String> values = option.getValuesList();</b>
<b class="fc"><i>272</i> if (values.size() >= 2)</b>
<i>273</i> {
<i>274</i> // use the first 2 arguments as the key/value pair
<b class="fc"><i>275</i> props.put(values.get(0), values.get(1));</b>
<i>276</i> }
<b class="fc"><i>277</i> else if (values.size() == 1)</b>
<i>278</i> {
<i>279</i> // no explicit value, handle it as a boolean
<b class="fc"><i>280</i> props.put(values.get(0), "true");</b>
<i>281</i> }
<i>282</i> }
<b class="fc"><i>283</i> }</b>
<i>284</i>
<b class="fc"><i>285</i> return props;</b>
<i>286</i> }
<i>287</i>
<i>288</i> /**
<i>289</i> * Retrieve any left-over non-recognized options and arguments
<i>290</i> *
<i>291</i> * @return remaining items passed in but not parsed as an array
<i>292</i> */
<i>293</i> public String[] getArgs()
<i>294</i> {
<b class="fc"><i>295</i> String[] answer = new String[args.size()];</b>
<i>296</i>
<b class="fc"><i>297</i> args.toArray(answer);</b>
<i>298</i>
<b class="fc"><i>299</i> return answer;</b>
<i>300</i> }
<i>301</i>
<i>302</i> /**
<i>303</i> * Retrieve any left-over non-recognized options and arguments
<i>304</i> *
<i>305</i> * @return remaining items passed in but not parsed as a <code>List</code>.
<i>306</i> */
<i>307</i> public List<String> getArgList()
<i>308</i> {
<b class="fc"><i>309</i> return args;</b>
<i>310</i> }
<i>311</i>
<i>312</i> /**
<i>313</i> * jkeyes
<i>314</i> * - commented out until it is implemented properly
<i>315</i> * <p>Dump state, suitable for debugging.</p>
<i>316</i> *
<i>317</i> * @return Stringified form of this object
<i>318</i> */
<i>319</i>
<i>320</i> /*
<i>321</i> public String toString() {
<i>322</i> StringBuilder buf = new StringBuilder();
<i>323</i>
<i>324</i> buf.append("[ CommandLine: [ options: ");
<i>325</i> buf.append(options.toString());
<i>326</i> buf.append(" ] [ args: ");
<i>327</i> buf.append(args.toString());
<i>328</i> buf.append(" ] ]");
<i>329</i>
<i>330</i> return buf.toString();
<i>331</i> }
<i>332</i> */
<i>333</i>
<i>334</i> /**
<i>335</i> * Add left-over unrecognized option/argument.
<i>336</i> *
<i>337</i> * @param arg the unrecognized option/argument.
<i>338</i> */
<i>339</i> protected void addArg(String arg)
<i>340</i> {
<b class="fc"><i>341</i> args.add(arg);</b>
<b class="fc"><i>342</i> }</b>
<i>343</i>
<i>344</i> /**
<i>345</i> * Add an option to the command line. The values of the option are stored.
<i>346</i> *
<i>347</i> * @param opt the processed option
<i>348</i> */
<i>349</i> protected void addOption(Option opt)
<i>350</i> {
<b class="fc"><i>351</i> options.add(opt);</b>
<b class="fc"><i>352</i> }</b>
<i>353</i>
<i>354</i> /**
<i>355</i> * Returns an iterator over the Option members of CommandLine.
<i>356</i> *
<i>357</i> * @return an <code>Iterator</code> over the processed {@link Option}
<i>358</i> * members of this {@link CommandLine}
<i>359</i> */
<i>360</i> public Iterator<Option> iterator()
<i>361</i> {
<b class="fc"><i>362</i> return options.iterator();</b>
<i>363</i> }
<i>364</i>
<i>365</i> /**
<i>366</i> * Returns an array of the processed {@link Option}s.
<i>367</i> *
<i>368</i> * @return an array of the processed {@link Option}s.
<i>369</i> */
<i>370</i> public Option[] getOptions()
<i>371</i> {
<b class="fc"><i>372</i> Collection<Option> processed = options;</b>
<i>373</i>
<i>374</i> // reinitialise array
<b class="fc"><i>375</i> Option[] optionsArray = new Option[processed.size()];</b>
<i>376</i>
<i>377</i> // return the array
<b class="fc"><i>378</i> return processed.toArray(optionsArray);</b>
<i>379</i> }
<i>380</i>
<i>381</i> /**
<i>382</i> * A nested builder class to create <code>CommandLine</code> instance
<i>383</i> * using descriptive methods.
<i>384</i> *
<i>385</i> * @since 1.4
<i>386</i> */
<b class="fc"><i>387</i> public static final class Builder</b>
<i>388</i> {
<i>389</i> /**
<i>390</i> * CommandLine that is being build by this Builder.
<i>391</i> */
<b class="fc"><i>392</i> private final CommandLine commandLine = new CommandLine();</b>
<i>393</i>
<i>394</i> /**
<i>395</i> * Add an option to the command line. The values of the option are stored.
<i>396</i> *
<i>397</i> * @param opt the processed option
<i>398</i> *
<i>399</i> * @return this Builder instance for method chaining.
<i>400</i> */
<i>401</i> public Builder addOption(Option opt)
<i>402</i> {
<b class="fc"><i>403</i> commandLine.addOption(opt);</b>
<b class="fc"><i>404</i> return this;</b>
<i>405</i> }
<i>406</i>
<i>407</i> /**
<i>408</i> * Add left-over unrecognized option/argument.
<i>409</i> *
<i>410</i> * @param arg the unrecognized option/argument.
<i>411</i> *
<i>412</i> * @return this Builder instance for method chaining.
<i>413</i> */
<i>414</i> public Builder addArg(String arg)
<i>415</i> {
<b class="fc"><i>416</i> commandLine.addArg(arg);</b>
<b class="fc"><i>417</i> return this;</b>
<i>418</i> }
<i>419</i>
<i>420</i> public CommandLine build()
<i>421</i> {
<b class="fc"><i>422</i> return commandLine;</b>
<i>423</i> }
<i>424</i> }
<i>425</i> }
</div>
</div>
<div class="footer">
<div style="float:right;">generated on 2017-05-18 21:41</div>
</div>
</body>
</html>
<file_sep>/CustomProjectMaven/src/test/java/CustomProjectMaven/ConcreteAdditionClassTest.java
package CustomProjectMaven;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by liyuanqi on 5/18/17.
*/
public class ConcreteAdditionClassTest {
@Test
public void testAbstractMethod(){
ConcreteAdditionClass targetClass = new ConcreteAdditionClass();
assertTrue(targetClass.abstractAdditionMethod(1,1)==2);
}
@Test
public void testConcreteMethod(){
ConcreteAdditionClass targetClass = new ConcreteAdditionClass();
assertTrue(targetClass.concreteAdditionMethod(1,1)==2);
}
@Test
public void testInterfaceMethod(){
ConcreteAdditionClass targetClass = new ConcreteAdditionClass();
assertTrue(targetClass.interfaceAdd(1,1)==2);
}
}
<file_sep>/Apache_Project_Test_Result/Clover_Test_Result/org/apache/commons/cli/bug/BugCLI13Test.js
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":54,"id":3425,"methods":[{"el":53,"sc":5,"sl":34}],"name":"BugCLI13Test","sl":32}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {"test_24":{"methods":[{"sl":34}],"name":"testCLI13","pass":true,"statements":[{"sl":37},{"sl":38},{"sl":45},{"sl":46},{"sl":47},{"sl":49},{"sl":50},{"sl":51},{"sl":52}]}}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [24], [], [], [24], [24], [], [], [], [], [], [], [24], [24], [24], [], [24], [24], [24], [24], [], []]
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/BranchCoverage.java
package CustomProjectMaven;
/**
* Hello world!
*
*/
public class BranchCoverage
{
public String concat(boolean append, String a,String b) {
String result = null;
if (append) {
result = a + b;
}
return result.toLowerCase();
}
public Boolean isOdd(int n) {
if (n%2 != 0)
return true;
else
return false;
}
public Boolean ternaryOperator (boolean A, boolean B){
boolean result = A?B:false;
return result;
}
public int switchOperator (int c){
int result = 0;
switch (c) {
case 1:
result = 1;
break;
case 2:
result = 2;
break;
default:
result = 3;
}
return result;
}
public int orOperator (int x, int y){
if(x > 0 || y > 0){
return x+y;
}
else if (x < -5){
return x;
}
return y;
}
public void andOperator(int x, int y){
if(x > 0 && y > 0){
System.out.println("x and y are both greater than 0");
}
}
public void oneLineIf(int x){
if(x > 0) System.out.println("x is greater than 0");
}
}
<file_sep>/Apache_Project_Test_Result/JMockit_Test/org/apache/commons/cli/MissingOptionException.html
<!DOCTYPE html>
<html>
<head>
<title>MissingOptionException.java</title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<link rel='stylesheet' type='text/css' href='../../../../coverage.css'/>
<link rel='shortcut icon' type='image/png' href='../../../../logo.png'/>
<script type='text/javascript' src='../../../../coverage.js'></script>
<script type='text/javascript' src='../../../../prettify.js'></script>
</head>
<body onload='prettyPrint()'>
<table cellpadding='0' cellspacing='1'>
<caption>commons-cli-1.4-src/src/main/java/org/apache/commons/cli/MissingOptionException.java</caption>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div>/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</div><span>/*...*/</span></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>18</td><td> </td>
<td><pre class='prettyprint'>package org.apache.commons.cli;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td><pre class='imports prettyprint' onclick='showHideLines(this)'><div>import java.util.List;
import java.util.Iterator;
</div><span>import ...</span></pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div>/**
* Thrown when a required option has not been provided.
*
* @version $Id: MissingOptionException.java 1443102 2013-02-06 18:12:16Z tn $
*/</div><span>/*...*/</span></td>
</tr>
<tr>
<td class='line'>28</td><td> </td>
<td><pre class='prettyprint'>public class MissingOptionException extends ParseException</pre></td>
</tr>
<tr>
<td class='line'>29</td><td> </td>
<td><pre class='prettyprint'>{</pre></td>
</tr>
<tr>
<td class='line'>30</td><td> </td>
<td><pre class='comment'> /** This exception {@code serialVersionUID}. */</pre></td>
</tr>
<tr>
<td class='line'>31</td><td> </td>
<td><pre class='prettyprint'> private static final long serialVersionUID = 8161889051578563249L;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>33</td><td> </td>
<td><pre class='comment'> /** The list of missing options and groups */</pre></td>
</tr>
<tr>
<td class='line'>34</td><td> </td>
<td><pre class='prettyprint'> private List missingOptions;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Construct a new <code>MissingSelectedException</code>
* with the specified detail message.
*
* @param message the detail message
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>42</td><td> </td>
<td><pre class='prettyprint'> public MissingOptionException(String message)</pre></td>
</tr>
<tr>
<td class='line'>43</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>44</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l44s0'> super(message);</pre></td>
</tr>
<tr>
<td class='line'>45</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l45s0'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Constructs a new <code>MissingSelectedException</code> with the
* specified list of missing options.
*
* @param missingOptions the list of missing options and groups
* @since 1.2
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>54</td><td> </td>
<td><pre class='prettyprint'> public MissingOptionException(List missingOptions)</pre></td>
</tr>
<tr>
<td class='line'>55</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>56</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l56s0'> this(createMessage(missingOptions));</pre></td>
</tr>
<tr>
<td class='line'>57</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l57s0'> this.missingOptions = missingOptions;</pre></td>
</tr>
<tr>
<td class='line'>58</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l58s0'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Returns the list of options or option groups missing in the command line parsed.
*
* @return the missing options, consisting of String instances for simple
* options, and OptionGroup instances for required option groups.
* @since 1.2
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>67</td><td> </td>
<td><pre class='prettyprint'> public List getMissingOptions()</pre></td>
</tr>
<tr>
<td class='line'>68</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>69</td><td class='count'>22</td>
<td><pre class='prettyprint covered' id='l69s0'> return missingOptions;</pre></td>
</tr>
<tr>
<td class='line'>70</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Build the exception message from the specified list of options.
*
* @param missingOptions the list of missing options and groups
* @since 1.2
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>78</td><td> </td>
<td><pre class='prettyprint'> private static String createMessage(List<?> missingOptions)</pre></td>
</tr>
<tr>
<td class='line'>79</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>80</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l80s0'> StringBuilder buf = new StringBuilder("Missing required option");</pre></td>
</tr>
<tr>
<td class='line'>81</td><td class='count'>21</td>
<td><pre class='prettyprint jmp'> <span id='l81s0' title='Executions: 21' class='covered'>buf.append(missingOptions.size() == 1</span> ? <span id='l81s1' title='Executions: 16' class='covered'>""</span> : <span id='l81s2' title='Executions: 5' class='covered'>"s");</span></pre></td>
</tr>
<tr>
<td class='line'>82</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l82s0'> buf.append(": ");</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>84</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l84s0'> Iterator<?> it = missingOptions.iterator();</pre></td>
</tr>
<tr>
<td class='line'>85</td><td class='count'>47</td>
<td><pre class='prettyprint jmp'> <span id='l85s0' title='Executions: 47' class='covered'>while (it.hasNext())</span></pre></td>
</tr>
<tr>
<td class='line'>86</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>87</td><td class='count'>26</td>
<td><pre class='prettyprint covered' id='l87s0'> buf.append(it.next());</pre></td>
</tr>
<tr>
<td class='line'>88</td><td class='count'>26</td>
<td><pre class='prettyprint covered' id='l88s0'> if (it.hasNext())</pre></td>
</tr>
<tr>
<td class='line'>89</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>90</td><td class='count'>5</td>
<td><pre class='prettyprint covered' id='l90s0'> buf.append(", ");</pre></td>
</tr>
<tr>
<td class='line'>91</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr>
<td class='line'>92</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>94</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l94s0'> return buf.toString();</pre></td>
</tr>
<tr>
<td class='line'>95</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr>
<td class='line'>96</td><td> </td>
<td><pre class='prettyprint'>}</pre></td>
</tr>
</table>
</body>
</html>
<file_sep>/Apache_Project_Test_Result/Emma_Test/Simple_Test_Case/build.xml
<?xml version="1.0"?>
<!-- ============= build file for ANT v1.x [requires v1.4+] ========= -->
<project name="EMMA demo (on-the-fly mode)" default="all" basedir="." >
<!-- the default target compiles and runs Main: -->
<target name="all" depends="compile, run" />
<!-- root directory for the example source code: -->
<property name="src.dir" value="${basedir}/src" />
<!-- javac class output directory: -->
<property name="out.dir" value="${basedir}/out" />
<!-- output directory used for EMMA coverage reports: -->
<property name="coverage.dir" value="${basedir}/coverage" />
<!-- directory that contains emma.jar and emma_ant.jar: -->
<property name="emma.dir" value="${basedir}/../lib" />
<!-- path element used by EMMA taskdef below: -->
<path id="emma.lib" >
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<!-- this loads <emma> and <emmajava> custom tasks: -->
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<target name="clean" description="resets this demo project to a clean state" >
<delete dir="${out.dir}" />
<delete dir="${coverage.dir}" />
</target>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<target name="init" >
<mkdir dir="${out.dir}" />
<path id="run.classpath" >
<pathelement location="${out.dir}" />
</path>
</target>
<target name="emma" description="turns on EMMA's on-the-fly instrumentation mode" >
<property name="emma.enabled" value="true" />
<!-- this property, if overriden via -Demma.filter=<list of filter specs>
on ANT's command line, will set the coverage filter; by default,
all classes found in 'run.classpath' pathref will be instrumented:
-->
<property name="emma.filter" value="" />
</target>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<target name="compile" depends="init" description="compiles the example source code" >
<!-- compile using javac [debug="on" ensures rich(er) emma reporting]: -->
<javac debug="on" srcdir="${src.dir}" destdir="${out.dir}" />
</target>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- if <emmajava> is disabled, it acts as a simple pass-through to
the original ANT <java> task: this is convenient, because it avoids
having to branch the build execution depending on whether you want
code coverage or not. Note that <emmajava> inherits all of <java>'s
attributes and nested elements.
-->
<target name="run" depends="init, compile" description="runs the examples" >
<emmajava enabled="${emma.enabled}" libclasspathref="emma.lib"
fullmetadata="yes" filter="${emma.filter}" sourcepath="${src.dir}"
classname="Main"
classpathref="run.classpath"
>
<jvmarg value="-XX:-UseSplitVerifier"/>
<!-- regular <java> options are still available: -->
<arg value="somearg" />
<!-- <emmajava> option extensions [see the reference manual for
complete details]: -->
<txt outfile="${coverage.dir}/coverage.txt" />
<html outfile="${coverage.dir}/coverage.html" />
</emmajava>
</target>
</project>
<!-- ========= END OF FILE ========================================== -->
<file_sep>/CustomProjectMaven/src/test/java/CustomProjectMaven/GenericTypeClassTest.java
package CustomProjectMaven;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Created by liyuanqi on 5/18/17.
*/
public class GenericTypeClassTest {
@Test
public void testGenericTypeClass(){
GenericTypeClass<String> pClass = new GenericTypeClass<String>();
assertTrue(pClass.concatString("A","B").equals("AB"));
}
}
<file_sep>/CustomProjectMaven/src/test/java/CustomProjectMaven/AnnotationTest.java
package CustomProjectMaven;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Haotian 18/05/2017.
*/
public class AnnotationTest {
@Test
public void AnnotationTest() {
@Annotation.ClassPreamble (
author = "<NAME>",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "<NAME>",
reviewers = {"Alice", "Bob", "Cindy"}
)
String a = "ccc";
assertEquals("ccc", a);
}
}
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/ConcreteAdditionClass.java
package CustomProjectMaven;
/**
* Created by liyuanqi on 5/18/17.
*/
public class ConcreteAdditionClass extends AbstractAdditionClass implements SimpleAdditionInterface{
public int abstractAdditionMethod(int a, int b) {
return a+b;
}
public int interfaceAdd(int a, int b) {
return a + b;
}
}
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/MultiplierEnum.java
package CustomProjectMaven;
/**
* Created by arielxin on 5/18/17.
*/
public enum MultiplierEnum {
DOUBLE(2.0),
TRIPLE(3.0);
private final double multiplier;
// check constructor?
MultiplierEnum(double multiplier) {
this.multiplier = multiplier;
}
Double applyMultiplier(Double value) {
return multiplier * value;
}
}
<file_sep>/Custom_Project_Test_Result/Clover/CustomProjectMaven/Collection.js
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":33,"id":30,"methods":[{"el":16,"sc":5,"sl":14},{"el":32,"sc":5,"sl":18}],"name":"Collection","sl":11}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {"test_14":{"methods":[{"sl":14}],"name":"multiplyThree","pass":true,"statements":[{"sl":15}]},"test_5":{"methods":[{"sl":18}],"name":"blockMap","pass":true,"statements":[{"sl":19},{"sl":20},{"sl":21},{"sl":22},{"sl":23},{"sl":24},{"sl":26},{"sl":27},{"sl":30}]}}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [14], [14], [], [], [5], [5], [5], [5], [5], [5], [5], [], [5], [5], [], [], [5], [], [], []]
<file_sep>/Apache_Project_Test_Result/IntelliJ_Test_Report/org.apache.commons.cli/.classes/CommandLineParser.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html id="htmlId">
<head>
<title>Coverage Report :: CommandLineParser</title>
<style type="text/css">
@import "../../.css/coverage.css";
</style>
</head>
<body>
<div class="header"></div>
<div class="content">
<div class="breadCrumbs">
[ <a href="../../index.html">all classes</a> ]
[ <a href="../index.html">org.apache.commons.cli</a> ]
</div>
<h1>Coverage Summary for Class: CommandLineParser (org.apache.commons.cli)</h1>
<table class="coverageStats">
<tr>
<th class="name">Class</th>
</tr>
<tr>
<td class="name">CommandLineParser</td>
</tr>
</table>
<br/>
<br/>
<div class="sourceCode"><i>1</i> /**
<i>2</i> * Licensed to the Apache Software Foundation (ASF) under one or more
<i>3</i> * contributor license agreements. See the NOTICE file distributed with
<i>4</i> * this work for additional information regarding copyright ownership.
<i>5</i> * The ASF licenses this file to You under the Apache License, Version 2.0
<i>6</i> * (the "License"); you may not use this file except in compliance with
<i>7</i> * the License. You may obtain a copy of the License at
<i>8</i> *
<i>9</i> * http://www.apache.org/licenses/LICENSE-2.0
<i>10</i> *
<i>11</i> * Unless required by applicable law or agreed to in writing, software
<i>12</i> * distributed under the License is distributed on an "AS IS" BASIS,
<i>13</i> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<i>14</i> * See the License for the specific language governing permissions and
<i>15</i> * limitations under the License.
<i>16</i> */
<i>17</i>
<i>18</i> package org.apache.commons.cli;
<i>19</i>
<i>20</i> /**
<i>21</i> * A class that implements the <code>CommandLineParser</code> interface
<i>22</i> * can parse a String array according to the {@link Options} specified
<i>23</i> * and return a {@link CommandLine}.
<i>24</i> *
<i>25</i> * @version $Id: CommandLineParser.java 1443102 2013-02-06 18:12:16Z tn $
<i>26</i> */
<i>27</i> public interface CommandLineParser
<i>28</i> {
<i>29</i> /**
<i>30</i> * Parse the arguments according to the specified options.
<i>31</i> *
<i>32</i> * @param options the specified Options
<i>33</i> * @param arguments the command line arguments
<i>34</i> * @return the list of atomic option and value tokens
<i>35</i> *
<i>36</i> * @throws ParseException if there are any problems encountered
<i>37</i> * while parsing the command line tokens.
<i>38</i> */
<i>39</i> CommandLine parse(Options options, String[] arguments) throws ParseException;
<i>40</i>
<i>41</i> /**
<i>42</i> * Parse the arguments according to the specified options and
<i>43</i> * properties.
<i>44</i> *
<i>45</i> * @param options the specified Options
<i>46</i> * @param arguments the command line arguments
<i>47</i> * @param properties command line option name-value pairs
<i>48</i> * @return the list of atomic option and value tokens
<i>49</i> *
<i>50</i> * @throws ParseException if there are any problems encountered
<i>51</i> * while parsing the command line tokens.
<i>52</i> */
<i>53</i> /* To maintain binary compatibility, this is commented out.
<i>54</i> It is still in the abstract Parser class, so most users will
<i>55</i> still reap the benefit.
<i>56</i> CommandLine parse(Options options, String[] arguments, Properties properties)
<i>57</i> throws ParseException;
<i>58</i> */
<i>59</i>
<i>60</i> /**
<i>61</i> * Parse the arguments according to the specified options.
<i>62</i> *
<i>63</i> * @param options the specified Options
<i>64</i> * @param arguments the command line arguments
<i>65</i> * @param stopAtNonOption if <tt>true</tt> an unrecognized argument stops
<i>66</i> * the parsing and the remaining arguments are added to the
<i>67</i> * {@link CommandLine}s args list. If <tt>false</tt> an unrecognized
<i>68</i> * argument triggers a ParseException.
<i>69</i> *
<i>70</i> * @return the list of atomic option and value tokens
<i>71</i> * @throws ParseException if there are any problems encountered
<i>72</i> * while parsing the command line tokens.
<i>73</i> */
<i>74</i> CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException;
<i>75</i>
<i>76</i> /**
<i>77</i> * Parse the arguments according to the specified options and
<i>78</i> * properties.
<i>79</i> *
<i>80</i> * @param options the specified Options
<i>81</i> * @param arguments the command line arguments
<i>82</i> * @param properties command line option name-value pairs
<i>83</i> * @param stopAtNonOption if <tt>true</tt> an unrecognized argument stops
<i>84</i> * the parsing and the remaining arguments are added to the
<i>85</i> * {@link CommandLine}s args list. If <tt>false</tt> an unrecognized
<i>86</i> * argument triggers a ParseException.
<i>87</i> *
<i>88</i> * @return the list of atomic option and value tokens
<i>89</i> * @throws ParseException if there are any problems encountered
<i>90</i> * while parsing the command line tokens.
<i>91</i> */
<i>92</i> /* To maintain binary compatibility, this is commented out.
<i>93</i> It is still in the abstract Parser class, so most users will
<i>94</i> still reap the benefit.
<i>95</i> CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption)
<i>96</i> throws ParseException;
<i>97</i> */
<i>98</i> }
</div>
</div>
<div class="footer">
<div style="float:right;">generated on 2017-05-18 21:41</div>
</div>
</body>
</html>
<file_sep>/Apache_Project_Test_Result/Clover_Test_Result/treemap-json.js
var treeMapJson = {"id":"Clover database Thu May 18 2017 16:41:36 PDT0","name":"","data":{
"$area":1730.0,"$color":96.01156,"title":
" 1730 Elements, 96% Coverage"},"children":[{"id":
"org.apache.commons.cli0","name":"org.apache.commons.cli","data":{
"$area":1730.0,"$color":96.01156,"title":
"org.apache.commons.cli 1730 Elements, 96% Coverage"},"children":[{
"id":"AlreadySelectedException0","name":
"AlreadySelectedException","data":{"$area":10.0,"$color":100.0,
"path":
"org/apache/commons/cli/AlreadySelectedException.html#AlreadySelectedException",
"title":"AlreadySelectedException 10 Elements, 100% Coverage"},
"children":[]},{"id":"AmbiguousOptionException10","name":
"AmbiguousOptionException","data":{"$area":22.0,"$color":100.0,
"path":
"org/apache/commons/cli/AmbiguousOptionException.html#AmbiguousOptionException",
"title":"AmbiguousOptionException 22 Elements, 100% Coverage"},
"children":[]},{"id":"BasicParser32","name":"BasicParser","data":{
"$area":2.0,"$color":100.0,"path":
"org/apache/commons/cli/BasicParser.html#BasicParser","title":
"BasicParser 2 Elements, 100% Coverage"},"children":[]},{"id":
"CommandLine34","name":"CommandLine","data":{"$area":90.0,"$color":
100.0,"path":
"org/apache/commons/cli/CommandLine.html#CommandLine","title":
"CommandLine 90 Elements, 100% Coverage"},"children":[]},{"id":
"CommandLine.Builder124","name":"CommandLine.Builder","data":{
"$area":8.0,"$color":100.0,"path":
"org/apache/commons/cli/CommandLine.html#CommandLine.Builder",
"title":"CommandLine.Builder 8 Elements, 100% Coverage"},
"children":[]},{"id":"CommandLineParser132","name":
"CommandLineParser","data":{"$area":0.0,"$color":-100.0,"path":
"org/apache/commons/cli/CommandLineParser.html#CommandLineParser",
"title":"CommandLineParser 0 Elements, - Coverage"},"children":
[]},{"id":"DefaultParser132","name":"DefaultParser","data":{
"$area":300.0,"$color":98.0,"path":
"org/apache/commons/cli/DefaultParser.html#DefaultParser",
"title":"DefaultParser 300 Elements, 98% Coverage"},"children":[]},
{"id":"GnuParser432","name":"GnuParser","data":{"$area":45.0,
"$color":100.0,"path":
"org/apache/commons/cli/GnuParser.html#GnuParser","title":
"GnuParser 45 Elements, 100% Coverage"},"children":[]},{"id":
"HelpFormatter477","name":"HelpFormatter","data":{"$area":308.0,
"$color":94.80519,"path":
"org/apache/commons/cli/HelpFormatter.html#HelpFormatter",
"title":"HelpFormatter 308 Elements, 94.8% Coverage"},"children":
[]},{"id":"HelpFormatter.OptionComparator785","name":
"HelpFormatter.OptionComparator","data":{"$area":2.0,"$color":
100.0,"path":
"org/apache/commons/cli/HelpFormatter.html#HelpFormatter.OptionComparator",
"title":
"HelpFormatter.OptionComparator 2 Elements, 100% Coverage"},
"children":[]},{"id":"MissingArgumentException787","name":
"MissingArgumentException","data":{"$area":7.0,"$color":100.0,
"path":
"org/apache/commons/cli/MissingArgumentException.html#MissingArgumentException",
"title":"MissingArgumentException 7 Elements, 100% Coverage"},
"children":[]},{"id":"MissingOptionException794","name":
"MissingOptionException","data":{"$area":23.0,"$color":100.0,
"path":
"org/apache/commons/cli/MissingOptionException.html#MissingOptionException",
"title":"MissingOptionException 23 Elements, 100% Coverage"},
"children":[]},{"id":"Option817","name":"Option","data":{"$area":
206.0,"$color":88.34952,"path":
"org/apache/commons/cli/Option.html#Option","title":
"Option 206 Elements, 88.3% Coverage"},"children":[]},{"id":
"Option.Builder1023","name":"Option.Builder","data":{"$area":
47.0,"$color":93.61702,"path":
"org/apache/commons/cli/Option.html#Option.Builder","title":
"Option.Builder 47 Elements, 93.6% Coverage"},"children":[]},{
"id":"OptionBuilder1070","name":"OptionBuilder","data":{"$area":
86.0,"$color":94.18604,"path":
"org/apache/commons/cli/OptionBuilder.html#OptionBuilder",
"title":"OptionBuilder 86 Elements, 94.2% Coverage"},"children":[]},
{"id":"OptionGroup1156","name":"OptionGroup","data":{"$area":50.0,
"$color":100.0,"path":
"org/apache/commons/cli/OptionGroup.html#OptionGroup","title":
"OptionGroup 50 Elements, 100% Coverage"},"children":[]},{"id":
"OptionValidator1206","name":"OptionValidator","data":{"$area":
22.0,"$color":100.0,"path":
"org/apache/commons/cli/OptionValidator.html#OptionValidator",
"title":"OptionValidator 22 Elements, 100% Coverage"},"children":
[]},{"id":"Options1228","name":"Options","data":{"$area":87.0,
"$color":90.804596,"path":
"org/apache/commons/cli/Options.html#Options","title":
"Options 87 Elements, 90.8% Coverage"},"children":[]},{"id":
"ParseException1315","name":"ParseException","data":{"$area":2.0,
"$color":100.0,"path":
"org/apache/commons/cli/ParseException.html#ParseException",
"title":"ParseException 2 Elements, 100% Coverage"},"children":[]},
{"id":"Parser1317","name":"Parser","data":{"$area":155.0,"$color":
97.41936,"path":"org/apache/commons/cli/Parser.html#Parser",
"title":"Parser 155 Elements, 97.4% Coverage"},"children":[]},{
"id":"PatternOptionBuilder1472","name":"PatternOptionBuilder",
"data":{"$area":55.0,"$color":98.18182,"path":
"org/apache/commons/cli/PatternOptionBuilder.html#PatternOptionBuilder",
"title":"PatternOptionBuilder 55 Elements, 98.2% Coverage"},
"children":[]},{"id":"PosixParser1527","name":"PosixParser","data":
{"$area":105.0,"$color":100.0,"path":
"org/apache/commons/cli/PosixParser.html#PosixParser","title":
"PosixParser 105 Elements, 100% Coverage"},"children":[]},{"id":
"TypeHandler1632","name":"TypeHandler","data":{"$area":70.0,
"$color":97.14286,"path":
"org/apache/commons/cli/TypeHandler.html#TypeHandler","title":
"TypeHandler 70 Elements, 97.1% Coverage"},"children":[]},{"id":
"UnrecognizedOptionException1702","name":
"UnrecognizedOptionException","data":{"$area":7.0,"$color":100.0,
"path":
"org/apache/commons/cli/UnrecognizedOptionException.html#UnrecognizedOptionException",
"title":
"UnrecognizedOptionException 7 Elements, 100% Coverage"},
"children":[]},{"id":"Util1709","name":"Util","data":{"$area":
21.0,"$color":100.0,"path":
"org/apache/commons/cli/Util.html#Util","title":
"Util 21 Elements, 100% Coverage"},"children":[]}]}]}
;
processTreeMapJson (treeMapJson);<file_sep>/CustomProjectMaven/src/test/java/CustomProjectMaven/PathCoverageTest.java
package CustomProjectMaven;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by arielxin on 5/18/17.
*/
public class PathCoverageTest {
@Test
// [Tricky]: gives 100% test coverage, but doesn't checked all path
public void pathCheckerTest() {
Boolean result1 = new PathCoverage().fourPaths(true, true);
Boolean result2 = new PathCoverage().fourPaths(false, false);
assertEquals(true, result1);
assertEquals(false, result2);
}
}<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/GenericTypeClass.java
package CustomProjectMaven;
/**
* Created by liyuanqi on 5/18/17.
*/
public class GenericTypeClass<T> {
public String concatString(T a, T b){
return a.toString() + b.toString();
}
}
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/StaticInnerClass.java
package CustomProjectMaven;
/**
* Created by liyuanqi on 5/18/17.
*/
public class StaticInnerClass {
public static int staticNestedClassAdd(int a, int b){
InnerStaticNested nested = new InnerStaticNested();
return nested.add(1,1);
}
//static nested class in java
private static class InnerStaticNested {
public int add(int a, int b){
return a+b;
}
}
}
<file_sep>/Apache_Project_Test_Result/JMockit_Test/org/apache/commons/cli/PatternOptionBuilder.html
<!DOCTYPE html>
<html>
<head>
<title>PatternOptionBuilder.java</title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<link rel='stylesheet' type='text/css' href='../../../../coverage.css'/>
<link rel='shortcut icon' type='image/png' href='../../../../logo.png'/>
<script type='text/javascript' src='../../../../coverage.js'></script>
<script type='text/javascript' src='../../../../prettify.js'></script>
</head>
<body onload='prettyPrint()'>
<table cellpadding='0' cellspacing='1'>
<caption>commons-cli-1.4-src/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java</caption>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div>/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</div><span>/*...*/</span></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>18</td><td> </td>
<td><pre class='prettyprint'>package org.apache.commons.cli;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td><pre class='imports prettyprint' onclick='showHideLines(this)'><div>import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Date;
</div><span>import ...</span></pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div>/**
* <p>Allows Options to be created from a single String.
* The pattern contains various single character flags and via
* an optional punctuation character, their expected type.
* </p>
*
* <table border="1">
* <caption>Overview of PatternOptionBuilder patterns</caption>
* <tr><td>a</td><td>-a flag</td></tr>
* <tr><td>b@</td><td>-b [classname]</td></tr>
* <tr><td>c></td><td>-c [filename]</td></tr>
* <tr><td>d+</td><td>-d [classname] (creates object via empty constructor)</td></tr>
* <tr><td>e%</td><td>-e [number] (creates Double/Long instance depending on existing of a '.')</td></tr>
* <tr><td>f/</td><td>-f [url]</td></tr>
* <tr><td>g:</td><td>-g [string]</td></tr>
* </table>
*
* <p>
* For example, the following allows command line flags of '-v -p string-value -f /dir/file'.
* The exclamation mark precede a mandatory option.
* </p>
*
* <pre>
* Options options = PatternOptionBuilder.parsePattern("vp:!f/");
* </pre>
*
* <p>
* TODO: These need to break out to OptionType and also to be pluggable.
* </p>
*
* @version $Id: PatternOptionBuilder.java 1677406 2015-05-03 14:27:31Z britter $
*/</div><span>/*...*/</span></td>
</tr>
<tr>
<td class='line'>57</td><td class='count'>0</td>
<td><pre class='prettyprint uncovered' id='l57s0'>public class PatternOptionBuilder</pre></td>
</tr>
<tr>
<td class='line'>58</td><td> </td>
<td><pre class='prettyprint'>{</pre></td>
</tr>
<tr>
<td class='line'>59</td><td> </td>
<td><pre class='comment'> /** String class */</pre></td>
</tr>
<tr>
<td class='line'>60</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l60s0'> public static final Class<String> STRING_VALUE = String.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>62</td><td> </td>
<td><pre class='comment'> /** Object class */</pre></td>
</tr>
<tr>
<td class='line'>63</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l63s0'> public static final Class<Object> OBJECT_VALUE = Object.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>65</td><td> </td>
<td><pre class='comment'> /** Number class */</pre></td>
</tr>
<tr>
<td class='line'>66</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l66s0'> public static final Class<Number> NUMBER_VALUE = Number.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>68</td><td> </td>
<td><pre class='comment'> /** Date class */</pre></td>
</tr>
<tr>
<td class='line'>69</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l69s0'> public static final Class<Date> DATE_VALUE = Date.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>71</td><td> </td>
<td><pre class='comment'> /** Class class */</pre></td>
</tr>
<tr>
<td class='line'>72</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l72s0'> public static final Class<?> CLASS_VALUE = Class.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>74</td><td> </td>
<td><pre class='comment'> /// can we do this one??</pre></td>
</tr>
<tr>
<td class='line'>75</td><td> </td>
<td><pre class='comment'> // is meant to check that the file exists, else it errors.</pre></td>
</tr>
<tr>
<td class='line'>76</td><td> </td>
<td><pre class='comment'> // ie) it's for reading not writing.</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>78</td><td> </td>
<td><pre class='comment'> /** FileInputStream class */</pre></td>
</tr>
<tr>
<td class='line'>79</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l79s0'> public static final Class<FileInputStream> EXISTING_FILE_VALUE = FileInputStream.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>81</td><td> </td>
<td><pre class='comment'> /** File class */</pre></td>
</tr>
<tr>
<td class='line'>82</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l82s0'> public static final Class<File> FILE_VALUE = File.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>84</td><td> </td>
<td><pre class='comment'> /** File array class */</pre></td>
</tr>
<tr>
<td class='line'>85</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l85s0'> public static final Class<File[]> FILES_VALUE = File[].class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>87</td><td> </td>
<td><pre class='comment'> /** URL class */</pre></td>
</tr>
<tr>
<td class='line'>88</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l88s0'> public static final Class<URL> URL_VALUE = URL.class;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Retrieve the class that <code>ch</code> represents.
*
* @param ch the specified character
* @return The class that <code>ch</code> represents
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>96</td><td> </td>
<td><pre class='prettyprint'> public static Object getValueClass(char ch)</pre></td>
</tr>
<tr>
<td class='line'>97</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>98</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l98s0'> switch (ch)</pre></td>
</tr>
<tr>
<td class='line'>99</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>100</td><td> </td>
<td><pre class='prettyprint'> case '@':</pre></td>
</tr>
<tr>
<td class='line'>101</td><td class='count'>4</td>
<td><pre class='prettyprint covered' id='l101s0'> return PatternOptionBuilder.OBJECT_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>102</td><td> </td>
<td><pre class='prettyprint'> case ':':</pre></td>
</tr>
<tr>
<td class='line'>103</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l103s0'> return PatternOptionBuilder.STRING_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>104</td><td> </td>
<td><pre class='prettyprint'> case '%':</pre></td>
</tr>
<tr>
<td class='line'>105</td><td class='count'>6</td>
<td><pre class='prettyprint covered' id='l105s0'> return PatternOptionBuilder.NUMBER_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>106</td><td> </td>
<td><pre class='prettyprint'> case '+':</pre></td>
</tr>
<tr>
<td class='line'>107</td><td class='count'>3</td>
<td><pre class='prettyprint covered' id='l107s0'> return PatternOptionBuilder.CLASS_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>108</td><td> </td>
<td><pre class='prettyprint'> case '#':</pre></td>
</tr>
<tr>
<td class='line'>109</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l109s0'> return PatternOptionBuilder.DATE_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>110</td><td> </td>
<td><pre class='prettyprint'> case '<':</pre></td>
</tr>
<tr>
<td class='line'>111</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l111s0'> return PatternOptionBuilder.EXISTING_FILE_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>112</td><td> </td>
<td><pre class='prettyprint'> case '>':</pre></td>
</tr>
<tr>
<td class='line'>113</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l113s0'> return PatternOptionBuilder.FILE_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>114</td><td> </td>
<td><pre class='prettyprint'> case '*':</pre></td>
</tr>
<tr>
<td class='line'>115</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l115s0'> return PatternOptionBuilder.FILES_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>116</td><td> </td>
<td><pre class='prettyprint'> case '/':</pre></td>
</tr>
<tr>
<td class='line'>117</td><td class='count'>3</td>
<td><pre class='prettyprint covered' id='l117s0'> return PatternOptionBuilder.URL_VALUE;</pre></td>
</tr>
<tr>
<td class='line'>118</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>120</td><td class='count'>0</td>
<td><pre class='prettyprint uncovered' id='l120s0'> return null;</pre></td>
</tr>
<tr>
<td class='line'>121</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Returns whether <code>ch</code> is a value code, i.e.
* whether it represents a class in a pattern.
*
* @param ch the specified character
* @return true if <code>ch</code> is a value code, otherwise false.
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>130</td><td> </td>
<td><pre class='prettyprint'> public static boolean isValueCode(char ch)</pre></td>
</tr>
<tr>
<td class='line'>131</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>132</td><td class='count'>48</td>
<td><pre class='prettyprint jmp'> <span id='l132s0' title='Executions: 48' class='covered'>return ch == '@'</span></pre></td>
</tr>
<tr>
<td class='line'>133</td><td> </td>
<td><pre class='prettyprint'> || ch == ':'</pre></td>
</tr>
<tr>
<td class='line'>134</td><td> </td>
<td><pre class='prettyprint'> || ch == '%'</pre></td>
</tr>
<tr>
<td class='line'>135</td><td> </td>
<td><pre class='prettyprint'> || ch == '+'</pre></td>
</tr>
<tr>
<td class='line'>136</td><td> </td>
<td><pre class='prettyprint'> || ch == '#'</pre></td>
</tr>
<tr>
<td class='line'>137</td><td> </td>
<td><pre class='prettyprint'> || ch == '<'</pre></td>
</tr>
<tr>
<td class='line'>138</td><td> </td>
<td><pre class='prettyprint'> || ch == '>'</pre></td>
</tr>
<tr>
<td class='line'>139</td><td> </td>
<td><pre class='prettyprint'> || ch == '*'</pre></td>
</tr>
<tr>
<td class='line'>140</td><td> </td>
<td><pre class='prettyprint'> || ch == '/'</pre></td>
</tr>
<tr>
<td class='line'>141</td><td> </td>
<td><pre class='prettyprint'> || ch == '!';</pre></td>
</tr>
<tr>
<td class='line'>142</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'></td><td> </td>
<td class='comment' onclick='showHideLines(this)'><div> /**
* Returns the {@link Options} instance represented by <code>pattern</code>.
*
* @param pattern the pattern string
* @return The {@link Options} instance
*/</div><span> /*...*/</span></td>
</tr>
<tr>
<td class='line'>150</td><td> </td>
<td><pre class='prettyprint'> public static Options parsePattern(String pattern)</pre></td>
</tr>
<tr>
<td class='line'>151</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>152</td><td class='count'>9</td>
<td><pre class='prettyprint covered' id='l152s0'> char opt = ' ';</pre></td>
</tr>
<tr>
<td class='line'>153</td><td class='count'>9</td>
<td><pre class='prettyprint covered' id='l153s0'> boolean required = false;</pre></td>
</tr>
<tr>
<td class='line'>154</td><td class='count'>9</td>
<td><pre class='prettyprint covered' id='l154s0'> Class<?> type = null;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>156</td><td class='count'>9</td>
<td><pre class='prettyprint covered' id='l156s0'> Options options = new Options();</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>158</td><td class='count'>57</td>
<td><pre class='prettyprint jmp'> <span id='l158s0' title='Executions: 57' class='covered'>for (int i = 0</span>; i < pattern.length(); i++)</pre></td>
</tr>
<tr>
<td class='line'>159</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>160</td><td class='count'>48</td>
<td><pre class='prettyprint covered' id='l160s0'> char ch = pattern.charAt(i);</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>162</td><td> </td>
<td><pre class='comment'> // a value code comes after an option and specifies</pre></td>
</tr>
<tr>
<td class='line'>163</td><td> </td>
<td><pre class='comment'> // details about it</pre></td>
</tr>
<tr>
<td class='line'>164</td><td class='count'>48</td>
<td><pre class='prettyprint jmp'> <span id='l164s0' title='Executions: 48' class='covered'>if (!isValueCode(ch))</span></pre></td>
</tr>
<tr>
<td class='line'>165</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>166</td><td class='count'>26</td>
<td><pre class='prettyprint jmp'> <span id='l166s0' title='Executions: 26' class='covered'>if (opt != ' ')</span></pre></td>
</tr>
<tr>
<td class='line'>167</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>168</td><td class='count'>18</td>
<td><pre class='prettyprint jmp'> <span id='l168s0' title='Executions: 18' class='covered'>final Option option = Option.builder(String.valueOf(opt))</span></pre></td>
</tr>
<tr>
<td class='line'>169</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l169s0'> .hasArg(type != null)</pre></td>
</tr>
<tr>
<td class='line'>170</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l170s0'> .required(required)</pre></td>
</tr>
<tr>
<td class='line'>171</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l171s0'> .type(type)</pre></td>
</tr>
<tr>
<td class='line'>172</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l172s0'> .build();</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>174</td><td> </td>
<td><pre class='comment'> // we have a previous one to deal with</pre></td>
</tr>
<tr>
<td class='line'>175</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l175s0'> options.addOption(option);</pre></td>
</tr>
<tr>
<td class='line'>176</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l176s0'> required = false;</pre></td>
</tr>
<tr>
<td class='line'>177</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l177s0'> type = null;</pre></td>
</tr>
<tr>
<td class='line'>178</td><td class='count'>18</td>
<td><pre class='prettyprint covered' id='l178s0'> opt = ' ';</pre></td>
</tr>
<tr>
<td class='line'>179</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>181</td><td class='count'>26</td>
<td><pre class='prettyprint covered' id='l181s0'> opt = ch;</pre></td>
</tr>
<tr>
<td class='line'>182</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr>
<td class='line'>183</td><td class='count'>22</td>
<td><pre class='prettyprint jmp'> else <span id='l183s0' title='Executions: 22' class='covered'>if (ch == '!')</span></pre></td>
</tr>
<tr>
<td class='line'>184</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>185</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l185s0'> required = true;</pre></td>
</tr>
<tr>
<td class='line'>186</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr>
<td class='line'>187</td><td> </td>
<td><pre class='prettyprint'> else</pre></td>
</tr>
<tr>
<td class='line'>188</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>189</td><td class='count'>21</td>
<td><pre class='prettyprint covered' id='l189s0'> type = (Class<?>) getValueClass(ch);</pre></td>
</tr>
<tr>
<td class='line'>190</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr>
<td class='line'>191</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>193</td><td class='count'>9</td>
<td><pre class='prettyprint jmp'> <span id='l193s0' title='Executions: 9' class='covered'>if (opt != ' ')</span></pre></td>
</tr>
<tr>
<td class='line'>194</td><td> </td>
<td><pre class='prettyprint'> {</pre></td>
</tr>
<tr>
<td class='line'>195</td><td class='count'>8</td>
<td><pre class='prettyprint jmp'> <span id='l195s0' title='Executions: 8' class='covered'>final Option option = Option.builder(String.valueOf(opt))</span></pre></td>
</tr>
<tr>
<td class='line'>196</td><td class='count'>8</td>
<td><pre class='prettyprint covered' id='l196s0'> .hasArg(type != null)</pre></td>
</tr>
<tr>
<td class='line'>197</td><td class='count'>8</td>
<td><pre class='prettyprint covered' id='l197s0'> .required(required)</pre></td>
</tr>
<tr>
<td class='line'>198</td><td class='count'>8</td>
<td><pre class='prettyprint covered' id='l198s0'> .type(type)</pre></td>
</tr>
<tr>
<td class='line'>199</td><td class='count'>8</td>
<td><pre class='prettyprint covered' id='l199s0'> .build();</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>201</td><td> </td>
<td><pre class='comment'> // we have a final one to deal with</pre></td>
</tr>
<tr>
<td class='line'>202</td><td class='count'>8</td>
<td><pre class='prettyprint covered' id='l202s0'> options.addOption(option);</pre></td>
</tr>
<tr>
<td class='line'>203</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>205</td><td class='count'>9</td>
<td><pre class='prettyprint covered' id='l205s0'> return options;</pre></td>
</tr>
<tr>
<td class='line'>206</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr>
<td class='line'>207</td><td> </td>
<td><pre class='prettyprint'>}</pre></td>
</tr>
</table>
</body>
</html>
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/SimpleAdditionInterface.java
package CustomProjectMaven;
/**
* Created by liyuanqi on 5/18/17.
*/
public interface SimpleAdditionInterface {
int interfaceAdd(int a, int b);
}
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/Simple.java
package CustomProjectMaven;
/**
* Created by liyuanqi on 5/18/17.
*/
public class Simple {
public int divide(int a, int b) {
return a/b;
}
public void stopAtN(int n){
for(int i=0; i<n; i++){
if(i == 0)
break;
System.out.println("This line will not execute");
}
}
}
<file_sep>/CustomProjectMaven/src/test/java/CustomProjectMaven/SimpleTest.java
package CustomProjectMaven;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by liyuanqi on 5/18/17.
*/
public class SimpleTest {
@Test
// divide 0 exception doesn't get checked
public void divideTest() {
int result = new Simple().divide(5, 2);
assertEquals(2, result);
}
@Test
// check if the coverage of "break" gets checked
public void loopTermConditionTest() {
new Simple().stopAtN(7);
}
}<file_sep>/README.md
# TestCoverage
CS 230 Project: Evaluation of Test Coverage Tools
### Team Member
- <NAME>, <EMAIL>
- <NAME>, <EMAIL>
- <NAME>, <EMAIL>
- <NAME>, <EMAIL>
- <NAME>, <EMAIL>
- <NAME>, <EMAIL>
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/Collection.java
package CustomProjectMaven;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by <NAME> on 5/18/17.
*/
public class Collection {
// test lamda expression.
public List<Integer> multiplyThree(ArrayList<Integer> input_list){
return input_list.stream().map(i -> i*3).collect(Collectors.toList());
}
public List<Integer> blockMap(ArrayList<Integer> input_list){
return input_list.stream().map(i -> {
Integer magicNumber = 0;
Integer anotherMagicNumber = 0;
if(i < 2){
magicNumber = 42;
anotherMagicNumber = 998;
}else{
magicNumber = 1;
anotherMagicNumber = 1;
}
return i*magicNumber+anotherMagicNumber;
}).collect(Collectors.toList());
}
}
<file_sep>/Apache_Project_Test_Result/Clover_Test_Result/org/apache/commons/cli/UtilTest.js
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":45,"id":3262,"methods":[{"el":34,"sc":5,"sl":27},{"el":44,"sc":5,"sl":36}],"name":"UtilTest","sl":25}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {"test_111":{"methods":[{"sl":36}],"name":"testStripLeadingAndTrailingQuotes","pass":true,"statements":[{"sl":39},{"sl":40},{"sl":41},{"sl":42},{"sl":43}]},"test_130":{"methods":[{"sl":27}],"name":"testStripLeadingHyphens","pass":true,"statements":[{"sl":30},{"sl":31},{"sl":32},{"sl":33}]}}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [130], [], [], [130], [130], [130], [130], [], [], [111], [], [], [111], [111], [111], [111], [111], [], []]
<file_sep>/CustomProjectMaven/src/main/java/CustomProjectMaven/PathCoverage.java
package CustomProjectMaven;
/**
* Created by arielxin on 5/18/17.
*/
public class PathCoverage {
public Boolean fourPaths (boolean A, boolean B){
Boolean result = false;
if(A){
result = true;
} else {
result = false;
}
if(B) {
result = true;
} else {
result = false;
}
return result;
}
}
<file_sep>/Apache_Project_Test_Result/Clover_Test_Result/org/apache/commons/cli/bug/BugCLI18Test.js
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":46,"id":3553,"methods":[{"el":45,"sc":5,"sl":33}],"name":"BugCLI18Test","sl":31}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {"test_80":{"methods":[{"sl":33}],"name":"testCLI18","pass":true,"statements":[{"sl":36},{"sl":37},{"sl":38},{"sl":39},{"sl":41},{"sl":42},{"sl":44}]}}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [80], [], [], [80], [80], [80], [80], [], [80], [80], [], [80], [], []]
<file_sep>/Apache_Project_Test_Result/Clover_Test_Result/treemap-dash-json.js
var treeMapJson = {"id":"Clover database Thu May 18 2017 16:41:36 PDT0","name":"","data":{
"$area":1730.0,"$color":96.01156,"title":
" 1730 Elements, 96% Coverage"},"children":[{"id":
"org.apache.commons.cli0","name":"org.apache.commons.cli","data":{
"$area":1730.0,"$color":96.01156,"title":
"org.apache.commons.cli 1730 Elements, 96% Coverage"},"children":[]}]}
;
processTreeMapDashJson (treeMapJson); | 09a3b30ad8e06d5533ce796fd8bde2bfbfb83ed7 | [
"HTML",
"JavaScript",
"Markdown",
"Java",
"Ant Build System"
] | 31 | JavaScript | liuhou/TestCoverage | df93e87ca47b443499a1cf46aacc346e9004cfef | 1dd2e62bbedd2e50f3a1cb09ff2ca33cf5b0ee96 |
refs/heads/master | <file_sep>import React, { useState, useEffect } from 'react';
import { View, Text, Button, TouchableOpacity } from "react-native";
import * as Location from 'expo-location';
const HomePage = ({ navigation }) => {
const [currLocation, setCurrLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
let location = await Location.getCurrentPositionAsync();
setCurrLocation(location);
})();
}, []);
let text = 'Waiting..';
if(errorMsg) {
text = errorMsg
} else if (currLocation) {
text = JSON.stringify(currLocation);
}
return (
<View>
<TouchableOpacity>
<Text>Where am I?</Text>
<Text>{text}</Text>
</TouchableOpacity>
<Button
title="Go to Jane's profile"
onPress={() =>
navigation.navigate('Profile', { name: 'Jane' })
}
/>
<Button
title="Go to Jane's video feed"
onPress={() =>
navigation.navigate('Video', { name: 'Jane' })
}
/>
<Button
title="Go to the map"
onPress={() =>
navigation.navigate('Map', { name: 'Jane' })
}
/>
</View>
);
};
export default HomePage;<file_sep>import 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomePage from './components/HomePage/HomePage';
import ProfileScreen from './components/ProfileScreen/ProfileScreen';
import MapPage from './components/MapPage/MapPage';
import VideoFeed from './components/VideoFeed/VideoFeed';
import { useState } from 'react';
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomePage}
options={{ title: 'Welcome' }}
/>
<Stack.Screen
name="Profile"
component={ProfileScreen}
/>
<Stack.Screen
name="Map"
component={MapPage}
/>
<Stack.Screen
name="Video"
component={VideoFeed}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
}); | 6c21ada555d25584ecf764259eee455eb466a6fc | [
"JavaScript"
] | 2 | JavaScript | EP36/poppin | 794d4f7334be22de5cb5bd2ce8f3d727a3ca0967 | 7b8a78c742566585a618b4aeb3ba6070d9d15e9c |
refs/heads/master | <file_sep>import { Pipe, PipeTransform } from '@angular/core';
import { filter } from 'rxjs/operators';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
// transform(value: any, filterString: string, propName:string): any {
// //console.log(value.length);//12
// if(value.length===0||filterString===""){// sometimes value代表的数组或者obj没有长度这个属性
// return value;
// }
// const resultArray=[];
// for(let item of value){
// if(item[propName]===filterString){
// resultArray.push(item);
// }
// }
// return resultArray;
// }
transform(value:any, filterString:string, keyword:string): any{
if(!filterString||!keyword){
return value;
}
return value.filter(item=>{
let filterStringValue=item[filterString];
//item 是所有集合的元素,就是value中的props,
// filterString会被定义为根据x属性过滤信息,把过滤后的值传给value
return filterStringValue.indexOf(keyword) >=0; //if yes, return true.
})
}
}
<file_sep>const express= require ('express')
const PostController= require('../controller/posts')
const router= express.Router();
router.get()<file_sep>import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FlightService } from './flight.service';
import { FlightInfo } from './flightInfo.model';
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
import {switchMap, debounceTime, tap, finalize} from 'rxjs/operators';
import "rxjs/Rx";
import { FlightInfoClass } from './flightInfo.class';
import { IfStmt } from '@angular/compiler';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
private keyword: string;
private titleFilter: FormControl=new FormControl(); //use in html, bind data with [FormControl]
constructor(private http:HttpClient, private flightService:FlightService, private fb: FormBuilder){
// this.titleFilter.valueChanges
// .debounceTime(500) //no trigger input value when user is type, after finished, it trigger. import'rxjs/Rx'
// .subscribe(value=>{this.keyword=value});// titleFilter.valueChanges这个字段流,订阅它,传给keyword
}
title = 'flightSrch';
filterStatus='';
// flightInfo: FlightInfo;//FlightInfo[] is wrong???
// error: Error; //??????
// ngOnInit(){
// this.flightService.getFlightInfo()
// .subscribe((data:FlightInfo)=> {this.flightInfo = data;},
// error=>this.error=error
// );
// // console.log(this.flightInfo);
// }
// //full response
// showFlightInfoResponse(){
// this.flightService.getFlightInfoResponse()//HttpResponse<FlightInfos>
// .subscribe(resp=>{
// //display headers
// const keys=resp.headers.keys();
// this.headers=keys.map(key=>`${key}:${resp.headers.get(key)}`);
// //access the body , type as flightInfo
// this.flightInfo={...resp.body};
// });
// }
filteredFlight:FlightInfoClass[]=[];
flightForm:FormGroup;
isLoading=false;
ngOnInit(){
// this.filteredFlight=this.fb.group({ // must has length!
// userInput:null
// })
console.log(this.flightForm);
this.flightForm.get('userInput').valueChanges
.pipe(
debounceTime(500),
tap(() => this.isLoading = true),
switchMap(value => this.flightService.search({carrier: value}, 1)
.pipe(
finalize(() => this.isLoading = false),
)
)
)
.subscribe(users => {this.filteredFlight = users.result;console.log(this.filteredFlight)});
}
displaySearch(item:FlightInfoClass){
if(item){
console.log("display-search");
return item.carrier;
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import {HttpClient, HttpResponse, HttpErrorResponse} from '@angular/common/http';
import { FlightInfo } from './flightInfo.model';
import { FlightInfoClass, FlightInfoClassResp } from './flightInfo.class';
import {Observable, throwError} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {catchError} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class FlightService {
constructor(private http: HttpClient) { }
flightInfoUrl='../assets/flight-info.json';
// getFlightInfo(){ //return an observable of FlightInfo
// return this.http.get<FlightInfo>(this.flightInfoUrl)
// .pipe(
// catchError(this.handleError)
// ); //pipe this Observable through to the error handler
// }
// private handleError(error:HttpErrorResponse){
// if(error.error instanceof ErrorEvent){
// console.error('an error occurred:', error.error.message)
// }//this above is 2nd type error: client-side or network errors
// else{
// console.error(
// `Backend returned code ${error.status}`+
// `body was: ${error.error}`);
// }// server reject req, return HTTP resp with 404 or 500
// return throwError(
// 'Sth bad happened; Tray again!'
// )
// }
// //return a full resp
// getFlightInfoResponse():Observable<HttpResponse<FlightInfo>>{
// return this.http.get<FlightInfo>(this.flightInfoUrl,{observer:'response'});
// }// .get returns an observable
search(filter:{carrier:string}={carrier:''},page=1):
Observable<FlightInfoClassResp>{
return this.http.get<FlightInfoClassResp>(this.flightInfoUrl)
.pipe(
tap((response:FlightInfoClassResp)=>{
response.result=response.result
.map<FlightInfoClass>(flightInfoClass => new FlightInfoClass(flightInfoClass.flightNumber,flightInfoClass.carrier))
.filter(flightInfoClass=>flightInfoClass.carrier.includes(filter.carrier))
return response;
})
);
}
}
<file_sep>export class FlightInfoClass {
constructor(public flightNumber: number , public carrier: string){}
}
export interface FlightInfoClassResp {
result: FlightInfoClass[];
} | 37b3ab1653dc0a26fb9b6d970169e437e7a75189 | [
"JavaScript",
"TypeScript"
] | 5 | TypeScript | nding120/flightSearch | c23ba212effc2484d2f438953c435d0ceadd85c6 | 3eef885fc97dc0856bb56f66124418b286f23548 |
refs/heads/master | <repo_name>luuckyfree/Intro2Graphics2<file_sep>/README.md
Intro2Graphics2
===============
<NAME>
<file_sep>/Assignment2 - Slot Machine/SlotMachine_1_3.py
# Source File Name: slotmachine.py
# Author's Name: <NAME>
# Last Modified By: <NAME>
# Date Last Modified: Tuesday May 23, 2013
"""
Program Description: This program simulates a Casino-Style Slot Machine. It provides an GUI
for the user that is an image of a slot machine with Label and Button objects
created through the tkinter module
Version: 0.1 - * Created Back end functions for the slot machine program Reels, pullthehandle, and
is_number (a validation function).
* Text output provides debugging information to check if the Slot Machine program does
what it's supposed to do.
* Used research from the internet to set the Reels function to simulate basic slot reels
"""
# import statements
import random
from Tkinter import *
class MyApp():
#define the attributes of the class
def __init__(self, parent):
self.myParent = parent
#creates a frame whose parent is root
self.myContainer1 = Frame(parent)
self.myContainer1.configure()
#pack the frame - show it on the screen
self.myContainer1.pack()
self.maxBet = 100
self.money = 10
self.labelReal1 = Label(self.myContainer1)
self.labelReal1.configure(text = "Reel One")
self.labelReal1.pack()
self.labelReal2 = Label(self.myContainer1)
self.labelReal2.configure(text = "Reel Two")
self.labelReal2.pack()
self.labelReal3 = Label(self.myContainer1)
self.labelReal3.configure(text = "Reel Three")
self.labelReal3.pack()
self.labelForMoney = Label(self.myContainer1)
self.labelForMoney.configure(text = "My Money: ")
self.labelForMoney.pack()
self.CurrentMoneys = 1000
self.labelMoneys = Label(self.myContainer1)
self.labelMoneys.configure(text = str(self.CurrentMoneys))
self.labelMoneys.pack()
self.labelForBet = Label(self.myContainer1)
self.labelForBet.configure(text = "My Bet: ")
self.labelForBet.pack()
self.label1 = Label(self.myContainer1)
self.label1.configure(text = self.money)
self.label1.pack()
#bet 10 button
self.button1 = Button(self.myContainer1)
self.button1.configure(text='10', background='green')
self.button1.pack(side=LEFT)
self.button1.bind("<Button-1>", self.button1Click)
'''self.myimage = PhotoImage(file="Desert.gif")'''
#bet 20 button
self.button2 = Button(self.myContainer1)
self.button2.configure(text='20')
'''i mage=self.myimage '''
self.button2.pack(side=LEFT)
self.button2.bind("<Button-1>", self.button2Click)
# bet 50 button
self.button3 = Button(self.myContainer1)
self.button3.configure(text = '50', background='green')
self.button3.pack(side=RIGHT)
self.button3.bind("<Button-1>", self.button3Click)
#max bet button
self.button4 = Button(self.myContainer1)
self.button4.configure(text='max bet', background='red')
self.button4.pack(side=RIGHT)
self.button4.bind("<Button-1>", self.button4Click)
'''
#Wins Label
self.labelForWins = Label(self.myContainer1)
self.labelForWins.configure(text='Wins: ')
self.labelForWins.pack()
self.labelWins = Label(self.myContainer1)
self.labelWins.configure(text = str(self.wins))
self.labelWins.pack()
#Losses Label
self.labelForLosses = Label(self.myContainer1)
self.labelForLosses.configure(text='Losses: ')
self.labelForLosses.pack()
self.labelLosses = Label(self.myContainer1)
self.labelLosses.configure(text = str(self.losses))
self.labelLosses.pack()
#Jackpot Label
self.labelForJack = Label(self.myContainer1)
self.labelForJack.configure(text='Jackpot: ')
self.labelForJack.pack()
self.labelJack = Label(self.myContainer1)
self.labelJack.configure(text = str(self.Jack))
self.labelJack.pack()
'''
#Reset Button
self.buttonReset = Button(self.myContainer1)
self.buttonReset.configure(text = 'Reset')
self.buttonReset.pack()
self.buttonReset.bind("<Button-1>", self.ButtonResetClick)
#Spin Button
self.buttonSpin = Button(self.myContainer1)
self.buttonSpin.configure(text = 'Spin!')
self.buttonSpin.pack()
self.buttonSpin.bind("<Button-1>", self.ButtonSpinClick)
def ButtonSpinClick(self, event):
Fruits = Reels()
def ButtonResetClick(self, event):
self.newMoney = 1000
self.labelMoneys.configure(text = str(self.newMoney))
#reset the labels for spins
self.money = self.newMoney
return self.money
def button1Click(self, event):
if (self.money != self.maxBet):
self.newMoney = self.money + 10
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
else:
self.newMoney = self.money
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
def button2Click(self, event):
if (self.money != self.maxBet):
self.newMoney = self.money + 20
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
else:
self.newMoney = self.money
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
def button3Click(self, event):
if (self.money != self.maxBet):
self.newMoney = self.money + 50
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
else:
self.newMoney = self.money
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
def button4Click(self, event):
self.newMoney = self.maxBet
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
'''if (self.mytext == 'clicky'):
self.mytext = 'hello'
self.label1.configure(text=self.mytext)
self.label1.pack()
else:
self.mytext = 'clicky'
self.label1.configure(text=self.mytext)
self.label1.pack()
if __name__ == "__main__": main()
def Reels(self, event):
self.Bet_Line = [" "," "," "]
self.Outcome = [0,0,0]
for self.spin in range(3):
# Spin those reels
if self.Outcome[spin] >= 1 and self.Outcome[spin] <=26: # 40.10% Chance
self.Bet_Line[spin] = "Blank"
if self.Outcome[spin] >= 27 and self.Outcome[spin] <=36: # 16.15% Chance
self.Bet_Line[spin] = "Grapes"
if self.Outcome[spin] >= 37 and self.Outcome[spin] <=45: # 13.54% Chance
self.Bet_Line[spin] = "Banana"
if self.Outcome[spin] >= 46 and self.Outcome[spin] <=53: # 11.98% Chance
self.Bet_Line[spin] = "Orange"
if self.Outcome[spin] >= 54 and self.Outcome[spin] <=58: # 7.29% Chance
self.Bet_Line[spin] = "Cherry"
if self.Outcome[spin] >= 59 and self.Outcome[spin] <=61: # 5.73% Chance
self.Bet_Line[spin] = "Bar"
if self.Outcome[spin] >= 62 and self.Outcome[spin] <=63: # 3.65% Chance
self.Bet_Line[spin] = "Bell"
if self.Outcome[spin] == 64: # 1.56% Chance
self.Bet_Line[spin] = "Seven"
self.Outcome[spin] = random.randrange(1,65,1)
# Spin those Reels!
return self.Bet_Line
'''
def Reels():
""" When this function is called it determines the Bet_Line results.
e.g. Bar - Orange - Banana """
# [0]Fruit, [1]Fruit, [2]Fruit
Bet_Line = [" "," "," "]
Outcome = [0,0,0]
# Spin those reels
for spin in range(3):
Outcome[spin] = random.randrange(1,65,1)
# Spin those Reels!
if Outcome[spin] >= 1 and Outcome[spin] <=26: # 40.10% Chance
Bet_Line[spin] = "Blank"
if Outcome[spin] >= 27 and Outcome[spin] <=36: # 16.15% Chance
Bet_Line[spin] = "Grapes"
if Outcome[spin] >= 37 and Outcome[spin] <=45: # 13.54% Chance
Bet_Line[spin] = "Banana"
if Outcome[spin] >= 46 and Outcome[spin] <=53: # 11.98% Chance
Bet_Line[spin] = "Orange"
if Outcome[spin] >= 54 and Outcome[spin] <=58: # 7.29% Chance
Bet_Line[spin] = "Cherry"
if Outcome[spin] >= 59 and Outcome[spin] <=61: # 5.73% Chance
Bet_Line[spin] = "Bar"
if Outcome[spin] >= 62 and Outcome[spin] <=63: # 3.65% Chance
Bet_Line[spin] = "Bell"
if Outcome[spin] == 64: # 1.56% Chance
Bet_Line[spin] = "Seven"
return Bet_Line
def is_number(Bet):
""" This function Checks if the Bet entered by the user is a valid number """
try:
int(Bet)
return True
except ValueError:
print("Please enter a valid number or Q to quit")
return False
def pullthehandle(Bet, Player_Money, Jack_Pot):
""" This function takes the Player's Bet, Player's Money and Current JackPot as inputs.
It then calls the Reels function which generates the random Bet Line results.
It calculates if the player wins or loses the spin.
It returns the Player's Money and the Current Jackpot to the main function """
Player_Money -= Bet
Jack_Pot += (int(Bet*.15)) # 15% of the player's bet goes to the jackpot
win = False
Fruit_Reel = Reels()
Fruits = Fruit_Reel[0] + " - " + Fruit_Reel[1] + " - " + Fruit_Reel[2]
# Match 3
if Fruit_Reel.count("Grapes") == 3:
winnings,win = Bet*20,True
elif Fruit_Reel.count("Banana") == 3:
winnings,win = Bet*30,True
elif Fruit_Reel.count("Orange") == 3:
winnings,win = Bet*40,True
elif Fruit_Reel.count("Cherry") == 3:
winnings,win = Bet*100,True
elif Fruit_Reel.count("Bar") == 3:
winnings,win = Bet*200,True
elif Fruit_Reel.count("Bell") == 3:
winnings,win = Bet*300,True
elif Fruit_Reel.count("Seven") == 3:
print("Lucky Seven!!!")
winnings,win = Bet*1000,True
# Match 2
elif Fruit_Reel.count("Blank") == 0:
if Fruit_Reel.count("Grapes") == 2:
winnings,win = Bet*2,True
if Fruit_Reel.count("Banana") == 2:
winnings,win = Bet*2,True
elif Fruit_Reel.count("Orange") == 2:
winnings,win = Bet*3,True
elif Fruit_Reel.count("Cherry") == 2:
winnings,win = Bet*4,True
elif Fruit_Reel.count("Bar") == 2:
winnings,win = Bet*5,True
elif Fruit_Reel.count("Bell") == 2:
winnings,win = Bet*10,True
elif Fruit_Reel.count("Seven") == 2:
winnings,win = Bet*20,True
# Match Lucky Seven
elif Fruit_Reel.count("Seven") == 1:
winnings, win = Bet*10,True
else:
winnings, win = Bet*2,True
if win:
print(Fruits + "\n" + "You Won $ " + str(int(winnings)) + " !!! \n")
Player_Money += int(winnings)
# Jackpot 1 in 450 chance of winning
jackpot_try = random.randrange(1,51,1)
jackpot_win = random.randrange(1,51,1)
if jackpot_try == jackpot_win:
print ("You Won The Jackpot !!!\nHere is your $ " + str(Jack_Pot) + "prize! \n")
Jack_Pot = 500
elif jackpot_try != jackpot_win:
print ("You did not win the Jackpot this time. \nPlease try again ! \n")
# No win
else:
print(Fruits + "\nPlease try again. \n")
return Player_Money, Jack_Pot, win
def main():
#create a top-level window
root = Tk()
#call the MyApp class
myapp = MyApp(root)
#execute the mainloop method of the "root" object
root.mainloop()
""" The Main function that runs the game loop """
# Initial Values
Player_Money = 1000
Jack_Pot = 500
Turn = 1
Bet = 0
Prev_Bet=0
win_number = 0
loss_number = 0
# Flag to initiate the game loop
KeepGoing = True
while KeepGoing == True:
win = 0
# Give the player some money if he goes broke
if Player_Money <1:
input("You have no more money. Here is $500 \nPress Enter\n")
Player_Money = 500
# User Input
Prompt = raw_input(" Place Your Bet ! \n Jackpot $ " + str(Jack_Pot) + "\n Money $ " + str(Player_Money) + "\n Q = quit \n")
if Prompt == "q" or Prompt == "Q":
KeepGoing = False
break
if Prompt == "" and Turn >1:
Bet = Prev_Bet
print("Using Previous Bet")
if Bet > Player_Money:
print("Sorry, you only have $" + str(Player_Money) + " \n")
elif Bet <= Player_Money:
Turn +=1
Prev_Bet = Bet
Player_Money, Jack_Pot, win = pullthehandle(Bet, Player_Money, Jack_Pot)
elif is_number(Prompt ):
Bet = int(Prompt )
# not enough money
if Bet > Player_Money:
print("Sorry, you only have $" + str(Player_Money) + " \n")
# Let's Play
elif Bet <= Player_Money:
Turn +=1
Prev_Bet = Bet
Player_Money, Jack_Pot, win = pullthehandle(Bet, Player_Money, Jack_Pot)
# determine win/loss ratio for debugging purposes
if win:
win_number += 1
else:
loss_number += 1
win_ratio = "{:.2%}".format(win_number / Turn)
print("Wins: " + str(win_number) + "\nLosses: " + str(loss_number) + "\nWin Ratio: " + win_ratio + "\n")
#The End
print("- Program Terminated -")
if __name__ == "__main__": main()<file_sep>/Dragon2.py
''''
Author: <NAME>
Date: May 14 2013
Title: Dragon Game
Version: 1.1
Date Last Modified: May 21st 2013
Modified Last By: Zach
Changes Made: Removed time to make for quicker testing. Removed Random caves. Added pre determined nodes.
'''
import random
import time
def displayIntro():
print ('You are on a planet full of dragons. In hunt of the secret treasure,')
print ('It will be a long journey. Perhaps you will catch the dragon sleeping,')
print ('if you are lucky, if not, prepare to fight for the treasure.')
print ('As many men have before.')
def chooseCave():
caveAtNodeOne = ''
while caveAtNodeOne != '1' and caveAtNodeOne != '2':
print ('Which cave will you go into? (1 or 2)')
caveAtNodeOne = raw_input()
if (caveAtNodeOne == '1'):
Node2()
elif (caveAtNodeOne == '2'):
Node3()
else:
print("Please Make a Valid Selection")
def Node2():
print 'Node2'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
Node4()
elif (Decision == '2'):
Node5()
else:
print'Please Make a valid decision (1 or 2)'
def Node3():
print 'Node3'
print 'You stumble'
print 'You take ten Damage!!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
Node6()
elif (Decision == '2'):
Node7()
else:
print'Please Make a valid decision (1 or 2)'
def Node4():
print 'Node4'
print 'You stumble'
print 'You take ten Damage!!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
OutNegativeTwo()
elif (Decision == '2'):
outNegativeFour()
else:
print'Please Make a valid decision (1 or 2)'
def Node5():
print'Node5'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
OutNegativeOne()
elif (Decision == '2'):
outNegativeThree()
else:
print'Please Make a valid decision (1 or 2)'
def Node6():
print 'Node6'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
OutNegativeOne()
elif (Decision == '2'):
outNegativeThree()
else:
print'Please Make a valid decision (1 or 2)'
def Node7():
print 'Node 7'
print 'You stumble'
print 'You can hear the dragon puffing'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
outNegativeThree()
elif (Decision == '2'):
positiveOutcome()
else:
print'Please Make a valid decision (1 or 2)'
def OutNegativeOne():
print 'Fight the Dragon and lose'
def OutNegativeTwo():
print 'Fight the Dragon but manage to escape'
def outNegativeThree():
print 'Fight the dragon down to his last health and lose'
def outNegativeFour():
print "You take one look at the dragon and run away"
def positiveOutcome():
print 'You defeat the dragon and collect his treasure!'
def main():
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
chooseCave()
print ('Do you want to play again? (yes or no)')
playAgain = raw_input()
if __name__ == "__main__": main()
<file_sep>/Assignment2 - Slot Machine/SlotMachine_1_2.py
# Source File Name: slotmachine.py
# Author's Name: <NAME>
# Last Modified By: <NAME>
# Date Last Modified: Tuesday June 6th, 2013
"""
Program Description: This program simulates a Casino-Style Slot Machine. It provides an GUI
for the user that is an image of a slot machine with Label and Button objects
created through the tkinter module
Version: 0.2- * Not connected with slotmachine.py yet. This was simply understanding tkinter andn usign the
buttons to alter labels.
"""
from Tkinter import *
class MyApp():
#define the attributes of the class
def __init__(self, parent):
self.myParent = parent
#creates a frame whose parent is root
self.myContainer1 = Frame(parent)
self.myContainer1.configure()
#pack the frame - show it on the screen
self.myContainer1.pack()
self.labelForBet = Label(self.myContainer1)
self.labelForBet.configure(text = "My Bet: ")
self.labelForBet.pack()
self.maxBet = 100
self.money = 10
self.mytext = str(self.money)
self.label1 = Label(self.myContainer1)
self.label1.configure(text = self.mytext)
self.label1.pack()
#bet 10 button
self.button1 = Button(self.myContainer1)
self.button1.configure(text='10', background='green')
self.button1.pack(side=LEFT)
self.button1.bind("<Button-1>", self.button1Click)
self.myimage = PhotoImage(file="Desert.gif")
#bet 20 button
self.button2 = Button(self.myContainer1)
self.button2.configure(image=self.myimage)
self.button2.pack(side=LEFT)
self.button2.bind("<Button-1>", self.button2Click)
# bet 50 button
self.button3 = Button(self.myContainer1)
self.button3.configure(text = '50', background='green')
self.button3.pack(side=RIGHT)
self.button3.bind("<Button-1>", self.button3Click)
#max bet button
self.button4 = Button(self.myContainer1)
self.button4.configure(text='max bet', background='red')
self.button4.pack(side=RIGHT)
self.button4.bind("<Button-1>", self.button4Click)
def button1Click(self, event):
if (self.money != self.maxBet):
self.newMoney = self.money + 10
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
else:
self.newMoney = self.money
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
def button2Click(self, event):
if (self.money != self.maxBet):
self.newMoney = self.money + 20
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
else:
self.newMoney = self.money
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
def button3Click(self, event):
if (self.money != self.maxBet):
self.newMoney = self.money + 50
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
else:
self.newMoney = self.money
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
def button4Click(self, event):
self.newMoney = self.maxBet
self.label1.configure(text = str(self.newMoney))
self.money = self.newMoney
return self.money
'''if (self.mytext == 'clicky'):
self.mytext = 'hello'
self.label1.configure(text=self.mytext)
self.label1.pack()
else:
self.mytext = 'clicky'
self.label1.configure(text=self.mytext)
self.label1.pack()
'''
def main():
#create a top-level window
root = Tk()
#call the MyApp class
myapp = MyApp(root)
#execute the mainloop method of the "root" object
root.mainloop()
if __name__ == "__main__": main()<file_sep>/Dragon.py
''''
Author: <NAME>
Date: May 14 2013
Title: Dragon Game
Version: 1.0
Date Last Modified: May 17th 2013
Modified Last By: Zach
Changes Made: Set up intro and created character function as well as added the rest of the nodes.
'''
import random
import time
#This is the main function that will start the game by calling the character info module to get
#some basic information
totalEarnings = 0
health = 50
def main():
characterInfo()
displayIntro()
caveNumber = chooseCave()
checkCaveOne(caveNumber, health, totalEarnings)
levelTwoIntro()
secondCave = chooseCave()
levelTwo(secondCave, health, totalEarnings)
justBeforeTheDragon(secondCave, health, totalEarnings)
'''
print ('Do you want to play again? (yes or no)')
playAgain = raw_input()
'''
# This module stores gets and store the character information.
def characterInfo():
#Declaring choice variablese to make their choice not case sensitive
yesChoice = "yes"
noChoice = "no"
#Get the users name
name = raw_input("What is your name?")
print ("Hello " + name + ".")
time.sleep(2)
#Give them a choice between risking their life or quiting
riskLife = raw_input("Are you sure you want to risk your life in search of the dragons treasure? (yes or no)")
#choosing to quit
if (riskLife == noChoice):
print("Smart Choice. Best not get involved with a dangerous dragon like that")
#choosing to play and calling the intro module
elif (riskLife == yesChoice):
print("Welcome ") + name + (" Let the adventure begin!")
time.sleep(3)
# error handling for inproper input
else:
print("noob")
#the introduction to the game. This is called in the character module
def displayIntro():
print ('You are on a planet full of dragons. In front of you,')
print ("......")
time.sleep(2)
print ('you see two caves. Who knows what is in either cave.')
print ("......")
time.sleep(2)
print ('perhaps you will stumble upon treasures or perhaps')
print ("......")
time.sleep(2)
print ('you will be eaten by the dragons.')
#This module choses between caves and gets the user input
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print ('Which cave will you go into? (1 or 2)')
cave = raw_input()
return cave
#this module determines the result of the cave choice, we are calling chosenCave health and total earnings from other modules.
def checkCaveOne(chosenCave, health, totalEarnings):
print ('You approach the cave...')
time.sleep(2)
print ('It is dark and spooky...')
time.sleep(2)
print ('You slip down the rocks and...')
time.sleep(2)
#this randomly decides which cave is friendly
friendlyCave = random.randint(1, 2)
#this if statement prints the results of the cave and displays updated health or earnings based on wether the cave was friendly or not.
if chosenCave == str(friendlyCave):
print ('you find some treasure!')
totalEarnings = totalEarnings + 25
time.sleep(1)
print ('You now have ' + str(totalEarnings) + ' gold')
return totalEarnings
#The negative side of the cave choice and updated health print
else:
print ('You Slip and take ten damage')
health = health - 10
time.sleep(1)
print ('You now have ' + str(health) + ' health')
return health
print('Hello')
def levelTwoIntro():
print ("You look around and realize there is more to this cave system than you originally thought!")
print ("It's probably best to keep going, you've gone too far now.")
print ("You come to another fork in the road!")
def levelTwo(secondCave, health, totalEarnings):
friendlyCave = random.randint(1, 2)
if secondCave == str(friendlyCave):
print ('you find some treasure!')
totalEarnings = totalEarnings + 25
time.sleep(1)
print ('You now have ' + str(totalEarnings) + ' gold')
return totalEarnings
else:
print ('You Slip and take ten damage')
health = health - 10
time.sleep(1)
print ('You now have ' + str(health) + ' health')
return health
print health
print totalEarnings
def justBeforeTheDragon(secondCave, health, totalEarnings):
time.sleep(3)
print ("You can hear the dragon now.")
print("..............")
print ("you get very scared")
print('.....................')
time.sleep(4)
print("OH $%#&#^$$!!!!!!!!!!!!!!!!")
friendlyDragon = random.randint(1, 2)
'''if endGame == str(friendlyDragon):
print ('You reason with the dragon and he lets you go')
print ('Whew that was close. At least I have my' + health + ' health and ' + totalEarnings + ' Gold')
'''
if __name__ == "__main__": main()<file_sep>/Dragon4.py
''''
Author: <NAME>
Date: May 14 2013
Title: Dragon Game
Version: 1.3
Date Last Modified: May 23nd 2013
Modified Last By: Zach
Changes Made: Finished commenting and ensure spelling and spacing are correct
'''
#import the time function
import time
# the function that appears at the start of the game. to start the journey
def displayIntro():
print ('You are on a planet full of dragons. In hunt of the secret treasure,')
print ('It will be a long journey. Perhaps you will catch the dragon sleeping,')
print ('if you are lucky, if not, prepare to fight for the treasure.')
print ('As many men have before.')
# the first cave decision
def chooseCave():
caveAtNodeOne = ''
#loop that validates user control
while caveAtNodeOne != '1' and caveAtNodeOne != '2':
print ('Which cave will you go into? (1 or 2)')
caveAtNodeOne = raw_input()
#based on user control send them to the next module
if (caveAtNodeOne == '1'):
Node2()
elif (caveAtNodeOne == '2'):
Node3()
else:
print("Please Make a Valid Selection")
# the module that handles the second node
def Node2():
print 'Node2'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
# the loop that handles the user input and sends them to the next module
Decision = raw_input()
if (Decision == '1'):
Node4()
elif (Decision == '2'):
Node5()
else:
print'Please Make a valid decision (1 or 2)'
#the module that handles the third node. a node needed to have the positive outcome
def Node3():
print 'Node3'
print 'You stumble'
print 'You take ten Damage!!'
print 'Cave 1 or 2?'
Decision = raw_input()
# the loop that handles the user input and sends them to the next module
if (Decision == '1'):
Node6()
elif (Decision == '2'):
Node7()
else:
print'Please Make a valid decision (1 or 2)'
# node 4 module. The start of the bad decision nodes, there is no more positive outcomes from here
#this only leads to negative outcomes and then loops back to play again
def Node4():
print 'Node4'
print 'You stumble'
print 'You take ten Damage!!'
print 'Cave 1 or 2?'
Decision = raw_input()
# the loop that handles the user input and sends them to a bad outcome which also restarts the game
if (Decision == '1'):
OutNegativeTwo()
elif (Decision == '2'):
outNegativeFour()
else:
print'Please Make a valid decision (1 or 2)'
# node 5 module. There is no more positive outcomes from here
#this only leads to negative outcomes and then loops back to play again
def Node5():
print'Node5'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
# the loop that controls user input and sends them to a negative outcome which also restarts the game
if (Decision == '1'):
OutNegativeOne()
elif (Decision == '2'):
outNegativeThree()
else:
print'Please Make a valid decision (1 or 2)'
# the 6th node which will send them to negative outcomes and restart the game.
def Node6():
print 'Node6'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
#the loop to control user input and send them to negative modules
if (Decision == '1'):
OutNegativeOne()
elif (Decision == '2'):
outNegativeThree()
else:
print'Please Make a valid decision (1 or 2)'
# the node you must make it to to get to the only positive outcome.
#this either sends the user to a negative outcome or to the positive.
def Node7():
print 'Node 7'
print 'You stumble'
print 'You can hear the dragon puffing'
time.sleep(3)
print 'Surely the dragon is right around the corner'
print 'Cave 1 or 2?'
Decision = raw_input()
#loop that controls player decision and sends them to the node.
if (Decision == '1'):
outNegativeThree()
elif (Decision == '2'):
positiveOutcome()
else:
print'Please Make a valid decision (1 or 2)'
#The prints for the first negative outcome. Then it loops to the option to play again
def OutNegativeOne():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "You wake him immediately."
time.sleep(1)
print "You take leap at him attacking with your sword!"
time.sleep(1)
print "He Attacks back instantly..."
time.sleep(1)
print "You take another swing at hime!"
time.sleep(1)
print "He is too quick and gobbles you up!"
#The prints for the first negative outcome. Then it loops to the option to play again
def OutNegativeTwo():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "You wake him immediately."
time.sleep(1)
print "You take leap at him attacking with your sword!"
time.sleep(1)
print "He Attacks back instantly..."
time.sleep(1)
print "You take another swing at hime!"
time.sleep(1)
print "You take a lot of damage!..."
time.sleep(2)
print"You manage to grab a bag of coins on the ground"
time.sleep(1)
print"and see an exit as you dodge his attacks..."
print"The Dragon dives towards you with his jaws open."
time.sleep(3)
print"You manage to leap him and escape with only a few coins"
#The prints for the first negative outcome. Then it loops to the option to play again
def outNegativeThree():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "He is still sleeping..."
time.sleep(1)
print "You sneak up behind him and pull out your treasure sack..."
time.sleep(1)
print "So Much GOLD!!!"
time.sleep(1)
print "You start collecting coins, you will get your treasure after all!"
time.sleep(1)
print "10 coins, 100 coins, 1000 coins! Ooops, you dropped one!"
time.sleep(2)
print"......"
time.sleep(2)
print"........."
print"You hear a loud roar from behind you!"
print"Time to battle the dragon"
print"....."
time.sleep(3)
print"He gobbled you up before you could even muster an effort!"
#The prints for the first negative outcome. Then it loops to the option to play again
def outNegativeFour():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "He is still sleeping..."
time.sleep(1)
print "Man that`s one big dragon!"
time.sleep(1)
print "You look at his teeth, wow they are sharp."
time.sleep(1)
print "You look at all the treasure... It`s a lot of treasure..."
time.sleep(1)
print "You hear a grunt from behind....."
time.sleep(2)
print"You drop everything and start running for the exit"
time.sleep(2)
print"........."
time.sleep(3)
print "You escape at the last second unharmed but not any richer."
#The prints for them positive outcome. Then it loops to the option to play again
def positiveOutcome():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "You wake him immediately."
time.sleep(1)
print "You take leap at him attacking with your sword!"
time.sleep(1)
print "He Attacks back instantly..."
time.sleep(1)
print "You take another swing at hime!"
time.sleep(1)
print "You take a lot of damage!..."
time.sleep(2)
print"With the last of your might you raise your sword and leap toward the dragon"
time.sleep(1)
print"...."
time.sleep(1)
print"...."
time.sleep(1)
print"...."
time.sleep(1)
print"You open your eyes and see you have hit the dragon in the heart"
print"He seems to be weak..."
time.sleep(3)
print"You give the dragon it's final blow..."
time.sleep(3)
print"It drops to the ground and you can relax now."
time.sleep(4)
print"Congratulations... You have defeated the dragon"
time.sleep(1)
print"You get to keep the secret treasure!"
def main():
#the play again loop, within the loop it will restart the opening module and cave picking system
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
chooseCave()
print ('Do you want to play again? (yes or no)')
playAgain = raw_input()
#calling the main function.
if __name__ == "__main__": main()
<file_sep>/Dragon3.py
''''
Author: <NAME>
Date: May 14 2013
Title: Dragon Game
Version: 1.2
Date Last Modified: May 22nd 2013
Modified Last By: Zach
Changes Made: Added sleeps and made the nodes actual story based prints, before they were just test prints for quick testing
'''
import random
import time
def displayIntro():
print ('You are on a planet full of dragons. In hunt of the secret treasure,')
print ('It will be a long journey. Perhaps you will catch the dragon sleeping,')
print ('if you are lucky, if not, prepare to fight for the treasure.')
print ('As many men have before.')
def chooseCave():
caveAtNodeOne = ''
while caveAtNodeOne != '1' and caveAtNodeOne != '2':
print ('Which cave will you go into? (1 or 2)')
caveAtNodeOne = raw_input()
if (caveAtNodeOne == '1'):
Node2()
elif (caveAtNodeOne == '2'):
Node3()
else:
print("Please Make a Valid Selection")
def Node2():
print 'Node2'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
Node4()
elif (Decision == '2'):
Node5()
else:
print'Please Make a valid decision (1 or 2)'
def Node3():
print 'Node3'
print 'You stumble'
print 'You take ten Damage!!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
Node6()
elif (Decision == '2'):
Node7()
else:
print'Please Make a valid decision (1 or 2)'
def Node4():
print 'Node4'
print 'You stumble'
print 'You take ten Damage!!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
OutNegativeTwo()
elif (Decision == '2'):
outNegativeFour()
else:
print'Please Make a valid decision (1 or 2)'
def Node5():
print'Node5'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
OutNegativeOne()
elif (Decision == '2'):
outNegativeThree()
else:
print'Please Make a valid decision (1 or 2)'
def Node6():
print 'Node6'
print 'You stumble'
print 'You find ten gold!'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
OutNegativeOne()
elif (Decision == '2'):
outNegativeThree()
else:
print'Please Make a valid decision (1 or 2)'
def Node7():
print 'Node 7'
print 'You stumble'
print 'You can hear the dragon puffing'
time.sleep(3)
print 'Surely the dragon is right around the corner'
print 'Cave 1 or 2?'
Decision = raw_input()
if (Decision == '1'):
outNegativeThree()
elif (Decision == '2'):
positiveOutcome()
else:
print'Please Make a valid decision (1 or 2)'
def OutNegativeOne():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "You wake him immediately."
time.sleep(1)
print "You take leap at him attacking with your sword!"
time.sleep(1)
print "He Attacks back instantly..."
time.sleep(1)
print "You take another swing at hime!"
time.sleep(1)
print "He is too quick and gobbles you up!"
def OutNegativeTwo():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "You wake him immediately."
time.sleep(1)
print "You take leap at him attacking with your sword!"
time.sleep(1)
print "He Attacks back instantly..."
time.sleep(1)
print "You take another swing at hime!"
time.sleep(1)
print "You take a lot of damage!..."
time.sleep(2)
print"You manage to grab a bag of coins on the ground"
time.sleep(1)
print"and see an exit as you dodge his attacks..."
print"The Dragon dives towards you with his jaws open."
time.sleep(3)
print"You manage to leap him and escape with only a few coins"
def outNegativeThree():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "He is still sleeping..."
time.sleep(1)
print "You sneak up behind him and pull out your treasure sack..."
time.sleep(1)
print "So Much GOLD!!!"
time.sleep(1)
print "You start collecting coins, you will get your treasure after all!"
time.sleep(1)
print "10 coins, 100 coins, 1000 coins! Ooops, you dropped one!"
time.sleep(2)
print"......"
time.sleep(2)
print"........."
print"You hear a loud roar from behind you!"
print"Time to battle the dragon"
print"....."
time.sleep(3)
print"He gobbled you up before you could even muster an effort!"
def outNegativeFour():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "He is still sleeping..."
time.sleep(1)
print "Man that`s one big dragon!"
time.sleep(1)
print "You look at his teeth, wow they are sharp."
time.sleep(1)
print "You look at all the treasure... It`s a lot of treasure..."
time.sleep(1)
print "You hear a grunt from behind....."
time.sleep(2)
print"You drop everything and start running for the exit"
time.sleep(2)
print"........."
time.sleep(3)
print "You escape at the last second unharmed but not any richer."
def positiveOutcome():
print "You walk in and see the dragon amoung it's treasure..."
time.sleep(2)
print "You wake him immediately."
time.sleep(1)
print "You take leap at him attacking with your sword!"
time.sleep(1)
print "He Attacks back instantly..."
time.sleep(1)
print "You take another swing at hime!"
time.sleep(1)
print "You take a lot of damage!..."
time.sleep(2)
print"With the last of your might you raise your sword and leap toward the dragon"
time.sleep(1)
print"...."
time.sleep(1)
print"...."
time.sleep(1)
print"...."
time.sleep(1)
print"You open your eyes and see you have hit the dragon in the heart"
print"He seems to be weak..."
time.sleep(3)
print"You give the dragon it's final blow..."
time.sleep(3)
print"It drops to the ground and you can relax now."
time.sleep(4)
print"Congratulations... You have defeated the dragon"
time.sleep(1)
print"You get to keep the secret treasure!"
def main():
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
chooseCave()
print ('Do you want to play again? (yes or no)')
playAgain = raw_input()
if __name__ == "__main__": main()
| c7b1c550ef8c0dcf657c0ec4f8d4de677cf9962b | [
"Markdown",
"Python"
] | 7 | Markdown | luuckyfree/Intro2Graphics2 | 88d1a8f5166c0b322850801517cdc9d52c4f1011 | 647d982e9fad6453a6341e8091de03e30704c1a9 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import time
import keras.callbacks as kcallbacks
import getopt
import sys
import warnings
from data_helper import *
from keras.layers import CuDNNLSTM, Dense, Input, Dropout, LSTM, Activation, BatchNormalization, concatenate, Subtract, Multiply, Bidirectional
from keras.layers.embeddings import Embedding
from keras.models import Model
np.random.seed(10000)
warnings.filterwarnings('ignore')
MAX_SEQUENCE_LENGTH = 10
EMBEDDING_DIM = 300
BATCH_SIZE = 32
NUM_CELL = 75
LSTM_DROPOUT = 0.5
DENSE_DROPOUT = 0.3
MODEL_ARCHITECTURE_PATH = './model/network_architecture.json'
# MODEL_WEIGHTS_PATH = './model/best.hdf5'
MODEL_WEIGHTS_PATH = './model/word_level_0.hdf5'
WORD_LEVEL = True
class SiameseLSTM(object):
def __init__(self, mode):
self.word2index, self.index2word, self.embed_matrix = load_embed_matrix(WORD_LEVEL)
self.features = load_features(mode)
print('embed_matrix: ', self.embed_matrix.shape)
question1 = Input(shape=(MAX_SEQUENCE_LENGTH,))
question2 = Input(shape=(MAX_SEQUENCE_LENGTH,))
embed_layer = Embedding(self.embed_matrix.shape[0], EMBEDDING_DIM, weights=[self.embed_matrix],
input_length=MAX_SEQUENCE_LENGTH, trainable=False)
q1_embed = embed_layer(question1)
q2_embed = embed_layer(question2)
shared_lstm_1 = Bidirectional(CuDNNLSTM(NUM_CELL, return_sequences=True))
shared_lstm_2 = Bidirectional(CuDNNLSTM(NUM_CELL))
q1 = shared_lstm_1(q1_embed)
q1 = Dropout(LSTM_DROPOUT)(q1)
q1 = BatchNormalization()(q1)
q1 = shared_lstm_2(q1)
q2 = shared_lstm_1(q2_embed)
q2 = Dropout(LSTM_DROPOUT)(q2)
q2 = BatchNormalization()(q2)
q2 = shared_lstm_2(q2)
d = Subtract()([q1, q2])
distance = Multiply()([d, d])
angle = Multiply()([q1, q2])
# train_features =
features_input = Input(shape=(self.features.shape[1],))
features_dense = BatchNormalization()(features_input)
features_dense = Dense(64, activation='relu')(features_dense)
merged = concatenate([distance, angle, features_dense])
merged = Dropout(DENSE_DROPOUT)(merged)
merged = BatchNormalization()(merged)
merged = Dense(256, activation='relu')(merged)
merged = Dropout(DENSE_DROPOUT)(merged)
merged = BatchNormalization()(merged)
merged = Dense(64, activation='relu')(merged)
merged = Dropout(DENSE_DROPOUT)(merged)
merged = BatchNormalization()(merged)
is_duplicate = Dense(1, activation='sigmoid')(merged)
self.model = Model(inputs=[question1, question2, features_input], outputs=is_duplicate)
def cross_val(self):
train_q1, train_q2, train_label = load_dataset(MAX_SEQUENCE_LENGTH, 'train', self.word2index, WORD_LEVEL)
best_val_score = {}
split_index = {}
for i in range(10):
split_index[i] = np.arange(i * 2000, (i+1) * 2000)
for model_count in range(10):
if model_count != 0:
continue
print('MODEL: ', model_count)
# split data into train/val set
idx_val = split_index[model_count]
idx_train = []
for i in range(10):
if i != model_count:
idx_train.extend(list(split_index[i]))
q1_train = train_q1[idx_train]
q2_train = train_q2[idx_train]
y_train = train_label[idx_train]
f_train = self.features.iloc[idx_train]
q1_val = train_q1[idx_val]
q2_val = train_q2[idx_val]
y_val = train_label[idx_val]
f_val = self.features.iloc[idx_val]
self.model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
self.model.summary()
# define save model
best_weights_filepath = './model/word_level_' + str(model_count) + '.hdf5'
early_stopping = kcallbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=1, mode='auto')
save_best_model = kcallbacks.ModelCheckpoint(best_weights_filepath, monitor='val_loss', verbose=1,
save_best_only=True, mode='auto')
hist = self.model.fit([q1_train, q2_train, f_train],
y_train,
validation_data=([q1_val, q2_val, f_val], y_val),
epochs=30,
batch_size=BATCH_SIZE,
shuffle=True,
callbacks=[early_stopping, save_best_model],
verbose=1)
self.model.load_weights(best_weights_filepath)
print(model_count, 'validation_loss: ', min(hist.history['val_loss']))
best_val_score[model_count] = min(hist.history['val_loss'])
# predict on the val set
preds = self.model.predict([q1_val, q2_val, f_val], batch_size=1024, verbose=1)
val_preds = pd.DataFrame({'y_pre': preds.ravel()})
val_preds['val_index'] = idx_val
save_path = './dataset/val_result/val_' + str(model_count) + '.csv'
val_preds.to_csv(save_path, index=0)
print(model_count, 'val preds saved.')
# predict on the test set
# preds = self.model.predict([test_q1, test_q2, test_features], batch_size=1024, verbose=1)
# test_preds = pd.DataFrame({'y_pre': preds.ravel()})
# save_path = 'dataset/val_result/test_' + str(model_count) + '.csv'
# test_preds.to_csv(save_path, index=0)
# print(model_count, 'test preds saved.')
f = open('./record.txt', 'a')
f.write(str(model_count) + str(best_val_score))
f.write('\n')
f.close()
def test(self):
test_q1, test_q2 = load_dataset(MAX_SEQUENCE_LENGTH, 'test', self.word2index, WORD_LEVEL)
for i in range(10):
self.model.load_weights('./model/word_level_'+str(i)+'.hdf5')
preds = self.model.predict([test_q1, test_q2, self.features], batch_size=1024, verbose=1)
preds = preds.ravel() + 0.5
preds = preds.astype(int)
df = pd.read_csv('./dataset/test.csv')
df['label'] = preds
df.to_csv('./dataset/result_'+str(i)+'.csv', index=False)
def train(self):
train_q1, train_q2, train_label = load_dataset(MAX_SEQUENCE_LENGTH, 'train', self.word2index, WORD_LEVEL)
self.model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
self.model.summary()
self.model.fit([train_q1, train_q2, self.features],
train_label,
validation_split=0,
epochs=30,
batch_size=BATCH_SIZE,
shuffle=True,
verbose=1)
self.model.save_weights('./dataset/word_level.hdf5')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], 'm:', ['mode='])
mode = 'train'
for op, value in opts:
if op in ('-m', '--mode'):
mode = value
if mode == 'test':
model = SiameseLSTM(mode)
model.test()
elif mode == 'val':
model = SiameseLSTM('train')
model.cross_val()
elif mode == 'train':
model = SiameseLSTM(mode)
start = time.time()
model.train()
end = time.time()
print('Training time {0:.3f}分钟'.format((end - start) / 60))
<file_sep># -*- coding: utf-8 -*-
import keras
import pandas as pd
from data_helper import *
from keras.models import load_model, model_from_json
MAXSEQUENCE_LENGTH = 30
test_q1, test_q2 = load_test_set(MAXSEQUENCE_LENGTH, word_level=True)
test_features = pd.read_csv('dataset/test_features.csv')
pick_columns = ['len_diff', 'edit_distance',
'adjusted_common_word_ratio', 'adjusted_common_char_ratio',
'pword_dside_rate', 'pword_oside_rate',
'pchar_dside_rate', 'pchar_oside_rate']
test_features = test_features[pick_columns]
model = model_from_json(open('model/network_architecture.json').read())
model.load_weights('./model/word_level_0.hdf5')
preds = model.predict_classes([test_q1, test_q2, test_features], batch_size=1024, verbose=1)
preds = preds.ravel() + 0.5
preds[preds['y_pred'] < -.5]<file_sep># -*- coding: utf-8 -*-
import os
import pandas as pd
filenames = os.listdir('./dataset/val_result/')
all = pd.read_csv('./dataset/test.csv')
all['label'] = 0
for filename in filenames:
df = pd.read_csv('./dataset/val_result/' + filename)
all['label'] += df['label']
all['label'] = all['label'] // 6
all.to_csv('./result/merge.csv', index=False)
<file_sep># -*- coding: utf-8 -*-
import numpy as np
def all_pair_dijkstra(train_graph, connected_component, max_distance):
m = len(connected_component)
cc = list(connected_component)
distance = {}
matrix = np.zeros((m, m))
for i in range(m):
dist = dijk
def generate_graph(train):
"""
把输入数据转化为以字典表示的无向图
:param train:
:return:
"""<file_sep># -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
def select_columns(data, question, word_level, need_label):
data = pd.merge(data, question, left_on=['qid1'], right_on=['qid'], how='left')
data = pd.merge(data, question, left_on=['qid2'], right_on=['qid'], how='left')
if word_level:
if need_label:
data = data[['label', 'wid_x', 'wid_y']]
else:
data = data[['wid_x', 'wid_y']]
else:
if need_label:
data = data[['label', 'cid_x', 'cid_y']]
else:
data = data[['cid_x', 'cid_y']]
if need_label:
data.columns = ['label', 'q1', 'q2']
else:
data.columns = ['q1', 'q2']
return data
def get_len_diff(data):
'''
Get the difference of length and normalize by the longest one of question pairs
'''
q1_len = data.q1.apply(lambda x: len(x.split(' '))).values
q2_len = data.q2.apply(lambda x: len(x.split(' '))).values
len_diff = np.abs(q1_len - q2_len) / np.max([q1_len, q2_len], axis=0)
return len_diff
def get_num_common_words(question, data):
'''
get the common words in q1 and q2
'''
q1_word_set = data.q1.apply(lambda x: x.split(' ')).apply(set).values
q2_word_set = data.q2.apply(lambda x: x.split(' ')).apply(set).values
result = [len(q1_word_set[i] & q2_word_set[i]) for i in range(len(q1_word_set))]
result = pd.DataFrame(result, index=data.index)
result.columns = ['num_common_words']
return result
def get_common_words_ratio(data):
q1_word_set = data.q1.apply(lambda x: x.split(' ')).apply(set).values
q2_word_set = data.q2.apply(lambda x: x.split(' ')).apply(set).values
q1_word_len = data.q1.apply(lambda x: len(x.split(' '))).values
q2_word_len = data.q2.apply(lambda x: len(x.split(' '))).values
result = [len(q1_word_set[i] & q2_word_set[i])/max(q1_word_len[i], q2_word_len[i]) for i in range(len(q1_word_set))]
result = pd.DataFrame(result, index=data.index)
result.columns = ['common_word_ratio']
return result
def get_tfidf_vector(data, vectorizer):
# vectorizer = TfidfVectorizer().fit(question.wid.values)
q1_tfidf = vectorizer.transform(data.q1.values)
q2_tfidf = vectorizer.transform(data.q2.values)
return vectorizer.vocabulary_, q1_tfidf, q2_tfidf
def adjust_common_word_ratio_by_tfidf(data, word2index, q1_tfidf, q2_tfidf):
adjusted_common_words_ratio = []
for i in range(q1_tfidf.shape[0]):
q1_words = {}
q2_words = {}
for word in data.loc[i, 'q1'].lower().split():
q1_words[word] = q1_words.get(word, 0) + 1
for word in data.loc[i, 'q2'].lower().split():
q2_words[word] = q2_words.get(word, 0) + 1
sum_shared_word_in_q1 = sum([q1_words[w] * q1_tfidf[i, word2index[w]] for w in q1_words if w in q2_words])
sum_shared_word_in_q2 = sum([q2_words[w] * q2_tfidf[i, word2index[w]] for w in q2_words if w in q1_words])
sum_total = sum([q1_words[w] * q1_tfidf[i, word2index[w]] for w in q1_words]) + sum([q2_words[w] * q2_tfidf[i, word2index[w]] for w in q2_words])
if 1e-6 > sum_total:
adjusted_common_words_ratio.append(0.)
else:
adjusted_common_words_ratio.append(1.0 * (sum_shared_word_in_q1 + sum_shared_word_in_q2) / sum_total)
return adjusted_common_words_ratio
def generate_powerful_word(data):
"""
计算数据中词语的影响力
0. 出现语句对数量
1. 出现语句对比例
2. 正确语句对比例
3. 单侧语句对比例
4. 单侧语句对正确比例
5. 双侧语句对比例
6. 双侧语句对正确比例
"""
words_power = {}
for i in data.index:
label = int(data.loc[i, 'label'])
q1_words = data.loc[i, 'q1'].lower().split()
q2_words = data.loc[i, 'q2'].lower().split()
all_words = set(q1_words + q2_words)
q1_words = set(q1_words)
q2_words = set(q2_words)
for word in all_words:
if word not in words_power:
words_power[word] = [0. for i in range(7)]
words_power[word][0] += 1.
words_power[word][1] += 1.
if (word in q1_words and word not in q2_words) or (word not in q1_words and word in q2_words):
# 计算单侧语句数量
words_power[word][3] += 1.
if 0 == label:
words_power[word][2] += 1.
words_power[word][4] += 1.
if word in q1_words and word in q2_words:
# 计算双侧语句数量
words_power[word][5] += 1.
if 1 == label:
# 计算正确语句对比例
words_power[word][2] += 1.
words_power[word][6] += 1.
for word in words_power:
# 计算出现语句对比例
words_power[word][1] /= data.shape[0]
# 计算正确语句对比例
words_power[word][2] /= data.shape[0]
# 计算单侧语句对正确比例
if words_power[word][3] > 1e-6:
words_power[word][4] /= words_power[word][3]
# 计算单侧语句对比例
words_power[word][3] /= words_power[word][0]
# 计算双侧语句对正确比例
if words_power[word][5] > 1e-6:
words_power[word][6] /= words_power[word][5]
# 计算双侧语句对比例
words_power[word][5] /= words_power[word][0]
sorted_words_power = sorted(words_power.items(), key=lambda d: d[1][0], reverse=True)
return sorted_words_power
def powerful_words_dside_tag(pword, data, threshold_num, threshold_rate):
"""
若问题两侧存在有预测力的powerful words,则设置标签为1,否则为0
"""
# 筛选powerful words(有预测力的)
pword_dside = []
pword = filter(lambda x: x[1][0] * x[1][5] >= threshold_num, pword) # 保证统计可靠性
pword_sort = sorted(pword, key=lambda d: d[1][6], reverse=True)
pword_dside.extend(map(lambda x: x[0], filter(lambda x: x[1][6] >= threshold_rate, pword_sort))) # 保证抽取到真正powerful的word
pword_dside_tags = []
for i in data.index:
tags = []
q1_words = set(data.loc[i, 'q1'].lower().split())
q2_words = set(data.loc[i, 'q2'].lower().split())
for word in pword_dside:
if word in q1_words and word in q2_words:
tags.append(1.0)
else:
tags.append(0.0)
pword_dside_tags.append(tags)
return pword_dside, pword_dside_tags
def powerful_words_oside_tag(pword, data, threshold_num, threshold_rate):
pword_oside = []
pword = filter(lambda x: x[1][0] * x[1][3] >= threshold_num, pword)
pword_oside.extend(map(lambda x: x[0], filter(lambda x: x[1][4] >= threshold_rate, pword)))
pword_oside_tags = []
for i in data.index:
tags = []
q1_words = set(data.loc[i, 'q1'].lower().split())
q2_words = set(data.loc[i, 'q2'].lower().split())
for word in pword_oside:
if word in q1_words and word not in q2_words:
tags.append(1.0)
elif word not in q1_words and word in q2_words:
tags.append(1.0)
else:
tags.append(0.0)
pword_oside_tags.append(tags)
return pword_oside, pword_oside_tags
def powerful_words_dside_rate(sorted_words_power, pword_dside, data):
num_least = 300
words_power = dict(sorted_words_power)
pword_dside_rate = []
for i in data.index:
rate = 1.0
q1_words = set(data.loc[i, 'q1'].lower().split())
q2_words = set(data.loc[i, 'q2'].lower().split())
share_words = list(q1_words.intersection(q2_words))
for word in share_words:
if word in pword_dside:
rate *= (1.0 - words_power[word][6])
pword_dside_rate.append(1-rate)
return pword_dside_rate
def powerful_words_oside_rate(sorted_words_power, pword_oside, data):
num_least = 300
words_power = dict(sorted_words_power)
pword_oside_rate = []
for i in data.index:
rate = 1.0
q1_words = set(data.loc[i, 'q1'].lower().split())
q2_words = set(data.loc[i, 'q2'].lower().split())
q1_diff = list(set(q1_words).difference(set(q2_words)))
q2_diff = list(set(q2_words).difference(set(q1_words)))
all_diff = set(q1_diff + q2_diff)
for word in all_diff:
if word in pword_oside:
rate *= (1.0 - words_power[word][4])
pword_oside_rate.append(1-rate)
return pword_oside_rate
def edit_distance(q1, q2):
str1 = q1.split(' ')
str2 = q2.split(' ')
matrix = [[i+j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
for i in range(1, len(str1) + 1):
for j in range(1, len(str2) + 1):
if str1[i-1] == str2[j-1]:
d = 0
else:
d = 1
matrix[i][j] = min(matrix[i-1][j]+1, matrix[i][j-1]+1, matrix[i-1][j-1]+d)
if i >1 and j > 1 and str1[i-1] == str2[j-2] and str1[i-2] == str2[j-1]:
d = 0
matrix[i][j] = min(matrix[i][j], matrix[i-2][j-2]+d)
return matrix[len(str1)][len(str2)]
def get_edit_distance(data):
q1_len = data['q1'].apply(lambda x: len(x.split(' '))).values
q2_len = data['q2'].apply(lambda x: len(x.split(' '))).values
# normalize the edit_distance by the max(len(q1), len(q2))
dist = [edit_distance(data.loc[i, 'q1'], data.loc[i, 'q2']) / np.max([q1_len, q2_len], axis=0)[i] for i in data.index]
return dist
def generate_features_csv(kind):
question = pd.read_csv('./dataset/question_id.csv')
raw = pd.read_csv('./dataset/' + kind + '.csv')
unlabeled_data = select_columns(raw, question, True, False)
labeled_data = select_columns(pd.read_csv('./dataset/train.csv'), question, True, True)
len_diff = get_len_diff(unlabeled_data)
vocab, q1_tfidf, q2_tfidf = get_tfidf_vector(unlabeled_data, TfidfVectorizer().fit(question.wid.values))
adjusted_common_word_ratio = adjust_common_word_ratio_by_tfidf(unlabeled_data, vocab, q1_tfidf, q2_tfidf)
edit = get_edit_distance(unlabeled_data)
sorted_words_power = generate_powerful_word(labeled_data)
pword_dside, pword_dside_tags = powerful_words_dside_tag(sorted_words_power, unlabeled_data, 1, 0.7)
pword_dside_rate = powerful_words_dside_rate(sorted_words_power, pword_dside, unlabeled_data)
pword_oside, pword_oside_tags = powerful_words_oside_tag(sorted_words_power, unlabeled_data, 1, 0.7)
pword_oside_rate = powerful_words_oside_rate(sorted_words_power, pword_oside, unlabeled_data)
unlabeled_data = select_columns(raw, question, False, False)
labeled_data = select_columns(pd.read_csv('./dataset/train.csv'), question, False, True)
vocab, q1_tfidf, q2_tfidf = get_tfidf_vector(unlabeled_data, TfidfVectorizer().fit(question.cid.values))
adjusted_common_char_ratio = adjust_common_word_ratio_by_tfidf(unlabeled_data, vocab, q1_tfidf, q2_tfidf)
sorted_chars_power = generate_powerful_word(labeled_data)
pchar_dside, pchar_dside_tags = powerful_words_dside_tag(sorted_chars_power, unlabeled_data, 1, 0.7)
pchar_dside_rate = powerful_words_dside_rate(sorted_chars_power, pchar_dside, unlabeled_data)
pchar_oside, pchar_oside_tags = powerful_words_oside_tag(sorted_chars_power, unlabeled_data, 1, 0.7)
pchar_oside_rate = powerful_words_oside_rate(sorted_chars_power, pchar_oside, unlabeled_data)
df = pd.DataFrame({'len_diff': len_diff, 'edit_distance': edit,
'adjusted_common_word_ratio': adjusted_common_word_ratio, 'adjusted_common_char_ratio': adjusted_common_char_ratio,
'pword_dside_rate': pword_dside_rate, 'pword_oside_rate': pword_oside_rate,
'pchar_dside_rate': pchar_dside_rate, 'pchar_oside_rate': pchar_oside_rate})
df.to_csv('./dataset/' + kind + '_features.csv', index=False)
if __name__ == '__main__':
generate_features_csv('train')
generate_features_csv('test')
<file_sep># -*- coding: utf-8 -*-
import os
import numpy as np
import pandas as pd
EMBEDDING_DIM = 300
WORD_EMBEDDING_PATH = './dataset/word_embedding.txt'
CHAR_EMBEDDING_PATH = './dataset/char_embedding.txt'
QUESTION_ID_PATH = './dataset/question_id.csv'
def sentences2indices(x, word2index, max_seq_len):
'''
Converts an array of sentences(string) into an array of indices corresponding to words in the sentences.
The output shape should be shuch that it can be given to 'Embedding()'
:param x: array of sentences(string), of shape(m, 1)
:param word2index: a dictionary containing the each word mapped to its index
:param max_len: maximum number of words in a sentence. You can assume every sentence in x is no longer than this.
:return: x_indices: array of indices corresponding to words in the sentences from x, of shape(m, max_len)
'''
m = x.shape[0] # Number of training examples
# Inintial x_indices as a numpy matrix of zeors and the correct shape
x_indices = np.zeros((m, max_seq_len))
for i in range(m):
# Split the sentences into a list of words
words_list = x[i].split(' ')
# oop over the words of words_list
for j, word in enumerate(words_list):
if j >= max_seq_len:
break
# Set the (i, j)th entry of x_indices to the index of the correct word
if word2index.get(word) is not None:
x_indices[i, j] = word2index[word]
return x_indices
def load_dataset(max_seq_len, mode, word2index, word_level=True):
# Load data and preprocessing
if mode == 'test':
path = os.path.join('dataset', 'test.csv')
else:
path = os.path.join('dataset', 'train.csv')
question = pd.read_csv(QUESTION_ID_PATH)
dataset = pd.read_csv(path)
# Transfer qid in train.csv to concrete question string in question_id.csv
dataset = pd.merge(dataset, question, left_on=['qid1'], right_on=['qid'], how='left')
dataset = pd.merge(dataset, question, left_on=['qid2'], right_on=['qid'], how='left')
if word_level:
dataset = dataset[['label', 'wid_x', 'wid_y']]
else:
dataset = dataset[['label', 'cid_x', 'cid_y']]
dataset.columns = ['label', 'q1', 'q2']
q1_indices = sentences2indices(dataset.q1.values, word2index, max_seq_len).astype(np.int32)
q2_indices = sentences2indices(dataset.q2.values, word2index, max_seq_len).astype(np.int32)
print(mode + '_q1: ', q1_indices.shape)
print(mode + '_q2: ', q2_indices.shape)
if mode == 'test':
return q1_indices, q2_indices
else:
label = dataset.label.values
return q1_indices, q2_indices, label
def load_features(mode):
# 读取手工特征
features = pd.read_csv('./dataset/' + mode + '_features.csv')
pick_columns = ['len_diff', 'edit_distance',
'adjusted_common_word_ratio', 'adjusted_common_char_ratio',
'pword_dside_rate', 'pword_oside_rate',
'pchar_dside_rate', 'pchar_oside_rate']
features = features[pick_columns]
print(features.info())
return features
def load_embed_matrix(word_level):
if word_level:
embed_path = WORD_EMBEDDING_PATH
else:
embed_path = CHAR_EMBEDDING_PATH
# Load word2vec
word2vec = pd.read_csv(embed_path, sep='\t', header=None, index_col=0)
# Create index dictionary
word = word2vec.index.values
word2index = dict([(word[i], i+1) for i in range(len(word))])
index2word = dict([(i + 1, word[i]) for i in range(len(word))])
# Generate embedding matrix
vocab_len = len(word2index) + 1
# Initialize the embedding matrix as numpy arrays of zeros
embed_matrix = np.zeros((vocab_len, EMBEDDING_DIM))
# Set each row 'index' of the embedding matrix to be word vector representation of the 'index'th word of the vocabulary
for word, index in word2index.items():
embed_matrix[index, :] = word2vec.loc[word].values
return word2index, index2word, embed_matrix,
| 6cc8e0ef4b2dd1d53059b8c049033ef96a1c8e59 | [
"Python"
] | 6 | Python | xuming1986/chip2018_task2_question_pairs_matching | 84878a9b945332b147f1274c90312ecb64191230 | a3ed839b1a729168f98b63136c3996123ac17561 |
refs/heads/master | <file_sep>mkdocs (docker image)
=====================
Similar to jobandtalent/mkdocs but integrates PythonMarkdown PlantUML extension.
This image will provide you mkdocs. Some examples of its usage:
Create a new project
--------------------
docker run -it --rm -v `pwd`:/docs coding2012/mkdocs new my-project
Serve your project
------------------
If you are inside a VM (boot2docker or similar) you will need to set the host to `0.0.0.0`:
cd my-project
docker run -it --rm -v `pwd`:/docs -p 8000:8000 coding2012/mkdocs serve -a 0.0.0.0:8000
Build your docs
---------------
cd my-project
docker run -it --rm -v `pwd`:/docs coding2012/mkdocs build
If you want to generate them in other place mount `/docs/site` as a volume:
docker run -it --rm -v `pwd`:/docs -v $HOME/Desktop/site:/docs/site coding2012/mkdocs build
PlantUML Usage
--------------
Inside your project file
```
site_name: My Site Name
markdown_extensions:
- plantuml:
outpath: "images"
```
See the following site for uml usage:
https://github.com/mikitex70/plantuml-markdown<file_sep>FROM java:openjdk-8u77-jdk-alpine
MAINTAINER <NAME> <<EMAIL>>
MAINTAINER <NAME> <<EMAIL>>
RUN apk add --update python3 py-pip
RUN pip install mkdocs
RUN rm -rf /var/cache/apk/*
ENV PLANTUML_VERSION 8038
RUN apk add --no-cache graphviz ttf-droid ttf-droid-nonlatin curl \
&& mkdir /app \
&& curl -L https://sourceforge.net/projects/plantuml/files/plantuml.${PLANTUML_VERSION}.jar/download -o /app/plantuml.jar \
&& apk del curl
COPY plantuml.py /usr/lib/python2.7/site-packages/markdown/extensions/
COPY plantuml /usr/local/bin/plantuml
RUN chmod +x /usr/local/bin/plantuml
WORKDIR /docs
VOLUME /docs
EXPOSE 8000
ENTRYPOINT ["mkdocs"]
<file_sep>#!/bin/sh
java -jar /app/plantuml.jar ${@} | 0b6cbcbf47f094449e8752584124c8c2ff8c08e5 | [
"Markdown",
"Dockerfile",
"Shell"
] | 3 | Markdown | huandzh/docker-mkdocs-plantuml | a0a4257aede8e72ae6711183beb5cf97f365aa3b | 484e18ee96f69e7e21138fbd76d2a8e77ce922ff |
refs/heads/master | <file_sep>const { suite, test } = intern.getInterface('tdd');
const { assert } = intern.getPlugin('chai');
import { url_compute } from "../../index";
import { is_absolute, upper_path_walk, UrlComp } from "../../lib/UrlComp";
suite('index', () => {
test('url_compute', () => {
let url_full = "http://example.com/index.html";
let url_dir = "http://example.com/dir/index.html";
assert.strictEqual( url_compute("some_file.txt", url_full), "http://example.com/some_file.txt",
"full url - single filename on root" );
assert.strictEqual( url_compute("some_file.txt", url_dir), "http://example.com/dir/some_file.txt",
"full url - single filename on dir" );
assert.strictEqual( url_compute("/some_file.txt", url_dir), "http://example.com/some_file.txt",
"full url - absolute file" );
assert.strictEqual( url_compute("../some_file.txt", url_dir), "http://example.com/some_file.txt",
"full url - parent path file" );
});
});
suite('UrlComp', () => {
test('basic_functions', () => {
let url_full = "http://example.com/index.html";
let url_full2 = "https://example.com/other/path/here/index.html";
let url3 = "/other/path/here/index.html";
let url4 = "other/path/here/index.html";
let UrlComp1 = new UrlComp(url_full);
let UrlComp2 = new UrlComp(url_full2);
let UrlComp3 = new UrlComp(url3);
let UrlComp4 = new UrlComp(url4);
assert.strictEqual( UrlComp1.get_scheme(), "http://", "get scheme" );
assert.strictEqual( UrlComp1.get_host(), "example.com", "get host" );
assert.strictEqual( UrlComp1.get_path(), "/index.html", "get path" );
assert.strictEqual( UrlComp2.get_scheme(), "https://", "get scheme - 2nd" );
assert.strictEqual( UrlComp2.get_host(), "example.com", "get host - 2nd" );
assert.strictEqual( UrlComp2.get_path(), url3, "get path - 2nd" );
assert.strictEqual( UrlComp3.get_path(), url3, "get path - 3nd" );
assert.strictEqual( UrlComp4.get_path(), url4, "get path - 4nd" );
assert.isTrue(UrlComp3.is_absolute(), "absolute test");
assert.isFalse(UrlComp4.is_absolute(), "absolute test");
assert.strictEqual( UrlComp3.get_path_wo_filename(), "/other/path/here/", "get path wo filename" );
assert.strictEqual( UrlComp4.get_path_wo_filename(), "other/path/here/", "get path wo filename - 2nd" );
assert.strictEqual( (new UrlComp("other/")).get_path_wo_filename(), "other/", "get path wo filename - 3rd" );
assert.strictEqual( (new UrlComp("other")).get_path_wo_filename(), "", "get path wo filename - 4th" );
assert.strictEqual( (new UrlComp("/other")).get_path_wo_filename(), "/", "get path wo filename - 5th" );
});
test('upper_walk', () => {
//upper_path_walk
let a = "asdf";
assert.strictEqual( upper_path_walk(a), a, "harmless 1");
assert.strictEqual( upper_path_walk("/"+a), "/"+a, "harmless 2");
assert.strictEqual( upper_path_walk(a+"/"), a+"/", "harmless 3");
assert.strictEqual( upper_path_walk(a+"/"+a), a+"/"+a, "harmless 4");
assert.strictEqual( upper_path_walk("a/b/../c"), "a/c", "works 1");
assert.strictEqual( upper_path_walk("/a/../b/../c"), "/c", "works 2");
assert.strictEqual( upper_path_walk("a/../b/../c"), "c", "works 3");
assert.strictEqual( upper_path_walk("/a/../b"), "/b", "works 4");
assert.strictEqual( upper_path_walk("/a/../../b"), "/b", "works 5");
assert.strictEqual( upper_path_walk("/a/../../../b"), "/b", "works 6");
assert.strictEqual( upper_path_walk("a/../b"), "b", "works 4b");
assert.strictEqual( upper_path_walk("a/../../b"), "../b", "works 5b");
assert.strictEqual( upper_path_walk("a/../../../b"), "../../b", "works 5b");
assert.strictEqual( upper_path_walk("../b"), "../b", "works 4b");
assert.strictEqual( upper_path_walk("../../b"), "../../b", "works 4b");
});
test('url_compute', () => {
let url_full = "http://example.com/index.html";
let url_dir = "http://example.com/dir/index.html";
let UrlComp1 = new UrlComp(url_full);
assert.strictEqual( UrlComp1.get_full(), url_full, "full url failure" );
UrlComp1 = new UrlComp("some_file.txt", url_full);
assert.strictEqual( UrlComp1.get_full(), "http://example.com/some_file.txt", "full url - single filename on root" );
UrlComp1 = new UrlComp("some_file.txt", url_dir);
assert.strictEqual( UrlComp1.get_full(), "http://example.com/dir/some_file.txt", "full url - single filename on dir" );
UrlComp1 = new UrlComp("/some_file.txt", url_dir);
assert.strictEqual( UrlComp1.get_full(), "http://example.com/some_file.txt", "full url - absolute file" );
UrlComp1 = new UrlComp("../some_file.txt", url_dir);
assert.strictEqual( UrlComp1.get_full(), "http://example.com/some_file.txt", "full url - parent path file" );
});
});
<file_sep>{
"name": "url-compute",
"version": "0.9.3",
"description": "compute non-absolute urls",
"main": "dist/index.js",
"directories": {
"test": "tests"
},
"dependencies": {
"systemjs": "~0.19.47",
"tslib": "1.9.0"
},
"devDependencies": {
"intern": "^4.0.0-rc.1"
},
"scripts": {
"compile": "tsc -p .",
"test": "intern"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tenuki/url-compute.git"
},
"keywords": [
"url",
"computation",
"relative",
"resolution"
],
"author": "<NAME>",
"license": "ISC",
"bugs": {
"url": "https://github.com/tenuki/url-compute/issues"
},
"homepage": "https://github.com/tenuki/url-compute#readme"
}
<file_sep>export
function is_absolute(a_path: string) {
return a_path.startsWith("/");
}
export
function upper_path_walk(path: string) {
let min = 0;
let isabs = is_absolute(path);
let upper = "..";
let parts = path.split("/");
let last = parts.indexOf(upper);
while (last > min) {
if (parts[last - 1].localeCompare(upper) != 0 || isabs) {
let new_parts = parts.slice(0, last - 1);
if (last <= 2 && parts[0].length == 0) {
new_parts = [''];
}
parts = new_parts.concat(parts.slice(last + 1));
} else {
min += 1;
}
last = parts.lastIndexOf(upper);
}
let result = parts.reduce(function (a, b) {
//if (a==null) {a=""} else {a=a+"/";}return a + b;
if (a == null) {
return b
}
return a + "/" + b;
}, null);
return result;
}
export
class UrlComp {
constructor(public urldef: string, public base?: string) {
}
have_scheme() {
return this.urldef.indexOf("://") != -1;
}
is_absolute() {
return is_absolute(this.urldef);
}
get_scheme() {
let start = this.urldef.indexOf("://");
return this.urldef.slice(0, this.urldef.indexOf("://") + 3);
}
get_host() {
let start = this.urldef.indexOf("://") + 3;
return this.urldef.slice(
start, this.urldef.indexOf("/", start)
);
}
get_path() {
let tmp;
if (this.have_scheme()) {
let host = this.get_host();
tmp = this.urldef.slice(
this.urldef.indexOf(host) + host.length);
} else {
//shall we detect host/path.../.. case?
tmp = this.urldef;
}
return tmp;
}
get_path_wo_filename() {
let path = this.get_path();
while (!path.endsWith("/") && path.length) {
path = path.slice(0, path.length - 1);
}
return path;
}
get_full() {
if (this.have_scheme()) {
return this.urldef;
}
let baseurl = new UrlComp(this.base);
let base_host = baseurl.get_scheme() + baseurl.get_host();
if (this.is_absolute()) {
return base_host + this.urldef;
}
let base_path = baseurl.get_path_wo_filename();
let result = base_host + base_path + this.urldef;
return upper_path_walk(result);
}
}<file_sep>import {UrlComp} from "./lib/UrlComp";
export
function url_compute(relative_url: string, base_url: string) {
let murl = new UrlComp(relative_url, base_url);
return murl.get_full();
}<file_sep>Compute relative url paths
## Install
```
$ npm install url-compute
```
## Usage
```
C:\Users\aweil\repos\url-compute-test>node
> var uc = require('url-compute');
> uc.url_compute("../some_file.txt", "http://example.com/dir/index.html")
'http://example.com/some_file.txt'
```
| d1d5d12e7ba600ee28babc9d9920854b202aa819 | [
"Markdown",
"JSON",
"TypeScript"
] | 5 | TypeScript | tenuki/url-compute | 35324dde664d88fff2de873ab2e04e2e759bab69 | 362080782d822cb5f478ec64765b60a93f0dd4ef |
refs/heads/main | <file_sep># Distant Life
## 🍿 Video Demo
https://youtu.be/zrIuFmyARn8
<br/>

## 🤖 Description
Raise virtual pets while improving your language skills! You've landed on a new planet and need to learn words and phrases in order to grow your family of pets and travel to new worlds. Certain pets can only be adopted with enough experience, and quizzes for certain words and phrases can only be unlocked once you've adopted the pets that live on the corresponding planet.
In addition to growing your pets, you'll be able to review words and test your knowledge with short quizzes. Gain experience as you answer quiz questions correctly.
Future enhancements include:
- Tracking which words are learned
- Notifications
- Badges earned
- Stores and inventory where a user can practice purchasing and using items in their targeted learning language
- Customized pets (colors)
- Customizable avatars
- Location backgrounds for different areas
### 📔 Administration
In addition to the member experience, there is an admin dashboard available to users with an admin role. In this area, an admin can:
- Create new word sets
- Add new words to word sets using a CSV file uploader
- Delete words from word sets
### 🪐 Localization and Internationalization
To better support users, the site supports language translation and internationalization. For languages that require a right-to-left (RTL) reading direction, the interface mirrors the normal reading direction. In addition, RTL includes small enhancements such as flipping the active pet image and general site layout.
From their profile, a member can switch between their native language and their targeted learning language. Currently, Distant Life only supports English and Hebrew but has been developed to dynamically support more languages.
Word sets and quizzes are supported using a translation table in the SQLite database. Alternatively, front-end words (text keys) such as "Log in", "Complete", "Profile", etc are defined and translated using Babel translations.
------
## File overview
The site is setup using Python, Flask with Jinja templates, and a custom CSS stylesheet.
Python files
- **application.py** - Contains routes and connection information for Redis (used for session storage) and the SQLite database connection (used for saving data.)
- **fileparser.py** - Processes the uploaded CSV used by admin to add words to word sets dynamically. Files are temporarily stored in `static/files` and then deleted after being processed to save space on the server.
- **helpers.py** - Contains reusable functions and decorators that are used within the application
- **wsgi.py** - Used for automatically running the virtual environment on an nginx server
Template files
- General Layout:
- **global** - A directory of global includes for the header, footer, and sidebar. These items were refactored into global includes due to the multiple layouts necessary for logged-in versus the anonymous full-page view. Using the global includes allows for easier maintenance.
- **layout-1col.html** - The general page layout with a sidebar.
- **layout.html** - The general page layout but full-width.
- **macros.html** - Contains reusable components for the Jinja templates: experience bar.
- User pages:
- **about.html** - Displays information generally about the site and credits.
- **adopt.html** - Allows a user to adopt a pet.
- **apology.html** - The error page shows the error code and related message.
- **dashboard.html** - The default landing page after logging in. Shows recent notifications and news items.
- **index.html** - The front page (anonymous) for visiting users.
- **list.html** - The list of a user's pets; also contains a link to adopt more.
- **profile.html** - The user's profile settings for native language, target learning language, account information, and password reset.
- **quizset.html** - The quiz module for testing ability to identify words and phrases.
- **train.html** - The list of available word sets that a user can learn and test on.
- **trainset.html** - The learning module for a word set.
- Sign up and login pages:
- **login.html** - Allows a user to log in.
- **signup.html** - Allows a new user to sign up.
- Admin pages:
- **createset.html** - Allows an admin to create a new word set.
- **editsets.html** - Shows all available word sets.
- **editset.html** - Allows an admin to edit a set by deleting existing words or uploading a CSV to add a group of new words to it (and optionally the translated-language word set equivalent.)
Other files:
- **babel.cfg** - Sets up which files to scan for translation text keys.
- **messages.pot** - The full list of words that will be converted into translation keys (in the `translations/en/LC_MESSAGES` and `translations/he/LC_MESSAGES` folders.)
------
## Data structure

Tables were created to allow for users to own multiple pets, translate words, create word sets and quizzes, and more.
------
## Development
```sh
brew install redis
```
Enable virtual environment:
```sh
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
export FLASK_APP=application
export FLASK_ENV=development # enable autoreload
```
## Running
```sh
redis-server # terminal #1
flask run # terminal #2 (venv)
```
## Translations
Get translation keys:
```python
pybabel extract -F babel.cfg -o messages.pot --input-dirs=.
# pybabel init -i messages.pot -d translations -l en # for init only
# pybabel init -i messages.pot -d translations -l he
pybabel update -i messages.pot -d translations -l en
pybabel update -i messages.pot -d translations -l he
```
After translating keys in translations folder compile .mo files:
```python
pybabel compile -d translations
```
Usage in templates with `_('Word')` or `gettext('Word')`:
```html
<h2>{{ _('Free Trial') }}</h2>
<input type="submit" value="{{ gettext('Sign up') }}"/>
```
Visit http://127.0.0.1:5000/
## Resources
- [Front-end styling and development](https://virtual.github.io/fed-projects/04) | [GitHub Repo](https://github.com/virtual/fed-projects)
- [Figma design](https://www.figma.com/file/6ckmGH0eDFj1956hPH8n0V/DistantLife-final-CS50x?node-id=6%3A2860)
<file_sep>{% extends "layout.html" %}
{% block title %}
{{ _('Adopt a Pet') }}
{% endblock %}
{% block main %}
<h1>{{ _('Adopt a Pet') }}</h1>
{% if (pet_types|length) > 0 %}
<table class="table table-striped">
<thead>
<tr>
<th>{{ _('Type') }}</th>
<th>{{ _('Image') }}</th>
<th>{{ _('Adopt') }}</th>
</tr>
</thead>
<tbody>
{% for pet_type in pet_types %}
<tr>
<td>{{ pet_type.pet_type }} ({{pet_type.id}})</td>
<td><img src="/static/{{ pet_type.imgsrc }}" alt="" /></td>
<td>
<form method="post" action="/adopt">
<input name="pet_type" type="hidden" value="{{pet_type.id}}" />
<input type="submit" value="{{ _('Adopt') }}" />
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
{% else %}
<p>{{ _('No pets') }}</p>
{% endif %}
{% endblock %}
<file_sep>import sqlite3
import csv
import redis
con = sqlite3.connect("distantlife.db")
con.row_factory = sqlite3.Row # Includes column name in return dictionary
db = con.cursor()
r = redis.StrictRedis(host="127.0.0.1", port=6379, db=0)
def save_words(csvf, word_set_id, orig_set_id=''):
"""Open the CSV file and read its contents into memory
Args:
csvf (file): the file to process
word_set_id (str): the translated word set to add to
orig_set_id (str, optional): The original language word set to add to. Defaults to ''.
Returns:
len (int): the number of words added
"""
words = []
headings = []
with open(csvf, "r", encoding='utf-8-sig') as file:
reader = csv.reader(file, delimiter=',')
# Create dictionary keys
for row in reader:
i = 0
while (i < len(row)):
headings.append(row[i])
i += 1
break
# Save STR values to each person
for row in reader:
i = 0
word = {}
while (i < len(row)):
key = str(headings[i])
value = row[i]
word[key] = value
i += 1
words.append(word)
# Get heading names
lang1 = headings[0] # Original Language
lang1p = headings[1] # Original transliteration
lang2 = headings[2] # Translation Language
lang2p = headings[3] # Translation transliteration
wtype = headings[4] # Type of word (noun, verb)
orig_lang_id = (db.execute(
"SELECT id FROM languages WHERE name = ?", (lang1, )).fetchall())[0]['id']
trans_lang_id = (db.execute(
"SELECT id FROM languages WHERE name = ?", (lang2, )).fetchall())[0]['id']
for w in words:
word_type_id = (db.execute(
"SELECT id FROM word_type WHERE type = ?", (w[wtype], )).fetchall())[0]['id']
new_orig_word_id = (db.execute("INSERT INTO words ('wordstr', 'language_id', 'type', 'pronunciation') VALUES (?, ?, ?, ?)",
(w[lang1], orig_lang_id, word_type_id, w[lang1p])
)).lastrowid
con.commit()
new_translated_word_id = (db.execute("INSERT INTO words ('wordstr', 'language_id', 'type', 'pronunciation') VALUES (?, ?, ?, ?)",
(w[lang2], trans_lang_id, word_type_id, w[lang2p])
)).lastrowid
con.commit()
db.execute("INSERT INTO word_set_words (word_set_id, word_id) VALUES (?, ?)",
(word_set_id, new_translated_word_id))
con.commit()
# if orig_set_id is set
if (orig_set_id != ''):
db.execute("INSERT INTO word_set_words (word_set_id, word_id) VALUES (?, ?)",
(int(orig_set_id), new_orig_word_id))
con.commit()
# insert orig and its translation equivalent
db.execute("INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (?, ?, ?, ?)",
(orig_lang_id, trans_lang_id, new_orig_word_id, new_translated_word_id))
con.commit()
# reverse orig & translation
db.execute("INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (?, ?, ?, ?)",
(trans_lang_id, orig_lang_id, new_translated_word_id, new_orig_word_id))
con.commit()
file.close()
return len(words)
<file_sep>-- CREATE TABLE users (id INTEGER, username TEXT NOT NULL, hash TEXT NOT NULL, cash NUMERIC NOT NULL DEFAULT 10000.00, PRIMARY KEY(id));
-- CREATE UNIQUE INDEX username ON users (username);
-- CREATE TABLE stocks (id INTEGER, symbol TEXT NOT NULL, name TEXT NOT NULL, PRIMARY KEY(id));
-- CREATE UNIQUE INDEX symbol ON stocks (symbol);
-- # CREATE TABLE portfolio (trans_id INTEGER, user_id INTEGER NOT NULL, stock_id INTEGER NOT NULL, count INTEGER, transaction_date DATETIME, PRIMARY KEY(trans_id));
-- CREATE TABLE portfolio (trans_id INTEGER, user_id INTEGER NOT NULL, stock_id INTEGER NOT NULL, count INTEGER, transaction_date DATETIME, price_per_share DECIMAL(19, 4), PRIMARY KEY(trans_id));
-- CREATE INDEX user_id ON portfolio (user_id);
-- CREATE INDEX stock_id ON portfolio (stock_id);
-- ALTER TABLE portfolio ADD price_per_share DECIMAL(19, 4);
CREATE TABLE `users` (
`id` integer,
`username` varchar(255) NOT NULL,
`full_name` varchar(255),
`password` <PASSWORD>,
`email` varchar(255),
`created_at` timestamp,
`last_login` timestamp,
`preferred_lang` integer,
`learning_lang` integer,
`active_pet_id` integer,
PRIMARY KEY(id)
);
CREATE UNIQUE INDEX username ON users (username);
CREATE TABLE `owners` (
`id` integer,
`owner_id` integer,
`pet_id` integer,
PRIMARY KEY(id)
);
CREATE TABLE `pets` (
`id` integer,
`type` integer,
`name` varchar(255),
`created` timestamp,
`exp` integer,
PRIMARY KEY(id)
);
CREATE TABLE `pet_types` (
`id` integer,
`imgsrc` varchar(255),
`pet_type` varchar(255),
`exp_required` integer,
PRIMARY KEY(id)
);
CREATE TABLE `word_sets` (
`id` integer,
`word_id` id,
`imgsrc` varchar(255),
PRIMARY KEY(id)
);
CREATE TABLE `words` (
`id` integer,
`wordstr` varchar(255),
`audiopath` varchar(255),
`language_id` integer,
`type` integer,
PRIMARY KEY(id)
);
CREATE TABLE `sets_learned` (
`id` integer,
`subject` varchar(255),
`user_id` integer,
`wordsets` integer,
`started` timestamp,
`completed` timestamp,
PRIMARY KEY(id)
);
CREATE TABLE `words_learned` (
`id` integer,
`user_id` integer,
`word` integer,
`sets_learned_id` integer,
`learned` boolean,
PRIMARY KEY(id)
);
CREATE TABLE `word_type` (
`id` integer,
`type` varchar(255),
PRIMARY KEY(id)
);
CREATE TABLE `word_translation` (
`id` integer,
`orig_lang` id,
`trans_lang` id,
`orig_word` id,
`trans_word` id,
PRIMARY KEY(id)
);
CREATE TABLE `languages` (
`id` integer,
`charcode` varchar(255),
`dir` varchar(255),
`name` varchar(255),
`bodyclass` varchar(255),
PRIMARY KEY(id)
);
CREATE TABLE `pet_types` (
`id` integer,
`imgsrc` varchar(255),
`pet_type` varchar(255),
PRIMARY KEY(id)
);
INSERT INTO `pet_types` (imgsrc, pet_type) values ('/pets/pet-wolf.png', 'Wolf');
INSERT INTO `pet_types` (imgsrc, pet_type) values ('/pets/pet-crow.png', 'Crow');
INSERT INTO `pet_types` (imgsrc, pet_type) values ('/pets/pet-gorilla.png', 'Gorilla');
-- ALTER TABLE `pets` ADD FOREIGN KEY (`id`) REFERENCES `owners` (`pet_id`);
-- ALTER TABLE `users` ADD FOREIGN KEY (`id`) REFERENCES `owners` (`owner_id`);
-- ALTER TABLE `pet_types` ADD FOREIGN KEY (`id`) REFERENCES `pets` (`type`);
-- ALTER TABLE `words` ADD FOREIGN KEY (`id`) REFERENCES `word_sets` (`word_id`);
-- ALTER TABLE `words` ADD FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`);
-- ALTER TABLE `words` ADD FOREIGN KEY (`language_id`) REFERENCES `users` (`preferred_lang`);
-- ALTER TABLE `words` ADD FOREIGN KEY (`language_id`) REFERENCES `users` (`learning_lang`);
-- ALTER TABLE `words_learned` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
-- ALTER TABLE `words_learned` ADD FOREIGN KEY (`word`) REFERENCES `words` (`id`);
-- ALTER TABLE `words_learned` ADD FOREIGN KEY (`sets_learned_id`) REFERENCES `sets_learned` (`id`);
-- ALTER TABLE `words` ADD FOREIGN KEY (`type`) REFERENCES `word_type` (`id`);
-- ALTER TABLE `word_translation` ADD FOREIGN KEY (`orig_lang`) REFERENCES `languages` (`id`);
-- ALTER TABLE `word_translation` ADD FOREIGN KEY (`trans_lang`) REFERENCES `languages` (`id`);
-- ALTER TABLE `word_translation` ADD FOREIGN KEY (`orig_word`) REFERENCES `words` (`id`);
-- ALTER TABLE `word_translation` ADD FOREIGN KEY (`trans_word`) REFERENCES `words` (`id`);
-- notes
-- pet needs active flag
INSERT INTO languages (charcode, dir, name) VALUES ('en', 'ltr', 'English');
INSERT INTO languages (charcode, dir, name) VALUES ('he', 'rtl', 'עברית');
CREATE TABLE `word_set_words` (
`id` integer,
`word_set_id` id,
`word_id` id,
PRIMARY KEY(id)
);
INSERT INTO word_sets (imgsrc, set_name) VALUES ("/sets/fruits.png", "פרי");
INSERT INTO word_type (type) VALUES ("noun");
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (2, 1, "Tapuch","תפוח");
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (2, 1, "Afarsek","אפרסק");
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (2, 1, "Shezif","שזיפ");
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (2, 1, "Mango","מנגו");
INSERT INTO word_set_words (word_set_id, word_id) VALUES (1, 1);
INSERT INTO word_set_words (word_set_id, word_id) VALUES (1, 2);
INSERT INTO word_set_words (word_set_id, word_id) VALUES (1, 3);
INSERT INTO word_set_words (word_set_id, word_id) VALUES (1, 4);
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (1, 1, "a-pl", "Apple");
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (1, 1, "peech", "Peach");
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (1, 1, "pluhm", "Plum");
INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (1, 1, "mang-go", "Mango");
INSERT INTO word_sets (imgsrc, set_name) VALUES ("/sets/fruits.png", "Fruits");
INSERT INTO word_set_words (word_set_id, word_id) VALUES (2, 5);
INSERT INTO word_set_words (word_set_id, word_id) VALUES (2, 6);
INSERT INTO word_set_words (word_set_id, word_id) VALUES (2, 7);
INSERT INTO word_set_words (word_set_id, word_id) VALUES (2, 8);
-- en to he
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (1, 2, 5, 1);
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (1, 2, 6, 2);
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (1, 2, 7, 3);
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (1, 2, 8, 4);
SELECT words.wordstr, words.pronunciation, word_type.type FROM words
JOIN word_set_words ON word_set_words.word_id = words.id
JOIN word_type ON words.type = word_type.id
where word_set_words.word_set_id = 1;
ALTER TABLE word_sets ADD COLUMN language_id integer;
update word_sets set language_id = 2 WHERE id = 1;
update word_sets set language_id = 1 WHERE id = 2;
UPDATE `pet_types` set imgsrc = '/pets/002-dragon.png', pet_type = 'Dragon', exp_required = 0 where id = 1;
UPDATE `pet_types` set imgsrc = '/pets/004-ufo.png', pet_type = 'UFO', exp_required = 0 where id = 2;
UPDATE `pet_types` set imgsrc = '/pets/005-robot.png', pet_type = 'Robot', exp_required = 0 where id = 3;
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/010-unicorn.png', 'Unicorn', 100);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/011-gnome.png', 'Gnome', 100);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/013-genie.png', 'Genie', 100);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/015-bigfoot.png', 'Bigfoot', 200);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/017-goblin.png', 'Goblin', 200);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/018-oni.png', 'Oni', 200);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/019-faun.png', 'Faun', 300);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/021-medusa.png', 'Medusa', 300);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/024-krampus.png', 'Krampus', 300);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/026-godzilla.png', 'Godzilla', 400);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/027-werewolf.png', 'Werewolf', 400);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/029-haunted.png', 'Haunted', 400);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/030-cyclops.png', 'Cyclops', 500);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/031-frog.png', 'Frog', 500);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/032-ogre.png', 'Ogre', 500);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/033-minotaur.png', 'Minotaur', 600);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/034-jackalope.png', 'Jackalope', 600);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/035-loch-ness-monster.png', 'Loch-ness Monster', 600);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/038-pegasus.png', 'Pegasus', 700);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/040-grim-reaper.png', 'Grim Reaper', 700);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/041-kraken.png', 'Kraken', 700);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/042-frankenstein.png', 'Frankenstein', 800);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/043-cerberus.png', 'Cerberus', 800);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/044-griffin.png', 'Griffin', 800);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/045-zombie.png', 'Zombie', 900);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/047-sphynx.png', 'Sphynx', 900);
INSERT INTO `pet_types` (imgsrc, pet_type, exp_required) values ('/pets/048-centaur.png', 'Centaur', 900);
-- updated table schema 2021/12/05
CREATE TABLE `users` (
`id` integer,
`username` varchar(255) NOT NULL,
`full_name` varchar(255),
`password` <PASSWORD>,
`email` varchar(255),
`created_at` timestamp,
`last_login` timestamp,
`preferred_lang` integer,
`learning_lang` integer, `active_pet_id` integer,
PRIMARY KEY(id)
);
CREATE UNIQUE INDEX username ON users (username);
CREATE TABLE `owners` (
`id` integer,
`owner_id` integer,
`pet_id` integer,
PRIMARY KEY(id)
);
CREATE TABLE `pets` (
`id` integer,
`type` integer,
`name` varchar(255),
`created` timestamp,
`exp` integer,
PRIMARY KEY(id)
);
CREATE TABLE `pet_types` (
`id` integer,
`imgsrc` varchar(255),
`pet_type` varchar(255), `exp_required` integer,
PRIMARY KEY(id)
);
CREATE TABLE `word_sets` (
`id` integer,
`imgsrc` varchar(255), set_name varchar, language_id integer,
PRIMARY KEY(id)
);
CREATE TABLE `words` (
`id` integer,
`wordstr` varchar(255),
`audiopath` varchar(255),
`language_id` integer,
`type` integer, pronunciation varchar,
PRIMARY KEY(id)
);
CREATE TABLE `sets_learned` (
`id` integer,
`subject` varchar(255),
`user_id` integer,
`wordsets` integer,
`started` timestamp,
`completed` timestamp,
PRIMARY KEY(id)
);
CREATE TABLE `words_learned` (
`id` integer,
`user_id` integer,
`word` integer,
`sets_learned_id` integer,
`learned` boolean,
PRIMARY KEY(id)
);
CREATE TABLE `word_type` (
`id` integer,
`type` varchar(255),
PRIMARY KEY(id)
);
CREATE TABLE `word_translation` (
`id` integer,
`orig_lang` id,
`trans_lang` id,
`orig_word` id,
`trans_word` id,
PRIMARY KEY(id)
);
CREATE TABLE `languages` (
`id` integer,
`charcode` varchar(255),
`dir` varchar(255),
`name` varchar(255),
`bodyclass` varchar(255),
PRIMARY KEY(id)
);
CREATE TABLE `word_set_words` (
`id` integer,
`word_set_id` id,
`word_id` id,
PRIMARY KEY(id)
);
CREATE TABLE `word_images` (
`id` integer,
`imgsrc` varchar,
PRIMARY KEY(id)
);
insert into word_images (imgsrc) values ('/words/fruit/apple.png');
insert into word_images (imgsrc) values ('/words/fruit/cherries.png');
insert into word_images (imgsrc) values ('/words/fruit/plums_b.png');
insert into word_images (imgsrc) values ('/words/fruit/tomato.png');
insert into word_images (imgsrc) values ('/words/fruit/berries_05_b.png');
insert into word_images (imgsrc) values ('/words/fruit/peach.png');
insert into word_images (imgsrc) values ('/words/fruit/pomegranate.png');
insert into word_images (imgsrc) values ('/words/fruit/watermelon.png');
SELECT words.wordstr, words.pronunciation, word_type.type, word_images.imgsrc FROM words JOIN word_set_words ON word_set_words.word_id = words.id JOIN word_type ON words.type = word_type.id
JOIN word_images ON words.imgsrc_id = word_images.id where word_set_words.word_set_id = 1
SELECT word_sets.id, words.wordstr, words.id, word_sets.imgsrc FROM word_sets
JOIN words ON word_sets.set_name_word_id = words.id
WHERE word_sets.language_id = 2;
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (1, 2, 10, 9);
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (2, 1, 9, 10);
-- he to en missing
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (2, 1, 1, 5);
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (2, 1, 2, 6);
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (2, 1, 3, 7);
INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (2, 1, 4, 8);<file_sep>Flask
Flask-Session
Flask-Babel
requests
redis
uwsgi
# Heroku
gunicorn
gevent
<file_sep>import sqlite3
import redis
from flask import redirect, render_template, session
from functools import wraps
con = sqlite3.connect("distantlife.db")
con.row_factory = sqlite3.Row
db = con.cursor()
r = redis.StrictRedis(host="127.0.0.1", port=6379, db=0)
def apology(message, code=400):
"""Render message as an apology to user."""
return render_template("apology.html", message=message, code=code)
def login_required(f):
"""
Decorate routes to require login.
https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session_get_int("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
"""
Decorate routes to require admin role.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
roles = db.execute(
"SELECT roles FROM users WHERE id = ?", (session_get_int('user_id'), )).fetchall()
if len(roles) != 1:
return apology("invalid user id", 403)
else:
if (int(roles[0]['roles']) != 9):
# Not Admin
return redirect("/")
return f(*args, **kwargs)
return decorated_function
def usd(value):
"""Format value as USD."""
return f"${value:,.2f}"
def set_active_pet_in_session(user_id):
"""
Query a user for their active pet and set it in the Session
:param int user_id - user's ID
:returns:
- id of active pet
"""
active_pet_info = db.execute("SELECT pets.id, name, pet_types.pet_type, exp, pet_types.imgsrc FROM pets JOIN users ON users.active_pet_id = pets.id JOIN pet_types ON pet_types.id = pets.type WHERE users.id = ?",
(user_id, )).fetchall()
if (len(active_pet_info) == 1):
active_pet = {
"name": active_pet_info[0]['name'],
"type": active_pet_info[0]['pet_type'],
"exp": active_pet_info[0]['exp'],
"id": active_pet_info[0]['id'],
"imgsrc": active_pet_info[0]['imgsrc']
}
session["active_pet"] = active_pet
return active_pet['id']
def set_languages(user_id):
"""
Query the preferred and targeted learning languages given a user's id and add them to the session for the language key
:param int user_id - user's ID
"""
language_info = db.execute("SELECT preferred_lang, learning_lang, dir, charcode, localization FROM users JOIN languages ON users.preferred_lang = languages.id WHERE users.id = ?",
(user_id, )).fetchall()
if (len(language_info) == 1):
language = {
"preferred": language_info[0]['preferred_lang'],
"learning": language_info[0]['learning_lang'],
"dir": language_info[0]['dir'],
"charcode": language_info[0]['charcode'],
"localization": language_info[0]['localization']
}
session["language"] = language
return True
def get_word_translation(word_id, orig_lang='', trans_lang=''):
"""
Given word_id, returns translated word in original (native) language
:param int word_id - word ID in translated language
:param int orig_lang - the language to return the given word in
:param int trans_lang - the language the word is in
:returns:
- string - word translated into orig_lang
"""
if (orig_lang == ''):
orig_lang = session.get('language')['preferred']
if (trans_lang == ''):
trans_lang = session.get('language')['learning']
translation = db.execute("SELECT wordstr FROM words where id = (SELECT word_translation.trans_word FROM words JOIN word_translation ON word_translation.orig_word = words.id WHERE words.id = ? AND word_translation.trans_lang = ? AND word_translation.orig_lang = ?)",
(word_id, orig_lang, trans_lang, )).fetchall()
return translation[0]['wordstr']
def get_sets(language_id='', trans_lang=''):
"""
Returns all word sets for a given language
:param int language_id - the language to return the given word in
:param int trans_lang - the language the word is in
:returns:
- list of words
"""
if (trans_lang == ''):
trans_lang = session.get('language')['learning']
if (language_id == ''):
language_id = session.get('language')['preferred']
setsqry = db.execute("SELECT word_sets.id as id, words.wordstr as wordstr, words.id as setnameid, word_sets.imgsrc FROM word_sets JOIN words ON word_sets.set_name_word_id = words.id WHERE word_sets.language_id = ?",
(trans_lang, )).fetchall()
sets = []
for setinfo in setsqry:
translation = get_word_translation(
int(setinfo['setnameid']), language_id, trans_lang)
totalcount = db.execute(
"select count(*) as count from word_set_words where word_set_id = ?",
(setinfo['id'], )).fetchall()
setinfo = {
"id": setinfo['id'],
"set_name": setinfo['wordstr'],
"imgsrc": setinfo['imgsrc'],
"totalcount": totalcount[0]['count'],
"translation": translation
}
sets.append(setinfo)
return sets
def get_set_by_id(set_id):
"""
Returns set information for a specific word set
:param int set_id: word set ID
:returns:
- id - word set ID
- wordstr - name of word set
- setnameid - word ID of wordstr
- imgsrc - image path for set cover image
"""
setsqry = db.execute("SELECT word_sets.id as id, words.wordstr as wordstr, words.id as setnameid, word_sets.imgsrc FROM word_sets JOIN words ON word_sets.set_name_word_id = words.id WHERE word_sets.language_id = ? AND word_sets.id = ?",
(session.get('language')['learning'], set_id, )).fetchall()
return setsqry[0]
def get_words_by_set_id(set_id):
"""
Returns all words in a single set
:param int set_id: word set ID
:returns:
- list of words
"""
words = db.execute("SELECT words.id, words.wordstr, words.pronunciation, word_type.type FROM words JOIN word_set_words ON word_set_words.word_id = words.id JOIN word_type ON words.type = word_type.id where word_set_words.word_set_id = ?",
(set_id, )).fetchall()
return words
def get_role():
"""
Returns the role of the active user
:returns:
- integer - role ID
"""
rolesqry = db.execute(
"SELECT roles FROM users WHERE id = ?", (session_get_int('user_id'), )).fetchall()
role = rolesqry[0]['roles']
return role
def session_get_int(key):
"""
Returns the value of a stored session variable converted to integer
:returns:
- integer
"""
if session.get(key) is not None:
return int(session.get(key))
else:
return None
def update_experience(amount):
"""
Updates the experience by the given amount
:param int amount: experience amount to increase or decrease
:returns:
- int - a pet's total experience including the added amount
"""
activepetqry = db.execute(
"SELECT active_pet_id FROM users WHERE id = ?", (session_get_int('user_id'), )).fetchone()
print(activepetqry['active_pet_id'])
active_pet_id = int(activepetqry['active_pet_id'])
expqry = db.execute("SELECT exp FROM pets WHERE id = ?", (active_pet_id, )).fetchall()
exp = int(expqry[0]['exp']) + int(amount)
updateqry = db.execute(
"UPDATE pets SET exp = ? WHERE id = ?", (exp, active_pet_id))
con.commit()
if (updateqry.rowcount > 0):
session.get("active_pet")["exp"] = exp
return exp
else:
return 0
<file_sep>{% extends "layout.html" %}
{% block title %}
{{ _('Edit Sets') }}
{% endblock %}
{% block main %}
<header>
<div class="main-options">
<h1>{{title_s}}</h1>
</div>
</header>
<table class="table-responsive-stack">
<thead>
<tr>
<th class="table-img"><span class="sr-only">{{ _('Icon') }}</span></th>
<th>{{ _('Word Set') }}</th>
<th>{{ _('Count') }}</th>
<th>{{ _('Options') }}</th>
</tr>
</thead>
<tbody>
{% for set in sets %}
<tr>
<td>
<img src="{{ url_for('static', filename=set.imgsrc) }}" alt="{{set.set_name}}">
</td>
<td><a href="/edit/set/?s={{set.id}}">
<strong>{{set.translation}}</strong> ({{set.set_name}})</a></td>
<td>{{set.totalcount}} words</td>
<td>
<form method="get" action="/edit/set/?s={{set.id}}">
<input name="set_id" type="hidden" value="{{set.id}}" />
<button class="btn btn-secondary" type="submit" value="{{ _('Edit') }}">
<span class="fal fa-pencil"></span>
<span class="sr-only">{{ _('Edit') }}</span>
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if role == 9 %}
<p class="text-center">
<a class="btn btn-primary" href="/create/set/">{{ _('Create new set') }}</a>
</p>
{% endif %}
{% endblock %}
<file_sep>import os
import random
import redis
import sqlite3
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from flask_babel import Babel
from helpers import apology, login_required, admin_required, usd, set_active_pet_in_session, set_languages, get_sets, get_set_by_id, get_words_by_set_id, get_role, get_word_translation, update_experience, session_get_int
from fileparser import save_words
# default it runs on port 6379
r = redis.StrictRedis(host="0.0.0.0", port=6379, db=0)
app = Flask(__name__)
babel = Babel(app)
app.config["TEMPLATES_AUTO_RELOAD"] = True
LANGUAGES = {
'en': 'English',
'he': 'Hebrew'
}
app.config['LANGUAGES'] = LANGUAGES
if __name__ == "__main__":
app.run(host='0.0.0.0')
@babel.localeselector
def get_locale():
"""Set localization for text keys"""
if (session.get("language") is not None):
return session.get('language')['charcode']
return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
UPLOAD_FOLDER = 'static/files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.jinja_env.filters["usd"] = usd
app.config["SESSION_FILE_DIR"] = mkdtemp()
# TODO
# Details on the Secret Key: https://flask.palletsprojects.com/en/1.1.x/config/#SECRET_KEY
# NOTE: The secret key is used to cryptographically-sign the cookies used for storing
# the session identifiesession.
app.secret_key = 'DL_SESSION_KEY'
# Configure Redis for storing the session data on the server-side
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_REDIS'] = redis.from_url('redis://0.0.0.0:6379')
Session(app)
con = sqlite3.connect("distantlife.db")
con.row_factory = sqlite3.Row # Includes column name in return dictionary
db = con.cursor()
@app.route("/")
def index():
"""Landing page for visitors, dashboard for registered users"""
if (session_get_int("user_id") is not None):
return render_template("dashboard.html")
else:
return render_template("index.html")
@app.route("/pets")
@login_required
def pets():
"""Lists all of user's pets"""
pets_owned = db.execute("SELECT pets.id, pet_types.imgsrc, pet_types.pet_type, pets.created, pets.exp, pets.name, users.active_pet_id FROM owners JOIN pets ON pets.id = owners.pet_id JOIN pet_types ON pets.type = pet_types.id JOIN users ON users.id = owners.owner_id WHERE owner_id = ?", (session_get_int("user_id"), )).fetchall()
return render_template("list.html", pets_owned=pets_owned)
@app.route("/train")
@login_required
def train():
"""Lists available word sets to learn and test on"""
role = get_role()
sets = get_sets()
return render_template("train.html", sets=sets, role=role)
@app.route("/train/set/")
@login_required
def trainset():
"""Allows a user to learn a set of words, one word at a time"""
tset = int(request.args.get('s'))
page = 0
if request.args.get('page') is not None:
page = int(request.args.get('page'))
if tset is not None:
words = get_words_by_set_id(tset)
set_info = db.execute(
"SELECT id, imgsrc FROM word_sets WHERE id = ?", (tset, )).fetchall()
return render_template("trainset.html", words=words, set_info=set_info, page=page, tset=tset)
else:
return redirect('/train')
@app.route("/edit/set/")
@login_required
@admin_required
def edit_set():
"""Admin: Allows an admin to edit word sets"""
role = get_role()
if request.args.get('set_id') is not None:
set_id = int(request.args.get('set_id'))
set_info = get_set_by_id(set_id)
words = get_words_by_set_id(set_id)
sets = get_sets(session.get('language')[
'learning'], session.get('language')['preferred'])
return render_template("editset.html", set_info=set_info, role=role, words=words, sets=sets)
else:
sets = get_sets()
return render_template("editsets.html", sets=sets, role=role)
@app.route("/quiz/set/", methods=["GET", "POST"])
@login_required
def quizset():
"""Shows a quiz for a given set of words, one word at a time. Experience is added on completion."""
if request.method == "POST":
experience = 0
if request.form.get('experience') is not None:
experience = int(request.form.get('experience'))
if request.form.get("finished"):
# Process exp
if (experience > 0):
# Add experience to active pet
update_experience(experience)
flash("Gained " + str(experience) + " experience!")
return redirect('/train')
elif request.form.get("set_id"):
set_id = int(request.form.get('set_id'))
page = 0
if request.form.get('page') is not None:
page = int(request.form.get('page'))
if set_id is not None:
words = get_words_by_set_id(int(set_id))
set_info = db.execute(
"SELECT id, imgsrc FROM word_sets WHERE id = ?", (set_id, )).fetchall()
activeword = words[page]
word_options = []
# Pull alternate word choices
for w in words:
# Don't duplicate answer word
if w['id'] != activeword['id']:
word_options.append({
'word': get_word_translation(w['id']),
'data': 'error',
'translation': w['wordstr']
})
# Shuffle and limit alternate answers to 3
random.shuffle(word_options)
if (len(word_options) > 3):
word_options = word_options[0:3]
# Add correct answer to the array of answers
word_options.append({
'word': get_word_translation(activeword['id']),
'data': 'success',
'translation': activeword['wordstr']
})
random.shuffle(word_options)
return render_template("quizset.html", words=words, word_options=word_options, set_info=set_info, page=page, set_id=set_id, experience=experience)
else:
return redirect('/train')
# GET
else:
return redirect('/train')
@app.route("/create/set/", methods=["GET", "POST"])
@login_required
@admin_required
def createset():
"""Admin: Allows an admin to create a new set"""
if request.method == "POST":
if request.form.get('setname') is not None:
setname = request.form.get('setname')
learning_lang = request.form.get('learning_lang')
plang_setname = request.form.get('plang_setname')
preferred_lang = request.form.get('preferred_lang')
# Sets will usually be a noun
learning_wordid = (db.execute("INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (?, ?, ?, ?)",
(learning_lang, 1, '', setname, ))).lastrowid
con.commit()
preferred_wordid = (db.execute("INSERT INTO words (language_id, type, pronunciation, wordstr) VALUES (?, ?, ?, ?)",
(preferred_lang, 1, '', plang_setname, ))).lastrowid
con.commit()
db.execute("INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (?, ?, ?, ?)",
(preferred_lang, learning_lang, preferred_wordid, learning_wordid, )).fetchall()
db.execute("INSERT INTO word_translation (orig_lang, trans_lang, orig_word, trans_word) VALUES (?, ?, ?, ?)",
(learning_lang, preferred_lang, learning_wordid, preferred_wordid, )).fetchall()
con.commit()
# TODO Set a default image here
insert_word_set = (db.execute("INSERT INTO word_sets (imgsrc, set_name_word_id, language_id) VALUES (?, ?, ?)",
("/sets/fruits.png", learning_wordid, learning_lang, ))).lastrowid
con.commit()
insert_word_set_orig = (db.execute("INSERT INTO word_sets (imgsrc, set_name_word_id, language_id) VALUES (?, ?, ?)",
("/sets/fruits.png", preferred_wordid, preferred_lang, ))).lastrowid
con.commit()
if (insert_word_set > 0):
flash("New set created: " + setname)
if (insert_word_set_orig > 0):
flash("New set created: " + plang_setname)
else:
flash("Error creating new set")
sets = get_sets()
return render_template("editsets.html", sets=sets)
else:
language_options = db.execute("SELECT * FROM languages").fetchall()
userinfo = db.execute(
"SELECT username, id, preferred_lang, learning_lang, created_at, email, full_name FROM users WHERE id = ?", (session_get_int("user_id"), )).fetchall()
return render_template("createset.html", language_options=language_options, userinfo=userinfo[0])
@app.route("/delete/word_set_word/", methods=["POST"])
@login_required
@admin_required
def delete_word():
"""Admin: Deletes word from word set only"""
if request.method == "POST":
if request.form.get('word_id') is not None:
if request.form.get('word_set_id') is not None:
# delete word from word_sets
deleteqry = db.execute("DELETE FROM word_set_words WHERE word_id = ? and word_set_id = ?",
(request.form.get("word_id"), request.form.get("word_set_id")))
con.commit()
if (deleteqry.rowcount > 0):
flash('delete successful')
return redirect("/edit/set")
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
if request.method == "POST":
if not request.form.get("username"):
return apology("must provide username", 403)
elif not request.form.get("password"):
return apology("must provide password", 403)
rows = db.execute("SELECT * FROM users WHERE username = ?",
(request.form.get("username"), )).fetchall()
if len(rows) != 1 or not check_password_hash(rows[0]["password"], request.form.get("password")):
return apology("invalid username and/or password", 403)
session["user_id"] = int(rows[0]["id"])
session["username"] = request.form.get("username")
set_active_pet_in_session(session_get_int("user_id"))
set_languages(session_get_int("user_id"))
return redirect("/")
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
session.clear()
r.flushdb()
return redirect("/")
@app.route("/signup", methods=["GET", "POST"])
def signup():
"""Sign up user"""
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
password2 = request.form.get("confirmation")
if not username:
return apology("must provide username", 400)
elif not password:
return apology("must provide password", 400)
elif not (password == password2):
return apology("passwords must match", 400)
elif not password2:
return apology("must confirm password", 400)
rows = db.execute("SELECT * FROM users WHERE username = ?", (username, )).fetchall()
if len(rows) != 1:
lastrow = (db.execute("INSERT INTO users(username, password, created_at, preferred_lang, learning_lang, roles) VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)",
(username, generate_password_hash(password), 1, 2, 1, ))).lastrowid
con.commit()
session["user_id"] = lastrow
session["username"] = username
set_languages(session["user_id"])
return redirect("/")
else:
return apology("username already taken", 400)
else:
return render_template("signup.html")
@app.route("/about")
def about():
"""About page"""
return render_template("about.html")
@app.route("/profile", methods=["GET"])
@login_required
def profile():
"""User Profile"""
userinfo = db.execute(
"SELECT username, id, preferred_lang, learning_lang, created_at, email, full_name FROM users WHERE id = ?", (session_get_int("user_id"), )).fetchall()
language_options = db.execute("SELECT * FROM languages").fetchall()
if (len(userinfo) > 0):
return render_template("profile.html", userinfo=userinfo[0], usd=usd, language_options=language_options)
return apology("error accessing profile", 400)
@app.route("/uploadwordset", methods=["GET", "POST"])
@login_required
@admin_required
def uploadFiles():
"""Admin: Allows an admin to upload a CSV to add more words to a word set"""
if request.method == "POST":
uploaded_file = request.files['file']
if request.form.get("word_set_id"):
word_set_id = request.form.get("word_set_id")
if uploaded_file.filename != '':
# Set the file path and save
file_path = os.path.join(
app.config['UPLOAD_FOLDER'], uploaded_file.filename)
uploaded_file.save(file_path)
if request.form.get("additional_set"):
orig_set_id = request.form.get("additional_set")
num_words = save_words(file_path, word_set_id, orig_set_id)
else:
num_words = save_words(file_path, word_set_id)
flash(str(num_words) + " words added to word set")
# Delete file from static after parsing
if os.path.exists(file_path):
os.remove(file_path)
return redirect("/edit/set/?set_id=" + word_set_id)
return redirect("/")
else:
return redirect("/")
@app.route("/pets/edit/", methods=["GET", "POST"])
@login_required
def petedit():
"""Allows a user to rename a pet in their account"""
if request.method == "POST":
pet_id = request.form.get("pet_id")
rename = request.form.get("rename")
rows = db.execute("SELECT count(*) as count FROM owners WHERE owner_id = ? AND pet_id = ?",
(session_get_int("user_id"), pet_id, )).fetchall()
# Confirmed user owns this pet
if rows[0]['count'] == 1:
exp = db.execute("SELECT exp FROM pets WHERE id = ?", (pet_id, )).fetchall()
if (int(exp[0]['exp']) >= 100):
db.execute("UPDATE pets SET name = ? WHERE id = ?", (rename, pet_id, ))
con.commit()
# Put updated info into session for pet
set_active_pet_in_session(session_get_int("user_id"))
flash("Pet renamed to " + rename)
else:
return apology("Your pet needs at least 100 experience to be renamed!", 403)
return redirect('/pets/edit/?id='+ str(pet_id))
else:
pet_id = int(request.args.get('id'))
# This ensures the current user owns the pet being renamed
pet_info = db.execute("SELECT pets.id, pet_types.imgsrc, pet_types.pet_type, pets.created, pets.exp, pets.name, users.active_pet_id FROM owners JOIN pets ON pets.id = owners.pet_id JOIN pet_types ON pets.type = pet_types.id JOIN users ON users.id = owners.owner_id WHERE owner_id = ? AND pet_id = ?",
(session_get_int("user_id"), pet_id, )).fetchall()
if len(pet_info) == 1:
return render_template("petedit.html", pet_info=pet_info)
else:
return apology("Error getting pet info", 403)
@app.route("/updatelanguage", methods=["GET", "POST"])
@login_required
def updatelanguage():
"""User Profile - change preference for native and learning language"""
if request.method == "POST":
preferred_lang = request.form.get("orig_language")
learning_lang = request.form.get("learning_lang")
if (preferred_lang == learning_lang):
return apology("Preferred language and learning language cannot be the same :)", 400)
db.execute("UPDATE users SET preferred_lang = ? WHERE id = ?",
(preferred_lang, session_get_int("user_id"), ))
con.commit()
db.execute("UPDATE users SET learning_lang = ? WHERE id = ?",
(learning_lang, session_get_int("user_id"), ))
con.commit()
set_languages(session_get_int("user_id"))
return redirect("/profile")
else:
return redirect("/profile")
@app.route("/updatepassword", methods=["GET", "POST"])
@login_required
def updatepassword():
"""User Profile - allows a user to change their password"""
if request.method == "POST":
password = request.form.get("password")
password2 = request.form.get("confirmation")
if not password:
return apology("must provide password", 400)
elif not (password == password2):
return apology("passwords must match", 400)
elif not password2:
return apology("must confirm password", 400)
rows = db.execute(
"SELECT password FROM users WHERE id = ?", (session_get_int("user_id"), )).fetchall()
if (check_password_hash(rows[0]["password"], password)):
return apology("password cannot be the same as existing password", 400)
else:
db.execute("UPDATE users SET password = ? WHERE id = ?",
(generate_password_hash(password), session_get_int("user_id")))
con.commit()
return redirect("/profile")
else:
return redirect("/profile")
@app.route("/adopt", methods=["GET", "POST"])
@login_required
def adopt():
"""Allows a user to add a new pet to their account """
if request.method == "POST":
# Check if user bought a pet
if not request.form.get("pet_type"):
return apology("must choose pet type", 403)
pet_type_id = int(request.form.get("pet_type"))
petname = db.execute(
"SELECT pet_type FROM pet_types WHERE id = ?", (pet_type_id, )).fetchall()
# Create pet with default name as pet type
petid = (db.execute("INSERT INTO pets(type, name, exp, created) VALUES (?, ?, ?, CURRENT_TIMESTAMP)",
(pet_type_id, petname[0]['pet_type'], 0 ))).lastrowid
con.commit()
# Add owner to pet
db.execute("INSERT INTO owners(owner_id, pet_id) VALUES (?, ?)",
(session_get_int("user_id"), petid))
con.commit()
# Set as user's active pet
db.execute("UPDATE users SET active_pet_id = ? WHERE id = ?",
(petid, session_get_int("user_id") ))
con.commit()
set_active_pet_in_session(session_get_int("user_id"))
return redirect("/pets")
else:
rows = db.execute("SELECT * FROM pet_types").fetchall()
if len(rows) < 1:
return apology("no pets", 403)
return render_template("adopt.html", pet_types=rows)
@app.route("/abandon/")
@login_required
def abandon():
"""Allows a user to remove a pet from their account"""
pet_id = int(request.args.get('id'))
# TODO
# Check that active pet is not the one being deleted
# print("SELECT active_pet_id FROM users WHERE id = ?",
# session_get_int("user_id"))
# Delete pet from pet owners
# This ensures the current user owns the pet being abandoned
rows = db.execute("DELETE FROM owners WHERE owner_id = ? AND pet_id = ?",
(session_get_int("user_id"), pet_id ))
con.commit()
if rows.rowcount == 1:
db.execute("DELETE FROM pets WHERE id = ?", (pet_id, ))
con.commit()
else:
return apology("Error abandoning pet", 403)
# TODO
# If active pet is deleted pet, change a different pet to active pet
# db.execute("UPDATE users SET active_pet_id = ? WHERE id = ?",
# petid, session_get_int("user_id"))
# set_active_pet_in_session(session_get_int("user_id"))
return redirect('/pets')
@app.route("/activate/")
@login_required
def activate():
"""Allows a user to change their active pet"""
pet_id = int(request.args.get('id'))
db.execute("UPDATE users SET active_pet_id = ? WHERE id = ?",
(pet_id, session_get_int("user_id"), ))
con.commit()
set_active_pet_in_session(session_get_int("user_id"))
return redirect('/pets')
def errorhandler(e):
"""Handle error"""
if not isinstance(e, HTTPException):
e = InternalServerError()
return apology(e.name, e.code)
for code in default_exceptions:
app.errorhandler(code)(errorhandler)
| 53b269b01407c637d22bd1326a85098606f701c4 | [
"SQL",
"HTML",
"Markdown",
"Python",
"Text"
] | 8 | Markdown | virtual/distantlife | 90e7ed5e6430c5861632505cee773897aaf97428 | f2e88d6555e885a35b7c50e0f7ab223ececc357f |
refs/heads/master | <file_sep>import React from "react";
import { Row, Col, Layout } from "antd";
const { Content } = Layout;
const Restricted = () => {
return (
<Row justify="center" style={{ height: "80vh" }}>
<Col span={23}>
<Content>
<h1>Access to this page restricted</h1>
</Content>
</Col>
</Row>
);
};
export default Restricted;
<file_sep>import React, { useEffect, useState, useContext } from "react";
import { Card, Col, Row, Tag, Select, Pagination, Layout } from "antd";
import { Link } from "react-router-dom";
import { SearchContext } from "../../contexts/searchContext";
import FilterBox from "../FilterBox";
import config from "../../config";
import moment from "moment";
import CardSkeleton from "../Skeletons/Card";
const { CheckableTag } = Tag;
const { Sider, Content } = Layout;
export default function VideoSelectionPage() {
const [videoData, setVideoData] = useState();
const { searchUrl } = useContext(SearchContext);
const { tagState, handleTagChange, paging, setPaging } = useContext(
SearchContext
);
const [total, setTotal] = useState(0);
//pagination page count + population for pages
useEffect(() => {
const getPaginationData = async () => {
const countRes = await fetch(config.BACKEND_URL_SEARCH_VIDEO_COUNT);
const countData = await countRes.json();
setTotal(countData[0].count);
const pagRes = await fetch(
config.BACKEND_URL_SEARCH_PAGINATION +
`position=${paging.position}&paging=${paging.paging}`
);
const pagData = await pagRes.json();
setVideoData(pagData);
};
if (!searchUrl) {
getPaginationData();
}
}, [paging]);
//search for text, tags, weeks, lecturers
useEffect(() => {
async function getSearchData() {
const response = await fetch(config.BACKEND_URL_SEARCH + searchUrl);
const data = await response.json();
setVideoData(data);
}
if (searchUrl) {
getSearchData();
}
}, [searchUrl]);
return (
<Row justify="center">
<Col span={23}>
<Layout>
<Sider width={266} theme="light">
<FilterBox />
</Sider>
<Content style={{ backgroundColor: "#fff" }}>
{!!!searchUrl && (
<Pagination
onChange={(page, pageSize) => {
setPaging({ position: page, paging: pageSize });
}}
total={total}
current={paging.position}
pageSize={paging.paging}
defaultCurrent={1}
defaultPageSize={15}
responsive={true}
pageSizeOptions={[15, 20, 25]}
style={{ marginBottom: "8px" }}
showSizeChanger
/>
)}
<ul
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))",
position: "relative",
padding: "0",
listStyle: "none",
}}
>
{videoData ? (
videoData.map((data) => {
return (
<li
key={data.id}
style={{
padding: "0",
listStyle: "none",
minWidth: "150px",
maxWidth: "600px",
marginRight: "1.5em",
marginBottom: "3em",
}}
>
<Card
bodyStyle={{ padding: "3px 3px" }}
bordered={false}
cover={
<Link
to={`/videoviewer/${data.id}`}
style={{ position: "relative" }}
>
<img
alt={data.title}
src={data.thumbnail_url}
style={{
width: "100%",
margin: "0px",
padding: "0px",
}}
/>
<div
style={{
position: "absolute",
right: "0.5em",
bottom: "0.5em",
color: "#fff",
backgroundColor: "#40a9ff",
padding: "2px 6px",
borderRadius: "3px",
}}
>{`Week ${data.bootcamp_week}`}</div>
</Link>
}
>
<h3 style={{ marginBottom: 0 }}>{data.title}</h3>
<p style={{ marginBottom: 10 }}>
{data.lecturer} on{" "}
{moment(data.lecture_date).format("DD MMM YYYY")}
</p>
{data.tags.map((tag) => (
<CheckableTag
key={tag}
checked={tagState.selectedTags.indexOf(tag) > -1}
onChange={(checked) => {
handleTagChange(tag, checked);
}}
style={{
userSelect: "none",
margin: "0px",
padding: "0px 3px",
border: "none",
fontSize: "1em",
color:
tagState.selectedTags.indexOf(tag) > -1
? "#fff"
: "#40a9ff",
}}
>
{`#${tag}`}
</CheckableTag>
))}
</Card>
</li>
);
})
) : (
<CardSkeleton count={16} />
)}
</ul>
</Content>
</Layout>
</Col>
</Row>
);
}
//<Tag key={tag}>{tag}</Tag>
<file_sep>import React, { useState } from "react";
import { Button, Dropdown } from "antd";
import { MenuOutlined } from "@ant-design/icons";
import CmsMenu from "../CoachCMSMenu";
const CmsDropdown = ({
toggleTagDisplay,
toggleLecturerDisplay,
switchVideoMode,
modeSelector,
updateVideoSelectPageOutput,
}) => {
const [dropdownVisible, setDropdownVisible] = useState(false);
const toggleVisible = () => {
setDropdownVisible(!dropdownVisible);
};
return (
<Dropdown
overlay={
<CmsMenu
toggleTagDisplay={toggleTagDisplay}
toggleLecturerDisplay={toggleLecturerDisplay}
toggleVisible={toggleVisible}
switchVideoMode={switchVideoMode}
modeSelector={modeSelector}
updateVideoSelectPageOutput={updateVideoSelectPageOutput}
/>
}
visible={dropdownVisible}
onVisibleChange={toggleVisible}
trigger="click"
>
<Button size="middle" type="primary" block>
<MenuOutlined />
Tools
</Button>
</Dropdown>
);
};
export default CmsDropdown;
<file_sep>import React, { useEffect, useState } from "react";
import app from "./Base.js";
import { Spin } from "antd";
import config from "../config";
export const AuthContext = React.createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [pending, setPending] = useState(true);
const [isAdmin, setIsAdmin] = useState(false);
const [adminUsers, setAdminUsers] = useState(false);
useEffect(() => {
app.auth().onAuthStateChanged((user) => {
setCurrentUser(user);
setPending(false);
});
}, []);
useEffect(() => {
const getAdminUsers = async () => {
const res = await fetch(config.BACKEND_URL_GET_ADMIN_USERS);
const users = await res.json();
setAdminUsers(users);
};
if (!adminUsers) {
getAdminUsers();
}
}, []);
useEffect(() => {
if (currentUser) {
setIsAdmin(adminUsers.some((user) => currentUser.email === user.email));
}
}, [currentUser]);
if (pending) {
return <Spin />;
}
return (
<AuthContext.Provider
value={{
currentUser,
isAdmin,
}}
>
{children}
</AuthContext.Provider>
);
};
<file_sep>import React, { useState } from "react";
import "antd/dist/antd.css";
import "./style.css";
import { Modal, Button, Input, message } from "antd";
import config from "../../config";
const { TextArea } = Input;
//Feedback success messages. Edit these to display different messages depending the success of the feedback form submit.
function successMsg() {
//Displays on feedback success
message.success("Thanks for your feedback!");
}
function errorMsg() {
//Displays on feedback error
message.error("An error occured. Please try again.");
}
//Sets whether or not the modal is visable
export default function FeedbackModal() {
//Gets the video id from the url
let url = window.location.href; //gets the whole url
let split = url.split("/"); //splits the url into an array by /
let ref = split[split.length - 1]; //Collects the last part of the array, which in this case will be the video id that is displaying on this page
const [isModalVisible, setIsModalVisible] = useState(false);
const [feedback, setFeedback] = useState("");
//Posts the feedback to the database
function postFeedback(value) {
if (!value.videoId) {
errorMsg();
} else {
//Value is the feedback to be submitted
fetch(`${config.BACKEND_URL_FEEDBACK_UPDATE}`, {
//Change this url on deployment
method: "post",
body: JSON.stringify({
videoId: value.videoId, //Taken from ref - see feedbackToSubmit below
feedback: value.feedback,
}),
headers: { "Content-Type": "application/json" },
//Validation: ContentType
})
.then((res) => res.json()) //res.json() is an async function
.then((data) => {
setFeedback(""); //Resets the form
setIsModalVisible(false); //closes the modal
successMsg(); //message confirming to the user that the feedback has gone through
})
.catch((error) => {
errorMsg(); //message alerting user that there has been an error and they may need to try again
}); //uncaught promise rejection. The promise throws and error and I need to catch otherwise it will be thrown into the ether
}
}
//This function changes the feedback state to whatever is inserted into the feedback textbox onChange
function handleChange(e) {
// e.preventDefault();
if (e.target.id === "feedback") {
setFeedback(e.target.value);
}
}
//handleSubmit takes the feedback state, and the video id (from params; see "ref" above) and posts it to postFeedback as an object
function handleSubmit(e) {
e.preventDefault();
const feedbackToSubmit = {
videoId: ref,
feedback: feedback,
};
postFeedback(feedbackToSubmit);
}
const showModal = () => {
//Sets modal visibility to true
setIsModalVisible(true);
};
const handleCancel = () => {
//Sets modal visibility to false, used if the user has pressed cancel
setIsModalVisible(false);
};
return (
<>
<Button type="primary" onClick={showModal}>
Give Feedback
</Button>
<Modal
title="Give Feedback on this lecture"
visible={isModalVisible}
onOk={handleSubmit}
onCancel={handleCancel}
>
<div>
<div id="feedback-form-container">
<form>
<TextArea
id="feedback"
placeholder="Insert Feedback"
value={feedback}
onChange={handleChange}
/>
</form>
</div>
</div>
</Modal>
</>
);
}
<file_sep>import React, { useState, useEffect } from "react";
import {
Pagination,
Spin,
Card,
Modal,
Popover,
Tooltip,
Skeleton,
Popconfirm,
Layout,
} from "antd";
import config from "../../config";
import {
PlusCircleOutlined,
PlayCircleOutlined,
QuestionCircleOutlined,
CloseCircleOutlined,
} from "@ant-design/icons";
import Meta from "antd/lib/card/Meta";
import moment from "moment";
import ReactPlayer from "react-player";
import DescriptionBox from "../CoachCMSDescription";
import { v4 as uuidv4 } from "uuid";
import CardSkeleton from "../Skeletons/Card";
const { Content } = Layout;
const CmsVideoSelector = ({
setFormVideoData,
modeSelector,
pageOutput,
updateVideoSelectPageOutput,
deleteLecture,
}) => {
const [total, setTotal] = useState(0);
const [paging, setPaging] = useState({ position: 1, paging: 30 });
const [viewerVisible, setViewerVisible] = useState(false);
const [viewerData, setViewerData] = useState();
useEffect(() => {
async function getVimeoVideoData() {
const vimRes = await fetch(
config.BACKEND_URL_VIMEO_GET_ALL_DATA +
`?pagePosition=${paging.position}&perPageCount=${paging.paging}`
);
const vimData = await vimRes.json();
const recapRes = await fetch(config.BACKEND_URL_SEARCH);
const recapData = await recapRes.json();
const vimPageData = [];
vimData.data.forEach((vim) => {
if (!recapData.some((rec) => rec.video_url === vim.link)) {
vimPageData.push(vim);
}
});
setTotal(vimData.total);
updateVideoSelectPageOutput(vimPageData);
}
if (modeSelector) {
getVimeoVideoData();
}
}, [modeSelector, paging]);
useEffect(() => {
const getRecapVideoData = async () => {
const response = await fetch(config.BACKEND_URL_SEARCH);
const data = await response.json();
updateVideoSelectPageOutput(data);
setTotal(data.length);
};
if (!modeSelector) {
getRecapVideoData();
}
}, [modeSelector, paging]);
const viewerDisplay = () => {
setViewerVisible(!viewerVisible);
};
// if (!pageOutput || pageOutput === undefined) {
// return <CardSkeleton count={16} minWidth={"120px"} maxWidth={"480px"} />;
// } else
return (
<>
<Modal
title="Video Viewer"
visible={viewerVisible}
width="fit-content"
onCancel={viewerDisplay}
footer={null}
destroyOnClose
>
{!!viewerData && (
<>
<ReactPlayer
url={modeSelector ? viewerData.link : viewerData.video_url}
controls={true}
style={{ marginBottom: "16px" }}
playing
/>
<DescriptionBox
width={640}
data={viewerData}
modeSelector={modeSelector}
/>
</>
)}
</Modal>
{modeSelector ? (
<h3>Vimeo API Video Selector</h3>
) : (
<h3>re:cap Video Editor</h3>
)}
<Pagination
onChange={(page, pageSize) => {
setPaging({ position: page, paging: pageSize });
}}
total={total}
current={paging.position}
pageSize={paging.paging}
defaultCurrent={1}
defaultPageSize={30}
responsive={true}
pageSizeOptions={[30, 40, 50]}
style={{ marginBottom: "16px" }}
/>
<Content style={{ backgroundColor: "#fff" }}>
<ul
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))",
position: "relative",
padding: "0",
listStyle: "none",
}}
>
{pageOutput ? (
pageOutput.map((vItem) => (
<li
style={{
padding: "0",
listStyle: "none",
minWidth: "120px",
maxWidth: "480px",
marginRight: "1.5em",
marginBottom: "1.5em",
}}
>
<Card
hoverable
cover={
<img
src={
modeSelector
? vItem.pictures.sizes[4].link
: vItem.thumbnail_url
}
alt={modeSelector ? vItem.name : vItem.title}
onClick={() => {
viewerDisplay();
setViewerData(vItem);
}}
/>
}
key={modeSelector ? vItem.link : vItem.video_url}
actions={[
<Tooltip title={"Play"}>
<PlayCircleOutlined
key="play"
onClick={() => {
viewerDisplay();
setViewerData(vItem);
}}
/>
</Tooltip>,
modeSelector ? (
<Popover
content={
<DescriptionBox
width={350}
data={vItem}
modeSelector={modeSelector}
/>
}
>
<QuestionCircleOutlined key="info" />
</Popover>
) : (
<Tooltip title={"Delete"}>
<Popconfirm
title="Confirm deletion of this lecture"
okText="Delete"
onConfirm={() => deleteLecture(vItem.id)}
>
<CloseCircleOutlined />
</Popconfirm>
</Tooltip>
),
<Tooltip title={"Select"}>
<PlusCircleOutlined
key="select"
onClick={() => {
if (modeSelector) {
setFormVideoData({
title: vItem.name,
url: vItem.link,
thumbnail: vItem.pictures.sizes[4].link,
timestamps: [
{
timeMoment: "2021-01-14T00:00:00.000Z",
timeSecondsValue: 0,
timeString: "00:00:00",
uuid: uuidv4(),
timeDesc: "start",
},
],
});
} else {
setFormVideoData({
id: vItem.id,
title: vItem.title,
lecturer: vItem.lecturer,
url: vItem.video_url,
thumbnail: vItem.thumbnail_url,
tags: vItem.tags,
lecture_date: moment(vItem.lecture_date),
bootcamp_week: vItem.bootcamp_week,
cohort: vItem.cohort,
description: vItem.description,
timestamps: vItem.timestamps,
github_links: vItem.github_links,
slides: vItem.slides,
other_links: vItem.other_links,
});
}
}}
/>
</Tooltip>,
]}
>
<Meta
onClick={() => {
viewerDisplay();
setViewerData(vItem);
}}
title={modeSelector ? vItem.name : vItem.title}
description={moment(
modeSelector ? vItem.created_time : vItem.lecture_date
).format("DD MMM YYYY")}
/>
</Card>
</li>
))
) : (
<CardSkeleton count={16} minWidth={"120px"} maxWidth={"480px"} />
)}
</ul>
</Content>
</>
);
};
export default CmsVideoSelector;
<file_sep>import React from "react";
import { Row, Col, Space } from "antd";
import {
FacebookOutlined,
TwitterOutlined,
YoutubeOutlined,
LinkedinOutlined,
MediumOutlined,
EnvironmentOutlined,
MailOutlined,
} from "@ant-design/icons";
import "./style.css";
const Footer = () => {
return (
<Row
style={{
display: "block",
height: "150px",
width: "100%",
marginTop: "10%",
}}
>
<Row
align="bottom"
justify="center"
style={{
backgroundColor: "#e2e2e2",
width: "100%",
height: "150px",
boxShadow: "0px 1px 11px 3px rgba(204,204,204,1)",
position: "relative",
bottom: 0,
left: 0,
}}
>
<p
style={{
textAlign: "center",
margin: "16px 32px",
color: "#c2c2c2",
width: "800px",
}}
>
<Col style={{ fontSize: "2em" }}>
<Space size="large">
<Space size="small">
<a
href="https://twitter.com/theschoolofcode?lang=en"
target="_blank"
rel="noopener noreferrer"
>
<TwitterOutlined
className="footer-link"
id="footer-link-twitter"
/>
</a>
<a
href="https://www.facebook.com/schoolofcode"
target="_blank"
rel="noopener noreferrer"
>
<FacebookOutlined
className="footer-link"
id="footer-link-facebook"
/>
</a>
<a
href="https://www.youtube.com/channel/UCKBzheEKcrqsaJhMV0f_Dmg"
target="_blank"
rel="noopener noreferrer"
>
<YoutubeOutlined
className="footer-link"
id="footer-link-youtube"
/>
</a>
<a
href="https://www.linkedin.com/school/school-of-code/"
target="_blank"
rel="noopener noreferrer"
>
<LinkedinOutlined
className="footer-link"
id="footer-link-linkedin"
/>
</a>
<a
href="https://blog.schoolofcode.co.uk/"
target="_blank"
rel="noopener noreferrer"
>
<MediumOutlined
className="footer-link"
id="footer-link-medium"
/>
</a>
</Space>
<Space>
<a
href="https://goo.gl/maps/QJZAACMTBw52"
target="_blank"
rel="noopener noreferrer"
>
<EnvironmentOutlined
className="footer-link"
id="footer-link-env"
/>
</a>
<a
href="mailto:<EMAIL>"
target="_blank"
rel="noopener noreferrer"
>
<MailOutlined className="footer-link" id="footer-link-mail" />
</a>
</Space>
</Space>
</Col>
© Copyright 2021 School of Code. All Rights Reserved - Privacy Policy
- Terms of Use School of Code Ltd is registered in England, Company
No. 09793790 School of Code, Custard Factory, Gibb Street, Birmingham,
B9 4AA
</p>
</Row>
</Row>
);
};
export default Footer;
<file_sep>import React, { useRef, useState, useCallback, useEffect } from "react";
import { Modal, Button, Input, Form, Space, TimePicker, message } from "antd";
import ReactPlayer from "react-player";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import moment from "moment";
import { v4 as uuidv4 } from "uuid";
const TimestampSelector = ({
timestampsVisible,
modalDisplay,
timestampVideoUrl,
ruleSetRequired,
submitFailed,
getTimeStampData,
modalHide,
modeSelector,
editTimestampData,
}) => {
const player = useRef(null);
const [form] = Form.useForm();
const [seekTimeMoment, setSeekTimeMoment] = useState(
moment("00:00:00", "HH:mm:ss")
);
const [seekTimeSeconds, setSeekTimeSeconds] = useState(0);
const [seekTimeString, setSeekTimeString] = useState("00:00:00");
const [playerBuffering, setPlayerBuffering] = useState(false);
useEffect(() => {
if (editTimestampData) {
form.setFieldsValue({
timestamps: editTimestampData.map((value) => ({
...value,
timeMoment: moment(value.timeMoment),
})),
});
}
}, [form, editTimestampData, modeSelector]);
const submitForm = useCallback(
(timestamps) => {
getTimeStampData(timestamps);
message.success("Timestamps saved", 1.5, modalHide());
},
[getTimeStampData, modalHide]
);
return (
<Modal
title="Timestamp Selector"
visible={timestampsVisible}
onOk={form.submit}
onCancel={() => {
modalDisplay();
}}
width="fit-content"
destroyOnClose={true}
okText={"Finish"}
>
<>
{timestampVideoUrl ? (
<ReactPlayer
ref={player}
url={timestampVideoUrl}
controls={true}
style={{ marginBottom: "20px" }}
onBuffer={() => setPlayerBuffering(true)}
onBufferEnd={() => setPlayerBuffering(false)}
/>
) : (
<p>select a video file or add url</p>
)}
</>
<Form
name="cms_timestamps"
form={form}
initialValues={{
remember: false,
}}
onFinish={submitForm}
onFinishFailed={(value) => {
submitFailed(value);
}}
>
<Form.Item label="Timestamps" required>
<Form.List name="timestamps" rules={ruleSetRequired}>
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Space
key={field.key}
style={{ display: "flex", marginBottom: 0 }}
align="baseline"
>
<Form.Item
{...field}
name={[field.name, "timeMoment"]}
fieldKey={[field.fieldKey, "timeMoment"]}
style={{ width: "140px" }}
rules={ruleSetRequired}
initialValue={seekTimeMoment}
>
<TimePicker />
</Form.Item>
<Form.Item
{...field}
name={[field.name, "timeDesc"]}
label="Description"
style={{ width: "350px" }}
fieldKey={[field.fieldKey, "timeDesc"]}
rules={ruleSetRequired}
>
<Input />
</Form.Item>
<Form.Item
{...field}
name={[field.name, "timeSecondsValue"]}
fieldKey={[field.fieldKey, "timeSecondsValue"]}
initialValue={seekTimeSeconds}
hidden
>
<Input />
</Form.Item>
<Form.Item
{...field}
name={[field.name, "timeString"]}
fieldKey={[field.fieldKey, "timeString"]}
initialValue={seekTimeString}
hidden
>
<Input />
</Form.Item>
<Form.Item
{...field}
name={[field.name, "uuid"]}
fieldKey={[field.fieldKey, "uuid"]}
hidden
initialValue={uuidv4()}
>
<Input />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(field.name)} />
</Space>
))}
<Form.Item>
<Button
disabled={playerBuffering}
type="dashed"
onClick={() => {
const timeString = new Date(
Math.floor(player.current.getCurrentTime()) * 1000
)
.toISOString()
.substr(11, 8);
setSeekTimeMoment(moment(timeString, "HH:mm:ss"));
setSeekTimeSeconds(
Math.floor(player.current.getCurrentTime())
);
setSeekTimeString(timeString);
add();
}}
icon={<PlusOutlined />}
>
{playerBuffering ? "Loading Timestamp" : "Add Timestamp"}
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form.Item>
</Form>
</Modal>
);
};
export default TimestampSelector;
<file_sep>import React, { useEffect, useState } from "react";
import {
Modal,
Button,
Table,
Form,
Input,
message,
Space,
Popconfirm,
} from "antd";
import config from "../../config";
import {
CloseCircleOutlined,
EditOutlined,
SaveOutlined,
StopOutlined,
} from "@ant-design/icons";
const CmsLecturerEditor = ({
lecturerEditorVisible,
toggleLecturerDisplay,
lecturerData,
updateLecturerData,
lastLecturerId,
updateLastLecturerId,
}) => {
const [lecturerDelete, setLecturerDelete] = useState(null);
const [lecturerAdd, setLecturerAdd] = useState(null);
const [form] = Form.useForm();
const [inputDisabled, setInputDisabled] = useState(true);
const [lecturerInput, setLecturerInput] = useState(null);
const [lecturerUpdate, setLecturerUpdate] = useState(null);
useEffect(() => {
const deleteLecturer = async () => {
await fetch(
config.BACKEND_URL_LECTURERS_DELETE + `${lecturerDelete.key}`,
{
method: "DELETE",
}
);
updateLecturerData(
lecturerData.filter((lecturer) => lecturer.key !== lecturerDelete.key)
);
message.success(`'${lecturerDelete.lecturer}' has been deleted`);
setLecturerDelete(null);
};
if (lecturerDelete) {
deleteLecturer();
}
}, [lecturerDelete]);
useEffect(() => {
const addLecturer = async () => {
await fetch(config.BACKEND_URL_LECTURERS_ADD, {
method: "POST",
body: JSON.stringify({ lecturer: lecturerAdd }),
headers: {
"Content-Type": "application/json",
},
});
updateLecturerData([
...lecturerData,
{ key: lastLecturerId, lecturer: lecturerAdd },
]);
message.success(`'${lecturerAdd}' has been added`);
setLecturerAdd(null);
};
if (lecturerAdd) {
addLecturer();
}
}, [lecturerAdd]);
useEffect(() => {
const updateLecturer = async () => {
await fetch(config.BACKEND_URL_LECTURERS_UPDATE, {
method: "PATCH",
body: JSON.stringify(lecturerUpdate),
headers: {
"Content-Type": "application/json",
},
});
};
if (lecturerUpdate) {
updateLecturer();
message.success(`Lecturer updated`);
setLecturerUpdate(null);
}
}, [lecturerUpdate]);
const { Column } = Table;
const submitLecturer = (submittedLecturer) => {
let lecturerCheck = null;
if (lecturerData) {
lecturerCheck = lecturerData.some(
(value) =>
value.lecturer.toLowerCase() === submittedLecturer.name.toLowerCase()
);
if (lecturerCheck) {
message.error(`Lecturer already exists`);
form.resetFields();
} else {
updateLastLecturerId(lastLecturerId + 1);
setLecturerAdd(submittedLecturer.name);
form.resetFields();
}
} else {
updateLastLecturerId(lastLecturerId + 1);
setLecturerAdd(submittedLecturer.name);
form.resetFields();
}
};
return (
<Modal
visible={lecturerEditorVisible}
onCancel={() => {
toggleLecturerDisplay();
setInputDisabled(!inputDisabled);
}}
footer={null}
closable
destroyOnClose
>
<h3>Lecturer Editor</h3>
<Form name="lecturerform" onFinish={submitLecturer} form={form}>
<Space>
<Form.Item
label="Lecturer Name"
name="name"
rules={[{ required: true }]}
>
<Space>
<Input
placeholder="Enter lecturer name"
style={{ width: "200px" }}
disabled={inputDisabled}
/>
<Button type="primary" htmlType="submit" disabled={inputDisabled}>
Submit
</Button>
</Space>
</Form.Item>
</Space>
</Form>
<Table
dataSource={lecturerData}
size="small"
pagination={{ pageSize: 50 }}
scroll={{ y: 500 }}
>
<Column title="ID" dataIndex="key" key="key" />
<Column
title="Lecturer"
key="lecturer"
render={(record) => (
<Input
defaultValue={record.lecturer}
bordered={false}
disabled={inputDisabled}
onChange={(e) =>
setLecturerInput({
updateRecord: record.key,
updateValue: e.target.value,
})
}
/>
)}
/>
<Column
title="Delete"
key="delete"
render={(record) => (
<Popconfirm
title={`Are you sure you want to delete '${record.lecturer}'`}
okText={`delete`}
cancelText={`cancel`}
onConfirm={() => setLecturerDelete(record)}
disabled={inputDisabled}
>
{inputDisabled ? (
<StopOutlined style={{ color: "#ccc" }} />
) : (
<CloseCircleOutlined style={{ color: "red" }} />
)}
</Popconfirm>
)}
/>
</Table>
{inputDisabled ? (
<p style={{ color: "green" }}>Viewing Mode</p>
) : (
<p style={{ color: "red" }}>Editing Mode</p>
)}
<Space>
<Button
onClick={() => {
setInputDisabled(!inputDisabled);
}}
>
Edit <EditOutlined />
</Button>
<Button
onClick={() => {
setLecturerUpdate(lecturerInput);
setLecturerInput(null);
}}
disabled={
(inputDisabled && !lecturerInput) || !lecturerInput ? true : false
}
>
Save <SaveOutlined />
</Button>
</Space>
</Modal>
);
};
export default CmsLecturerEditor;
<file_sep>import React, { useEffect, useRef, useState, useContext } from "react";
import { useLocation, Redirect } from "react-router-dom";
import ReactPlayer from "react-player";
import "./style.css";
import { SearchContext } from "../../contexts/searchContext";
import config from "../../config";
import FeedbackForm from "../FeedbackForm";
import {
GithubOutlined,
FundProjectionScreenOutlined,
FileTextOutlined,
} from "@ant-design/icons";
import { AuthContext } from "../../firebase/Auth";
import { Spin, Row, Col, Space, Button, Divider } from "antd";
import FeedbackViewer from "../FeedbackViewer";
const LectureViewer = () => {
const { isAdmin } = useContext(AuthContext);
const id = useLocation().pathname.split("/").pop();
const player = useRef(null);
const [videoData, setVideoData] = useState(false);
const { searchText } = useContext(SearchContext);
const [previousSearch] = useState(searchText);
useEffect(() => {
async function getVideoData() {
const response = await fetch(config.BACKEND_URL_SEARCH_BY_ID + id);
const data = await response.json();
setVideoData(data[0]);
}
getVideoData();
}, [id]);
if (searchText !== previousSearch) {
return <Redirect exact to="/" />;
}
function seekToTimestamp(seconds) {
return player.current.seekTo(seconds);
}
if (!videoData) {
return (
<>
<Spin />
</>
);
} else
return (
<Row justify="center" style={{ minHeight: "1000px" }}>
<Col span={15}>
<Col className="player-wrapper">
<ReactPlayer
ref={player}
url={videoData.video_url}
controls={true}
className="react-player"
width="95%"
height="95%"
/>
<Col
style={{
margin: "0px",
padding: "0px 3px",
border: "none",
fontSize: "1em",
color: "#40a9ff",
}}
>
{videoData.tags.map((tag) => `#${tag} `)}
</Col>
</Col>
<Col span={23}>
<h1 style={{ padding: "0px", marginBottom: "0px" }}>
{videoData.title}
</h1>
<h2 style={{ padding: "0px", color: "#b2b2b2" }}>
{videoData.lecturer}
</h2>
<Space direction="vertical" style={{ width: "99%" }}>
<Divider style={{ marginBottom: "0", marginTop: "0" }} />
<Row style={{ textAlign: "justify" }}>
{videoData.description}
</Row>
</Space>
</Col>
</Col>
<Col span={5}>
<Divider orientation="left">Resources</Divider>
<Space direction="vertical">
{videoData.github_links !== [] &&
videoData.github_links.map((value) => (
<a
key={value.uuid}
href={value.link}
target="_blank"
rel="noopener noreferrer"
>
<Space>
<GithubOutlined />
{value.desc}
</Space>
</a>
))}
{videoData.slides !== [] &&
videoData.slides.map((value) => (
<a
key={value.uuid}
href={value.link}
target="_blank"
rel="noopener noreferrer"
>
<Space>
<FundProjectionScreenOutlined /> {value.desc}
</Space>
</a>
))}
{videoData.other_links.map((value) => (
<a
key={value.uuid}
href={value.link}
target="_blank"
rel="noopener noreferrer"
>
<Space>
<FileTextOutlined />
{value.desc}
</Space>
</a>
))}
</Space>
<Divider orientation="left">Timestamps</Divider>
<Space size="small" direction="vertical" style={{ width: "100%" }}>
{videoData.timestamps.map((value) => {
return (
<Button
key={value.uuid}
style={{
width: "100%",
textAlign: "left",
overflow: "hidden",
}}
onClick={() => seekToTimestamp(value.timeSecondsValue)}
>
{`${value.timeString} - ${value.timeDesc}`}
</Button>
);
})}
</Space>
<Divider orientation="left">Feedback</Divider>
{isAdmin ? <FeedbackViewer /> : <FeedbackForm />}
</Col>
<Col span={20}></Col>
</Row>
);
};
export default LectureViewer;
<file_sep>import React from "react";
import { Menu } from "antd";
import {
UserOutlined,
TagOutlined,
VideoCameraOutlined,
} from "@ant-design/icons";
const CmsMenu = ({
toggleTagDisplay,
toggleVisible,
toggleLecturerDisplay,
switchVideoMode,
modeSelector,
updateVideoSelectPageOutput,
}) => {
return (
<Menu
style={{
userSelect: "none",
textAlign: "center",
opacity: "0.93",
fontWeight: "bold",
}}
>
<Menu.Item
key="1"
icon={<TagOutlined />}
onClick={() => {
toggleVisible();
toggleTagDisplay();
}}
>
Tag Editor
</Menu.Item>
<Menu.Item
key="2"
icon={<UserOutlined />}
onClick={() => {
toggleVisible();
toggleLecturerDisplay();
}}
>
Lecturer Editor
</Menu.Item>
<Menu.Item
key="3"
icon={<VideoCameraOutlined />}
onClick={() => {
toggleVisible();
updateVideoSelectPageOutput(false);
switchVideoMode(!modeSelector);
}}
>
{modeSelector
? "Switch to re:cap Video Editor"
: "Switch to Vimeo Video Selector"}
</Menu.Item>
</Menu>
);
};
export default CmsMenu;
<file_sep>import React from "react";
import { Descriptions } from "antd";
import moment from "moment";
const DescriptionBox = ({ width, data, modeSelector }) => {
return (
<Descriptions
title="Video Info"
size="small"
column={1}
style={{ width: width }}
>
<Descriptions.Item label="Title">
{modeSelector ? data.name : data.title}
</Descriptions.Item>
<Descriptions.Item label="Created">
{moment(modeSelector ? data.created_time : data.lecture_date).format(
"DD MMM YYYY"
)}
</Descriptions.Item>
<Descriptions.Item label="URL">
{modeSelector ? data.link : data.video_url}
</Descriptions.Item>
</Descriptions>
);
};
export default DescriptionBox;
<file_sep>import React from "react";
import { Link } from "react-router-dom";
export default function ContentManagementButton() {
return (
<Link
className="header-bar-links"
to="/cms"
style={{ color: "#000", userSelect: "none" }}
>
CMS
</Link>
);
}
| eb92b26b1f10e1de837b74c091614a86e89de2c0 | [
"JavaScript"
] | 13 | JavaScript | moms-spaghetti/react_recap_frontend | 14c46f9184f28cfc16a3f2f2eee307f2b29caefd | 8274bb3cda1e7d09c4a1efa572e16c172bf9846e |
refs/heads/master | <file_sep>
# coding: utf-8
# In[4]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set_style('ticks')
import warnings
warnings.filterwarnings('ignore')
pd.options.display.html.table_schema = True # Data Explorer On!
pd.options.display.max_rows = None # Send all the data! (careful!)
# In[5]:
# Import Data
df=pd.read_csv('Financial Planning and Budgeting.csv')
# Remove any unwanted data
df=df[df.Age!='Under 18'] #remove responses from Under 18 population
# display first 10 rows
df.head(10)
# In[9]:
# Display available columns
df.columns.tolist()
# In[35]:
""" USE FOR EXAMINING THE MUTLI-CHOICE ANSWERS AS A FUNCTION OF VARIOUS CONTROLS (AGE, INCOME, ETC)"""
# Filter data to only one select subset for one parameter
Filterby = 'None' #eg 'Age', 'None'
Filter = '' #eg '45-54'
if 'None' in Filterby:
df2=df.copy()
else:
df2=df[df[Filterby]==Filter]
# Control_on determines the y-axis and the groups are the various bars you want to display
Control_On = 'Age' #eg Income
Groups ='Online_Advice' #eg InvestmentTools
column_set= [col for col in df.columns if Groups in col]
# remove the "describe" data from the plots here since it is not interesting
# this could also be done for "other" or any answer type you don't care for
if 'Describe' in column_set[-1]:
column_set=column_set[:-1]
# extract subset of columns that are in the "control_on" category
column_set= np.append(Control_On,column_set)
print(column_set)
# count all response types for each column
test_grouped = df2[column_set]
test_grouped = test_grouped.groupby([Control_On]).count()
print(test_grouped)
# Normalize all answers by total number of respondents in "control_on" category
numberofentries=df2[Control_On].value_counts()
test_grouped=test_grouped.div(numberofentries,axis=0)
test_grouped=test_grouped.multiply(100)
# plot
ax=test_grouped.sort_index(ascending=True).plot(
kind='barh',
figsize=(10, 15),
cmap='Spectral',
width=0.7,
edgecolor='black',
fontsize=17,
grid='On')
ax.set_xlabel('Percent of Responses',fontsize=16)
ax.set_ylabel(Control_On,fontsize=16)
ax.set_title('Percent of ' + Groups + ' Responses Grouped by ' + Control_On + ' (Filter: ' + Filterby + '=' + Filter + ')',fontsize=18)
# In[56]:
""" BETTER SUITED TOWARD MUTLIPLE CHOICE ANSWERS WHERE THERE IS ONLY ONE ANSWER PER QUESTION """
# This is the question we will look at in bar charts with the y axis
Examine='OnTrack'
examine_unique=df[Examine].unique()
# each subplot will be for a different set of responses to this other multiple-choice question
Var='Income'
Filters=np.sort(df[Var].unique())
nplots1 = int((len(Filters)+np.mod(len(Filters),2))/2)
# prepare plots
fig, ax = plt.subplots(nplots1,2,sharex=True,sharey=True)
axs=ax.ravel()
#cycle through all sub-categories for each subplot
Q=0
for Filter in Filters:
d3=df[df[Var]==Filter].sort_values(Examine)
# normalize all answers by the number of respondents in this "Var" subgroup
numberofentries=d3[Examine].value_counts(normalize=True)
numberofentries=numberofentries.sort_index(ascending=False)
numberofentries=numberofentries.multiply(100)
### Fold in all options so y axes are common
examine_unique=df[Examine].unique() #find unique options for variable being examined
a=pd.DataFrame(np.zeros(len(examine_unique))) #construct a dataframe
a.index=examine_unique #reindex using the options
a.columns=[Examine] #rename columns
#covert numberofentries to dataframe
b=pd.DataFrame(numberofentries)
#merge the two on all unique options (a) and fillna with 0
C=a.merge(b,how='left', left_index=True, right_index=True)
C=C.iloc[:,[-1]]
C.columns=[Examine]
C=C.fillna(0)
# PLOT
AX2=C.plot(
ax=(axs[Q]),
kind='barh',
figsize=(15, 15),
cmap='Spectral',
width=0.7,
edgecolor='black',
fontsize=17,
grid='On',
).yaxis.label.set_visible(False)
title_str=Var + ' = ' + Filter
title_str=title_str.replace('and'," - ")
axs[Q].set_xlabel('Percent of Responses',fontsize=16)
axs[Q].set_title(title_str,fontsize=16)
Q+=1
fig.tight_layout()
| 658997dea6c002c08606c7fb0ba041d790e65203 | [
"Python"
] | 1 | Python | simbazemba/BobbyCo | 4c467be6bae45595d5da6c715d94b55108517626 | 28fe7d4a9299da5177f931482a3f0907fa9f1670 |
refs/heads/master | <repo_name>SamuelHFerreira/push-lib<file_sep>/PushLib/Example/Podfile
use_frameworks!
pod 'OCMapper', '2.1'
pod 'AFNetworking', '2.6.3'
target 'PushLib_Example', :exclusive => true do
pod 'PushLib', :path => '../'
end
target 'PushLib_Tests', :exclusive => true do
pod 'PushLib', :path => '../'
end
<file_sep>/PushLib/README.md
# PushLib
[](https://travis-ci.org/samuel.ferreira/PushLib)
[](http://cocoapods.org/pods/PushLib)
[](http://cocoapods.org/pods/PushLib)
[](http://cocoapods.org/pods/PushLib)
## Usage
To run the example project, clone the repo, and run `pod install` from the Example directory first.
## Requirements
## Installation
PushLib is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod "PushLib"
```
## Author
samuel.ferreira, <EMAIL>
## License
PushLib is available under the MIT license. See the LICENSE file for more info.
| be81940075ab1d94f0b72ea0c1dd307d51e2efb6 | [
"Markdown",
"Ruby"
] | 2 | Ruby | SamuelHFerreira/push-lib | 4f858eb4f01eb09598c4523c65f4eeca125af72a | 9c7592bdafd3dec4a3cfffc6dddb3e190dad4b8c |
refs/heads/master | <file_sep>##
# Cropping controller for photos. Always expects a parent model (Book,
# Evidence, TitlePage, or ContextImage) and a Photo. The `#create` action
# expects a source_photo_id paramter, which is used by the
# ThumbnailsController to find the correct divs in which to display the new
# image.
#
# Note that this is a rather willful use of the rails pattern of nesting
# resources. Strictly speaking the nested model should have a `:belongs_to`
# assocation with its parent. This is true for Books and Photos, but
# contrarily Evidence, TitlePage, and ContextImage belong to Photos.
#
# This method serves the need to have single controller and set of views
# handle the editing an redisplay of all image types when editing occurs.
#
# There are two key div types, `.thumb-contatiner` and `.thumb-div`. They look
# like this:
#
# ```html
# <div class="thumb-container" data-parent="32" data-parent-type="title_pages" data-thumbnail="118" id="ui-id-2">
# <div class="thumb" data-parent="32" data-parent-type="title_pages" data-thumbnail="118">
# <a target="_blank" data-toggle="tooltip" rel="noopener noreferrer" href="/system/photos/images/000/000/118/original/data.jpg?1472843017" data-original-title="Click to open in new window.">
# <img class="img-responsive center-block" src="/system/photos/images/000/000/118/thumb/data.jpg?1472843017" alt="Data">
# </a>
# </div>
# </div>
# ```
#
# The `.thumb` div is generated in the `/thumbnails/show` partial. The
# `.thumb` div has an optional `data-source-photo` attribute to hold the ID of
# the photo from which the new photo was created. The code that dynamically
# loads the new image, must know the ID of the previous photo in order to find
# the correct parent div to replace its content. The `data-source-photo`
# attribute makes this possible when a photo is new.
class Cropping::PhotosController < ApplicationController
include ApplicationHelper
include PolymorphicParent
include LinkToContextImage
before_action :set_or_create_parent
before_action :set_parent_type, only: [:new, :create]
before_action :set_source_photo, only: [:new, :create]
before_action :set_photo, except: [:new, :create]
def create
authorize! :update, @source_photo
@photo = build_photo @parent, photo_params
set_original_details @photo, @source_photo
link_to_context_image @parent, @source_photo.id, no_clobber: true
if @photo.save
# we have to save non-Books with the new photo
update_parent @parent, @photo
respond_to do |format|
format.html { redirect_to @parent }
format.js {
redirect_to parent_thumbnail_path(@parent, @photo, source_photo_id: @source_photo.id), format: :js
}
end
else
format.html { render :new }
end
end
def new
authorize! :update, @source_photo
@photo = build_photo @parent, photo_params
respond_to do |format|
format.html {
if request.xhr?
render layout: false
else
render layout: 'cropper'
end
}
end
end
def edit
authorize! :update, @photo
respond_to do |format|
format.html do
if request.xhr?
render layout: false
else
render layout: 'cropper'
end
end
end
end
def update
authorize! :update, @photo
@photo.assign_attributes photo_params
# @photo.image = @photo.data_url
respond_to do |format|
if @photo.save
format.html { redirect_to @parent }
format.js {
redirect_to parent_thumbnail_path(@parent,@photo), format: :js
}
else
format.html { render :edit }
end
end
end
private
def update_parent parent, photo
return unless parent.persisted?
return if parent.is_a? Book
@parent.update_attributes photo: photo
end
def set_original_details photo, source_photo
photo.image_file_name = source_photo.image_file_name
return if photo.original.present?
photo.original = source_photo
end
def set_photo
@photo = Photo.find params[:id]
end
def set_source_photo
@source_photo = Photo.find params[:source_photo_id]
end
def build_photo parent, params={}
return parent.photos.build params if parent.is_a?(Book)
Photo.new params
end
def photo_params
return unless params[:photo]
params.require(:photo).permit :data_url, :parent_type
end
end
<file_sep># Configuration
Environment variables are required for deploy. See the file .subpop-
environment-sample for details.
<file_sep>class AddAttachmentColumnsToPhotos < ActiveRecord::Migration
def up
add_attachment :photos, :image
end
def remove
remove_attachment :photos, :image
end
end
<file_sep>require 'rails_helper'
RSpec.describe PublicationData, type: :model do
context 'factory' do
it 'creates a PublicationData' do
expect(create(:publication_data)).to be_a PublicationData
end
it 'builds a PublicationData without a publishable' do
expect(build(:unassigned_publication_data)).to be_a PublicationData
end
end
context 'initialization' do
it 'creates a PublicationData' do
expect(PublicationData.new).to be_a PublicationData
end
end
end
<file_sep>class AddPhotoIdToEvidence < ActiveRecord::Migration
def change
add_reference :evidence, :photo, index: true, foreign_key: true
add_column :evidence, :flickr_id, :string
add_column :evidence, :flickr_info, :text
add_index :evidence, :flickr_id
end
end
<file_sep>class ThumbnailsController < ApplicationController
include PolymorphicParent
before_action :set_thumbnail
before_action :set_or_create_parent
before_action :set_parent_type
before_action :set_source_photo
def show
respond_to do |format|
format.js {
if @thumbnail.image_processing?
render format: :js, template: '/thumbnails/processing'
else
render format: :js
end
}
format.json
end
end
private
def set_thumbnail
@thumbnail = Photo.find params[:id]
end
def set_source_photo
return unless params[:source_photo_id].present?
@source_photo = Photo.find params[:source_photo_id]
end
end<file_sep># See Thoughtbot's article on running background jobs inline for tests.
# https://robots.thoughtbot.com/process-jobs-inline-when-running-acceptance-tests
module BackgroundJobs
def run_background_jobs_immediately
delay_jobs = Delayed::Worker.delay_jobs
Delayed::Worker.delay_jobs = false
yield
Delayed::Worker.delay_jobs = delay_jobs
end
end<file_sep>FactoryGirl.define do
factory :evidence do
format 'bookplate_label'
book
end
factory :evidence_complete, class: Evidence do
book
format 'other'
format_other 'Ribbon'
content_types [ ContentType.find_or_create_by(name: 'Armorial') ]
location_in_book 'page_number'
location_in_book_page '5'
transcription 'Text of transcription'
year_start 1820
year_end 1828
date_narrative "c. 1820 - 1828"
where "Philadelphia"
comments "Text comments"
photo
association :publication_data, factory: :publication_data
end
factory :evidence_on_flickr, class: Evidence do
format 'bookplate_label'
year_when 1874
location_in_book 'front_endleaf'
book
end
end<file_sep>class RemoveColumnsFlickrIdFlickrInfoFromPhotos < ActiveRecord::Migration
def change
remove_column :photos, :flickr_id, :string
remove_column :photos, :flickr_info, :text
end
end
<file_sep>module CroppingHelper
def link_to_crop_photo parent, photo, options
text = options.delete(:link_name) || "Edit photo"
options[:title] ||= text
link_to text, crop_image_path(parent, photo), options
end
def crop_image_path parent, photo
return new_parent_crop_image_path parent, photo unless parent.persisted?
case parent
when Book
book_crop_image_path parent, photo
when Evidence
evidence_crop_image_path parent, photo
when TitlePage
title_page_crop_image_path parent, photo
when ContextImage
context_image_crop_image_path parent, photo
end
end
def book_crop_image_path parent, photo
return edit_cropping_book_photo_path parent, photo unless photo.used?
# We can't change a photo already assigned to a Title Page or Evidence. If
# the photo has been used, we have have to create a new photo after the
# crop.
new_cropping_book_photo_path parent, { source_photo_id: photo.id }
end
def evidence_crop_image_path parent, photo
return edit_cropping_evidence_photo_path parent, photo if photo.isolated?
new_cropping_evidence_photo_path parent, { source_photo_id: photo.id }
end
def context_image_crop_image_path parent, photo
return edit_cropping_context_image_photo_path parent, photo if photo.isolated?
new_cropping_context_image_photo_path parent, { source_photo_id: photo.id }
end
def title_page_crop_image_path parent, photo
return edit_cropping_title_page_photo_path parent, photo if photo.isolated?
new_cropping_title_page_photo_path parent, { source_photo_id: photo.id }
end
##
# If the parent is persisted, we have to create a new photo and then find
# the div based on the parent type and the ID of the source photo.
def new_parent_crop_image_path parent, photo
attrs = {
source_photo_id: photo.id,
parent_type: parent.model_name.plural
}
new_cropping_photo_path attrs
end
def new_cropped_photo_reason parent, photo
case parent
when Book
"This photo has alreedy been used #{photo.use_count} #{'time'.pluralize photo.use_count}."
end
end
def use_count photo
# return unless photo.used?
"Used #{photo.use_count} #{'time'.pluralize photo.use_count}"
end
end<file_sep>class AddEvidencCountToContextImages < ActiveRecord::Migration
def up
add_column :context_images, :evidence_count, :integer
ContextImage.reset_column_information
ContextImage.all.each do |ci|
ci.update_column :evidence_count, ci.evidence.length
end
end
def down
remove_column :context_image, :evidence_count
end
end
<file_sep>class AddPublishingToTitlePages < ActiveRecord::Migration
def change
add_column :title_pages, :publishing_to_flickr, :boolean
end
end
<file_sep>json.extract! @item, :id
json.processing @item.processing?<file_sep>require 'rails_helper'
RSpec.describe Book, type: :model do
context 'factories' do
it 'has a factory' do
expect(create(:book)).to be_a Book
end
it 'creates a complete book' do
expect(create(:complete_book)).to be_a Book
end
end
end
<file_sep># This will guess the User class
FactoryGirl.define do
factory :book do
repository 'Penn Libraries'
call_number 'BK 123'
title 'My book title'
end
# This will use the User class (Admin would have been guessed)
factory :complete_book, class: Book do
repository "Penn Manuscripts"
collection "Smith Colleciton"
geo_location "Philadelphia, PA"
call_number "BK 123"
catalog_url "http//example.com/bk123"
vol_number "1"
author "<NAME>"
title "Great Expectations"
creation_place "London"
creation_date "1873"
publisher "Fezziwig"
other_id "1234567"
other_id_type "bibid"
sammelband true
end
end<file_sep>class Flickr::BooksController < Flickr::BaseController
def create
authorize! :update, @item
respond_to do |format|
create_publish_jobs
format.js
format.html { redirect_to @item, notice: "Publishing all book images" }
end
end
def update
authorize! :update, @item
respond_to do |format|
create_publish_jobs
format.js
format.html { redirect_to @item, notice: "Publishing all book images" }
end
end
def destroy
authorize! :update, @item
respond_to do |format|
create_unpublish_jobs
format.js
format.html
end
end
def status
authorize! :read, @item
respond_to do |format|
format.js
format.json
end
end
end<file_sep>module FeatureMacros
DEFAULT_FILE_PATH = "#{Rails.root}/spec/fixtures/images/BS_185_178207.jpg"
def login_as username, attributes={}
add_user username, attributes
password = attributes[:password] || '<PASSWORD>'
visit '/users/sign_in'
fill_in 'Username', with: username
fill_in 'Password', with: <PASSWORD>
click_button 'Log in'
expect(page).to have_content 'Signed in successfully.'
end
def add_user username, attributes={}
User.find_by(username: username) or FactoryGirl.create(:user, attributes.merge(username: username))
end
def sign_out username
click_link username
click_link 'Sign out'
expect(page).to have_content 'Signed out successfully.'
end
def visit_evidence
# we do the following to ensure the associations are loaded
@evidence.inspect
visit evidence_path(@evidence)
end
def visit_book
@book ||= FactoryGirl.create :book
@book.reload.photos
visit book_path @book
end
def visit_new_bookplate
# /books/1/evidence/new?utf8=%E2%9C%93&photo_id=1&book_id=1&use=bookplate_label&evidence%5Bphoto_id%5D=1&evidence%5Bbook_id%5D=1&evidence%5Bformat%5D=bookplate_label
params = {
photo_id: @photo.id,
'evidence[photo_id]': @photo.id,
'evidence[format]': 'bookplate_label',
'evidence[book_id]': @book.id
}
visit new_book_evidence_path(@book, params)
end
def create_name_by username, attributes={}
user = add_user username
local_attrs = attributes.dup
local_attrs[:name] ||= '<NAME>'
Name.new(attributes).save_by user
end
def create_book_with_photo_by username, attributes={}
create_book_by username
create_photo book: @book
end
def make_photo_a_title_page
@title_page = FactoryGirl.create :title_page, book: @book, photo: @photo
end
def create_book_by username, attributes={}
user = add_user username
local_attrs = attributes.dup
local_attrs[:title] ||= 'A book title'
local_attrs[:call_number] ||= 'BK 65431 .c'
local_attrs[:repository] ||= 'Big Old Library'
@book = Book.new local_attrs
@book.save_by user or raise_invalid_model @book
@book
end
def create_photo attributes={}
local_attrs = attributes.dup
local_attrs[:image] ||= File.new(DEFAULT_FILE_PATH)
local_attrs[:in_queue] ||= true
@photo = Photo.new local_attrs
@photo.valid? or raise_invalid_model @photo
@photo.save
@photo
end
def create_context_image_by username, attributes={}
user = add_user username
local_attrs = attributes.dup
local_attrs[:book] = @book || create_book_by(username)
unless local_attrs[:photo] || local_attrs[:photo_id]
local_attrs[:photo] = (Photo.first || create_photo)
end
@context_image = ContextImage.new local_attrs
@context_image.save_by user or raise_invalid_model @context_image
@context_image
end
def create_evidence_by username, attributes={}
user = add_user username
local_attrs = attributes.dup
local_attrs[:book] ||= create_book_by username
# we create the photo using the book
local_attrs[:photo] ||= create_photo book: local_attrs[:book]
local_attrs[:format] ||= 'binding'
@evidence = Evidence.new local_attrs
@evidence.save_by user or raise_invalid_model @evidence
@evidence
end
def add_context_image_to_evidence_by username, evidence=nil
context_image = ContextImage.first || create_context_image_by(username)
@evidence.update_attributes! context_image: context_image
end
def raise_invalid_model obj
raise "Invalid #{obj.model_name}: #{obj.errors.full_messages}"
end
end<file_sep>class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :repository
t.string :owner
t.string :collection
t.string :geo_location
t.string :call_number
t.string :catalog_url
t.string :vol_number
t.string :author
t.string :title
t.string :creation_place
t.integer :creation_date
t.string :publisher
t.timestamps null: false
end
end
end
<file_sep>class RemovePaperclipColumnsFromEvidence < ActiveRecord::Migration
def change
remove_column :evidence, :image_file_name, :string
remove_column :evidence, :image_content_type, :string
remove_column :evidence, :image_file_size, :integer
remove_column :evidence, :image_updated_at, :datetime
end
end
<file_sep>FactoryGirl.define do
factory :publication_data do
association :publishable, factory: :evidence
flickr_id "25367313472"
metadata IO.read(Rails.root.join 'spec', 'fixtures', 'flickr_photo.json')
end
factory :unassigned_publication_data, class: PublicationData do
flickr_id "25367313472"
metadata IO.read(Rails.root.join 'spec', 'fixtures', 'flickr_photo.json')
end
end<file_sep>class ContentType < ActiveRecord::Base
validates :name, uniqueness: true
validates :name, presence: true
def <=> other
self.sort_name <=> other.sort_name
end
def sort_name
self.name.sub /^\W+/, ''
end
end
<file_sep>class Ability
include CanCan::Ability
# We have three kinds of users: (1) the public, not logged in;
# (2) a logged in user; (3) an admin
def initialize(user)
user ||= User.new
# the public can read most things (not users)
can :read, Book
can :read, Evidence
can :read, Name
can :read, TitlePage
return if user.new_record?
# admins can manage anything
if user.admin?
can :manage, :all
return
end
# user must be logged in allow full management
# allow user to manage all child objects of own books
can :manage, Book, created_by_id: user.id
can :manage, Evidence, book: { created_by_id: user.id }
can :manage, TitlePage, book: { created_by_id: user.id }
# Have photo abilities depend on associated objects.
#
# https://github.com/CanCanCommunity/cancancan/wiki/Share-Ability-Definitions
can :manage, Photo do |photo|
case
when photo.book.present?
can? :manage, photo.book
when photo.evidence.present?
can? :manage, photo.evidence.first
when photo.title_pages.present?
can? :manage, photo.title_pages.first
when photo.context_images.present?
can? :manage, context_images.first
end
end
can :manage, Name, created_by_id: user.id
end
end<file_sep>Hints for
#city, state/region, country on geographic location field
*entering name *Ask Doug about this*
Move
#geographic location field to Who Has It? heading
#add book button to top
Add
#Field for immediate source of acquisition
#dropdown under evidence format for "stamped binding"
#dropdown under evidence "presentation inscription"
*role "annotator" becomes role "other" *talk to Doug about this*
#header above image upload field
Fix
#date narrative field so that you can put narrative in
TOTHINK
-add clarifying text at the start of each page so workflow is clear
-Make required and not required fields more clear
-Re-arrange layout to put required fields nearer top
-Add a name under the format and content type for provenance marks
<file_sep>class PhotosController < ApplicationController
before_action :set_book
before_action :set_photo, only: [ :update, :show ]
authorize_resource only: [:index, :show, :update]
def index
@photos = @book.photos.queued
respond_to do |format|
format.html
format.js
end
end
def show
respond_to do |format|
format.js
format.json
end
end
# PATCH/PUT /book/1/photos/1
# PATCH/PUT /book/1/photos/1.json
def update
respond_to do |format|
if @photo.update(photo_params)
format.html { redirect_to @book, notice: 'Photo was successfully updated.' }
format.json { render :show, status: :ok, location: [ @book ] }
format.js { render :index, status: :ok, location: [ @book ] }
else
format.html { redirect_to @book, alert: 'Unable to update photo' }
format.json { render status: :unprocessable_entity }
format.js { }
end
end
end
def restore_queue
authorize! :update, Photo
@book.photos.update_all(in_queue: true)
respond_to do |format|
format.html { redirect_to @book }
format.js { render action: 'index' }
end
end
private
def set_photo
@photo = Photo.find params[:id]
end
def set_book
@book = Book.find params[:book_id]
end
def photo_params
params.require(:photo).permit(:in_queue, :book_id)
end
end
<file_sep>User.excluded_names = [ 'all', 'admin', 'system', 'sysadmin' ]<file_sep> source 'https://rubygems.org'
ruby '2.2.5'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5'
# Use mysql as the database for Active Record
# Ugh, Rails 4.2.4 is broken w/r/t/ mysql2 gem > 0.3.x
gem 'mysql2', '~> 0.3.18'
gem 'bootstrap-sass', '~> 3.3.5'
gem 'font-awesome-rails'
gem 'sass-rails', '>= 3.2'
gem 'autoprefixer-rails', '~> 6.3.1'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
gem 'therubyracer', '~> 0.12.2', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 4.1.0'
gem 'jquery-ui-rails', '~> 5.0.5'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks', '~> 2.5.3'
gem 'jquery-turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'rails-jquery-autocomplete', '~> 1.0.3'
gem 'jquery-cropper', '~> 2.3.2'
# authentication
gem 'devise', '~> 4.1.1'
# authorization
gem 'cancancan', '~> 1.10'
# pagination
gem 'kaminari', '~> 0.16.3'
# attach images
gem 'paperclip', '~> 4.3'
# do some jobs in the background
gem 'delayed_job_active_record', '~> 4.1.0'
# process paperclip in the background
gem 'delayed_paperclip', '~> 2.9.1'
gem 'daemons', '1.1.9'
# send emails when things go wrong
gem 'exception_notification', '~> 4.1.1'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Puma as the app server
gem 'puma', '~> 2.16.0'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
gem 'rb-fsevent', '~> 0.9.7', group: :darwin
gem 'flickraw-cached'
gem 'lograge'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', '~> 8.2.2'
gem 'pry-rails', '~> 0.3.4'
gem 'minitest', '5.8.1'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', '~> 1.6.2'
gem 'spring-commands-rspec', '~> 1.0.4'
gem 'rspec-rails', '~> 3.4'
gem 'guard-rspec', '~> 4.6.4'
gem 'dotenv-rails', '~> 2.1.0'
gem 'factory_girl_rails', '~> 4.6.0', require: false
gem 'database_cleaner', '~> 1.5.1'
gem 'poltergeist', '~> 1.9'
gem 'launchy', '~> 2.4.3' # save_and_open_page functionality
gem 'capybara', '~> 2.7'
gem 'capybara-screenshot', '~> 1.0.13'
gem 'simplecov', '~> 0.11.2', :require => false
end
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0', group: :development
<file_sep>class DropTableTitlePhotos < ActiveRecord::Migration
def up
drop_table :title_page_photos
end
def down
raise "Migration cannot be reversed"
end
end
<file_sep>class CreateContextImages < ActiveRecord::Migration
def change
create_table :context_images do |t|
t.references :book, index: true, foreign_key: true
t.references :photo, index: true, foreign_key: true
t.boolean :publishing_to_flickr
t.boolean :deleted
t.integer :created_by_id
t.integer :updated_by_id
t.timestamps null: false
end
end
end
<file_sep>class AddDeletedToTitlePages < ActiveRecord::Migration
def up
add_column :title_pages, :deleted, :boolean, default: false
TitlePage.update_all deleted: false
end
def down
remove_column :title_pages, :deleted
end
end
<file_sep>module Flickr
class Info
attr_reader :info
PHOTOS_URL = 'https://www.flickr.com/photos/'.freeze
##
# Create a new Flickr::Info object.
#
# Parameters:
#
# `user_id`: the Flickr user ID; a string in the format `123456789@N00`
#
# `info`: data returned by `flickr.photos.getInfo` as JSON or Hash
def initialize user_id, info=nil
@user_id = user_id
@info = case info
when nil
nil
when Hash
info
when String
JSON::load info
end
end
# Generate the URL for this tag within the user's Flickr photostream. The
# `flickr_tag` can be either a Flickr::Tag instance or a String
def tag_url flickr_tag
tag = flickr_tag.is_a?(Tag) ? flickr_tag : Tag.new(raw: flickr_tag)
"#{photostream_url}/tags/#{tag.normalize}"
end
def tags_on_flickr
return [] if @info.nil?
return [] if @info['tags'].nil?
@info['tags'].map { |data| Tag.new data }
end
def photostream_url
"#{PHOTOS_URL}#{nsid}"
end
def photopage_url
"#{photostream_url}/#{photo_id}"
end
SHORT_URL = 'https://flic.kr/p/'.freeze
##
# Generate the short URL for Flickr. The `url_mod` can be one of:
#
# `nil` Return short URL for photo page [default]
# `"m"` Small
# `"s"` Square
# `"t"` Thumbnail
# `"q"` Large square
# `"n"` Small 320
def short_url url_mod=nil
return nil if photo_id.blank?
mod_string = url_mod.nil? ? '' : "_#{url_mod}.jpg"
SHORT_URL + base58(photo_id) + mod_string
end
def photo_id
@info['id']
end
def nsid
@user_id
end
def owner_data
@info and @info['owner']
end
private
# base58 code below taken directly from FlickRaw. Here:
#
# <https://github.com/hanklords/flickraw/blob/master/lib/flickraw/api.rb>
#
# FlickRaw has a method for creating these URLs, but it depends on the
# FlickRaw Response object, which I don't store, don't want to recreate or
# depend on.
#
# There is another way to handle this: The info hash could be wrapped in a
# class that uses method missing to extract hash values and pass that
# wrapper to FlickRaw. This would probably work. This class could also
# implement method missing and be handed to FlickRaw.
BASE58_ALPHABET="123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".freeze
def base58(id)
id = id.to_i
alphabet = BASE58_ALPHABET.split(//)
base = alphabet.length
begin
id, m = id.divmod(base)
r = alphabet[m] + (r || '')
end while id > 0
r
end
end
end<file_sep>#!/usr/bin/env bash
################################################################################
#
# Name: docker-tunnels
#
# Description: Restart the subpop docker-tunnels using the `docker-tunnel-ctl`
# script.
#
# There are two tunnels, which should be defined in the $HOME/.ssh/config file:
#
# Host docker-daemon-tunnel
# HostName emeryrdev02
# IdentityFile ~/.ssh/id_dsa
# LocalForward 2375 127.0.0.1:2375
#
# Host docker-repo-tunnel
# HostName emeryrdev02
# IdentityFile ~/.ssh/id_dsa
# LocalForward 5000 127.0.0.1:5000
#
CMD=`basename $0`
CTL_CMD=`dirname $0`/docker-tunnel-ctl
TUNNELS="docker-daemon-tunnel docker-repo-tunnel"
PATTERN=
for tunnel in $TUNNELS
do
echo "[$CMD] Restarting tunnel $tunnel"
$CTL_CMD $tunnel restart
echo
if [[ -z $PATTERN ]]; then
PATTERN="\b${tunnel}\b"
else
PATTERN="${PATTERN}|\b${tunnel}\b"
fi
done
echo "[$CMD] Running tunnels:"
ps -ef | egrep "$PATTERN" | grep -v grep
<file_sep># Docker ReadMe for subpop #
These are instructions for building subpop with `docker-compose` and
pushing it to the `emeryrdev02` server.
## Set up SSH tunnel to remote ##
Tunnel to `emeryrdev02`, forwarding port `2375` to localhost:
```bash
$ ssh -fnNL 2375:localhost:2375 emeryrdev02
```
Note that the local user `emeryr` is the same on `emeryrdev02`.
Alternately, config the tunnel as host in `$HOME/.ssh/config`, as below, with
correct values for `hostname`, `the.key`, and `user_name`. `User_name` is not
required if it's the same on both hosts.
```
Host docker-tunnel
HostName hostname
IdentityFile ~/.ssh/the.key
LocalForward 2375 127.0.0.1:2375
User: user_name
```
Then you can do:
```bash
$ ssh -f -N docker-tunnel
```
## Build with docker-compose ##
Set `DOCKER_HOST` environment variable in bash init file:
```bash
export DOCKER_HOST=localhost:2375
```
Be sure `DOCKER_HOST` is set the local environment and run `docker-compose`.
```bash
✘ 16:16 ~/code/GIT/subpop [development|✚ 3] $ docker-compose build
db uses an image, skipping
Building web
Step 1 : FROM ruby:2.2.4
---> 9168c99105ac
...
---> Using cache
---> 1248b12cd4c9
Successfully built 1248b12cd4c9
```
## Tag and push docker-images on remote server
Log in to remote server, e.g., `emeryrdev02`.
Tag the web and delayedjob images:
```
emeryrdev02[~]$ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
subpop_delayedjob latest 2b44b46993a4 14 minutes ago 905 MB
subpop_web latest 2b44b46993a4 14 minutes ago 905 MB
localhost:5000/subpop_web latest d82916b4eba2 2 weeks ago 905 MB
localhost:5000/subpop_delayedjob latest d82916b4eba2 2 weeks ago 905 MB
...
emeryrdev02[~]$ docker tag -f 2b44b46993a4 localhost:5000/subpop_delayedjob
emeryrdev02[~]$ docker tag -f 2b44b46993a4 localhost:5000/subpop_web
```
> Note the `-f` flag to force the reassignment of the tag to a new image.
Push the delayedjob and web images to the repository:
```
emeryrdev02[~]$ docker push localhost:5000/subpop_delayedjob
....
emeryrdev02[~]$ docker push localhost:5000/subpop_web
....
emeryrdev02[~]$
```
List the images:
```bash
emeryrdev02[~]$ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
subpop_delayedjob latest 2b44b46993a4 15 minutes ago 905 MB
subpop_web latest 2b44b46993a4 15 minutes ago 905 MB
localhost:5000/subpop_web latest 2b44b46993a4 15 minutes ago 905 MB
localhost:5000/subpop_delayedjob latest 2b44b46993a4 15 minutes ago 905 MB
...
```
## Run the application
Clone the `subpop-docker` project on the deployment server:
```
$ git clone ssh://git@gitlab.library.upenn.edu:2222/emeryr/subpop-docker.git
```
Copy a `.docker-environment` file into the `subpop-docker` folder. The file should
look like this:
```bash
MYSQL_ROOT_PASSWORD=<PASSWORD>
RAILS_ENV=production
RAILS_SERVE_STATIC_FILES=true
# DEV POP Flickr site keys
SUBPOP_FLICKR_API_KEY=REPLACEME
SUBPOP_FLICKR_API_SECRET=REPLACEME
SUBPOP_FLICKR_ACCESS_TOKEN=REPLACEME
SUBPOP_FLICKR_ACCESS_SECRET=REPLACEME
SUBPOP_FLICKR_USERID=REPLACEME
SUBPOP_FLICKR_USERNAME=REPLACEME
SUBPOP_DB_NAME=subpop
SUBPOP_DB_USER=root
SUBPOP_DB_PASSWORD=$MYSQL_<PASSWORD>
SUBPOP_DEVISE_SECRET_KEY=REPLACEME
SUBPOP_SECRET_TOKEN=<PASSWORD>ME
SUBPOP_SECRET_KEY_BASE=REPLACEME
```
Stop any running process:
```
emeryrdev02[~]$ cd subpop-docker
...
emeryrdev02[~/subpop-docker]$ sudo docker-compose stop
Stopping subpopdocker_delayedjob_1 ... done
Stopping subpopdocker_web_1 ... done
Stopping subpopdocker_db_1 ... done
emeryrdev02[~/subpop-docker]$
```
In a screen session, start the docker process:
```
emeryrdev02[~/subpop-docker]$ sudo docker-compose up
Starting subpopdocker_db_1
Starting subpopdocker_data_1
Recreating subpopdocker_web_1
Recreating subpopdocker_delayedjob_1
Attaching to subpopdocker_db_1, subpopdocker_data_1, subpopdocker_web_1, subpopdocker_delayedjob_1
subpopdocker_data_1 exited with code 0
web_1 | Array values in the parameter to `Gem.paths=` are deprecated.
web_1 | Please use a String or nil.
web_1 | An Array ({"GEM_PATH"=>["/usr/local/bundle"]}) was passed in from bin/rails:3:in `load'
web_1 | => Booting Puma
web_1 | => Rails 4.2.5 application starting in production on http://0.0.0.0:3000
web_1 | => Run `rails server -h` for more startup options
web_1 | => Ctrl-C to shutdown server
delayedjob_1 | [Worker(host:0c4eac4edced pid:1)] Starting job worker
delayedjob_1 | I, [2016-06-06T14:53:21.457020 #1] INFO -- : 2016-06-06T14:53:21+0000: [Worker(host:0c4eac4edced pid:1)] Starting job worker
web_1 | Puma starting in single mode...
web_1 | * Version 3.4.0 (ruby 2.2.4-p230), codename: Owl Bowl Brawl
web_1 | * Min threads: 0, max threads: 16
web_1 | * Environment: production
web_1 | * Listening on tcp://0.0.0.0:3000
web_1 | Use Ctrl-C to stop
```
If needed, run `rake db:migrate`:
```
emeryrdev02[~/subpop-docker]$ sudo docker-compose run web rake db:migrate
```
<file_sep>class RemoveContentTypeFromEvidence < ActiveRecord::Migration
def change
remove_column :evidence, :content_type, :string
end
end
<file_sep>##
# This concern is included in models that belong to a photo: Evidence,
# TitlePage, and ContextImage.
#
module BelongsToPhoto
extend ActiveSupport::Concern
included do
belongs_to :photo
delegate :has_image?, to: :photo, prefix: false, allow_nil: true
delegate :in_queue?, to: :photo, prefix: true, allow_nil: true
delegate :has_book?, to: :photo, prefix: true, allow_nil: true
delegate :image, to: :photo, prefix: false, allow_nil: true
end
def dequeue_photo
return unless photo.present?
return unless photo_in_queue?
return unless photo_has_book? # queue is meaningless otherwise
# mark without changing timestamp
photo.update_columns in_queue: false
end
def requeue_photo
return unless photo.present?
return if photo_in_queue?
return unless photo_has_book? # queue is meaningless otherwise
# mark without changing timestamp
photo.update_columns in_queue: true
end
end<file_sep># PublicationData represents columns shared by all Publishable objects
# (Evidence, TitlePage); columns include: flickr_id and metadata.
#
# The relationship between Publishable models and PublicationData is managed
# by the Publishable model concern.
class PublicationData < ActiveRecord::Base
include UserFields
# TODO add user fields?
belongs_to :publishable, polymorphic: true, inverse_of: :publication_data
validates :publishable, presence: true
def published_at
return if flickr_id.blank? # nil if not on flickr
updated_at
end
def clear_flickr_data
self.flickr_id = self.metadata = nil
end
end<file_sep>namespace :paperclip do
desc "Recreate attachments and save them to new destination"
task :move_attachments => :environment do
Photo.find_each do |photo|
unless photo.image_file_name.blank?
partition = sprintf("%09d", photo.id).scan /\d{3}/
parts = [
'public',
'system',
'photos',
'images',
partition,
'original',
photo.image_file_name
].flatten
filename = Rails.root.join(*parts)
if File.exists? filename
puts "Re-saving image attachment #{photo.id} - #{filename}"
image = File.new filename
photo.image = image
photo.save
# if there are multiple styles, you want to recreate them :
photo.image.reprocess!
image.close
else
puts "Couldn't find file: #{filename}"
end
end
end
end
end<file_sep># Custom methods for form tag handling.
module SubpopFormTagHelper
# Moving hint_tag handling into its own helper. Roughly parallels hint
# methods in SubpopFormbuilder.
def hint_tag obj, attribute, options={}
val = options[:hint_text] || hint_tag_text(obj, attribute, options)
return if val == ''
hint_class = options[:hint_class] || 'help-block'
tag = options[:hint_tag] || :span
# "<span class=\"help-block\">#{val}</span>"
content_tag tag, val, class: hint_class
end
def hint_tag_text obj, attribute, options={}
key = options[:hint_key] || hint_tag_key(obj, attribute)
t hint_tag_key(obj, attribute), default: ''
end
def hint_tag_key obj, attribute, options={}
"activerecord.hints.#{hint_tag_object_name obj}.#{attribute}"
end
def hint_tag_object_name obj
return obj.model_name.element if obj.is_a? ActiveRecord::Base
obj.to_s
end
end<file_sep>class CreatePublicationData < ActiveRecord::Migration
def migrate_data pub
return unless pub.on_flickr?
data = PublicationData.create!(
flickr_id: pub.flickr_id,
metadata: pub.flickr_info,
publishable: pub)
data.update_columns created_at: pub.published_at, updated_at: pub.published_at
end
def up
create_table :publication_data do |t|
t.string :flickr_id
t.text :metadata
t.integer :publishable_id
t.string :publishable_type
t.timestamps null: false
end
Evidence.find_each { |e| migrate_data e }
TitlePage.find_each { |t| migrate_data t }
end
def down
drop_table :publication_data
end
end
<file_sep>#!/usr/bin/env ruby
def handle_line line
s = line.strip
s = "\"#{s}\"" unless line =~ /^"/
s.gsub(/\u200F|\u200E/, '').gsub(/\&/, '&')
end
IO.foreach(File.expand_path('../../doc/POP_Names.csv', __FILE__)) do |line|
s = handle_line line
puts s
end
<file_sep>require 'rails_helper'
RSpec.describe Evidence, type: :model do
let(:subject) { create(:evidence) }
context 'factories' do
it "creates an evidence object" do
expect(create(:evidence)).to be_a Evidence
end
it "creates evidence that's on flickr" do
expect(create(:evidence_on_flickr)).to be_a Evidence
end
it 'creates a complete evidence instance' do
evidence = create(:evidence_complete)
expect(evidence).to be_a Evidence
expect(evidence.publication_data.publishable).to eq(evidence)
end
end
context 'flickr_metadata' do
it_behaves_like 'flickr_metadata'
end
context 'validations' do
it 'is valid' do
expect(build(:evidence)).to be_valid
end
it "is not valid if format is blank" do
expect(build(:evidence, format: nil)).not_to be_valid
end
it "is valid if format is a valid value" do
expect(build(:evidence, format: 'drawing_illumination')).to be_valid
end
it "it not valid if format is not in formats list" do
expect(build(:evidence, format: 'drawing_illuminationxxxx')).not_to be_valid
end
it "is not valid if format is 'other' and format_other is blank" do
expect(build(:evidence, format: 'other', format_other: nil)).not_to be_valid
end
it "has an error on format_other if it is blank and format is 'other'" do
evidence = build(:evidence, format: 'other', format_other: nil)
evidence.valid?
expect(evidence.errors[:format_other].size).to eq 1
end
it "is not valid if format_other is present unles format is 'other'" do
expect(build(:evidence, format: 'binding', format_other: 'ribbon')).not_to be_valid
end
it 'is valid if format_other is present and format is "other"' do
expect(build(:evidence, format: 'other', format_other: 'ribbon')).to be_valid
end
it "is valid if location is blank" do
expect(build(:evidence, location_in_book: nil)).to be_valid
end
it "is valid if location is in list" do
expect(build(:evidence, location_in_book: 'inside_front_cover')).to be_valid
end
it "is not valid if location is not in list" do
expect(build(:evidence, location_in_book: 'inside_front_coverxxxx')).not_to be_valid
end
it "is not valid if location is 'page_number' and location_in_book_page is blank" do
expect(build(:evidence, location_in_book: 'page_number', location_in_book_page: nil)).not_to be_valid
end
it "has an error on location_in_book_page if it is blank and location is 'page_number'" do
evidence = build(:evidence, location_in_book: 'page_number', location_in_book_page: nil)
evidence.valid?
expect(evidence.errors[:location_in_book_page].size).to eq 1
end
it "is not valid if location is not 'page_number' but location_in_book_page has a value" do
expect(build(:evidence, location_in_book: 'front_cover', location_in_book_page: 'some page')).not_to be_valid
end
it 'is valid if location_in_book_page is present and location is "page_number"' do
expect(build(:evidence, location_in_book: 'page_number', location_in_book_page: 'page 6')).to be_valid
end
end
end
<file_sep>##
# PageContextController is used to locate ContextImages for dynamic rediplay
# on evidence pages following an image crop.
#
# The `show` action locates the ContextImage for the provided Evidence `:id`.
# The `find` action locates the ContextImage for the provided Photo
# `:derivative_id`.
#
# The `:derivative_id` method for locating the ContextImage is required on the
# new Evidence page, as the evidence instance on that page is new and has no
# `id`.
#
class PageContextController < ApplicationController
include LinkToContextImage
before_action :set_evidence
before_action :set_derivative, only: [:find]
def show
@context_image = @evidence.context_image
respond_to do |format|
format.html
format.js
end
end
def edit
respond_to do |format|
format.html { render layout: !request.xhr? }
end
end
def update
link_to_context_image @evidence, evidence_params[:context_photo_id]
respond_to do |format|
if @evidence.update_by current_user, context_image: @context_image
format.html { redirect_to @evidence }
format.js
else
format.html { render :choose_context_image }
end
end
end
def find
@context_image = find_context_image @derivative
respond_to do |format|
# format.html
format.js
end
end
private
def find_context_image derivative
return unless derivative.present?
return unless derivative.original_id.present?
ContextImage.find_by photo_id: derivative.original_id
end
def evidence_params
params.require(:evidence).permit(
:context_image_id,
:context_photo_id
)
end
def set_evidence
return if params[:id].blank?
return if params[:id] == 'new'
@evidence = Evidence.find params[:id]
end
def set_derivative
return unless params[:derivative_id].present?
@derivative = Photo.find params[:derivative_id]
end
end<file_sep># README
This README would normally document whatever steps are necessary to get the
application up and running.
Things you may want to cover:
* Ruby version
## Software version
Ruby v2.2.3
Rails 4.2.4
* System dependencies
* Configuration
* Database creation
* Database initialization
* How to run the test suite
* Services (job queues, cache servers, search engines, etc.)
* Deployment instructions
* ...
Please feel free to use a different markup language if you do not plan to run
<tt>rake doc:app</tt>.
# Install
Install Docker Machine:
- <https://docs.docker.com/machine/install-machine/>
Follow these instructions for setting up Rails with `docker-compose`:
> Based on instructions here: <https://docs.docker.com/compose/rails/>
>
### Exceptions
Add `Dockerfile`:
```
FROM ruby:2.2.3
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev
RUN mkdir /subpop
WORKDIR /subpop
ADD Gemfile /subpop/Gemfile
RUN bundle install
ADD . /subpop
```
Add bootstrap `Gemfile`:
```
source 'https://rubygems.org'
gem 'rails', '4.2.0'
```
Add `docker-compose.yml`:
```yml
db:
image: mysql/mysql-server:5.7
env_file: .docker-environment
ports:
- "3306:3306"
web:
build: .
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/subpop
ports:
- "3000:3000"
links:
- db
```
Add `.docker-environment`:
```bash
MYSQL_ROOT_PASSWORD=<PASSWORD>
```
Run `docker-compose run` to create containers:
```bash
docker-compose run web rails new . --force --database=mysql --skip-bundle --skip-test-unit
```
Replace `Gemfile` with:
```ruby
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.4'
# Use mysql as the database for Active Record
# Ugh, Rails 4.2.4 is broken w/r/t/ mysql2 gem > 0.3.x
gem 'mysql2', '~> 0.3.18'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
```
Build the app:
```bash
docker-compose build
```
Replace `config/database.yml` with:
```yaml
# MySQL. Versions 5.0+ are recommended.
#
# Install the MYSQL driver
# gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
# gem 'mysql2'
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
#
default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: root
password: <%= ENV['MYSQL_ROOT_PASSWORD'] %>
host: db
development:
<<: *default
database: subpop
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: subpop_test
# As with config/secrets.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password as a unix environment variable when you boot
# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase"
#
# You can use this database configuration with:
#
# production:
# url: <%= ENV['DATABASE_URL'] %>
#
production:
<<: *default
database: subpop
username: subpop
password: <%= ENV['<PASSWORD>'] %>
```
Boot the app:
```bash
docker-compose up
```
# RSPEC
Add the following to the Gemfile test, development groups:
```ruby
group :development, :test do
gem 'spring-commands-rspec'
gem 'rspec-rails'
gem 'guard-rspec'
gem 'rb-fsevent' if `uname` =~ /Darwin/
end
```
`$ bundle install`
`$ rails g rspec:install`
# GUARD
`$ guard init`
Change guard invocation line from:
```ruby
guard :rspec, cmd: "bundle exec rspec" do
```
to:
```ruby
guard :rspec, cmd:"spring rspec" do
```
# BOOTSTRAP
The following instructions taken fromx
<http://www.gotealeaf.com/blog/integrating-rails-and-bootstrap-part-1>.
Add the gems:
```ruby
gem 'bootstrap-sass', '~> 3.2.0'
gem 'autoprefixer-rails'
```
`$ bundle install`
Rename `app/assets/stylesheets/application.css` to
`app/assets/stylesheets/application.css.sass`
```bash
$ mv app/assets/stylesheets/application.css \
app/assets/stylesheets/application.css.sass
```
Add the imports to `app/assets/stylesheets/application.css.sass`
```sass
@import "bootstrap-sprockets"
@import "bootstrap"
```
To `app/assets/javascripts/application.js` add the following after the
jQuery import:
```js
//= require bootstrap-sprockets
```
It should look like this when done:
```js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
```
# Markdown over rdoc for readme
rename README.rdoc -> README.md
# SIMPLE FORM
Add simple form gem:
```ruby
gem 'simple_form'
```
Run bundle install:
```bash
$ bundle install
```
Make simple_form use bootstrap:
```bash
$ rails generate simple_form:install --bootstrap
```
# MYSQL2
Remove sqlite3 and add mysql2 database gem.
```ruby
# Use sqlite3 as the database for Active Record
# gem 'sqlite3' # nope: de 20150113
# Add mysql2 adapter - de 20150113
gem 'mysql2'
```
Run bundle install:
```bash
$ bundle install
```
Replace config/database.yml contents with:
```yaml
# Using mysql2 gem:
#
# gem 'mysql2'
#
default: &default
adapter: mysql2
encoding: utf8
pool: 5
timeout: 5000
development:
<<: *default
database: pop_development
username: root
password:
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: pop_test
username: root
password:
production:
<<: *default
database: pop
username: popuser
password: ENV['<PASSWORD>']
```
Try to create the database:
```bash
$ rake db:create
```
Now, try to connect to the database:
```bash
$ mysql pop_development -u root -p
Enter password: # <-- password is blank; hit enter
# blah, blah, blah
mysql> \r
Connection id: 6450
Current database: pop_development
```
The database is empty, but you should be able to connect to it.
# DEVISE
Add devise to Gemfile:
```ruby
gem 'devise'
```
Run bundle install:
```bash
$ bundle install
```
Generate the initializer:
```bash
$ rails generate devise:install
```
Be sure to follow configuration instructions:
===============================================================================
Some setup you must do manually if you haven't yet:
1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
In production, :host should be set to the actual host of your application.
2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:
root to: "home#index"
3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:
config.assets.initialize_on_precompile = false
On config/application.rb forcing your application to not access the DB
or load models when precompiling your assets.
5. You can copy Devise views (for customization) to your app by running:
rails g devise:views
===============================================================================
Edit config files as described above:
```ruby
# config/environments/development.rb
# Devise stuff
# Ensure you have defined default url options in your environments files. Here
# is an example of default_url_options appropriate for a development environment
# in config/environments/development.rb:
# In production, :host should be set to the actual host of your application.
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
```
```ruby
# config/environments/production.rb
# Devise stuff
# Ensure you have defined default url options in your environments files. Here
# is an example of default_url_options appropriate for a development environment
# in config/environments/development.rb:
#
# config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
#
# In production, :host should be set to the actual host of your application.
# TODO: set production host for action_mailer
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
```
Add add a welcome#index controller and action for root:
```bash
$ rails g controller welcome index
```
Set the root in config/routes.rb to this action:
```ruby
# config/routes.rb
# You can have the root of your site routed with "root"
root to: 'welcome#index'
```
Start the rails server and make sure the route is working:
```bash
$ rails s
```
Now go to <http://localhost:3000>.
If it's working, then create the devise model and migrate the database.
```bash
$ rails generate devise user
invoke active_record
create db/migrate/20150113222857_devise_create_users.rb
create app/models/user.rb
invoke rspec
create spec/models/user_spec.rb
insert app/models/user.rb
route devise_for :users
$ rake db:migrate
```
See devise github page for configuring devise:
- <https://github.com/plataformatec/devise#controller-filters-and-helpers>
<file_sep>require 'rails_helper'
RSpec.describe Photo, type: :model do
context 'factory' do
it 'creates a photo' do
expect(create(:photo)).to be_a(Photo)
end
end
context 'initialization' do
it 'creates a photo' do
expect(Photo.new).to be_a(Photo)
end
end
end
<file_sep>class AddPublishingToEvidence < ActiveRecord::Migration
def change
add_column :evidence, :publishing_to_flickr, :boolean
end
end
<file_sep>class UserController < ApplicationController
before_action :set_user, except: [:index, :new, :create]
authorize_resource
def index
@users = User.all.order('username').page(params[:page])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "Successfully created user '#{@user.username}'."
redirect_to user_index_path
else
render :action => 'new'
end
end
def edit
end
def update
params_temp = user_params
params_temp.delete(:password) if params_temp[:password].blank?
if params_temp[:password].blank? && params_temp[:password_confirmation].blank?
params_temp.delete(:password_confirmation)
end
if @user.update_attributes(params_temp)
flash[:notice] = "Successfully updated user '#{@user.username}'."
redirect_to user_index_path
else
render :action => 'edit'
end
end
def destroy
@user.soft_delete
flash[:notice] = "Cancelled account '#{@user.username}'."
redirect_to user_index_path
end
private
def set_user
@user = User.find params[:id]
end
def user_params
params.require(:user).permit(:username, :email, :admin, :password, :password_confirmation, :restore_account, :full_name)
end
end<file_sep>class SetDefaultFalseOnDeletedInContextImages < ActiveRecord::Migration
def up
ContextImage.update_all deleted: false
# change_column_default(:suppliers, :qualification, 'new')
change_column_default :context_images, :deleted, false
end
def down
change_column_default :context_images, :deleted, nil
end
end
<file_sep>require 'rails_helper'
RSpec.describe User, type: :model do
context 'factory' do
it 'creates a User' do
expect(create(:user)).to be_a(User)
end
it 'creates an admin' do
expect(create(:admin)).to be_a(User)
end
end
context 'initialization' do
it 'creates a User' do
expect(User.new).to be_a(User)
end
it 'can be an admin' do
expect(build(:user, admin: true)).to be_a(User)
end
end
context 'validations:' do
it 'is valid' do
expect(build(:user)).to be_valid
end
it 'is invalid without a email' do
expect(build(:user, email: nil)).not_to be_valid
end
it 'is invalid without a password' do
expect(build(:user, password: nil)).not_to be_valid
end
it 'is invalid without a username' do
expect(build(:user, username: nil)).not_to be_valid
end
it 'must have a unique username' do
user = create(:user)
expect(build(:user, username: user.username)).not_to be_valid
end
it 'is not valid with username "all"' do
User.excluded_names = ["boz"]
expect(build(:user, username: "boz")).not_to be_valid
end
end
end
<file_sep>class AddOtherIdToBooks < ActiveRecord::Migration
def change
add_column :books, :other_id, :string
add_column :books, :other_id_type, :string
end
end
<file_sep># Following Devise Wiki instructions for soft_deleting a user, rather than the
# default devise behavior which is to destroy the account. We can't do delete
# the records because we will record the user ID information with the records
# they create and modify.
#
# https://github.com/plataformatec/devise/wiki/How-to:-Soft-delete-a-user-when-user-deletes-account
#
class Users::RegistrationsController < Devise::RegistrationsController
# DELETE /resource
def destroy
resource.soft_delete
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
set_flash_message! :notice, :destroyed
yield resource if block_given?
respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
end
end<file_sep>require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
RSpec.describe EvidenceController, type: :controller do
login_admin
let(:book) { create(:book) }
# This should return the minimal set of attributes required to create a valid
# Evidence. As you add validations to Evidence, be sure to
# adjust the attributes here as well.
# `book_id` is not a valid attribute for creating the object
let(:valid_attributes) {
{
format: 'binding',
book: book
}
}
# With an association, you can't push the model as a param; you have to push
# the foreign key
let(:valid_params) {
{
format: 'binding',
book_id: book
}
}
let(:invalid_attributes) {
{
format: nil,
book: book
}
}
let(:invalid_params) {
{
format: nil,
book_id: book
}
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# EvidenceController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET #index" do
it "assigns all evidence as @evidence" do
evidence = Evidence.create! valid_attributes
# evidence = Evidence.create! valid_attributes
get :index, {book: book}, valid_session
expect(assigns(:evidence)).to eq([evidence])
end
end
describe "GET #show" do
it "assigns the requested evidence as @evidence" do
evidence = Evidence.create! valid_attributes
get :show, {id: evidence.to_param}, valid_session
expect(assigns(:evidence)).to eq(evidence)
end
end
describe "GET #new" do
it "assigns a new evidence as @evidence" do
# the new action actually call evidence_params to get :format
get :new, { book_id: book.id, evidence: valid_params }, valid_session
expect(assigns(:evidence)).to be_a_new(Evidence)
end
end
describe "GET #edit" do
it "assigns the requested evidence as @evidence" do
evidence = Evidence.create! valid_attributes
get :edit, {id: evidence.id }, valid_session
expect(assigns(:evidence)).to eq(evidence)
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new Evidence" do
expect {
post :create, { book_id: book, evidence: valid_params }, valid_session
}.to change(Evidence, :count).by(1)
end
it "assigns a newly created evidence as @evidence" do
post :create, { book_id: book, evidence: valid_params }, valid_session
expect(assigns(:evidence)).to be_a(Evidence)
expect(assigns(:evidence)).to be_persisted
end
it "redirects to the created evidence" do
post :create, {book_id: book, evidence: valid_params }, valid_session
expect(response).to redirect_to(Evidence.last)
end
end
context "with invalid params" do
it "assigns a newly created but unsaved evidence as @evidence" do
post :create, { book_id: book, evidence: invalid_params }, valid_session
expect(assigns(:evidence)).to be_a_new(Evidence)
end
it "re-renders the 'new' template" do
post :create, { book_id: book, evidence: invalid_params }, valid_session
expect(response).to render_template("new")
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
{
year_when: "1931",
book_id: book
}
}
it "updates the requested evidence" do
evidence = Evidence.create! valid_attributes
put :update, { id: evidence.to_param, evidence: new_attributes }, valid_session
evidence.reload
expect(evidence.year_when).to eq(1931)
end
it "assigns the requested evidence as @evidence" do
evidence = Evidence.create! valid_attributes
put :update, {id: evidence.to_param, evidence: valid_attributes}, valid_session
expect(assigns(:evidence)).to eq(evidence)
end
it "redirects to the evidence" do
evidence = Evidence.create! valid_attributes
put :update, {id: evidence.to_param, evidence: valid_attributes}, valid_session
expect(response).to redirect_to(evidence)
end
end
context "with invalid params" do
it "assigns the evidence as @evidence" do
evidence = Evidence.create! valid_attributes
put :update, {id: evidence.to_param, evidence: invalid_attributes}, valid_session
expect(assigns(:evidence)).to eq(evidence)
end
it "re-renders the 'edit' template" do
evidence = Evidence.create! valid_attributes
put :update, {id: evidence.to_param, evidence: invalid_attributes}, valid_session
expect(response).to render_template("edit")
end
end
end
# describe "DELETE #destroy" do
# it "destroys the requested evidence" do
# evidence = Evidence.create! valid_attributes
# expect {
# delete :destroy, {id: evidence.to_param}, valid_session
# }.to change(Evidence, :count).by(-1)
# end
# it "redirects to the evidence list" do
# evidence = Evidence.create! valid_attributes
# delete :destroy, {id: evidence.to_param}, valid_session
# expect(response).to redirect_to(evidence_index_url)
# end
# end
end
<file_sep>require 'rails_helper'
RSpec.feature "Names", type: :feature do
scenario 'user creates name' do
login_as 'testuser'
click_link 'Names'
click_link 'New Name'
fill_in 'Name', with: '<NAME>'
fill_in 'Year start', with: 1735
fill_in 'Year end', with: 1818
fill_in 'VIAF identifier', with: '59880275'
fill_in 'Comment', with: 'The text of the comment.'
click_button 'Create Name'
expect(page).to have_content 'Name was successfully created.'
expect(page).to have_content '<NAME>'
expect(page).to have_content '1735'
expect(page).to have_content '1818'
expect(page).to have_content '59880275'
expect(page).to have_content 'The text of the comment.'
end
scenario 'user updates name' do
create_name_by 'testuser', { name: '<NAME>' }
login_as 'testuser'
# update the name
click_link 'Names'
find('tr', text: '<NAME>').click_link 'Edit'
# make sure the fields are empty
expect(page).to have_field 'Name', with: '<NAME>'
expect(find_field('Year start').value).to be_blank
expect(find_field('Year end').value).to be_blank
expect(find_field('VIAF identifier').value).to be_blank
expect(find_field('Comment').value).to be_blank
# fill in stuff
fill_in 'Year start', with: 1735
fill_in 'Year end', with: 1818
fill_in 'VIAF identifier', with: '59880275'
fill_in 'Comment', with: 'The text of the comment.'
click_button 'Update Name'
# confirm changes
expect(page).to have_content 'Name was successfully updated.'
expect(page).to have_content '<NAME>'
expect(page).to have_content '1735'
expect(page).to have_content '1818'
expect(page).to have_content '59880275'
expect(page).to have_content 'The text of the comment.'
end
end
<file_sep>class AddSammelbandToBooks < ActiveRecord::Migration
def change
add_column :books, :sammelband, :boolean
end
end
<file_sep>#!/usr/bin/env bash
# Sample command to connect to a mysql database running in a container
# You should probably memorize it. Ha ha! Just kidding.
# Here's the page where I got this:
#
# - https://hub.docker.com/_/mysql/
#
# docker run -it --link 72e4e053f5b0:mysql --rm mysql sh -c 'exec mysql -h"192.168.99.100" -P"3306" -uroot -p"<PASSWORD>"'
#
# Here's what all that means:
#
# run: run something
# -it: Run an [i]nteractive pseudo-[t]ty
#
# --link: Link an existing container (72e4e053f5b0) to a new
# container (mysql)
#
# --rm: Remove the new container (mysql) on exit
#
# -c: the command to run
MYSQL_SERVER_CONTAINER_ID=`docker ps | grep mysql-server | awk '{ print $1 }'`
if [[ -n "$MYSQL_SERVER_CONTAINER_ID" ]]; then
echo "Using MYSQL_SERVER_CONTAINER_ID: $MYSQL_SERVER_CONTAINER_ID:"
echo
docker ps | egrep "^CONTAINER|mysql-server" | sed 's/^/> /'
echo
else
echo "ERROR: couldn't find mysql-server in contain list:"
echo
docker ps | sed 's/^/> /'
echo
exit 1
fi
NEW_CONTAINER=mysql
DOCKER_MACHINE_IP=`docker-machine ip default`
echo "DOCKER_MACHINE_IP is $DOCKER_MACHINE_IP"
MYSQL_PORT=3306
MYSQL_USER=root
DOCKER_ENV=`dirname $0`/../.docker-environment
if [[ -f $DOCKER_ENV ]]; then
source $DOCKER_ENV
else
echo "ERROR: Could not find Docker environment file: $DOCKER_ENV"
exit 1
fi
if [[ -n "$MYSQL_ROOT_PASSWORD" ]]; then
:
else
echo "ERROR: Required env var MYSQL_ROOT_PASSWORD not set in $DOCKER_ENV"
exit 1
fi
docker run -it --link $MYSQL_SERVER_CONTAINER_ID:mysql \
--rm mysql \
sh -c "exec mysql -h\"$DOCKER_MACHINE_IP\" -P\"$MYSQL_PORT\" \-uroot -p\"$MYSQL_ROOT_PASSWORD\""
<file_sep>require 'rails_helper'
RSpec.describe ProvenanceAgent, type: :model do
context 'factory' do
it 'creates a ProvenanceAgent' do
expect(create(:provenance_agent)).to be_a(ProvenanceAgent)
end
end
context 'initialization' do
it 'creates a ProvenanceAgent' do
expect(ProvenanceAgent.new).to be_a(ProvenanceAgent)
end
end
context 'validations:' do
it 'is valid' do
expect(build(:provenance_agent)).to be_valid
end
it 'is invalid without a role' do
expect(build(:provenance_agent, role: nil)).not_to be_valid
end
it 'is invalid without an evidence' do
expect(build(:provenance_agent, evidence: nil)).not_to be_valid
end
it 'is invalid without a name' do
expect(build(:provenance_agent, name: nil)).not_to be_valid
end
end
end
<file_sep>class ContextImage < ActiveRecord::Base
include Publishable
include BelongsToPhoto
include UserFields
belongs_to :book, required: true, inverse_of: :context_images
has_many :evidence, inverse_of: :context_image, dependent: :nullify
delegate :full_name, to: :book, prefix: true, allow_nil: true
scope :used, -> { active.where 'evidence_count > 0'}
def name
return "context image" unless book_full_name.present?
"context image of #{book_full_name}"
end
def to_s
model_name.human
end
end
<file_sep>require 'rails_helper'
RSpec.feature 'Context images', type: :feature, js: true do
scenario 'user selects a context image' do
create_evidence_by 'testuser'
login_as 'testuser'
visit_evidence
expect(page).to have_content 'Page image'
click_link 'Link to page image'
expect(page).to have_content 'Choose page image'
choose 'Use image'
click_button 'Select context image'
expect(page).to have_button 'Remove link to page image'
end
scenario 'user removes a context image', type: :feature, js: true do
create_evidence_by 'testuser'
add_context_image_to_evidence_by 'testuser'
login_as 'testuser'
visit_evidence
expect(page).to have_button 'Remove link to page image'
click_button 'Remove link to page image'
expect(page).to have_link 'Link to page image'
expect(page).not_to have_button 'Remove link to page image'
end
scenario 'user edits evidence with a context image', type: :feature, js: true do
create_evidence_by 'testuser'
add_context_image_to_evidence_by 'testuser'
login_as 'testuser'
visit_evidence
click_link 'Edit'
fill_in 'Exact Year', with: 1822
click_button 'Update Evidence'
expect(page).to have_content 'Evidence was successfully updated.'
end
scenario 'user crops a new evidence', type: :feature, js: true do
create_book_with_photo_by 'testuser'
login_as 'testuser'
visit_new_bookplate
expect(page).not_to have_content 'Page image'
click_link 'Edit photo'
expect(page).to have_button 'Crop image'
click_button 'Crop image'
expect(page).to have_content 'Page image'
end
end<file_sep>class TitlePagesController < ApplicationController
before_action :set_title_page, only: [ :show, :destroy ]
before_action :set_book, only: [ :create, :destroy ]
authorize_resource
rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.json { head :forbidden }
format.html { redirect_to @book, :alert => exception.message }
end
end
def show
respond_to do |format|
format.html { redirect_to @title_page.book }
end
end
def create
@title_page = @book.title_pages.build title_page_params
respond_to do |format|
if @title_page.save_by current_user
format.html { redirect_to @book, notice: 'Added title page.' }
format.json { render :show, status: :ok, location: @book }
else
format.html { redirect_to @book, notice: 'Error adding title page' }
format.json { redirect_to json: @title_page.errors, status: :unprocessable_entity }
end
end
end
def destroy
@title_page.mark_deleted
DeletePublishableJob.perform_later @title_page, current_user
respond_to do |format|
format.js
format.html { redirect_to @book, notice: 'Title page was removed.' }
end
end
private
def title_page_params
params.require(:title_page).permit(:photo_id, :book_id)
end
def set_title_page
@title_page = TitlePage.find params[:id]
end
def set_book
@book = Book.find params[:book_id]
end
end
<file_sep>class AddPublishedAtToEvidence < ActiveRecord::Migration
def change
add_column :evidence, :published_at, :datetime
end
end
<file_sep>require 'rails_helper'
RSpec.describe Name, type: :model do
subject(:name) { create(:name) }
context 'initialization' do
it 'creates new name' do
expect(subject).to be_a Name
end
end
context 'validates' do
it "is valid" do
expect(build(:name)).to be_valid
end
it "isn't valid if name is blank" do
expect(build(:name, name: nil)).not_to be_valid
end
it "isn't valid is name is not unique" do
expect(build(:name, name: name.name)).not_to be_valid
end
it "is valid if VIAF ID is numerical" do
expect(build(:name, viaf_id: "123456789012345678901234567890")).to be_valid
end
it "is not valid if VIAF ID is not a number" do
expect(build(:name, viaf_id: "123456789012345678901234567890x")).not_to be_valid
end
end
context 'date_string' do
it 'returns nil when no dates provided' do
expect(build(:name, year_start: nil, year_end: nil).date_string).to be_nil
end
it 'returns a combined date' do
expect(build(:name, year_start: 1820, year_end: 1902).date_string).to eq('1820-1902')
end
it 'returns a "-<YEAR_END>" when only end year is provided' do
expect(build(:name, year_start: nil, year_end: 1902).date_string).to eq('-1902')
end
it 'returns a "<YEAR_START>-" when only start year is provided' do
expect(build(:name, year_start: 1820, year_end: nil).date_string).to eq('1820-')
end
end
context 'full_name' do
it 'returns a name without a date' do
expect(build(:name, name: "<NAME>").full_name).to eq("<NAME>")
end
it 'returns a name with a date' do
expect(build(:name, name: "<NAME>, 1820-1902").full_name).to eq("<NAME>, 1820-1902")
end
it 'returns a name without a date and a date string' do
expect(build(:name, name: "<NAME>", year_start: 1953).full_name).to eq("<NAME>, 1953-")
end
it 'returns a name with a date and a date string' do
expect(build(:name, name: "<NAME>, -1902", year_start: 1820, year_end: 1902).full_name).to eq("<NAME>, -1902")
end
end
context 'counter cache' do
it 'adds a new provenance agent' do
expect {
create(:provenance_agent, name: name)
}.to change { name.provenance_agents_count
}.by 1
end
it 'prevents destruction if counter cache is more than 0' do
create(:provenance_agent, name: name)
expect { name.destroy }.not_to change { Name.count }
end
it 'generates an error is counter cache is more than 0' do
create(:provenance_agent, name: name)
expect(name.destroy).to eq(false)
expect(name.errors.size).to eq(1)
end
it 'allows destruction if counter cache is 0' do
name = create(:name)
expect { name.destroy }.to change { Name.count }.by -1
end
end
end
<file_sep>class NamesController < ApplicationController
before_action :set_name, only: [:show, :edit, :update, :destroy]
authorize_resource
autocomplete :name, :name, full: true
# GET /names
# GET /names.json
def index
respond_to do |format|
format.html {
@search ||= params[:search]
if @search.present?
@names = Name.name_like("%#{params[:search]}%").order('name').page(params[:page])
else
@names = Name.order(:name).page params[:page]
end
}
format.json { @names = Name.name_like("%#{params[:term]}%").order('name').limit(20) }
end
end
# GET /names/1
# GET /names/1.json
def show
end
# GET /names/new
def new
@name = Name.new
respond_to do |format|
if request.xhr?
format.html {
@modal = true
render layout: false
}
else
format.html
end
end
end
# GET /names/1/edit
def edit
end
# POST /names
# POST /names.json
def create
@name = Name.new(name_params)
respond_to do |format|
if @name.save_by current_user
format.html { redirect_to @name, notice: 'Name was successfully created.' }
format.json { render :show, status: :created, location: @name }
format.js { render :show, status: :created, location: @name }
else
format.html { render :new }
format.json { render status: :unprocessable_entity }
format.js
end
end
end
# PATCH/PUT /names/1
# PATCH/PUT /names/1.json
def update
respond_to do |format|
if @name.update_by current_user, name_params
format.html { redirect_to @name, notice: 'Name was successfully updated.' }
format.json { render :show, status: :ok, location: @name }
else
format.html { render :edit }
format.json { render status: :unprocessable_entity }
end
end
end
# DELETE /names/1
# DELETE /names/1.json
def destroy
@name.destroy
respond_to do |format|
format.html { redirect_to names_url, notice: 'Name was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_name
@name = Name.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def name_params
params.require(:name).permit(:name, :year_start, :year_end, :viaf_id, :comment)
end
end
<file_sep>class AddFormatOtherToEvidence < ActiveRecord::Migration
def change
add_column :evidence, :format_other, :string
end
end
<file_sep>FactoryGirl.define do
factory :content_type do
sequence :name do |n|
"Content #{n}"
end
end
end<file_sep>class Flickr::TitlePagesController < Flickr::PublishablesController
end<file_sep>require 'rails_helper'
RSpec.describe AddToFlickrJob, type: :job do
let(:evidence) { create(:evidence) }
let(:user) { create :user }
subject(:job) { described_class.perform_later evidence }
it 'enquues the job' do
ActiveJob::Base.queue_adapter = :test
expect {
AddToFlickrJob.perform_later evidence, user.id
}.to have_enqueued_job(AddToFlickrJob).with evidence, user.id
end
it 'executes publish_new' do
expect(evidence).to receive(:publish_new)
described_class.perform_now evidence, user.id
end
end
<file_sep>#!/bin/sh
mysql -uroot -p""
<file_sep>class Evidence < ActiveRecord::Base
include Publishable
include BelongsToPhoto
include UserFields
attr_accessor :context_photo_id
belongs_to :book, required: true, inverse_of: :evidence
belongs_to :context_image, inverse_of: :evidence, counter_cache: true
has_many :evidence_content_types, dependent: :destroy
has_many :content_types, through: :evidence_content_types
accepts_nested_attributes_for :evidence_content_types, allow_destroy: true
has_many :provenance_agents, dependent: :destroy, inverse_of: :evidence
has_many :names, through: :provenance_agents
accepts_nested_attributes_for :provenance_agents, allow_destroy: true,
reject_if: proc { |attributes| attributes['name_id'].blank? }
delegate :photos, to: :book, prefix: true, allow_nil: true
delegate :photo, to: :context_image, prefix: true, allow_nil: true
delegate :photo_id, to: :context_image, prefix: true, allow_nil: true
FORMATS = [
[ 'Binding', 'binding' ],
[ 'Binding Waste', 'binding_waste' ],
[ 'Bookplate/Label', 'bookplate_label' ],
[ 'Drawing/Illumination', 'drawing_illumination' ],
[ 'Inscription', 'inscription' ],
[ 'Other paste-in', 'other_paste_in' ],
[ 'Stamp -- inked', 'stamp_inked' ],
[ 'Stamp -- blind or embossed', 'stamp_blind_or_embossed' ],
[ 'Stamp -- perforated', 'stamp_perforated' ],
[ 'Wax Seal', 'wax_seal' ],
[ 'Other Format', 'other' ],
]
FORMATS_BY_CODE = FORMATS.inject({}) { |hash, pair|
hash.merge(pair.last => pair.first)
}
LOCATIONS = [
[ 'Front Cover', 'front_cover' ],
[ 'Inside Front Cover', 'inside_front_cover' ],
[ 'Front Endleaf', 'front_endleaf' ],
[ 'Title Page', 'title_page' ],
[ 'Title Page, Verso', 'title_page_verso' ],
[ 'Page, Folio, or Signature Number',
'page_number' ],
[ 'Insertion', 'insertion' ],
[ 'Back Endleaf', 'back_endleaf' ],
[ 'Inside Back Cover', 'inside_back_cover' ],
[ 'Back Cover', 'back_cover' ],
[ 'Spine', 'spine' ],
[ 'Head, Tail, Fore Edge', 'head_tail_fore_edge' ],
]
LOCATIONS_BY_CODE = LOCATIONS.inject({}) { |hash, pair|
hash.merge(pair.last => pair.first)
}
validates :format, inclusion: { in: FORMATS.map(&:last), message: "'%{value}' is not in list" }
# validates :book, presence: true
validates :format_other, presence: true, if: :has_other_format?
validates :location_in_book, inclusion: { in: LOCATIONS.map(&:last), message: "'%{value}' is not in list", allow_blank: true }
validates :location_in_book_page, presence: true, if: :located_on_page?
validates :format_other, absence: true, unless: :has_other_format?
validates :location_in_book_page, absence: true, unless: :located_on_page?
def full_name
sprintf "%s, %s", (format_name || 'New evidence'), book_full_name
end
def format_name
return format_other if self.format == 'other_format'
FORMATS_BY_CODE[self.format]
end
def location_name
return location_in_book_page if location_in_book == 'page_number'
LOCATIONS_BY_CODE[location_in_book]
end
def content_type_names
content_types.map(&:name)
end
def evidence_summary
[ format_name, content_type_names ].flat_map { |s|
s.present? ? s : []
}.join ', '
end
def has_date?
[ year_when, year_start, year_end ].any? &:present?
end
def has_other_format?
format == 'other'
end
def located_on_page?
location_in_book == 'page_number'
end
def date_string
return nil unless has_date?
return year_when.to_s if year_when.present?
[ year_start, year_end ].join '-'
end
def to_s
format_name
end
end<file_sep>json.extract! @name, :id, :name, :viaf_id, :created_at, :updated_at
<file_sep>module ApplicationHelper
include SubpopFormTagHelper
def human_name obj, attr
obj && obj.class.human_attribute_name(attr) || ''
end
NON_EVIDENCE_PHOTOS = [
[ 'Title page', 'title_page' ],
[ 'Remove from queue', 'unqueue' ],
]
PHOTO_ASSIGNMENTS = [
[ 'Evidence format', Evidence::FORMATS ],
[ 'Non-evidence', NON_EVIDENCE_PHOTOS ],
]
FLICKR_STATUS_LABEL_CLASSES = {
Publishable::UNPUBLISHED => "label-warning",
Publishable::UP_TO_DATE => "label-success",
Publishable::OUT_OF_DATE => "label-danger",
Publishable::IN_PROCESS => "label-info"
}
def link_to_add_fields(name, f, association, options={})
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
options[:class] ||= ""
options[:class] += " add_fields"
options[:data] = {id: id, fields: fields.gsub("\n", "")}
link_to(raw(name), '#', options)
end
def thumbnail_link_to item,path=nil
return unless item.has_image?
link_to thumbnail_image_tag(item), item.image.url(:original), target: '_blank',
'data-toggle': 'tooltip', title: 'Click to open in new window'
end
def thumbnail_image_tag item
return unless item.has_image?
image_tag item.image.url(:thumb), class: 'img-thumbnail'
end
def parent_thumbnail_path parent, photo, options={}
unless parent.persisted?
parent_type = parent.model_name.plural
return thumbnail_path photo, options.merge(parent_type: parent_type)
end
case parent
when Book
book_thumbnail_path parent, photo, options
when TitlePage
title_page_thumbnail_path parent, photo, options
when Evidence
evidence_thumbnail_path parent, photo, options
when ContextImage
context_image_thumbnail_path parent, photo, options
end
end
def link_to_delete_publishable book, item, options
if item.processing?
options[:disabled] = true
options[:title] = "Processing; please wait..."
name = "Please wait..."
path = '#'
else
format = item.publishable_format
options[:data] ||= {}
options[:data][:confirm] = "Delete this #{format}?"
options[:method] = :delete
name = 'Delete'
path = [book,item]
end
link_to name, path, options
end
##
# Returns a dasherized tag to add to HTML id elements. For example, for an
# TitlePage object with `id` 6, will retrun `title-page-6`
def html_id_for obj
return '' if obj.nil?
"#{obj.model_name.element.dasherize}-#{obj.id}"
end
def flickr_label_class flickr_status
FLICKR_STATUS_LABEL_CLASSES[flickr_status] || "label-default"
end
def bootstrap_class_for(flash_type)
case flash_type
when "success"
"alert-success" # Green
when "error"
"alert-danger" # Red
when "alert"
"alert-warning" # Yellow
when "notice"
"alert-info" # Blue
else
flash_type.to_s
end
end
def hint_text_tag obj, attribute
obj = obj.object if obj.kind_of? ActionView::Helpers::FormBuilder
key = "activerecord.hints.#{obj.model_name.element}.#{attribute.to_s}"
val = t key, default: ''
return if val == ''
raw "<span class=\"help-block\">#{val}</span>"
end
# We don't call this 'thumbnail' because bootstrap has a 'thumbnail' class.
# A `thumb-container` is a `<div>` that contains a 'thumb` div, which
# itself conatins the actual content.
#
# The ThumbnailsController returns an html fragment containing a `thumb`.
# The `thumb` has `data` attributes that make possible finding it and its
# corresponding `thumb-container`. These are
#
# 'data-parent': ID of the parent Book, Evidence, TitlePage, etc.,
# or 'new' if the parent has not been persisted
#
# 'data-parent-type': plural underscore name of the parent; `books`,
# 'evidence', etc. ('evidence' is uninflected)
#
# 'data-thumbnail': ID of the photo
#
# 'data-source-photo': [`thumb` only] ID of the original photo
#
# When an image is edited and a new photo created, we want to dynamically
# display the new photo in the place of the one being replace. Since the new
# photo will have a new ID, we can't use its ID to find the right parent
# `thumb-container`. The `data-source-photo`, when present, is used to find
# the correct `div`.
#
# Valid options:
#
# `:source_photo`: source photo ID
#
def thumb_div parent, photo, options={}, &block
attrs = {
'class': 'thumb',
'data-parent': parent.id || 'new',
'data-parent-type': parent.model_name.plural,
'data-thumbnail': photo.id,
'data-source-photo': source_photo_id(options)
}
content_tag 'div', attrs do
yield if block_given?
end
end
def edit_photo_div parent, photo, options={}, &block
attrs = {
'class': 'edit-photo',
'data-parent': parent.id || 'new',
'data-parent-type': parent.model_name.plural,
'data-thumbnail': photo.id,
'data-source-photo': source_photo_id(options)
}
content_tag 'div', attrs do
yield if block_given?
end
end
def source_photo_id options={}
return if options[:source_photo].blank?
return options[:source_photo].id if options[:source_photo].is_a?(Photo)
options[:source_photo]
end
##
# Using format the datetime string, by default output looks like this:
#
# Mon 14 Mar 2016 4:00PM EDT
#
# Not really much use unless you're using the default format.
#
# TODO: If need, add options for canned date formats like `:long`, `:short`,
# `:w3c`, etc.
def format_datetime datetime, fmt="%F %H:%M %Z"
return unless datetime.present?
datetime.strftime fmt if datetime
end
# Use devis links outside of devise controllers:
# http://stackoverflow.com/a/6393151
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
##
# Create select options for all users, marking as selected the options for
# `username`. If `username` is `all`, 'All users' will be selected. If
# `username` is `nil`, `current_user` will be selected.
def user_filter_options username=nil
user_list = User.by_name.map { |u| [u.username, u.username] }
user_list.unshift ['All users', 'all']
selected = get_user_filter username
options_for_select user_list, selected
end
def get_user_filter username=nil
return username.downcase if username.present?
return 'all' unless user_signed_in?
current_user.username
end
end
<file_sep>module LinkToContextImage
extend ActiveSupport::Concern
##
# Link item to ContextImage if item responds to `:context_image=`.
#
# Use option `:no_clobber` to prevent reassignment.
def link_to_context_image item, source_photo_id, options={}
return unless item.respond_to? :context_image=
return if options[:no_clobber] && item.context_image.present?
item.context_image = get_context_image source_photo_id
end
def get_context_image source_photo_id
return nil unless source_photo_id.present?
photo = Photo.find source_photo_id
return unless photo.book_id.present?
@context_image = ContextImage.find_or_create_by! photo_id: photo.id, book_id: photo.book_id
end
end<file_sep>class Photo < ActiveRecord::Base
belongs_to :book, inverse_of: :photos
# Join photo to self. A photo can belong to an original, and inversely an
# original can have many derivatives.
belongs_to :original, class_name: 'Photo', inverse_of: :derivatives
has_many :derivatives, class_name: 'Photo', inverse_of: :original, foreign_key: :original_id, dependent: :nullify
# We nullify here, when photos are deleted. This makes possible deleting an
# entire book, which may choose to delete photos before evidence, etc.
# Without :nullify a foreign key constraint will be violated when the photo
# is deleted.
has_many :title_pages, inverse_of: :photo, dependent: :nullify
has_many :evidence, inverse_of: :photo, dependent: :nullify
has_many :context_images, inverse_of: :photo, dependent: :nullify
# See config/initializers/paper_clip.rb for :url and :path
has_attached_file :image,
styles: {
original: [ '1800x1800>', :jpg ],
medium: [ '800x800>', :jpg ],
small: [ '400x400>', :jpg ],
thumb: [ '190x190>', :jpg ]
}, convert_options: {
thumb: "-quality 75 -strip"
},
preserve_files: false,
path: Rails.configuration.x.subpop.paperclip_path,
url: Rails.configuration.x.subpop.paperclip_url
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
process_in_background :image, processing_image_url: "/images/:style/processing.png"
scope :queued, -> { where in_queue: true }
scope :unqueued, -> { where in_queue: false }
def image_data
Paperclip.io_adapters.for(image)
end
def has_image?
image.present?
end
def has_book?
book.present?
end
# Set the image from the base64-encoded url
def data_url= url
self.image = url
end
# No use in returning a data_url, but we don't want form fields to break for
# lack of the attribute.
def data_url
nil
end
def orphaned?
return false if book.present?
!used?
end
def cropped?
book.blank?
end
# Return true if the photo is not a attached to a book and is associated
# with less than 2 publishables.
def isolated?
return false if book.present?
use_count < 2
end
def use_count
evidence.count + title_pages.count + context_images.count
end
##
# Return false, unless the photo has been used for evidence, title page, or
# context image.
def used?
return true unless evidence.empty?
return true unless title_pages.empty?
return true unless context_images.empty?
false
end
end<file_sep># 2016-09-30 DE: Updating Dockerfile following <NAME>' "Dockerize a
# Rails 5, Postgres, Redis, Sidekiq and Action Cable Application":
#
# http://nickjanetakis.com/blog/dockerize-a-rails-5-postgres-redis-sidekiq-action-cable-app-with-docker-compose
#
FROM ruby:2.2.5-slim
MAINTAINER <NAME> <<EMAIL>>
RUN apt-get update -qq && apt-get install -y --no-install-recommends \
libmysqlclient-dev \
build-essential \
imagemagick \
file
ENV INSTALL_PATH /subpop
RUN mkdir -p $INSTALL_PATH
WORKDIR $INSTALL_PATH
COPY Gemfile Gemfile.lock ./
RUN bundle install --binstubs
COPY . .
# We're not setting any of the SUBPOP vars; we just need some dummy information
# so we can precompile the assets.
RUN bundle exec rake \
RAILS_ENV=production \
SUBPOP_DEVISE_SECRET_KEY=dummy \
SUBPOP_FLICKR_API_KEY=dummy \
SUBPOP_FLICKR_API_SECRET=dummy \
SUBPOP_FLICKR_ACCESS_TOKEN=dummy \
SUBPOP_FLICKR_ACCESS_SECRET=dummy \
SUBPOP_FLICKR_USERID=dummy \
SUBPOP_FLICKR_USERNAME=dummy \
SUBPOP_SECRET_KEY_BASE=dummy \
SUBPOP_SECRET_TOKEN=dummy \
SUBPOP_EMAIL_FROM=dummy \
SUBPOP_SMTP_HOST=example.com \
assets:precompile --trace
VOLUME ["$INSTALL_PATH/public"]
# From the blog:
# In production you will very likely reverse proxy Rails with nginx.
# This sets up a volume so that nginx can read in the assets from
# the Rails Docker image without having to copy them to the Docker host
#
# TODO: Figure out how to handle paperclip images in `public/system`. Use an
# s3 style client?
# Delete old server.pid or it just won't start
CMD [ "rm", "-f" "/subpop/tmp/pids/server.pid"]
CMD ["rails","server","-b","0.0.0.0"]
# CMD ["rake","jobs:work"]
# CMD ["foreman","start"]<file_sep>##
# This concern manages the including model's presence on Flickr:
#
# - initial publication of the object's photo, tags, and metadata;
# - subsequent updates to the tag and metadata; and
# - deletion of the photo from Flickr.
#
# Including models should belong to a Photo and have these attributes:
# `book_id`, `book` `flickr_id`, `flickr_info`, `published_at`, and
# `publishing_to_flickr`.
#
# Flickr informatino is stored in the PublicationData assocation. Each
# Publishable may have one PublicationData. Upon initial publication, a
# PublicationData object is created. It is then updated upon subsequent
# updates to Flickr; and deleted if an item is unpublished. Any item on Flickr
# should have an associated PublicationData instance.
##
module Publishable
extend ActiveSupport::Concern
include FlickrMetadata
UNPUBLISHED = "unpublished"
UP_TO_DATE = "up-to-date"
OUT_OF_DATE = "out-of-date"
IN_PROCESS = "in-process"
included do
has_one :publication_data, as: :publishable, inverse_of: :publishable,
dependent: :destroy
accepts_nested_attributes_for :publication_data
delegate :updated_at, to: :book, prefix: true, allow_nil: true
delegate :updated_at, to: :photo, prefix: true, allow_nil: true
delegate :published_at, to: :publication_data, prefix: false, allow_nil: true
delegate :flickr_id, to: :publication_data, prefix: false, allow_nil: true
delegate :full_name, to: :book, prefix: true, allow_nil: true
delegate :cropped?, to: :photo, prefix: true, allow_nil: true
scope :active, -> { where deleted: false }
end
def publish user_id
return unless publishable?
# TODO: Changing to update_columns as a kludge in order to prevent
# changing the timestamp. Need to add locking/in_process tracking to
# different object.
mark_in_process
return publish_new user_id unless on_flickr?
republish user_id
end
def publish_new user_id
begin
client = Flickr::Client.connect!
id = client.upload(photo.image_data, upload_data)
info = client.get_info id
self.publication_data ||= PublicationData.new publishable: self
self.publication_data.assign_attributes flickr_id: id, metadata: info.to_json
self.publication_data.save_by! User.find user_id
ensure
unmark_in_process
end
end
def republish user_id
begin
client = Flickr::Client.connect!
tags_to_remove.each do |tag|
begin
client.remove_tag tag
rescue FlickRaw::FailedResponse => ex
Rails.logger.warn "Unable to delete tag: #{tag}; reason #{ex}"
end
end
client.set_tags flickr_id, flickrize_tags(tags_from_object)
client.set_meta flickr_id, metadata
info = client.get_info flickr_id
self.publication_data.assign_attributes metadata: info.to_json
self.publication_data.update_by! User.find user_id
ensure
unmark_in_process
end
end
def on_flickr?
# flickr_id is delegated to publication_data; flickr_id.present? returns
# true only if publication_data and publication_data.flickr_id are present
flickr_id.present?
end
##
# Returns `true` if the item can be removed from Flickr; specifically if the
# item's Flickr status is `UP_TO_DATE` or `OUT_OF_DATE`. Items with status
# `IN_PROCESS` and `UNPUBLISHED` cannot be removed from Flickr.
def unpublishable?
[ UP_TO_DATE, OUT_OF_DATE ].include? flickr_status
end
##
# Returns `true` if the Flickr status of the model is `UNPUBLISHED` or
# `OUT_OF_DATE`.
#
def publishable?
[ UNPUBLISHED, OUT_OF_DATE ].include? flickr_status
end
def mark_in_process
return if publishing_to_flickr? # already marked true
update_columns publishing_to_flickr: true
end
def unmark_in_process
return unless publishing_to_flickr? # already marked false
update_columns publishing_to_flickr: false
end
def publishable_format
if respond_to? :format_name
format_name
else
"#{model_name.human}"
end
end
##
# Returns the current flickr status of the model, one of:
#
# - Publishable::UNPUBLISHED
# - Publishable::UP_TO_DATE
# - Publishable::OUT_OF_DATE
# - Publishable::IN_PROCESS
def flickr_status
return IN_PROCESS if publishing_to_flickr?
return UNPUBLISHED unless on_flickr?
return OUT_OF_DATE if changed_since_publication?
UP_TO_DATE
end
def processing?
flickr_status == IN_PROCESS
end
##
# Delete the photo from flickr and nullify the Flickr attributes
# `flickr_id`, `flickr_info`, and `published_at`.
#
# **Does not save the attribute changes.** Caller must save or destroy the
# model object.
def delete_from_flickr user_id=nil
return unless user_id.present?
begin
# DE - 2016-08-05 change delete_from_flickr behavior to clear flickr data;
# previously, publication_data was deleted; changed to keep pub..n_data,
# but clear flickr_id and metadata. #on_flickr? changed to report presence
# of publication_data.flickr_id (handled by delegate; above)
return unless on_flickr?
client = Flickr::Client.connect!
client.delete flickr_id
# remove all the flickr data
self.publication_data.clear_flickr_data
self.publication_data.save_by! User.find user_id
ensure
unmark_in_process
end
end
def mark_deleted
update_attributes deleted: true
end
def unmark_deleted
update_attributes deleted: false
end
##
# Return whether `last_updated` (see `#last_updated`) has changed since
# publication. Always returns `true` if the flickr ID column is empty;
# otherwise, returns true if `last_updated` timestamp is newer than
# `published_at` timestamp plus one second.
#
# NOTES:
#
# Not sure whether this method always gives the desired result -- is it
# possible that insignificant changes to the object will result in a repush?
#
# One second is added to the published_at time. The updated_at value for the
# `Publishable` model will always be at least a few millisceconds after the
# `published_at` value; as in this case, for example:
#
# publishable.update_attributes published_at: DateTime.now
#
# MySQL has seconds precision for datetime values; however, it is possible
# (about 2 times out of a thousand based on my crude tests) for updated_at to
# be in the next second. Adding the second to published_at should catch those
# cases.
def changed_since_publication?
return true unless on_flickr?
last_updated > published_at + 1.second
end
##
# Return the latest `updated_at` for model, photo, or book.
def last_updated
[updated_at, book_updated_at, photo_updated_at].compact.max
end
end<file_sep>class Flickr::PublishablesController < Flickr::BaseController
before_action :set_book
def show
authorize! :read, @item
respond_to do |format|
format.html { render layout: !request.xhr? }
end
end
private
def set_book
@item ||= get_item
@book = Book.find @item.book_id # god only knows why i have to do this
end
end
<file_sep>require 'rails_helper'
RSpec.describe DeletePublishableJob, type: :job do
# make sure the photo is orphaned
let(:photo) { create(:photo, book: nil) }
let(:evidence) { create(:evidence, photo: photo) }
let(:user) { create(:user) }
it 'enquues the job' do
ActiveJob::Base.queue_adapter = :test
expect {
DeletePublishableJob.perform_later evidence
}.to have_enqueued_job(DeletePublishableJob).with evidence
end
it 'executes destroy' do
expect(evidence).to receive(:destroy)
described_class.perform_now evidence, user
end
it 'destroys the photo' do
expect(photo).to receive(:destroy)
DeletePublishableJob.perform_now evidence, user
end
end
<file_sep>class AddAttachmentColumnsToTitlePages < ActiveRecord::Migration
def change
add_attachment :title_pages, :image
end
end
<file_sep>require 'rails_helper'
RSpec.feature "Books", type: :feature, js: true do
feature 'User creates a book' do
scenario 'with evidence' do
login_as 'testuser'
# create a book with an images
visit '/books/new'
fill_in 'Current repository', with: 'Penn Libraries'
fill_in 'Call number / Shelf mark', with: 'BK 123'
fill_in 'Title', with: 'Holy Bible'
fill_in 'Publisher / Printer / Scribe', with: 'Aitken'
attach_file 'image_', "#{Rails.root}/spec/fixtures/images/BS_185_178207.jpg"
click_button 'Create Book'
expect(page).to have_content 'Book was successfully created.'
expect(page).to have_content '1 photos'
expect(page).to have_css '.field-value', text: 'Penn Libraries'
expect(page).to have_select 'use', selected: 'Use image for'
# Use the image for a bookplate
select 'Bookplate/Label'
expect(page).to have_content 'New Bookplate/Label'
click_button 'Create Evidence'
# Confirm the page exists
expect(page).to have_content 'Evidence was successfully created.'
expect(page).to have_content 'Publish image'
# return to the book page
click_link 'Book'
expect(page).to have_content 'Publish image'
expect(page).to have_content 'Publish book'
# look at the details
click_link 'Details'
expect(page).to have_content 'Bookplate/Label'
end
scenario 'with a title page' do
login_as 'testuser'
visit '/books/new'
fill_in 'Current repository', with: 'Penn Libraries'
fill_in 'Call number / Shelf mark', with: 'BK 123'
fill_in 'Title', with: 'Holy Bible'
fill_in 'Publisher / Printer / Scribe', with: 'Aitken'
attach_file 'image_', "#{Rails.root}/spec/fixtures/images/BS_185_178207.jpg"
click_button 'Create Book'
expect(page).to have_content 'Book was successfully created.'
expect(page).to have_content '1 photos'
expect(page).to have_css '.field-value', text: 'Penn Libraries'
expect(page).to have_select 'use', selected: 'Use image for'
# Use the image for a bookplate
select 'Title page'
expect(page).to have_content 'Remove title page'
click_link 'Preview'
expect(page).to have_css 'h1', text: 'Title'
# Note: following '×' is the rendering of ×
click_button '×'
end
end
end
<file_sep>require 'rails_helper'
RSpec.feature "Evidence", type: :feature, js: true do
scenario 'User previews evidence' do
create_evidence_by 'testuser'
login_as 'testuser'
visit_evidence
find("a[data-modal-id=preview-modal]").trigger 'click'
expect(page).to have_css 'h1', text: 'Title'
expect(page).to have_css 'h1', text: 'Tags'
end
end<file_sep>Rails.application.routes.draw do
get 'flash/show'
resources :books do
resources :evidence, only: [ :create, :new, :destroy ]
resources :photos, only: [ :update, :index, :show ] do
patch 'restore_queue', on: :collection
end
resources :title_pages, only: [ :create, :destroy ]
resources :thumbnails, only: :show
resources :context_images, only: :destroy
end
resources :page_context, only: [:show,:edit,:update]
get '/page_context/find/:derivative_id' => 'page_context#find', as: 'find_page_context'
resources :title_pages, only: [:show] do
resources :thumbnails, only: :show
end
resources :evidence, only: [ :show, :update, :edit, :index ] do
resources :thumbnails, only: :show
end
resources :names do
get :autocomplete_name, on: :collection
end
resources :context_images, only: [] do
resources :thumbnails, only: :show
end
resources :thumbnails, only: :show
# Routes for cropping photos. Apart from :books, all resources are nested as
# a convention for passing the parent and photo to a single controller for
# universal handling of cropping and dynamic display of the edited images.
#
# The Cropping::PhotosController relies on the ThumbnailsController for
# display of edited photos.
#
# See `app/controllers/concerns/polymorphic_parent.rb` for details.
namespace :cropping do
resources :photos, only: [:new, :create]
resources :books, only: [] do
resources :photos, only: [ :edit, :update, :new, :create ]
end
resources :evidence, only: [] do
resources :photos, only: [ :edit, :update, :new, :create ]
end
resources :title_pages, only: [] do
resources :photos, only: [ :edit, :update, :new, :create ]
end
resources :context_images, only: [] do
resources :photos, only: [ :edit, :update, :create, :new ]
end
end
namespace :flickr do
resources :evidence, only: [ :show, :update, :destroy ] do
post :create, on: :member
get :status, on: :member
end
resources :title_pages, only: [ :show, :update, :destroy ] do
post :create, on: :member
get :status, on: :member
end
resources :books, only: [ :show, :update, :destroy ] do
post :create, on: :member
get :status, on: :member
end
resources :context_images, only: [ :show, :update, :destroy ] do
post :create, on: :member
get :status, on: :member
end
end
devise_for :users, :controllers => { :registrations => 'users/registrations' }
devise_scope :user do
get '/login' => 'devise/sessions#new'
get '/logout' => 'devise/sessions#destroy'
end
# devise_for :users, :skip => [:registrations]
as :user do
get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration'
put 'users' => 'devise/registrations#update', :as => 'user_registration'
delete 'users' => 'users/registrations#destroy', :as => 'delete_user_registration'
end
resources :user, :controller => "user"
get 'welcome/index'
root to: 'books#index'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
post 'books/:id/add_title_page/:photo_id' => 'books#add_title_page', as: :add_title_page, defaults: { format: :html }
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
<file_sep>class EvidenceContentType < ActiveRecord::Base
belongs_to :evidence, touch: true
belongs_to :content_type
end
<file_sep># To-do items
## Scratch
Add sidebar prompt to choose title page images
### General
Docker
- data volume for database
- logs
- test log options
<!-- - fix `.dockerignore` -- stop copying log files into container
+ figure out why `delayed_job.log` alone isn't ignored -->
- backup plan for database
- talk to OEM about setting up production box -- with space allocation for images
Set up permanent servers:
- Production
- Administration of workflow for "probation" users
Migrate current spreadsheets to app
Spreadsheet import: Deal with single images for multiple pieces of provenance
Add Blacklight to application
#### All sections:
Manage position of side image, when resizing to smaller page layout
- TODO Make image both fixed and responsive, from CSS comments:
// TOOD: Placeholder for the evidence image div, so we can make it fixed
// later. It's hard with bootstrap to fix the image *and* have it be
// responsive to window resizing. If fixed, the text floats over and
// covers the fixed image upon resizing.
#### Flickr ####
<!-- Move flickr_preview partial from shared to flickr/show view -->
#### Books ####
<!-- Add date_narrative field
- form
- show
- hint
-->
#### Evidence
<!-- Edit/New pages
- "Back to photo queue" anchor on Safari doesn't scroll down far enough -->
<!-- Create context images -->
<!-- Investigate image cropping -->
<!-- Evidence show page:
- Add name window from Add name list -->
Evidence form:
- Provenance agents hide/delete button instead of checkbox
Provenance agents:
- When selecting name and user hits enter, prevent form submission
<!-- Where?
- ?? Provenance place?
- Hint? <-- Try this one. "Give a place named in the provenance mark or the location of the book at the time the mark was added." -->
<!-- X - fit image in container
x - Decide whether a used master image can be edited and how to behave if yes
x
x - Option 1) If the image has been used for evidence or a title page, create
x a new photo object to assign to each publishable to which the image is
x attached
x
x - Option 2) If the image has been used for evidence or a title page, create
x a new *master* photo and edit it.
x
x - Option 3) Locking: Lock the master image if it has been used.
x
x - Option 3a) Modified locking: Lock master image, but allow it to be
x duplicated (this is about the same thing as Option 2).
x
x - set cropped modal max size to window size?
x - upload image to app
x - create/update image
x - when updating photo show progress bar for image in status element -->
<!-- x - Rename concern HasPhoto -> BelongsToPhoto -->
<!-- Automatically display context image created for cropped photos -->
<!-- Do not attach context image on crop if one is already assigned -->
<!-- Delete action for publishables removes 'Delete' button from all publishables -->
<!-- User model: exclude certain user names: 'all', 'admin', etc. -->
<!-- Add exception notification -->
<!-- - create context image -->
<!-- ## Flickr
- make sure flickrize_tags calculates correct tags for existing photos
## Unordered list of stuff -->
<!-- Rename HasPhoto to BelongsToPhoto; it's confusing as it's named now. -->
<!-- + stop copying `doc/api` -->
<!-- SubPopFormbuilder: hints don't work for nest form objects -->
<!-- User support: -->
<!-- - Add full_name to user -->
<!-- - Add user to books and evidence: `created_by`, `updated_by` -->
<!-- - Show user's books -->
<!-- - Push to Flickr workflow -->
<!-- Clean up pages; improve layout -->
<!-- Model name: -->
<!-- - replace `item.class.name.underscore` with `item.model_name.element`
throughout --><file_sep>FactoryGirl.define do
factory :provenance_agent do
association :evidence
association :name
role 'owner'
end
end
<file_sep>class DropTableEvidencePhotos < ActiveRecord::Migration
def up
drop_table :evidence_photos
end
def down
raise "Migration cannot be reversed"
end
end
<file_sep>require 'rails_helper'
RSpec.feature "Users", type: :feature, js: true do
scenario 'admin creates user' do
login_as 'adminx', admin: true
# go to the users page and create a new user
click_link 'Users'
click_link 'New User'
fill_in 'Full name', with: '<NAME>'
fill_in 'Username', with: 'doom'
fill_in 'Email', with: '<EMAIL>'
fill_in 'Password', with: '<PASSWORD>'
fill_in 'Password confirmation', with: '<PASSWORD>'
check 'Admin'
click_button 'Create'
# verify user created correctly
expect(page).to have_content "Successfully created user 'doom'."
find('tr', text: 'doom').click_link 'Edit'
expect(page).to have_field 'Full name', with: '<NAME>'
expect(page).to have_field 'Email', with: '<EMAIL>'
expect(page).to have_field 'Username', with: 'doom'
expect(page).to have_checked_field 'Admin'
end
scenario 'admin edits user' do
add_user('doom',
full_name: '<NAME>',
email: '<EMAIL>',
admin: true)
login_as 'adminx', admin: true
# go to the user edit page
click_link 'Users'
find('tr', text: 'doom').click_link 'Edit'
expect(page).to have_field 'Full name', with: '<NAME>'
expect(page).to have_field 'Email', with: '<EMAIL>'
expect(page).to have_field 'Username', with: 'doom'
expect(page).to have_checked_field 'Admin'
# edit the user
fill_in 'Full name', with: '<NAME>'
fill_in 'Email', with: '<EMAIL>'
uncheck 'Admin'
click_button 'Update'
expect(page).to have_content "Successfully updated user 'doom'."
# confirm user details
find('tr', text: 'doom').click_link('Edit')
expect(page).to have_field 'Full name', with: '<NAME>'
expect(page).to have_field 'Email', with: '<EMAIL>'
expect(page).to have_field 'Username', with: 'doom'
expect(page).to have_unchecked_field 'Admin'
end
scenario 'admin cancels user' do
add_user('doom',
full_name: '<NAME>',
email: '<EMAIL>',
admin: false)
login_as 'adminx', admin: true
# go to the user edit page and cancel the account
click_link 'Users'
find('tr', text: 'doom').click_link 'Edit'
click_button 'Cancel account'
expect(page).to have_content "Cancelled account 'doom'."
click_link 'adminx'
click_link 'Sign out'
# user tries to sign in
click_link 'Sign in'
fill_in 'Username', with: 'doom'
fill_in 'Password', with: '<PASSWORD>'
click_button 'Log in'
expect(page).to have_content 'Sorry, your account has been cancelled.'
end
scenario "admin restores user's account" do
add_user('doom',
full_name: '<NAME>',
email: '<EMAIL>',
admin: false,
deleted_at: Time.now)
login_as 'adminx', admin: true
# go to the user edit page and restore the account
click_link 'Users'
find('tr', text: 'doom').click_link 'Edit'
# Poltergeist reports 'Restore account' is overlapped by nav bar, but
# clearly from the screen shot it is not; using trigger instead
# click_button 'Restore account'
find("input[value='Restore account']").trigger 'click'
expect(page).to have_content "Successfully updated user 'doom'."
click_link 'adminx'
click_link 'Sign out'
# user signs in with restored account
click_link 'Sign in'
fill_in 'Username', with: 'doom'
fill_in 'Password', with: '<PASSWORD>'
click_button 'Log in'
expect(page).to have_content 'Signed in successfully.'
end
end
<file_sep>require 'rails_helper'
module Flickr
RSpec.describe Tag do
let(:tag_data) { JSON::load(%q{ {
"id": "130596540-24810167602-37659184",
"author": "130616888@N02",
"authorname": "popdevelopment",
"raw": "Penn Libraries",
"_content": "pennlibraries",
"machine_tag": 0
}}) }
subject(:subject) { Tag.new tag_data }
context "initialize" do
it "creates a Tag" do
expect {
Tag.new raw: "tag string"
}.not_to raise_error
end
it 'has an id' do
expect(subject.id).to eq("130596540-24810167602-37659184")
end
it 'has an author' do
expect(subject.author).to eq("130616888@N02")
end
it 'has an authorname' do
expect(subject.authorname).to eq("popdevelopment")
end
it 'has _content' do
expect(subject._content).to eq("pennlibraries")
end
it 'has machine_tag' do
expect(subject.machine_tag).to eq(0)
end
it 'creates a tag from hash' do
expect(Tag.new tag_data).to be_a Tag
end
it 'raises an error for bad options' do
expect {
Tag.new "not_an_option" => "Not an option", "_contentx" => "Content x"
}.to raise_error ArgumentError
end
end
context "quoting" do
it "quotes the string" do
expect(Tag.new(raw: "tag string").quote).to eq('"tag string"')
end
it "single quotes the string" do
expect(Tag.new(raw: "tag string").single_quote).to eq("'tag string'")
end
it "double quotes the string" do
expect(Tag.new(raw: "tag string").double_quote).to eq('"tag string"')
end
it "cute quotes the string with ` and '" do
expect(Tag.new(raw: "tag string").cute_quote).to eq("`tag string'")
end
end
context "formatting" do
it "leaves raw tags without spaces unchanged" do
expect(Tag.new(raw: "tagstring").flickr_format).to eq("tagstring")
end
it "quote raw tags with spaces" do
expect(Tag.new(raw: "tag string").flickr_format).to eq('"tag string"')
end
end
context "normalize" do
it "removes spaces" do
expect(Tag.new(raw: "tag string ").normalize).to eq("tagstring")
end
it "respects diacritics" do
expect(Tag.new(raw: "münchen").normalize).to eq("münchen")
end
it "strips underscores" do
expect(Tag.new(raw: "tag_string").normalize).to eq("tagstring")
end
it "strips punctuation" do
expect(Tag.new(raw: "tag,;@!'\"?.string").normalize).to eq("tagstring")
end
end
context 'text' do
it "returns normalize if _content not defined" do
expect(Tag.new(raw: "my tag").text).to eq("mytag")
end
it 'returns _content if it is defined' do
expect(Tag.new(raw: "my tag", _content: "othervalue").text).to eq("othervalue")
end
end
context 'equals' do
it 'says two tags are equal if the raw is the same' do
expect(Tag.new raw: 'a').to eq(Tag.new(raw: 'a'))
end
it 'says two tags are equal if the content equals the text' do
expect(Tag.new _content: 'a').to eq(Tag.new raw: 'a')
end
it 'says a flickr tag equals an ad hoc tag' do
expect(subject).to eq(Tag.new raw: 'Penn Libraries')
end
end
context 'tag sets' do
it 'subtracts one set from another' do
a = Tag.new raw: 'a'
b = Tag.new raw: 'b'
# We want two distinct tags that are equivalent
c1 = Tag.new raw: 'c'
c2 = Tag.new raw: 'c'
d = Tag.new raw: 'd'
set1 = [ a, b, c1 ]
set2 = [ c2, d ]
expect(set1 - set2).to eq([ a, b ])
end
end
end
end<file_sep>class EvidenceController < ApplicationController
before_action :set_book, only: [ :new, :create, :destroy ]
before_action :set_evidence, only: [:show, :edit, :update, :destroy, :choose_context_image, :update_context_image ]
authorize_resource
autocomplete :name, :name, full: true
# GET /evidence
# GET /evidence.json
def index
@evidence = Evidence.all
end
# GET /evidence/1
# GET /evidence/1.json
def show
end
# GET /evidence/new
def new
@evidence = @book.evidence.build evidence_params
end
# GET /evidence/1/edit
def edit
end
# POST /evidence
# POST /evidence.json
def create
@evidence = @book.evidence.build evidence_params
respond_to do |format|
if @evidence.save_by current_user
@evidence.dequeue_photo
format.html {
redirect_to @evidence, notice: 'Evidence was successfully created.'
}
format.json { render :show, status: :created, location: @evidence }
else
format.html { render :new }
format.json { render json: @evidence.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /evidence/1
# PATCH/PUT /evidence/1.json
def update
respond_to do |format|
if @evidence.update_by current_user, evidence_params
format.html { redirect_to [@evidence], notice: 'Evidence was successfully updated.' }
format.json { render :show, status: :ok, location: @evidence }
else
format.html { render :edit }
format.json { render json: @evidence.errors, status: :unprocessable_entity }
end
end
end
# DELETE /evidence/1
# DELETE /evidence/1.json
def destroy
@evidence.requeue_photo
@evidence.save_by current_user
@evidence.mark_deleted
DeletePublishableJob.perform_later @evidence, current_user
respond_to do |format|
format.js
format.html { redirect_to @book, notice: 'Evidence was deleted.' }
end
end
private
def get_photo
Photo.find params[:photo_id] if params[:photo_id].present?
end
# Use callbacks to share common setup or constraints between actions.
def set_evidence
@evidence = Evidence.includes(:book).find params[:id]
end
def set_book
@book = Book.find(params[:book_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def evidence_params
params.require(:evidence).permit(
:book_id,
:format,
:format_other,
:content_type,
:location_in_book,
:location_in_book_page,
:transcription,
:translation,
:year_when,
:year_start,
:year_end,
:date_narrative,
:where,
:comments,
:citations,
:photo,
:photo_id,
:context_photo_id,
:context_image_id,
content_type_ids: [],
provenance_agents_attributes: [ :id, :name_id, :role, :_destroy ]
)
end
end
<file_sep>class ProvenanceAgent < ActiveRecord::Base
belongs_to :evidence, required: true, inverse_of: :provenance_agents
belongs_to :name, required: true, counter_cache: true
delegate :full_name, to: :name, prefix: false, allow_nil: true
delegate :book, to: :evidence, allow_nil: true
ROLES = [
[ "Owner", "owner" ],
[ "Binder", "binder" ],
[ "Annotator", "annotator" ],
[ "Bookseller/Auction House", "bookseller" ],
[ "Librarian", "librarian" ],
[ "Unknown role", "unknown" ],
]
ROLES_BY_CODE = ROLES.inject({}) { |hash, pair|
hash.merge(pair.last => pair.first)
}
validates :role, inclusion: ROLES.map(&:last)
def role_name
return if role.blank?
ROLES_BY_CODE[role]
end
end
<file_sep>require 'rails_helper'
RSpec.describe ContentType, type: :model do
subject(:subject) { create :content_type }
context 'initialize' do
it 'creates a ContentType' do
expect(subject).to be_a ContentType
end
end
context 'factories' do
it "creates a content type" do
expect(create(:content_type)).to be_a ContentType
end
end
context 'validates' do
it "is valid" do
expect(subject).to be_valid
end
it "requires a name" do
expect(build(:content_type, name: nil)).not_to be_valid
end
it "requires name be unique" do
expect(build(:content_type, name: subject.name)).not_to be_valid
end
end
end
<file_sep># A concern for model classes that have created_by and updated_by fields
# Swiped wholesale from the new SDBM code:
#
# https://github.com/upenn-libraries/sdbmss/blob/master/app/models/concerns/user_fields.rb
module UserFields
extend ActiveSupport::Concern
included do
belongs_to :created_by, class_name: 'User'
belongs_to :updated_by, class_name: 'User'
delegate :username, to: :created_by, prefix: true, allow_nil: true
delegate :username, to: :updated_by, prefix: true, allow_nil: true
end
# Note that `#save_by` invokes `#save`, which does not take attributes.
def save_by(user, *args, &block)
self.created_by = user if !persisted?
self.updated_by = user
save *args, &block
end
# Note that `#save_by!` invokes `#save!`, which does not take attributes.
def save_by!(user, *args, &block)
self.created_by = user if !persisted?
self.updated_by = user
save! *args, &block
end
# Note that `#updated_by` invokes `#update`, which requires an `attributes`
# argument.
def update_by(user, attributes, &block)
self.updated_by = user
update attributes, &block
end
# Note that `#updated_by` invokes `#update`, which requires an `attributes`
# argument.
def update_by!(user, attributes, &block)
self.updated_by = user
update! attributes, &block
end
end<file_sep># This will guess the User class
FactoryGirl.define do
factory :photo do
image_file_name 'BS_185_178206.jpg'
image_content_type 'image/jpeg'
image_file_size 1060104
association :book
end
factory :actual_photo, class: Photo do
image File.new("#{Rails.root}/spec/fixtures/images/BS_185_178207.jpg")
association :book
end
end
<file_sep>class AddTranslationToEvidence < ActiveRecord::Migration
def change
add_column :evidence, :translation, :text
end
end
<file_sep>require 'rails_helper'
RSpec.describe UpdateFlickrJob, type: :job do
let(:user) { create :user }
let(:evidence) { create(:evidence) }
it 'enquues the job' do
ActiveJob::Base.queue_adapter = :test
expect {
UpdateFlickrJob.perform_later evidence, user.id
}.to have_enqueued_job(UpdateFlickrJob).with evidence, user.id
end
it 'executes republish' do
expect(evidence).to receive(:republish)
described_class.perform_now evidence, user.id
end
end
<file_sep># Flickr::Client uses FlickRaw for accessing Flickr.
module Flickr
class Client
# url_s : Square
# url_q : Large Square
# url_t : Thumbnail
# url_m : Small
# url_n : Small 320
# url : Medium
# url_z : Medium 640
# url_c : Medium 800
# url_b : Large
# url_o : Original
# url_profile
# url_photopage
# url_photoset, url_photosets
# url_short, url_short_m, url_short_s, url_short_t
# url_photostream
# Flickr API key
cattr_accessor :flickr_api_key
@@flickr_api_key = nil
# Flickr API secret
cattr_accessor :flickr_shared_secret
@@flickr_shared_secret = nil
# Following items are specific to the POP Flickr user account. SubPOP has
# a single Flickr account so we just connect to the one account.
#
# Flickr access token
cattr_accessor :flickr_access_token
@@flickr_access_token = nil
# Flickr access secret
cattr_accessor :flickr_access_secret
@@flickr_access_secret = nil
# Flickr user ID; the POP account userid
cattr_accessor :flickr_userid
@@flickr_userid = nil
# Flickr user name; the POP account user name
cattr_accessor :flickr_username
@@flickr_username = nil
@@flickr_required_vars = [
:@@flickr_api_key,
:@@flickr_shared_secret,
:@@flickr_access_token,
:@@flickr_access_secret,
:@@flickr_userid,
:@@flickr_username
]
class << self
def setup
yield self
end # setup
def validate
missing_attributes = []
@@flickr_required_vars.each do |var|
unless class_variable_get(var)
name = var.to_s.sub(/^@@/, '')
missing_attributes << "config.#{name} = ENV['#{name.upcase}']"
end # unless
end # @@flickr_required_vars.each
unless missing_attributes.empty?
raise <<-ERROR
Required Flickr::Client configuration variable(s) not set. Please set these
in the Flickr::Client initializer:
#{missing_attributes.join "\n "}
Please ensure you restarted your application after setting the variables.
ERROR
end # unless
end # validate
def connect! options={}
validate
client = Flickr::Client.new
client.connect
client
end # connect!
end # class << self
def connect
FlickRaw.api_key = Flickr::Client.flickr_api_key
FlickRaw.shared_secret = Flickr::Client.flickr_shared_secret
@flickr = FlickRaw::Flickr.new
@flickr.access_token = Flickr::Client.flickr_access_token
@flickr.access_secret = Flickr::Client.flickr_access_secret
@login = @flickr.test.login
end
# Upload file to Flickr with provided metadata and return the
# Flickr ID of the new photo. Data is hash containing any of
# the allowed Flickr upload arguments (see
# https://www.flickr.com/services/api/upload.api.html):
#
# :title (optional)
# The title of the photo.
#
# :description (optional)
# A description of the photo. May contain some limited HTML.
#
# :tags (optional)
# A space-seperated list of tags to apply to the photo.
#
# :is_public, :is_friend, :is_family (optional)
# Set to 0 for no, 1 for yes. Specifies who can view the photo.
#
# :safety_level (optional)
# Set to 1 for Safe, 2 for Moderate, or 3 for Restricted.
#
# :content_type (optional)
# Set to 1 for Photo, 2 for Screenshot, or 3 for Other.
#
# :hidden (optional)
# Set to 1 to keep the photo in global search results, 2 to hide
# from public searches.
#
#
def upload file, data={}
@flickr.upload_photo file, data
end
def get_info photo_id
@flickr.photos.getInfo photo_id: photo_id
end
def set_tags photo_id, tags
@flickr.photos.setTags photo_id: photo_id, tags: tags
end
def set_meta photo_id, metadata
@flickr.photos.setMeta({ photo_id: photo_id }.merge(metadata))
end
def url info, url_type
FlickRaw.send url_type, info
end
def remove_tag tag
@flickr.photos.removeTag tag_id: tag.id
end
def add_tags tags
tags.each do |tag|
end
end
def flickr
@flickr
end
# photo_id (Required)
# The id of the photo to delete.
#
# ERROR CODES
# ===========
#
# 1: Photo not found
# The photo id was not the id of a photo belonging to the
# calling user.
#
# 95: SSL is required
# SSL is required to access the Flickr API.
#
# 96: Invalid signature
# The passed signature was invalid.
#
# 97: Missing signature
# The call required signing but no signature was sent.
#
# 98: Login failed / Invalid auth token
# The login details or auth token passed were invalid.
#
# 99: User not logged in / Insufficient permissions
# The method requires user authentication but the user was not
# logged in, or the authenticated method call did not have the
# required permissions.
#
# 100: Invalid API Key
# The API key passed was not valid or has expired.
#
# 105: Service currently unavailable
# The requested service is temporarily unavailable.
#
# 106: Write operation failed
# The requested operation failed due to a temporary issue.
#
# 111: Format "xxx" not found
# The requested response format was not found.
#
# 112: Method "xxx" not found
# The requested method was not found.
#
# 114: Invalid SOAP envelope
# The SOAP envelope send in the request could not be parsed.
#
# 115: Invalid XML-RPC Method Call
# The XML-RPC request document could not be parsed.
#
# 116: Bad URL found
# One or more arguments contained a URL that has been used for
# abuse on Flickr.
#
def delete photo_id
@flickr.photos.delete(photo_id: photo_id)
end
end
end
<file_sep>json.array!(@names) do |name|
json.extract! name, :id, :name, :viaf_id
json.label name.full_name
json.value name.id
json.url name_url(name, format: :json)
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
content_types = [
"Armorial",
"Binder's Mark",
"Binding Stamp",
"Signature",
"Gift/Presentation",
"Monogram",
"Shelf Mark",
"Seller's Mark",
"Sale Record",
"Price/Purchase Information",
"Colophon",
"(De)Accession Mark",
"Forgery/Copy",
"Effaced",
"Bibliographic Note",
"Stamped Binding"
]
content_types.each do |name|
ContentType.find_or_create_by name: name
end
names_file = File.expand_path '../POP_Names.txt', __FILE__
if File.exists? names_file
puts "INFO: Using names file: #{names_file}"
File.open names_file do |f|
numlines = f.count
idx = 0
f.rewind
f.each do |name|
Name.find_or_create_by name: name.strip
idx += 1
if idx % 100 == 0
puts sprintf("INFO: %5d/%d names handled", idx, numlines)
end
end
puts sprintf("INFO: %5d/%d names handled", numlines, numlines)
end
else
puts "WARNING: Could not find names file: #{names_file}"
end
puts "INFO: Total count of names in database: #{Name.count}"
ADMIN_USERS = [
{
username: 'LauraAy',
email: '<EMAIL>',
full_name: '<NAME>',
admin: true
},
{
username: 'doug',
email: '<EMAIL>',
full_name: '<NAME>',
admin: true
}]
ADMIN_USERS.each do |data|
if User.exists? username: data[:username]
puts "User already exists: #{data[:username]}"
else
pass = <PASSWORD>
User.find_or_create_by username: data[:username] do |user|
user.password = <PASSWORD>
user.email = data[:email]
user.full_name = data[:full_name]
user.admin = data[:admin]
end
puts "CREATED User #{data[:username]} with password #{pass}."
end
end<file_sep>class AddProvenanceAgentsCountToNames < ActiveRecord::Migration
def change
add_column :names, :provenance_agents_count, :integer, default: 0
reversible do |dir|
dir.up { data }
end
end
def data
Name.all.each do |name|
if name.provenance_agents.count > 0
puts "Updating provenance_agents_count for #{name} to #{name.provenance_agents.count}"
Name.reset_counters(name.id, :provenance_agents)
end
end
end
end<file_sep>class CreateProvenanceAgents < ActiveRecord::Migration
def change
create_table :provenance_agents do |t|
t.string :role
t.references :evidence, index: true, foreign_key: true, null: false
t.references :name, index: true, foreign_key: true, null: false
t.timestamps null: false
end
end
end
<file_sep>class AddUserStampsToTitlePages < ActiveRecord::Migration
def get_user
pass = <PASSWORD>
User.find_or_create_by(username: 'LauraAy') do |user|
user.password = <PASSWORD>
user.password_confirmation = <PASSWORD>
user.email = '<EMAIL>'
user.full_name = '<NAME>'
user.admin = true
end
end
def change
add_column :title_pages, :created_by_id, :integer
add_column :title_pages, :updated_by_id, :integer
user = get_user
TitlePage.update_all created_by_id: user.id, updated_by_id: user.id
end
end
<file_sep>#!/usr/bin/env bash
alias rails >/dev/null 2>&1 || alias rails="bundle exec bin/rails"
# make sure we're in the project root
cd `dirname $0`/..
generator_options="--no-helper --no-view-specs --no-helper-specs --no-assets --no-stylesheets"
rails generate migration add_translation_to_evidence \
translation:text \
$generator_options
#rails generate migration add_original_id_to_photos \
# original_id:integer
# rails generate migration set_default_false_on_deleted_in_context_images
# rails generate migration remove_book_id_from_context_images \
# book_id:integer \
# $generator_options
# rails generate controller cropping/photos create edit update \
# $generator_options
# rails generate migration add_user_stamps_to_publication_data \
# created_by_id:integer \
# updated_by_id:integer \
# $generator_options
# rails generate model context_image \
# book:references \
# photo:references \
# publishing_to_flickr:boolean \
# delete:boolean \
# created_by_id:integer \
# updated_by_id:integer \
# $generator_options
# rails generate model publication_data flickr_id:string \
# metadata:text \
# published_at:datetime \
# publishing_to_flickr:boolean \
# publishable_id:integer \
# publishable_type:string \
# $generator_options
# rails generate migration remove_publication_data_columns_from_title_page \
# flickr_id:string \
# flickr_info:text \
# published_at:datetime \
# $generator_options
# rails generate migration add_date_narrative_to_books \
# date_narrative:string \
# $generator_options
#rails generate migration add_date_narrative_to_books \
# date_narrative:string \
#$generator_options
# rails generate migration add_user_stamps_to_names \
# created_by_id:integer \
# updated_by_id:integer \
# $generator_options
# rails generate migration add_user_stamps_to_title_pages \...
# rails generate migration add_user_stamps_to_evidence \...
# rails generate migration add_user_stamps_to_books \...
# rails generate migration add_full_name_to_users full_name:string $generator_options
# rails g migration add_deleted_at_column_to_users deleted_at:datetime
# bundle exec rails g migration add_deleted_to_title_pages deleted:boolean
# bundle exec rails g migration add_deleted_to_evidence deleted:boolean
# bin/rails g migration add_in_queue_to_photos in_queue:boolean
# bin/rails g controller photos update $generator_options
# bin/rails g migration add_hidden_to_photos hidden:boolean
# bin/rails g controller flash show $generator_options
# bin/rails g controller title_pages show $generator_options
# bin/rails g migration add_citations_to_evidence citations:text
# bin/rails g migration add_publishing_to_title_pages publishing_to_flickr:boolean
# bin/rails g migration add_publishing_to_evidence publishing_to_flickr:boolean
# bin/rails g migration add_published_at_to_title_pages published_at:datetime
# bin/rails g controller flickr preview $generator_options
# bin/rails g migration remove_paperclip_columns_from_title_pages \
# image_file_name:string \
# image_content_type:string \
# image_file_size:integer \
# image_updated_at:datetime
# bin/rails g migration add_format_other_to_evidence format_other:string
# bin/rails g migration drop_table_book_photos
# bin/rails g migration drop_table_evidence_photos
# bin/rails g migration remove_columns_flickr_id_flickr_info_from_photos \
# flickr_id:string \
# flickr_info:text
# bin/rails g migration drop_table_title_photos
# bin/rails g migration add_photo_id_to_title_pages \
# photo:references \
# flickr_id:string \
# flickr_info:text
# rails g migration add_flickr_info_to_photos flickr_info:text \
# $generator_options
# rails g model evidence_photo \
# evidence:references \
# photo:references \
# $generator_options
# rails g model title_page_photos \
# tite_page:references \
# photo:references \
# $generator_options
# rails g scaffold_controller name \
# $generator_options
# rails g model provenance_agents \
# role:string \
# evidence:references \
# name:references \
# $generator_options
# rails g model name name:string \
# year_start:integer \
# year_end:integer \
# viaf_id:string \
# comment:string \
# $generator_options
# rails g model evidence_content_type evidence:references \
# content_type:references \
# $generator_options
# rails g scaffold evidence book:references \
# format:string \
# content_type:string \
# location_in_book:string \
# location_in_book_page:string \
# transcription:text \
# year_when:integer \
# year_start:integer \
# year_end:integer \
# date_narrative:string \
# where:string \
# comments:text \
# $generator_options
# rails g model title_page \
# book:references
# rails g model photo \
# flickr_id:string \
# user_id:integer
# rails g scaffold books \
# repository \
# owner \
# collection \
# geo_location \
# acq_source \
# call_number \
# catalog_url \
# vol_number \
# author \
# title \
# creation_place \
# creation_date:integer \
# publisher \
# $generator_options
<file_sep>module FlickrData
extend ActiveSupport::Concern
def user_id
Flickr::Client.flickr_userid
end
def info_obj
# don't cache @info_obj if flickr_info is empty
return Flickr::Info.new user_id if publication_data.blank?
@info_obj ||= Flickr::Info.new(user_id, publication_data.metadata)
end
def respond_to_missing? method, include_private=false
info_obj.respond_to?(method, include_private) || super
end
def method_missing method, *args, &block
if info_obj.respond_to? method
info_obj.send(method, *args, &block)
else
super
end
end
end<file_sep>json.extract! @thumbnail, :id
json.processing @thumbnail.image_processing?<file_sep>require 'rails_helper'
RSpec.feature "Registrations", type: :feature, js: true do
scenario 'user edits full name and email' do
login_as 'testuser'
click_link 'testuser'
click_link 'Manage account'
fill_in 'Full name', with: '<NAME>'
fill_in 'Email', with: '<EMAIL>'
fill_in 'Current password', with: '<PASSWORD>'
click_button 'Update'
expect(page).to have_content 'Your account has been updated successfully.'
# check that the value was changed
click_link 'testuser'
click_link 'Manage account'
expect(page).to have_field 'Full name', with: '<NAME>'
expect(page).to have_field 'Email', with: '<EMAIL>'
end
scenario 'user edits password' do
login_as 'testuser'
click_link 'testuser'
click_link 'Manage account'
fill_in 'Password', with: '<PASSWORD>'
fill_in 'Password confirmation', with: '<PASSWORD>'
fill_in 'Current password', with: '<PASSWORD>'
click_button 'Update'
expect(page).to have_content 'Your account has been updated successfully.'
# log out and then log in with the new password
click_link 'testuser'
click_link 'Sign out'
click_link 'Sign in'
fill_in 'Username', with: 'testuser'
fill_in 'Password', with: '<PASSWORD>'
click_button 'Log in'
expect(page).to have_content 'Signed in successfully.'
end
scenario 'user cancels account' do
login_as 'testuser'
click_link 'testuser'
click_link 'Manage account'
click_button 'Cancel my account'
expect(page).to have_content 'Bye! Your account has been successfully cancelled.'
# try to log in
click_link 'Sign in'
fill_in 'Username', with: 'testuser'
fill_in 'Password', with: '<PASSWORD>'
click_button 'Log in'
expect(page).to have_content 'Sorry, your account has been cancelled.'
end
end
<file_sep>##
# Photos can have several types of Photo "parents" (usually not really a
# parent; see below). This module examines the params hash for parent ID types
# -- `book_id`, `evidence_id`, etc. It has methods for setting the parent to
# `@parent`; getting the class of the parent, its model name, and finding the
# parent based on its id.
#
# On the `lie` of the parent metaphor
# ===================================
#
# Publishables, that is, Evidence, TitlePage, and ContextImage, are not in
# fact parents of photos. While a photo `belongs_to` a book and, thus, a book
# is a photo's parent, a publishable `belongs_to` a photo and, thus, the photo
# is the publishable's parent.
#
# Nevertheless, I use the convention of parent as a convenience here. This
# allows us to have nested routes and have single actions that work with
# either a Book, Evidence, TitlePage, or ContextImage. For Ajax calls that
# load partials during image processing and for image cropping, we need a way
# to pass round the photo ID and the ID of the associated object. This
# information is used by controllers to update associations and then redirect
# to actions that display forms and partials with the correct associations.
# The information is also used by JavaScript methods to locate divs to replace
# based on photo and associations IDs. This is illustrated by the following
# routes for editing a photo associated with particular association model:
#
# cropping_book_photo PATCH /cropping/books/:book_id/photos/:id(.:format) cropping/photos#update
# cropping_evidence_photo PATCH /cropping/evidence/:evidence_id/photos/:id(.:format) cropping/photos#update
# cropping_title_page_photo PATCH /cropping/title_pages/:title_page_id/photos/:id(.:format) cropping/photos#update
# cropping_context_image_photo PATCH /cropping/context_images/:context_image_id/photos/:id(.:format) cropping/photos#update
#
# When any of these actions is invoked the system begins processing the
# updated image and browser is redirected to the `thumbnails#show` action for
# that 'parent' and photo. The action returns JavaScript that locates the
# `div` or `div`'s to load the new thumbnail partial into based on the photo
# ID and associated 'parent'. The ThumbnailsController likewise takes
# advantage of nested resources for this purpose:
#
# book_thumbnail GET /books/:book_id/thumbnails/:id(.:format) thumbnails#show
# title_page_thumbnail GET /title_pages/:title_page_id/thumbnails/:id(.:format) thumbnails#show
# evidence_thumbnail GET /evidence/:evidence_id/thumbnails/:id(.:format) thumbnails#show
# context_image_thumbnail GET /context_images/:context_image_id/thumbnails/:id(.:format) thumbnails#show
#
# The method relies on to div classes `.thumb-container` and `.thumb`. Here's an example:
#
# <div class="thumb-container" id="ui-id-1">
# <div class="thumb" data-parent="10" data-parent-type="evidence" data-thumbnail="174">
# <a target="_blank" data-toggle="tooltip" rel="noopener noreferrer" title="Click to open in new window."
# href="/system/photos/images/000/000/174/original/BS_185_178207.jpg?1473367360">
# <img class="img-responsive center-block" src="/system/photos/images/000/000/174/small/BS_185_178207.jpg?1473367360"
# alt="Bs 185 178207" />
# </a>
# </div>
# </div>
#
# Note the `data-parent-type`, `data-parent`, and `data-thumbnail` atrributes
# which contain the parent type, parent ID, and photo ID, respectively, and
# are used to locate the `div.thumb` and it's parent `div.thumb-container`.
#
# Note that we cannot simply rely on the photo ID because in some case more
# than one parent may be associated with the same photo. This happens when a
# photo is first assigned to a publishable, like a TitlePage. In this case the
# same photo ID is assigned to book and to the title page. Thumbnails for both
# are displayed on the books#show page. In fact, the TitlePage thubmnail
# appears twice: once in the sidebar and once in the list of image statuses,
# meaning that before editing the same image thumbnail appears three times on
# the page. When the user chooses to edit the title page photo, a new photo is
# created for the title page, but not for the book. We have to redisplay the
# image for each of the two title page thumbnails, but not for the book. Also,
# the new photo has a new ID; thus, we need to find the `div.thumb` based on
# the ID of the original photo (`source_photo_id` parameter).
#
# TODO?
# =====
#
# The purer way to do this would, perhaps, be to have something like a
# PhotoAssignment\* model that connects a photo to a Book or Publishable
# (asterisk to indicate the model doesn't yet exist). The PhotoAssignment
# would have a `belongs_to` association with the parent. A Book object would
# `have_many` PhotoAssignment\*, while each Publishable object would
# `have_one` PhotoAssignment\*.
#
# It requires further investigation to determine whether the PhotoAssignment\*
# model would work. Presumably the association would be polymorphic, books and
# publishables being treated as `:assignable` or similar, with PhotoAssignment\*
# having
#
# ```ruby
# belongs_to :assignable, polymorphic: true
# ```
#
# See the Rails guides for more on [polymorphic associations][rails-poly].
#
# [rails-poly]: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
#
# This method, using the PhotoAssignment\* has many potential benefits. One of
# these would be to reduce the complexity of locating the div to replace. We
# would replace the div based on the ID of the assignment, not the photo. When
# a photo edit results in a new photo (see below), a new assignment would
# **not** be created; rather, the assignment would be updated to point to the
# new photo. All this means that the `div.thumb` from above can be changed to:
#
# <div class="thumb-container" id="ui-id-1">
# <!-- OLD VERSION: <div class="thumb" data-parent="10" data-parent-type="evidence" data-thumbnail="174"> -->
# <div class="thumb" data-photo-assignment="10">
# <!-- ... etc. ... -->
# </a>
# </div>
# </div>
#
# Another advantage of the PhotoAssignment\* model is simplifying the
# controller processes. At present, the cropping `POST`/`#create` actions
# require a new assignment. The assignment happens differently for books and
# publishables owing to the different types of association. For the
# PhotoAssignment\* model the associations would be closer, though not the
# same. Note:
#
# ```ruby
# # Books have many photos
# class Book
# has_many :photo_assignments, as: :assignable
# end
#
# # Whereas publishables, like Evidence have one photo
# class Evidence
# has_one :photo_assignment, as: :assignable
# end
# ```
#
# __IMPORTANT__: It remains to be seen whether this `has_one`/`has_many`
# combination will work with the same polymorphic association.
#
# __IMPORTANT__: One of the more complicated pieces here is the editing of a
# photo when a new Evidence is created. We display a photo in the sidebar of
# the new Evidence page with an `Edit` button. Now we have to do some funky
# business with a `data-parent-id` value of `new` in order to find the div to
# update:
#
# ```erb
# <div class="thumb" data-parent="new" data-parent-type="evidence" data-thumbnail="174">
# <!-- ... -->
# </div>
# ```
#
# This problem will still exist with a PhotoAssignment\* model, which in this
# case will still be a non-persisted instance. Will we have to do the
# following?
#
# ```erb
# <div class="thumb" data-photo-assignment="new">
# <!-- ... etc. ... -->
# </a>
# </div>
# ```
# Creating a new photo
# --------------------
#
# When is a new photo created? If a user wants to edit a photo that belongs to
# both a book and some publishable, we create a new photo that is then
# associated with the selected parent (book or publishable).
#
module PolymorphicParent
extend ActiveSupport::Concern
PARENT_ID_TYPES = %w{
book_id evidence_id title_page_id context_image_id
}.map &:to_sym
def set_parent
@parent = find_parent
end
def set_or_create_parent
@parent = find_or_create_parent
end
def set_parent_type
@parent_type = params[:parent_type]
end
def parent_model
return parent_id_param.to_s.chomp '_id' if parent_id_param.present?
return if params[:parent_type].blank?
params[:parent_type].singularize
end
def parent_id_param
# Return the first param name that matches the param hash.
PARENT_ID_TYPES.find { |p| params[p] }
end
def parent_class
return unless parent_model.present?
parent_model.classify.safe_constantize
end
def parent_id
return if parent_id_param.blank?
params[parent_id_param]
end
def find_parent
return if parent_id.blank?
parent_class.find parent_id
end
##
# Always return a parent if at all possible: either the specific parent
# instance or a new instance. If there's no parent ID or `parent_type`
# available, return `nil`.
def find_or_create_parent
return if parent_class.blank?
return parent_class.new if parent_id.blank? || parent_id == 'new'
parent_class.find parent_id
end
end<file_sep>class Book < ActiveRecord::Base
include UserFields
has_many :title_pages, dependent: :destroy, inverse_of: :book
has_many :evidence, dependent: :destroy, inverse_of: :book
has_many :context_images, dependent: :destroy, inverse_of: :book
has_many :photos, dependent: :destroy, inverse_of: :book
validates_presence_of :title
accepts_nested_attributes_for :title_pages
scope :for_user, -> (user) {
where "created_by_id = ? or updated_by_id = ?", user.id, user.id
}
def holder
return repository if repository.present?
owner
end
def photos_queued
photos.queued.count
end
def photos_hidden
photos.unqueued.count
end
def all_queued?
photos_hidden == 0
end
def queued_photos
photos.queued if photos.present?
end
def publishables
title_pages.active + context_images.used + evidence.active
end
def full_call_number
return '' unless call_number.present?
parts = [ repository, call_number ].flat_map { |s|
s.present? ? s : []
}.join ' '
end
def full_name
s = full_call_number
return s if s.present?
# If there is no call number, return the repository and title.
[ repository, title ].flat_map { |s| s.present? ? s : [] }.join ': '
end
def volume_name
return nil unless vol_number.present?
return vol_number if vol_number =~ /v\.|vol/i
"Vol. #{vol_number}"
end
def full_title
[ title, vol_number ].flat_map { |s| s.present? ? s : [] }.join ', '
end
alias_method :name, :full_title
def publication_info?
[ creation_place, creation_date, publisher ].any? &:present?
end
def publication_info
[ publisher, creation_place, creation_date ].flat_map { |s|
s.present? ? s : []
}.join ', '
end
def publishable?
return false if processing?
publishables.any? &:publishable?
end
def unpublishable?
return false if processing?
on_flickr?
end
def on_flickr?
publishables.any? &:on_flickr?
end
def processing?
publishables.any? &:processing?
end
def publish
publishables.each { |item| item.publish }
end
def to_s
full_call_number
end
end
<file_sep>require 'rails_helper'
RSpec.describe ContextImage, type: :model do
context 'factory' do
it 'creates a ContextImage' do
expect(create(:context_image)).to be_a(ContextImage)
end
end
context 'initialization' do
it 'creates a ContextImage' do
expect(ContextImage.new).to be_a(ContextImage)
end
end
context 'flickr_metadata' do
it_behaves_like 'flickr_metadata'
end
context 'validations:' do
it 'is valid' do
expect(build(:context_image)).to be_valid
end
it 'is invalid without a book' do
expect(build(:context_image, book: nil)).not_to be_valid
end
end
end
<file_sep>namespace :subpop do
namespace :dev do
task _dev_only: :environment do
if Rails.env !~ /development/
raise "This task can only be run in the development environment"
end
end
desc "Create a passel of filler users (well, 4, actually)"
task fill_users: :_dev_only do
%w{ lil_oliver millie viktorvaughn geedorah }.each do |username|
User.find_by username: username or User.create! username: username, password: '<PASSWORD>', email: <EMAIL>"
end
end
desc "Create a mess of books, 50 of 'em"
task fill_books: :_dev_only do
BOOKS.each do |title|
user = User.offset(rand(User.count)).first
book = Book.find_or_initialize_by title: title
if book.new_record?
book.save_by user or raise_invalid_model(book)
puts sprintf("Created book: %-65s user: %s", title, user.username)
else
puts sprintf("Found book: %-65s user: %s", title, user.username)
end
end
end
end
def raise_invalid_model obj
raise "Invalid #{obj.model_name}: #{obj.errors.full_messages}"
end
BOOKS = [
"Absalom, Absalom!",
"A che punto è la notte",
"After Many a Summer Dies the Swan",
"Ah, Wilderness!",
"Alien Corn (play)",
"The Alien Corn (short story)",
"All Passion Spent",
"All the King's Men",
"Alone on a Wide, Wide Sea",
"An Acceptable Time",
"Antic Hay",
"An Evil Cradling",
"Arms and the Man",
"As I Lay Dying",
"A Time to Kill",
"Behold the Man",
"Beneath the Bleeding",
"Beyond the Mexique Bay",
"Blithe Spirit",
"Blood's a Rover",
"Blue Remembered Earth",
"Blue Remembered Hills",
"<NAME>",
"Brandy of the Damned",
"Bury My Heart at Wounded Knee",
"Butter In a Lordly Dish",
"By Grand Central Station I Sat Down and Wept",
"Cabbages and Kings",
"Carrion Comfort",
"A Catskill Eagle",
"The Children of Men",
"Clouds of Witness",
"A Confederacy of Dunces",
"Consider Phlebas",
"Consider the Lilies",
"Cover Her Face",
"The Cricket on the Hearth",
"The Curious Incident of the Dog in the Night-Time",
"The Daffodil Sky",
"Dance Dance Dance",
"A Darkling Plain",
"Death Be Not Proud",
"The Doors of Perception",
"Down to a Sunless Sea",
"Dulce et Decorum Est",
"Dying of the Light",
"East of Eden",
"Ego Dominus Tuus",
"Endless Night",
"Everything is Illuminated",
"Eyeless in Gaza",
"Fair Stood the Wind for France",
"Fame Is the Spur",
"A Fanatic Heart",
"The Far-Distant Oxus",
"A Farewell to Arms",
"Far From the Madding Crowd",
"Fear and Trembling",
"For a Breath I Tarry",
"For Whom the Bell Tolls",
"Frequent Hearses",
"From Here to Eternity",
"A Glass of Blessings",
"The Glory and the Dream",
"The Golden Apples of the Sun",
"The Golden Bowl",
"Gone with the Wind",
"The Grapes of Wrath",
"Great Work of Time",
"The Green Bay Tree",
"A Handful of Dust",
"Have His Carcase",
"The Heart Is a Lonely Hunter",
"The Heart Is Deceitful Above All Things",
"His Dark Materials",
"The House of Mirth",
"How Sleep the Brave",
"How Sleep the Brave",
"How Sleep the Brave",
"I Know Why the Caged Bird Sings",
"I Sing the Body Electric",
"I Will Fear No Evil",
"If I Forget Thee Jerusalem",
"If Not Now, When?",
"In a Dry Season",
"In a Glass Darkly",
"In Death Ground",
"In Dubious Battle",
"An Instant in the Wind",
"It's a Battlefield",
"Jacob Have I Loved",
"O Jerusalem!",
"Jesting Pilate",
"The Last Enemy",
"The Last Temptation",
"The Lathe of Heaven",
"Let Us Now Praise Famous Men",
"Lilies of the Field",
"This Lime Tree Bower",
"The Line of Beauty",
"The Little Foxes",
"Little Hands Clapping",
"Look Homeward, Angel",
"Look to Windward",
"The Man Within",
"Many Waters",
"A Many-Splendoured Thing",
"The Mermaids Singing",
"The Millstone",
"The Mirror Crack'd from Side to Side",
"Moab Is My Washpot",
"The Monkey's Raincoat",
"A Monstrous Regiment of Women",
"The Moon by Night",
"Mother Night",
"The Moving Finger",
"The Moving Toyshop",
"Mr Standfast",
"Nectar in a Sieve",
"The Needle's Eye",
"Nine Coaches Waiting",
"No Country for Old Men",
"No Highway",
"Noli Me Tangere",
"No Longer at Ease",
"Now Sleeps the Crimson Petal",
"Number the Stars",
"Of Human Bondage",
"Of Mice and Men",
"Oh! To be in England",
"The Other Side of Silence",
"The Painted Veil",
"Pale Kings and Princes",
"The Parliament of Man",
"Paths of Glory",
"A Passage to India",
"O Pioneers!",
"Postern of Fate",
"Precious Bane",
"The Proper Study",
"Quo Vadis",
"Recalled to Life",
"Recalled to Life",
"Ring of Bright Water",
"The Road Less Traveled",
"A Scanner Darkly",
"Shall not Perish",
"The Skull Beneath the Skin",
"The Soldier's Art",
"Some Buried Caesar",
"Specimen Days",
"The Stars' Tennis Balls",
"Stranger in a Strange Land",
"Such, Such Were the Joys",
"A Summer Bird-Cage",
"The Sun Also Rises",
"Surprised by Joy",
"A Swiftly Tilting Planet",
"Taming a Sea Horse",
"Tender Is the Night",
"Terrible Swift Sword",
"That Good Night",
"That Hideous Strength",
"Things Fall Apart",
"This Side of Paradise",
"Those Barren Leaves",
"Thrones, Dominations",
"Tiger! Tiger! - alternative title of The Stars My Destination",
"Tiger! Tiger!",
"A Time of Gifts",
"Time of our Darkness",
"Time To Murder And Create",
"Tirra Lirra by the River",
"To a God Unknown",
"To Sail Beyond the Sunset",
"To Say Nothing of the Dog",
"To Your Scattered Bodies Go",
"The Torment of Others",
"Unweaving the Rainbow",
"Vanity Fair",
"Vile Bodies",
"The Violent Bear It Away",
"Waiting for the Barbarians",
"The Waste Land",
"The Way of All Flesh",
"The Way Through the Woods",
"The Wealth of Nations",
"What's Become of Waring",
"When the Green Woods Laugh",
"Where Angels Fear to Tread",
"The Widening Gyre",
"Wildfire at Midnight",
"The Wind's Twelve Quarters",
"The Wings of the Dove",
"The Wives of Bath",
"The World, the Flesh and the Devil",
"The Yellow Meads of Asphodel"
]
end<file_sep>module Flickr
class Tag
attr_reader :raw, :author, :authorname, :id, :_content, :machine_tag
ALLOWABLE_OPTIONS = [ :raw, :author, :authorname, :id, :_content, :machine_tag ]
def initialize options
validate_options options
options.each do |k,v|
var = "@#{k}".to_sym
val = v.kind_of?(String) ? v.strip : v
instance_variable_set var, val
end
end
# Return the raw tag string formatted for submission to Flickr. Tags with
# spaces are enclosed in quotes:
#
# "my tag" => "\"my tag\""
def flickr_format
raw =~ /\s/ ? double_quote : raw
end
# Return the raw tag string quoted by `open` and `close` values, by
# default '"' and '"', which will format a string with spaces for
# submission to Flickr.
#
# "my tag" => "\"my tag\""
def quote open='"', close='"'
open + raw + close
end
# Quote raw tag with double quotes: "'" and "'":
#
# "my tag" => '`"my tag"`'
def double_quote
quote '"', '"'
end
# Quote the raw tag with '`' and '"':
#
# "my tag" => "`my tag'"
def cute_quote
quote "`", "'"
end
# Quote raw tag with single quotes: "'" and "'":
#
# "my tag" => "'my tag'"
def single_quote
quote "'", "'"
end
# Strip out non-alphanumeric characters and downcase to return valid
# Flickr tag 'text'.
#
# Tag.new(raw: 'My tag').normalize # => "mytag"
# Tag.new(raw: 'my täg').normalize # => "mytäg"
# Tag.new(raw: "Mike's tag").normalize # => "mikestag"
# Tag.new(raw: 'my_tag').normalize # => "mytag"
def normalize
raw && raw.downcase.gsub(/[^\p{Alnum}]+/, '')
end
def to_s
raw
end
def text
# if the flickr tag _content value is present return that; otherwise,
# generate a _content value using #normalize
@_content || normalize
end
def <=> o
s.downcase_raw <=> o.downcase_raw
end
def == o
# compare the text values; this is a more accurate comparison of tags
o.class == self.class && o.text == text
end
alias_method :eql?, :==
def hash
downcase_raw.hash
end
def to_s
inspect
end
protected
def downcase_raw
@raw and @raw.downcase or ''
end
private
# Make sure the options to Tag::new are valid.
#
# NB: This will break if Flickr changes the content of the tag information
# section.
def validate_options options
bad_opts = options.flat_map { |k,v|
ALLOWABLE_OPTIONS.include?(k.to_sym) ? [] : k
}
unless bad_opts.empty?
msg = "Illegal option(s): #{bad_opts.join ' '}"
raise ArgumentError.new(msg)
end
end
end
end<file_sep>module FlickrHelper
def publishable_div_id item
"publishable-#{item.model_name.element}-#{item.id}"
end
def flickr_path item
case item
when Evidence
flickr_evidence_path item
when TitlePage
flickr_title_page_path item
when Book
flickr_book_path item
when ContextImage
flickr_context_image_path item
end
end
def link_to_publish_evidence name, item, options={}
if ! item.publishable?
options[:disabled] = true
options[:title] = disabled_reason(item.flickr_status)
name = 'Please wait...' if item.processing?
path = '#'
elsif item.on_flickr?
options[:method] = :put
path = flickr_evidence_path(item)
else
options[:method] = :post
path = flickr_evidence_path(item)
end
link_to name, path, options
end
def link_to_publish_item name, item, options={}
return link_to_publish_evidence(name,item,options) if item.is_a? Evidence
if ! item.publishable?
options[:disabled] = true
options[:title] = disabled_reason(item.flickr_status)
name = 'Please wait...' if item.processing?
path = '#'
elsif item.on_flickr?
options[:method] = :put
# path = update_flickr_item_path item_type: item.model_name.element, id: item
path = flickr_path item
else
options[:method] = :post
# path = create_flickr_item_path item_type: item.model_name.element, id: item
path = flickr_path item
end
link_to name, path, options
end
def link_to_publish_book name, book, options={}
if book.processing?
options[:disabled] = true
options[:title] = 'Processing; please wait...'
name = "Please wait..."
path = '#'
elsif ! book.publishable?
options[:disabled] = true
options[:title] = 'All book images up-to-date on Flickr.'
path = '#'
elsif book.on_flickr?
options[:method] = :put
path = flickr_book_path book
else
options[:method] = :post
path = flickr_book_path book
end
link_to name, path, options
end
def link_to_unpublish_item name, item, options={}
if ! item.unpublishable?
options[:disabled] ||= true
options[:title] ||= disabled_reason(item.flickr_status)
name = 'Please wait...' if item.processing?
path = '#'
else
options[:method] ||= :delete
options[:data][:confirm] ||= 'Remove this image from Flickr?'
#path = delete_flickr_item_path item_type: item.model_name.element, id: item
path = flickr_path item
end
link_to name, path, options
end
def link_to_unpublish_book name, book, options={}
if book.processing?
options[:disabled] = true
options[:title] = 'Processing; please wait...'
name = 'Please wait...' if book.processing?
path = '#'
elsif ! book.unpublishable?
options[:disabled] = true
options[:title] = 'Book not published to Flickr'
path = '#'
else
options[:method] = :delete
options[:data][:confirm] = "Remove all this book's images from Flickr?"
path = flickr_book_path id: book
end
link_to name, path, options
end
def disabled_reason flickr_status
return 'Processing; please wait...' if flickr_status == Publishable::IN_PROCESS
return 'Item up-to-date' if flickr_status == Publishable::UP_TO_DATE
return 'Item not on Flickr' if flickr_status == Publishable::UNPUBLISHED
end
end<file_sep>class AddInQueueToPhotos < ActiveRecord::Migration
def change
add_column :photos, :in_queue, :boolean, default: true
Photo.update_all in_queue: true
end
end
<file_sep>require 'rails_helper'
RSpec.describe TitlePagesController, type: :controller do
login_admin
let(:title_page) { create(:title_page) }
describe "GET #show" do
it "returns http success" do
get :show, { id: title_page }
expect(response).to have_http_status(:redirect)
end
end
end
<file_sep>class SubpopFormbuilder < ActionView::Helpers::FormBuilder
def underscore_name
return @obect_name.to_s if object.blank?
object.model_name.element
end
def text_field attribute, options={}
super + hint(attribute, options)
end
def select attribute, choices=nil, options={}, html_options={}
super + hint(attribute, options)
end
def text_area attribute, options={}
super + hint(attribute, options)
end
def number_field method, options={}
super + hint(method, options)
end
def collection_check_boxes attribute, collection, value_method, text_method, options={}, html_options={}
super + hint(attribute, options)
end
def check_box attribute, options={}, checked_value = "1", unchecked_value = "0"
super + hint(attribute, options)
end
def color_field attribute, options={}
super + hint(attribute, options)
end
def date_field attribute, options={}
super + hint(attribute, options)
end
def datetime_field attribute, options={}
super + hint(attribute, options)
end
def datetime_local_field attribute, options={}
super + hint(attribute, options)
end
def email_field attribute, options={}
super + hint(attribute, options)
end
def file_field attribute, options={}
super + hint(attribute, options)
end
def month_field attribute, options={}
super + hint(attribute, options)
end
def password_field attribute, options={}
super + hint(attribute, options)
end
def phone_field attribute, options={}
super + hint(attribute, options)
end
def radio_button attribute, tag_value, options={}
super + hint(attribute, options)
end
def range_field attribute, options={}
super + hint(attribute, options)
end
def search_field attribute, options={}
super + hint(attribute, options)
end
def telephone_field attribute, options={}
super + hint(attribute, options)
end
def time_field attribute, options={}
super + hint(attribute, options)
end
def url_field attribute, options={}
super + hint(attribute, options)
end
def week_field attribute, options={}
super + hint(attribute, options)
end
def hint attribute, options={}
val = options[:hint_text] || hint_text(attribute, options)
return unless val.present?
hint_class = options[:hint_class] || 'help-block'
tag = options[:hint_tag] || :span
# "<span class=\"help-block\">#{val}</span>"
@template.content_tag tag, val, class: hint_class
end
def hint_text attribute, options={}
key = options[:hint_key] || "activerecord.hints.#{underscore_name}.#{attribute}"
I18n.t key, default: ''
end
end<file_sep>class Flickr::BaseController < ApplicationController
include FlickrHelper
before_action :get_item, only: [ :show, :status, :create, :update, :destroy ]
# Subclasses must implement this and return a item class for the
# controller
def item_class
controller_name.camelize.singularize.constantize
end
def item_class_lstr
item_class.to_s.underscore
end
def status
authorize! :read, @item
respond_to do |format|
format.js
format.json
end
end
def create
authorize! :update, @item
respond_to do |format|
if @item.publishable?
create_publish_jobs
format.json { render json: @item }
format.js
format.html { redirect_to @item, notice: "Publishing #{@item} to Flickr" }
else
format.html { redirect_to @item, notice: "#{@item} is up-to-date or already being published to Flickr" }
format.json { render json: [ "#{@item} is up-to-date or already being published to Flickr" ], status: :unprocessable_entity }
end
end
end
def update
authorize! :update, @item
respond_to do |format|
if @item.publishable?
create_publish_jobs
format.js
format.json { render json: @item }
format.html { redirect_to @item, notice: "Publishing #{@item} to Flickr" }
else
format.html { redirect_to @item, notice: "#{@item} is up-to-date or already being published to Flickr" }
format.json { render json: [ "#{@item} is up-to-date or already being published to Flickr" ], status: :unprocessable_entity }
end
end
end
def destroy
authorize! :udpate, @item
respond_to do |format|
if @item.unpublishable?
create_unpublish_jobs
format.js
format.json { render json: @item }
format.html { redirect_to @item, notice: 'Removing photo from Flickr.' }
else
format.js { redirect_to @item, notice: 'Cannot remove photo from Flickr.' }
format.html { redirect_to @item, notice: 'Cannot remove photo from Flickr.' }
format.json { render json: [ 'Item cannot be removed from Flickr.' ], status: :unprocessable_entity }
end
end
end
private
def create_publish_jobs
return enqueue_publish @item unless @item.respond_to? :publishables
# item is a book; enqueue each publishable
@item.publishables.each { |item| enqueue_publish item }
end
def enqueue_publish item
return unless item.publishable?
item.mark_in_process
return UpdateFlickrJob.perform_later item, current_user.id if item.on_flickr?
AddToFlickrJob.perform_later item, current_user.id
end
def create_unpublish_jobs
return enqueue_unpublish @item unless @item.respond_to? :publishables
# item is a book; add all unpublishable items
@item.publishables.each { |item| enqueue_unpublish item }
end
def enqueue_unpublish item
return unless item.unpublishable?
item.mark_in_process
RemoveFromFlickrJob.perform_later item, current_user.id
end
def get_item
if item_class == Book
@item = item_class.find params[:id]
else
@item = item_class.includes(:book).find params[:id]
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe RemoveFromFlickrJob, type: :job do
let(:user) { create(:user) }
let(:evidence) { create(:evidence) }
it 'enquues the job' do
ActiveJob::Base.queue_adapter = :test
expect {
RemoveFromFlickrJob.perform_later evidence
}.to have_enqueued_job(RemoveFromFlickrJob).with evidence
end
it 'executes delete_from_flickr' do
expect(evidence).to receive(:delete_from_flickr)
expect(evidence).to receive(:save!)
described_class.perform_now evidence, user.id
end
end
<file_sep>require 'rails_helper'
RSpec.feature "Cropping", type: :feature, js: true do
scenario 'User crops book photo' do
create_book_with_photo_by 'testuser'
login_as 'testuser'
visit_book
expect(page).to have_current_path book_path(@book)
expect(page).to have_content "1 photos"
click_link 'Edit master photo'
expect(page).to have_content 'Crop image'
click_button('Crop image')
expect(page).not_to have_content 'Crop image'
end
scenario 'User edits title page photo' do
create_book_with_photo_by 'testuser'
make_photo_a_title_page
login_as 'testuser'
visit_book
expect(page).to have_content 'Remove title page'
within '#sidebar' do
find('a', text: 'Edit photo').trigger('click')
end
click_button('Crop image')
expect(page).not_to have_content 'Crop image'
end
scenario 'User edits a title page twice' do
create_book_with_photo_by 'testuser'
make_photo_a_title_page
login_as 'testuser'
visit_book
expect(page).to have_content 'Remove title page'
# edit first time
within '#sidebar' do
find('a', text: 'Edit photo').trigger('click')
end
expect(page).to have_content 'Crop image'
find("button[title='Rotate Left']").trigger 'click'
click_button('Crop image')
expect(page).not_to have_content 'Crop image'
# edit second time
within '#sidebar' do
find('a', text: 'Edit photo').trigger('click')
end
expect(page).to have_content 'Crop image'
click_button('Crop image')
expect(page).not_to have_content 'Crop image'
end
scenario 'User edits evidence photo' do
create_evidence_by 'testuser'
login_as 'testuser'
visit_evidence
within '#sidebar' do
find('a', text: 'Edit photo').trigger('click')
end
click_button('Crop image')
expect(page).not_to have_content 'Crop image'
end
scenario 'User edits new evidence photo' do
create_book_with_photo_by 'testuser'
login_as 'testuser'
visit_book
expect(page).to have_select 'use', selected: 'Use image for'
select 'Bookplate/Label'
expect(page).to have_content 'New Bookplate/Label'
within '#sidebar' do
find('a', text: 'Edit photo').trigger('click')
end
click_button('Crop image')
expect(page).not_to have_content 'Crop image'
end
end<file_sep>class AddDeletedToEvidence < ActiveRecord::Migration
def up
add_column :evidence, :deleted, :boolean, default: false
Evidence.update_all deleted: false
end
def down
remove_column :evidence, :deleted
end
end
<file_sep>class Flickr::ContextImagesController < Flickr::PublishablesController
end<file_sep>json.array!(@evidence) do |evidence|
json.extract! evidence, :id, :book_id, :format, :content_type, :location_in_book, :location_in_book_page, :transcription, :year_when, :year_start, :year_end, :date_narrative, :where, :comments
json.url evidence_url(evidence, format: :json)
end
<file_sep>class CreateEvidence < ActiveRecord::Migration
def change
create_table :evidence do |t|
t.references :book, index: true, foreign_key: true
t.string :format
t.string :content_type
t.string :location_in_book
t.string :location_in_book_page
t.text :transcription
t.integer :year_when
t.integer :year_start
t.integer :year_end
t.string :date_narrative
t.string :where
t.text :comments
t.timestamps null: false
end
end
end
<file_sep>class CreateNames < ActiveRecord::Migration
def change
create_table :names do |t|
t.string :name, null: false
t.integer :year_start
t.integer :year_end
t.string :viaf_id
t.string :comment
t.timestamps null: false
end
add_index :names, :name, unique: true
end
end
<file_sep>class Name < ActiveRecord::Base
include UserFields
before_destroy :check_counter_cache
has_many :provenance_agents
validates :name, presence: true
validates :name, uniqueness: true
validates_numericality_of :viaf_id, allow_nil: true, allow_blank: true
validates_numericality_of :year_start, allow_nil: true, allow_blank: true
validates_numericality_of :year_end, allow_nil: true, allow_blank: true
scope :name_like, -> (name) { where("lower(name) like ?", name.downcase) }
def full_name
return name if name_has_date?
return name unless date_string.present?
[ name, date_string ].flat_map { |x| x.present? ? x.strip : [] }.join ', '
end
def date_string
years = [ year_start, year_end ]
years.all?(&:blank?) ? nil : years.join('-')
end
def name_has_date?
name =~ /^[[:alnum:]]+.*\d{4}/
end
def to_s
name
end
private
def check_counter_cache
# proceed with destroy if provenance_agents is 0
return true if provenance_agents.size == 0
# otherwise, there's a problem
errors[:base] << "Cannot delete name with provenance agents"
false
end
end
<file_sep>class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable,
:rememberable, :trackable, :validatable
# local attribute for account restoration
attr_accessor :restore_account
cattr_accessor :excluded_names
before_save :undelete, if: :restore_account?
validates :username, presence: true, uniqueness: true
validate :excluded_user_names
# TODO exclude usernames 'all', 'admin', ???
scope :by_name, -> { order("coalesce(full_name, username)") }
def display_name
return full_name if full_name.present?
username
end
# instead of deleting, indicate the user requested a delete & timestamp it
def soft_delete
update_attribute(:deleted_at, Time.current)
end
# restore the account
def undelete
self.deleted_at = nil
end
def restore_account?
@restore_account.present?
end
# ensure user account is active
def active_for_authentication?
super && !deleted_at
end
# provide a custom message for a deleted account
def inactive_message
!deleted_at ? super : :deleted_account
end
def excluded_user_names
return unless username.present?
return unless excluded_names.present?
return unless excluded_names.include? username.strip.downcase
errors.add :username, 'is not allowed'
end
end
<file_sep>json.merge! @photo.attributes
# add `processing` to work with general poll_process function
json.processing @photo.image_processing
<file_sep>module Subpop
class Application < Rails::Application
config.to_prepare do
Flickr::Client.setup do |config|
config.flickr_api_key = ENV['SUBPOP_FLICKR_API_KEY']
config.flickr_shared_secret = ENV['SUBPOP_FLICKR_API_SECRET']
config.flickr_access_token = ENV['SUBPOP_FLICKR_ACCESS_TOKEN']
config.flickr_access_secret = ENV['SUBPOP_FLICKR_ACCESS_SECRET']
config.flickr_userid = ENV['SUBPOP_FLICKR_USERID']
config.flickr_username = ENV['SUBPOP_FLICKR_USERNAME']
end
Flickr::Client.validate
end
end
end<file_sep>version: '2'
services:
db:
image: mysql/mysql-server:5.7
env_file: .docker-environment
ports:
- '3306:3306'
volumes:
- 'db:/var/lib/mysql'
web:
depends_on:
- 'db'
build: .
volumes:
- .:/subpop
ports:
- "3000:3000"
env_file: .docker-environment
delayedjob:
depends_on:
- 'db'
command: bundle exec rake jobs:work
build: .
volumes:
- .:/subpop
env_file: .docker-environment
volumes:
db:<file_sep>require 'rails_helper'
RSpec.describe TitlePage, type: :model do
context 'factory' do
it 'creates a TitlePage' do
expect(create(:title_page)).to be_a(TitlePage)
end
end
context 'initialization' do
it 'creates a TitlePage' do
expect(TitlePage.new).to be_a(TitlePage)
end
end
context 'flickr_metadata' do
it_behaves_like 'flickr_metadata'
end
context 'validations:' do
it 'is valid' do
expect(build(:title_page)).to be_valid
end
it 'is invalid without a book' do
expect(build(:title_page, book: nil)).not_to be_valid
end
end
end
<file_sep>class BooksController < ApplicationController
before_action :set_book, except: [ :new, :index, :create ]
authorize_resource
# GET /books
# GET /books.json
def index
filter = user_filter
if filter.present?
@books = Book.for_user(filter).order("coalesce(repository, owner)").page params[:page]
else
@books = Book.order("coalesce(repository, owner)").page params[:page]
end
end
# GET /books/1
# GET /books/1.json
def show
end
# GET /books/new
def new
@book = Book.new
end
# GET /books/1/edit
def edit
end
# POST /books
# POST /books.json
def create
@book = Book.new(book_params)
respond_to do |format|
if @book.save_by current_user
if params[:image].present?
params[:image].each do |image|
@book.photos.create image: image
end
end
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /books/1
# PATCH/PUT /books/1.json
def update
respond_to do |format|
if @book.update_by current_user, book_params
if params[:image].present?
params[:image].each do |image|
@book.photos.create! image: image
end
end
format.html { redirect_to @book, notice: 'Book was successfully updated.' }
format.json { render :show, status: :ok, location: @book }
else
format.html { render :edit }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# DELETE /books/1
# DELETE /books/1.json
def destroy
@book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def user_filter
return current_user if params[:user_filter].blank?
return if params[:user_filter].strip =~ /^all$/i
User.find_by username: params[:user_filter]
end
# Use callbacks to share common setup or constraints between actions.
def set_book
@book = Book.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def book_params
params.require(:book).permit(:repository, :owner, :collection, :geo_location, :acq_source, :call_number, :catalog_url, :vol_number, :author, :title, :creation_place, :creation_date, :date_narrative, :publisher, :date_narrative)
end
end
<file_sep>class AddCitationsToEvidence < ActiveRecord::Migration
def change
add_column :evidence, :citations, :text
end
end
<file_sep>class DeletePublishableJob < ActiveJob::Base
queue_as :default
def perform publishable, user
publishable.delete_from_flickr user
photo = publishable.photo
publishable.destroy
photo.destroy if photo.present? && photo.orphaned?
end
end
<file_sep>shared_examples_for 'flickr_metadata' do
let(:model) { described_class } # the class that includes the concern
let(:item) { FactoryGirl.create(model.to_s.underscore.to_sym) }
let(:photo_json) { open(File.join(fixture_path, 'flickr_photo_tags.json')).read }
let(:photo_info) { JSON::load(photo_json) }
def add_flickr_data item
item.build_publication_data(flickr_id: photo_info['id'],
metadata: photo_json)
end
it "has a Flickr title" do
expect(item.respond_to? :flickr_title).to be true
end
context 'tags' do
it "has tags_from_object" do
expect(item.tags_from_object).to include(Flickr::Tag.new(raw: item.book.title))
end
it "has tags from Flickr" do
add_flickr_data item
expect(item.tags_on_flickr).to include(Flickr::Tag.new(raw: item.book.title))
end
it 'has tags_to_remove' do
add_flickr_data item
expect(item.tags_to_remove).to include(Flickr::Tag.new(raw: "Not in object"))
end
it 'has tags_to_add' do
new_tag = Flickr::Tag.new raw: "Not on Flickr"
add_flickr_data item
item.book.title = new_tag.raw
expect(item.tags_to_add).to include(new_tag)
end
end
end<file_sep># This will guess the User class
FactoryGirl.define do
factory :context_image do
book
end
end<file_sep>require 'rails_helper'
module Flickr
RSpec.describe Info do
let(:photo_json) { open(File.join(fixture_path, 'flickr_photo.json')).read }
let(:photo_info) { JSON::load(photo_json) }
let(:flickr_userid) { '130616888@N02' }
subject(:info) { Info.new flickr_userid, photo_info }
context "initialize" do
it "creates an Info object from a hash" do
expect(Info.new(flickr_userid, photo_json).info).to be_a Hash
end
it "creates an Info obect from a json string" do
expect(Info.new(flickr_userid, photo_json).info).to be_a Hash
end
it "creates an Info object with a nil #info" do
expect(Info.new(flickr_userid).info).to be_nil
end
it 'has an info hash' do
expect(subject.info).to be_a Hash
end
end
context "accessor methods" do
it "has a photo ID" do
expect(subject.photo_id).to eq("25425808545")
end
it 'has an nsid' do
expect(subject.nsid).to eq('130616888@N02')
end
end
context "urls" do
it "creates a photostream URL" do
# "#{PHOTOS_URL}#{nsid}"
expect(info.photostream_url).to eq('https://www.flickr.com/photos/130616888@N02')
end
it "creates a photopage URL" do
expect(subject.photopage_url).to eq('https://www.flickr.com/photos/130616888@N02/25425808545')
end
it 'creates a tag URL' do
expect(subject.tag_url("tag value")).to eq('https://www.flickr.com/photos/130616888@N02/tags/tagvalue')
end
end
end
end<file_sep>class RemovePublicationDataColumnsFromTitlePage < ActiveRecord::Migration
def restore_publication_data pub
return if pub.publication_data.blank?
pub_data = pub.publication_data
pub.update_columns(
flickr_id: pub_data.flickr_id,
flickr_info: pub_data.metadata,
published_at: pub_data.updated_at)
end
def up
remove_column :title_pages, :flickr_id, :string
remove_column :title_pages, :flickr_info, :text
remove_column :title_pages, :published_at, :datetime
end
def down
add_column :title_pages, :flickr_id, :string
add_column :title_pages, :flickr_info, :text
add_column :title_pages, :published_at, :datetime
TitlePage.find_each { |pub| restore_publication_data pub }
end
end
<file_sep>class ContextImagesController < ApplicationController
before_action :set_photo, only: :find_by_photo
before_action :set_context_image, only: [:show, :destroy]
before_action :set_book, only: [:destroy]
authorize_resource only: [:show]
def find_or_create_for_photo
end
def show
end
# DELETE /evidence/1
# DELETE /evidence/1.json
def destroy
@context_image.save_by current_user
@context_image.mark_deleted
DeletePublishableJob.perform_later @context_image, current_user
respond_to do |format|
format.js
format.html { redirect_to @book, notice: 'Context image was deleted.' }
end
end
private
def set_photo
@photo = Photo.find params[:photo_id]
@photo = @photo.original if @photo.cropped?
end
def set_context_image
@context_image = ContextImage.find params[:id]
end
def set_book
@book = Book.find params[:book_id]
end
end<file_sep>##
# Module to be included in Publishable. Generates metadata for model object
# for publication to Flickr.
module FlickrMetadata
extend ActiveSupport::Concern
include FlickrData
FLICKR_YES = 1
FLICKR_NO = 0
TAG_ATTRS = %w(
book.repository
book.full_call_number
book.owner
book.collection
book.author
book.title
book.creation_place
book.creation_date
book.publisher
format_name
content_types.name
location_name
year_when
where
provenance_agents.name.full_name
)
##
# Flickr's API method `flickr.photos.setMeta` accepts the title and
# description. `metadata` returns a hash of these values.
def metadata
{
title: flickr_title,
description: description
}
end
##
# Return hash with values suitable for the Fickr `upload` call; by default
# `metadatata` and the tags from the object. Values passed into
# `options` will be merged into the resulting hash. If present, the keys
# `:title`, `:description`, and `:tags` will override the default
# values.
#
# See documentation of `Flickr::Client#upload` for valid options.
def upload_data options={}
metadata.merge({ tags: flickrize_tags(tags_from_object) }).merge(options)
end
def flickr_title
what = if self.respond_to? :format_name
format_name
else
# DE 2016-09-20 don't append ' image' to avoid 'Context image image'
self.model_name.human
end
[ book_full_name, what ].join ': '
end
def tags_to_add
# return all the tags not on Flickr
tags_from_object - tags_on_flickr
end
def tags_to_remove
# return all the tags on Flickr, no longer in the object
tags_on_flickr - tags_from_object
end
def description
ac = ActionController::Base.new()
ac.render_to_string('/flickr/description',
locals: { item: self, book: book })
end
def flickrize_tags tags
tags.map { |t| "\"#{t.raw}\"" }.join ' '
end
def tags_from_object
tag_strings = TAG_ATTRS.flat_map { |attr_chain|
extract_tag(self, attr_chain) || []
}
tag_strings << context_image_tag
tag_strings.compact.uniq.map { |s| Flickr::Tag.new(raw: s) }
end
def context_image_tag
s = "Page context ID-%d"
return sprintf(s, id) if is_a? ContextImage
return unless respond_to? :context_image
return unless context_image.present?
return sprintf s, context_image_id
end
##
# Recursively extract the tag value(s) from `obj` using the
# string of chained attributes `attrs`:
#
# book.author # => "<NAME>"
# format_name # => "Bookplate/Label"
# content_types.name # => [ "Armorial", "Forgery" ]
#
# Returns `nil` when obj does not respond to the next attr in the chain;
# that is, if `obj` does not have a method `foo` then processing
# stops and `nil` is returned.
def extract_tag obj, attrs
# if there are no more attributes, return obj
return obj if attrs.blank?
# Process the next attribute in the chain and keep the rest
curr_attr, remaining_attrs = attrs.split '.', 2
# if curr_attr is not a method of obj, return nil
return nil unless obj.respond_to? curr_attr
# grab the next value
val = obj.send(curr_attr)
return nil if val.blank?
return val.to_s if remaining_attrs.blank?
return extract_tag val, remaining_attrs unless val.respond_to? :map
# val must be a list, process each member
val.map { |o| extract_tag o, remaining_attrs.dup }
end
end<file_sep>json.merge! @item.attributes
json.processing @item.processing?<file_sep>require 'rails_helper'
RSpec.describe "Evidence", type: :request do
subject(:subject) { create(:evidence) }
describe "GET /evidence" do
it "works! (now write some real specs)" do
get @evidence
expect(response).to have_http_status(200)
end
end
end
<file_sep>FactoryGirl.define do
factory :name do
sequence :name do |n|
"Smith#{n}, Jane"
end
end
end<file_sep>class RemoveFromFlickrJob < ActiveJob::Base
queue_as :default
before_perform do |job|
job.arguments.first.mark_in_process
end
after_perform do |job|
job.arguments.first.unmark_in_process
end
def perform publishable, user_id
publishable.delete_from_flickr user_id
publishable.save_by! User.find user_id
end
end
<file_sep>module Subpop
class Application < Rails::Application
# url: "/system/#{Rails.env}/:class/:attachment/:id_partition/:style/:filename"
# path: ":rails_root/public/system/#{Rails.env}/:class/:attachment/:id_partition/:style/:filename",
# Use env-specific path if Rails.env != 'production'
env_string = Rails.env == 'production' ? nil : Rails.env
paperclip_url = [
'', 'system', env_string, ':class', ':attachment', ':id_partition',
':style', ':filename',
].flatten.join '/'
config.x.subpop.paperclip_url = paperclip_url
config.x.subpop.paperclip_path = ":rails_root/public#{paperclip_url}"
end
end<file_sep>json.name do
if @name.errors.present?
json.errors @name.errors
json.error_messages @name.errors.full_messages
json.error_count_message "The form has #{pluralize(@name.errors.count, 'error')}."
end
json.model @name.model_name.param_key
end
<file_sep>class TitlePage < ActiveRecord::Base
include Publishable
include BelongsToPhoto
include UserFields
belongs_to :book, required: true, inverse_of: :title_pages
delegate :full_name, to: :book, prefix: true, allow_nil: true
def name
return "title page" unless book_full_name.present?
"title page of #{book_full_name}"
end
def to_s
model_name.human
end
end<file_sep>class PublishableDestroyJob
def destroy klass, id
publishable = klass.find id
publishable.destroy
end
handle_asynchronously :destroy
end<file_sep>#!/usr/bin/env bash
#!/usr/bin/env bash
# docker-tunnel-ctl: docker tunnel control script
#
# Description:
#
# Requires you configure a docker-tunnel in SSH configuration
#
# Host docker-tunnel
# HostName hostname
# IdentityFile ~/.ssh/the.key
# LocalForward 2375 127.0.0.1:2375
# User: user_name
#
#
#### USAGE AND ERRORS
usage() {
echo "Usage: $0 SSH_HOST {start|stop|restart}"
echo ""
}
### OPTIONS
while getopts "hp:" opt; do
case $opt in
h)
usage
exit 1
;;
\?)
echo "ERROR Invalid option: -$OPTARG" >&2
echo ""
usage
exit 1
;;
esac
done
shift $((OPTIND-1))
# ssh -f -N tunnel
if [[ "$#" -eq 2 ]]; then
:
else
echo "Wrong number of arguments"
usage
exit 1
fi
SSH_HOST=$1
ACTION=$2
COMMAND="ssh -f -N $SSH_HOST"
PIDFILE=$HOME/var/run/$SSH_HOST.pid
case "$ACTION" in
start)
printf "%-50s" "Starting $SSH_HOST..."
msg=`$COMMAND >/dev/null 2>&1`
if [ $? -eq 0 ]; then
printf "%s\n" "OK"
else
printf "%s\n" "ERROR"
echo "$msg"
fi
;;
status)
printf "%-50s" "Checking $SSH_HOST..."
PID=`ps -ef | grep ssh | grep "\b$SSH_HOST\b" | awk '{ print $2 }'`
if [ -z "$PID" ]; then
printf "%s\n" "Process not running"
else
echo "Running"
fi
;;
stop)
printf "%-50s" "Stopping $SSH_HOST"
PID=`ps -ef | grep ssh | grep "\b$SSH_HOST\b" | awk '{ print $2 }'`
if [ -n "$PID" ]; then
kill $PID
printf "%s\n" "OK"
else
printf "%s\n" "PID not found"
fi
;;
restart)
$0 $SSH_HOST stop
$0 $SSH_HOST start
;;
*)
usage
exit 1
esac
<file_sep>class Flickr::EvidenceController < Flickr::PublishablesController
end | 34f86110d381e71f17462ce7ae74f4371160b957 | [
"Ruby",
"YAML",
"Markdown",
"Dockerfile",
"Shell"
] | 143 | Ruby | upenn-libraries/subpop | fb538f3c51d6976e999775f598fc3a2f7edf29f7 | 5474addb6deb6fd5bef121ea1f0780d29b53e1c7 |
refs/heads/master | <file_sep>var express = require("express");
var app = express();
var port = 3000;
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/campus_db");
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
//Define the Schemas
var studentSchema = new mongoose.Schema({
name: String,
major: String,
age: Number
});
var userSchema = new mongoose.Schema({
email: String,
pw: String
});
var student = mongoose.model("Student", studentSchema);
var user = mongoose.model("Login", userSchema);
// Home page route
app.get('/', function(req, res) {
res.sendFile(__dirname + "/main.html");
});
app.get('/computer_science.html', function(req, res) {
res.sendFile(__dirname + "/computer_science.html");
});
app.get('/architecture.html', function(req, res) {
res.sendFile(__dirname + "/architecture.html");
});
app.get('/engineering.html', function(req, res) {
res.sendFile(__dirname + "/engineering.html");
});
app.get('/main.html', function(req, res) {
res.sendFile(__dirname + "/main.html");
});
app.get('/math.html', function(req, res) {
res.sendFile(__dirname + "/math.html");
});
app.get('/student_life.html', function(req, res) {
res.sendFile(__dirname + "/student_life.html");
});
app.get('/login_page.html', function(req, res) {
res.sendFile(__dirname + "/login_page.html");
});
app.get('/admissions.html', function(req, res) {
res.sendFile(__dirname + "/admissions.html");
});
app.get('/about_us.html', function(req, res) {
res.sendFile(__dirname + "/about_us.html");
});
app.get('/humanities.html', function(req, res) {
res.sendFile(__dirname + "/humanities.html");
});
app.get('/notable_graduates.ejs', (req, res) => {
db.collection('students').find().toArray((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render(__dirname+'/notable_graduates.ejs', {students: result})
})
})
app.post("/addStudent", (req, res) => {
console.log(req.body);
var myData = new student(req.body);
myData.save()
.then(item => {
res.sendFile(__dirname+'/admissions.html');
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.post("/login", (req, res) => {
var myData = new user(req.body);
myData.save()
.then(item => {
res.send("User could log in if db setup correctly.");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
| 0107b97276e4dd06669694f783824b8296b2f1b6 | [
"JavaScript"
] | 1 | JavaScript | Bryce21/Campus_Tour | 006be18f5ff5f9893f78980a0552774beb5f487b | 95dd66de822f2e5e4a72de280f536397e095dbac |
refs/heads/master | <file_sep>#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int MAXSIZE = 1000;//定义最大页面数
const int NUM = 3;//定义页框数(物理块数)
typedef struct node {
int loaded; //记录该物理块存储的页面
int time; //记录该物理块没有被使用的时间
}page;
page pages[NUM]; //定义页框表 (物理块表)
int queue[MAXSIZE];
int quantity;
//初始化结构函数
void initial() {
int i;
for (i = 0; i < NUM; i++) {
pages[i].loaded = -1;
}
for (i = 0; i < MAXSIZE; i++)
queue[i] = -1;
quantity = 0;
}
//读入页面流
void readData() {
FILE* fp;
char fname[20] = "3.txt";
int i;
cout << "请输入页面流文件名:";
//cin >> fname;
if ((fp = fopen(fname, "r")) == NULL) {
cout << "错误,文件打不开,请检查文件名";
} else {
while (!feof(fp)) {
fscanf(fp, "%d ", &queue[quantity]);
quantity++;
}
}
cout << "读入的页面流:";
for (i = 0; i < quantity; i++) {
cout << queue[i] << " ";
}
}
//FIFO调度算法
void FIFO() {
int i, j, p, flag;
int absence = 0; //记录缺页次数
p = 0;
cout << endl << "----------------------------------------------------" << endl;
cout << "先进先出调度算法(FIFO)页面调出流:";
for (i = 0; i < NUM; i++) //前3个进入内存的页面
{
pages[p].loaded = queue[i];
cout << pages[p].loaded << " ";
p = (p + 1) % NUM;
}
absence = 3;
for (i = NUM; i < quantity; i++) {
flag = 0;
for (j = 0; j < NUM; j++) //判断当前需求的页面是否在内存
{
if (pages[j].loaded == queue[i])
flag = 1;
}
if (flag == 0) {
cout << pages[p].loaded << " ";
pages[p].loaded = queue[i];
p = (p + 1) % NUM;
absence++;
}
}
cout << endl << "总缺页数:" << absence << endl;
}
//最近最少使用调度算法(LRU)
void LRU() {
int i = 0; //待入数组索引
int p = 0; //存储块对垒索引
int absence = 0;
bool in_pages = NULL;
cout << endl << "----------------------------------------------------" << endl;
cout << "LRU调度算法,页面调出流:";
for (i = 0; i < NUM; i++) {
pages[p].loaded = queue[i];
pages[p].time = 0;
if (p == 1) {
pages[p - 1].time--;
}
if (p == 2) {
pages[p - 1].time--;
pages[p - 2].time--;
}
p = (p + 1) % NUM; //此时最大为2
}
absence = 3;
//前三填充完毕
for (i = NUM; i < quantity; i++) {
for (int j = 0; j < NUM; j++) {
if (pages[j].loaded == queue[i]) {
pages[j].time = 0;
in_pages = true;
for (int k = 0; k < NUM; k++) {
if (k != j) {
pages[k].time--;
}
}
break;
}
}
if (in_pages == false) {
int farthest_time = 0;
int pre_exchange_index = 0;
for (int j = 0; j < NUM; j++) {
if (pages[j].time < farthest_time) {
farthest_time = pages[j].time;
pre_exchange_index = j;
}
}
absence++;
cout << pages[pre_exchange_index].loaded << " ";
pages[pre_exchange_index].loaded = queue[i];
pages[pre_exchange_index].time = 0;
for (int j = 0; j < NUM; j++) {
if (j != pre_exchange_index) {
pages[j].time--;
}
}
}
in_pages = NULL; //为true时运行到此后要更改值,否则后面恒为true
}
cout << endl << "缺页中断次数 " << absence << endl;
}
void main() {
cout << " /**********虚拟存储管理器的页面调度**************/" << endl;
initial();
readData();
//FIFO();
LRU();
}
<file_sep>#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <vector>
using namespace std;
#define MAX_PROCESS 32 //最大进程数
#define MAX_RESOURCE 64 //最大资源类别
int PROCESS_NUM; //实际总进程数
int RESOURCE_NUM; //实际资源类别数
int Available[MAX_RESOURCE]; //可利用资源向量
int Max[MAX_PROCESS][MAX_RESOURCE]; //最大需求矩阵
int Allocation[MAX_PROCESS][MAX_RESOURCE]; //分配矩阵
int Need[MAX_PROCESS][MAX_RESOURCE]; //需求矩阵,一个描述还需要多少资源的矩阵
int Request_PROCESS; //发出请求的进程
int Request_RESOURCE_NEMBER[MAX_RESOURCE]; //请求资源数
void Read_Available_list(); //读入可用资源Available
void Read_Max_list(); //读入最大需求矩阵Max
void Read_Allocation_list(); //读入已分配矩阵Allocation
void PrintInfo(); //打印各数据结构信息
void Read_Request(); //输入请求向量
void Allocate_Source(); //开始正式分配资源(修改Allocation_list.txt)
void Recover_TryAllocate(); //恢复试分配前状态
int Test_Safty(); //安全性检测
void RunBanker(); //执行银行家算法
//读入可用资源Available
void Read_Available_list() {
FILE* fp;
if ((fp = fopen("Available_list.txt", "r")) == NULL) {
cout << "错误,文件打不开,请检查文件名" << endl;
exit(0);
}
fscanf(fp, "%d", &RESOURCE_NUM);
int i = 0;
while (!feof(fp)) {
fscanf(fp, "%d", &Available[i]);
i++;
}
fclose(fp);
}
//读入最大需求矩阵Max
void Read_Max_list() {
FILE* fp;
if ((fp = fopen("Max_list.txt", "r")) == NULL) {
cout << "错误,文件打不开,请检查文件名" << endl;
exit(0);
}
fscanf(fp, "%d", &PROCESS_NUM);
for (int i = 0; i < PROCESS_NUM; i++)
for (int j = 0; j < RESOURCE_NUM; j++)
fscanf(fp, "%d", &Max[i][j]);
fclose(fp);
}
//读入已分配矩阵Allocation
void Read_Allocation_list() {
FILE* fp;
if ((fp = fopen("Allocation_list.txt", "r")) == NULL) {
cout << "错误,文件打不开,请检查文件名" << endl;
exit(0);
}
for (int i = 0; i < PROCESS_NUM; i++)
for (int j = 0; j < RESOURCE_NUM; j++)
fscanf(fp, "%d", &Allocation[i][j]);
fclose(fp);
}
//设置需求矩阵Need
void Set_Need_Available() {
for (int i = 0; i < PROCESS_NUM; i++)
for (int j = 0; j < RESOURCE_NUM; j++) {
Need[i][j] = Max[i][j] - Allocation[i][j];
Available[j] = Available[j] - Allocation[i][j];
}
}
//打印各数据结构信息
void PrintInfo() {
cout << "进程个数: " << PROCESS_NUM << "\t" << "资源个数: " << RESOURCE_NUM << endl;
cout << "可用资源向量Available:" << endl;
int i, j;
for (i = 0; i < RESOURCE_NUM; i++)
cout << Available[i] << "\t";
cout << endl;
cout << "最大需求矩阵Max:" << endl;
for (i = 0; i < PROCESS_NUM; i++) {
for (j = 0; j < RESOURCE_NUM; j++)
cout << Max[i][j] << "\t";
cout << endl;
}
cout << "已分配矩阵Allocation:" << endl;
for (i = 0; i < PROCESS_NUM; i++) {
for (j = 0; j < RESOURCE_NUM; j++)
cout << Allocation[i][j] << "\t";
cout << endl;
}
cout << "需求矩阵Need:" << endl;
for (i = 0; i < PROCESS_NUM; i++) {
for (j = 0; j < RESOURCE_NUM; j++)
cout << Need[i][j] << "\t";
cout << endl;
}
}
//输入请求向量
void Read_Request() {
cout << "输入发起请求的进程(0-" << PROCESS_NUM - 1 << "):";
cin >> Request_PROCESS;
cout << "输入请求资源的数目:按照这样的格式输入 x x x:";
for (int i = 0; i < RESOURCE_NUM; i++)
cin >> Request_RESOURCE_NEMBER[i];
}
//开始正式分配资源(修改Allocation_list.txt)
void Allocate_Source() {
cout << '\n' << "开始给第" << Request_PROCESS << "个进程分配资源..." << endl;
FILE* fp;
if ((fp = fopen("Allocation_list.txt", "w")) == NULL) {
cout << "错误,文件打不开,请检查文件名" << endl;
exit(0);
}
for (int i = 0; i < PROCESS_NUM; i++) {
for (int j = 0; j < RESOURCE_NUM; j++)
fprintf(fp, "%d ", Allocation[i][j]);
fprintf(fp, "\n");
}
cout << "分配完成,已更新Allocation_list.txt" << endl;
fclose(fp);
}
//恢复试分配前状态
void Recover_TryAllocate() {
for (int i = 0; i < RESOURCE_NUM; i++) {
Available[i] = Available[i] + Request_RESOURCE_NEMBER[i];
Allocation[Request_PROCESS][i] = Allocation[Request_PROCESS][i] - Request_RESOURCE_NEMBER[i];
Need[Request_PROCESS][i] = Need[Request_PROCESS][i] + Request_RESOURCE_NEMBER[i];
}
}
//安全性检测
//返回值:0:未通过安全性测试; 1:通过安全性测试
int Test_Safty() {
int m = sizeof(Available) / sizeof(int); //m 资源种类数
int n = (sizeof(Need) / sizeof(int)) / (sizeof(Need[0]) / sizeof(int)); //n 还在等待资源的进程数
vector<int> Work(m);
vector<bool> Finish(n);
for (int i = 0; i < m; i++) {
Work[i] = Available[i];
}
for (int i = 0; i < n; i++) {
Finish[i] = false;
}
int compared_time = 0; //已经循环全组比较次数
int max_compare_time = 0; //最大循环全组比较次数
for (int _n = n; _n > 1; _n--) {
max_compare_time *= _n;
}
while (compared_time != max_compare_time) {
for (int i = 0; i < n; i++) {
if (Finish[i] == false) {
compared_time++;
for (int j = 0; j < m; j++) {
if (Need[i][j] <= Work[j]) {
while (j == (m - 1)) {
for (int k = 0; k < m; k++) {
Work[k] += Allocation[i][k];
}
Finish[i] = true;
i = 0; //从头开始
break;
}
} else {
break; //有一个资源不符合条件就没必要再比较该进程了
}
}
}
}
}
for (int i = 0; i < n; i++) {
if (Finish[i] == true) {
return 1;
} else {
return 0;
}
}
}
void RunBanker() { //执行银行家算法
cout << endl;
cout << "开始执行银行家算法..." << endl;
for (int i = 0; i < RESOURCE_NUM; i++) //检查是否满足条件Request<=Need
if (Request_RESOURCE_NEMBER[i] > Need[Request_PROCESS][i]) {
cout << "\n第" << Request_PROCESS << "个进程请求资源不成功" << endl;
cout << "原因:超出该进程尚需的资源的最大数量!" << endl;
return;
}
for (int i = 0; i < RESOURCE_NUM; i++) //检查是否满足条件Request<=Available
if (Request_RESOURCE_NEMBER[i] > Available[i]) {
cout << "\n第" << Request_PROCESS << "个进程请求资源不成功" << endl;
cout << "原因:系统中无足够的资源!" << endl;
return;
} else {
//试分配,更新各相关数据结构
Available[i] = Available[i] - Request_RESOURCE_NEMBER[i];
Allocation[Request_PROCESS][i] = Allocation[Request_PROCESS][i] + Request_RESOURCE_NEMBER[i];
Need[Request_PROCESS][i] = Need[Request_PROCESS][i] - Request_RESOURCE_NEMBER[i];
}
cout << endl << "试分配完成..." << endl;
if (Test_Safty()) //使用安全性算法检查,若满足,则正式分配
Allocate_Source();
else //否则恢复试分配前状态
Recover_TryAllocate();
}
void main() {
char c;
Read_Available_list();
Read_Max_list();
Read_Allocation_list();
Set_Need_Available();
PrintInfo();
while (1) {
Read_Request();
RunBanker();
cout << "\n\n需要继续吗?(y-继续;n-终止)";
cin >> c;
if (c == 'n')
break;
cout << endl << endl;
PrintInfo();
}
}
<file_sep>#include "stdio.h"
#include "stdlib.h"
#include "time.h"
#include "iostream"
using namespace std;
#define PROCESSNUM 2 //输出进程个数
#define BUFFERNUM 100 //内存缓冲字节个数
#define OUTBUFFERNUM 200 //输出井存储字节个数
#define REQBLOCKNUM 10
struct pcb //进程控制块PCB
{
int id; //进程标识
int status; //状态
int length;//输出长度
int buf[BUFFERNUM];//输出缓冲
}PCB[PROCESSNUM + 1];
struct req //请求输出块
{
int reqid;//要求输出的进程
int length;//输出长度
int addr;//输出首地址
}ReqBlock[REQBLOCKNUM];
struct outbuf //输出井结构
{
int buf[OUTBUFFERNUM]; //输出井缓冲区
int usedNum; //输出井缓冲区已使用的数目
int head; //指示输出井空闲块首地址
//int tail; //指示输出井信息块(有信息的部分)尾地址
}OutBuffer[PROCESSNUM];
int UsedReqBlockNum = 0; //记录当前已使用的请求块数目
int head = 0, tail = 0; //指示当前使用的输出请求块,request从tail开始取,spooling从head开始取
int FileNum[PROCESSNUM];
void input()//输入函数
{
for (int i = 0; i < PROCESSNUM; i++) {
cout << "输入第" << i + 1 << "个用户需要输出的文件数目:";
cin >> FileNum[i];
}
}
void init()//初始化函数
{
int i, j;
for (i = 0; i < PROCESSNUM; i++) {
OutBuffer[i].head = 0;
OutBuffer[i].usedNum = 0;
for (j = 0; j < OUTBUFFERNUM; j++)
OutBuffer[i].buf[j] = 0;
}
for (i = 0; i < REQBLOCKNUM; i++) {
ReqBlock[i].reqid = -1;
ReqBlock[i].length = 0;
ReqBlock[i].addr = 0;
}
for (i = 0; i < PROCESSNUM + 1; i++) {
PCB[i].id = i;
PCB[i].status = 0;
PCB[i].length = 0;
for (j = 0; j < BUFFERNUM; j++)
PCB[i].buf[j] = 0;
}
PCB[PROCESSNUM].status = 2; //spooling进程的状态置2(输出井空)
}
void request(int i) {
int j, length = 0;
if (PCB[i].length == 0) //判断上次的输出是否处理完
{
FileNum[i] = FileNum[i] - 1;
//srand((unsigned)time(NULL));
while (1) {
j = rand() % 10;
if ((j == 0) && (length != 0)) //以0结束此次输出
{
PCB[i].length = length;
break;
}
PCB[i].buf[length] = j;
length++;
}
}
if (OutBuffer[i].usedNum + length > OUTBUFFERNUM) //判断输出井是否满
{
PCB[i].status = 1; //输出井满,进程状态置1
return;
}
if (UsedReqBlockNum == REQBLOCKNUM) //判断是否有空闲的请求块
{
PCB[i].status = 3; //没有空闲的请求块,进程状态置3
return;
}
//填写请求块
ReqBlock[tail].reqid = i;
ReqBlock[tail].addr = OutBuffer[i].head;
ReqBlock[tail].length = PCB[i].length;
UsedReqBlockNum++;
//将数据写到输出井
int k;
for (k = 0; k < PCB[i].length; k++)
OutBuffer[i].buf[(OutBuffer[i].head + k) % OUTBUFFERNUM] = PCB[i].buf[k];
OutBuffer[i].head = (OutBuffer[i].head + PCB[i].length) % OUTBUFFERNUM;
OutBuffer[i].usedNum += PCB[i].length;
PCB[i].length = 0;
if (PCB[PROCESSNUM].status == 2) //若spooling进程阻塞,则修改其状态为可执行(0)
PCB[PROCESSNUM].status = 0;
tail = (tail + 1) % REQBLOCKNUM;
if (FileNum[i] == 0)
PCB[i].status = 4;
}
void spooling() {
if (UsedReqBlockNum !=0 ) {
//取数据--打印
PCB[0].length=0;
PCB[0].status=4;
PCB[1].length = 0;
PCB[1].status = 4;
if (ReqBlock[0].addr!=0) {
ReqBlock[0].reqid=0;
}
if (ReqBlock[1].addr != 0) {
ReqBlock[1].reqid = 0;
}
} else {
if (sizeof(OutBuffer[0].buf)==0 && sizeof(OutBuffer[1].buf) == 0) {
PCB[3].status=4;
} else {
PCB[3].status=2;
}
}
return;
}
void work()//模拟进程调度
{
int i;
bool isFinish;
srand((unsigned)time(NULL));
while (1) {
i = rand() % 100;
if (i <= 45) {
if (PCB[0].status == 0)
request(0);
} else if (i <= 90) {
if (PCB[1].status == 0)
request(1);
} else
spooling();
isFinish = true;
for (i = 0; i < PROCESSNUM + 1; i++) //判断是否所有进程都结束
if (PCB[i].status != 4)
isFinish = false;
if (isFinish) //若所有进程都结束,则退出
return;
}
}
int main() //主程序
{
printf("\n>>>>>>>>>>>>>>>> SPOOLing系统模拟程序 <<<<<<<<<<<<<<<<<\n");
init();
input();
work();
return 0;
}
| ed0e0fbd0efbf50ea1996254c545bd2eafd8b118 | [
"C++"
] | 3 | C++ | hJinRong/Computer-Operating-System-Experiments | 923028ec596f8b25691cd2429c944831f1e463a9 | 88d5a0e27a9d69f29caaf1c29c221bd16441fbdf |
refs/heads/master | <file_sep>import React from "react";
import {
Card,
Button,
CardTitle,
CardText
} from "reactstrap";
const CardWithTitle = ({ title, text, children }) => (
<Card body>
{title ? <CardTitle>{title}</CardTitle> : ""}
{text ? <CardText>{text}</CardText> : ""}
{children ? children : <Button>Go somewhere</Button>}
</Card>
);
export default CardWithTitle;
<file_sep>import React from 'react';
import { Alert } from 'reactstrap';
import { hideAlert } from './custom-alert-actions'
import { connect } from 'react-redux'
/*This is Custom Alert.
Type can following type : default will be info
1.primary
2.secondary
3.success
4.danger
5.warning
6.info
7.light
8.dark
*/
const CustomAlert = ({isOpen, message, type='info', onHide=f=>f}) => {
const onDismiss = () => {
onHide()
}
setTimeout(function() {
onHide()
}, 6000)
return (
<div className='custom-alert'>
<Alert color={type} isOpen={isOpen} toggle={onDismiss}>
{message}
</Alert>
</div>
)
}
const mapStatToProps = (state, props) =>
({
isOpen : state.customAlert.isOpen,
message : state.customAlert.message,
type : state.customAlert.type
})
const mapDispatchToProps = (dispatch) =>
({
onHide () {
dispatch(
hideAlert()
)
}
})
const constainer = connect(mapStatToProps, mapDispatchToProps)(CustomAlert)
export default constainer;
<file_sep>import React from 'react'
import {
InputGroup,
InputGroupAddon,
Button,
Input } from 'reactstrap';
const searchBox = () => {
return (
<div>
<InputGroup>
<Input placeholder="Search Product by Name or Category..." />
<InputGroupAddon addonType="append">
<Button color="info">Search</Button>
</InputGroupAddon>
</InputGroup>
</div>
)
}
export default searchBox;<file_sep>import C from './sign-up-constants'
export const signUp = (firstName, lastName, email, password, dob, sex, mobileNumber) =>
({
type : C.SIGN_UP,
payload : {firstName : firstName, lastName : lastName, email : email, password : <PASSWORD>, dob : dob, sex:sex, mobileNumber : mobileNumber}
})<file_sep>import { takeEvery } from 'redux-saga/effects'
import C from './sign-up/sign-up-constants'
import { signUp } from './sign-up/sign-up-sagas'
import LOGIN_CONSTANTS from './login/login-constants'
import { login } from './login/login-sagas'
export default function* mySaga() {
yield takeEvery(C.SIGN_UP, signUp)
yield takeEvery(LOGIN_CONSTANTS.LOGIN, login)
}
<file_sep>
const userRef = window.db.collection('users');
export const onLogin = async (obj) => {
try {
const response = await userRef.where("email", "==", obj.email).where("password", "==", obj.password).get();
return response;
} catch(e) {
}
}<file_sep>import C from './login-constants'
export const login = (email, password) =>
({
type :C.LOGIN,
payload : {email : email, password : <PASSWORD>}
})
export const logout = () =>
({
type: C.LOGOUT
}) <file_sep>import { Cookies } from 'react-cookie';
const cookies = new Cookies();
const AUTH_USER = "auth-user"
const cookiesUtils = (function() {
let setCookie = (key, value) => {
cookies.set(key, value, { path: '/' })
}
let getCookie = (key) => {
return cookies.get(key)
}
let removeCookie = (key) => {
return cookies.remove(key)
}
return {
setAuthorisedUser : function(userObj) {
setCookie(AUTH_USER, userObj)
},
getAuthorisedUser : function() {
getCookie(AUTH_USER)
},
logout : function() {
removeCookie(AUTH_USER)
}
}
})();
export default cookiesUtils;<file_sep>import { call, put } from 'redux-saga/effects'
import C from './sign-up-constants'
import ALERT_CONSTANTS from '../share/components/custom-alert/custom-alert-constants'
import {signUpUserApi} from './sign-up-api'
export function* signUp(action) {
try {
const users = yield call (signUpUserApi, action.payload);
console.log("Users : "+users)
// // Instructing middleware to dispatch corresponding action.
yield put({type: C.SIGN_UP_SUCCESS, payload : users});
yield put({type: ALERT_CONSTANTS.SHOW_ALERT, payload : {isOpen : true, message : 'Sign Up has been completed successfuly.'}});
} catch (e) {
console.log("Error : " + e.message);
}
}
<file_sep>const constants = {
SHOW_ALERT : "SHOW_ALERT",
HIDE_ALERT : "HIDE_ALERT"
}
export default constants;<file_sep>import { createStore, applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga'
import appReducer from './index-reducer'
import mySaga from './index-sagas'
const initialState = {
"signUp" : [],
"customAlert" : {
isOpen : false
},
authUser : {
isAuthUser : false
}
};
// create the saga middleware
const sagaMiddleware = createSagaMiddleware();
const store = createStore(appReducer, initialState, applyMiddleware(sagaMiddleware));
// then run the saga
sagaMiddleware.run(mySaga)
export default store<file_sep>import React from 'react'
import loadingImg from "../../assets/images/loading.gif";
const loading = ({height="500px"}) => {
return(
<img src={loadingImg} height={height}/>
)
}
export default loading;<file_sep>import C from './sign-up-constants'
const signUp = (state=[], action) => {
switch(action.type) {
case C.SIGN_UP:
return state
case C.SIGN_UP_SUCCESS:
return [...state, action.payload]
default:
return state
}
}
export default signUp<file_sep>import React from 'react'
import { Card, Button, CardBody, CardTitle } from 'reactstrap'
import { Form, FormGroup, Label, Input } from 'reactstrap';
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import { signUp } from './sign-up-actions'
import InputWithLabel from '../share/components/InputWithLabel'
const SignUp = ({signUp, onSignUp=f=>f}) => {
let _dob, _email, _firstName, _lastName, _mobileNumber, _sex, _password;
const clickHandler = () => {
onSignUp(getObj());
}
const ID_FIRT_NAME = "firstName";
const ID_LAST_NAME = "lastName";
const ID_EMAIL = "email";
const ID_DOB = "dob";
const ID_MOBILE_NUMBER = "mobileNumber";
const ID_SEX = "sex";
const ID_PASSWORD = "<PASSWORD>";
const getObj = () => ({
'dob' : _dob,
'email' : _email,
'firstName' : _firstName,
'lastName' : _lastName,
'mobileNumber' : _mobileNumber,
'sex' : _sex,
'password' : <PASSWORD>
})
const onHanlderChange = (e, id) => {
let value = e.currentTarget.value;
switch(id) {
case ID_FIRT_NAME :
_firstName = value
break
case ID_LAST_NAME :
_lastName = value
break
case ID_DOB :
_dob = value
break
case ID_EMAIL :
_email = value
break
case ID_MOBILE_NUMBER :
_mobileNumber = value
break
case ID_SEX :
_sex = value
break
case ID_PASSWORD :
_password = value
break
default :
break
}
}
return(
<div className='signup'>
<Card>
<CardTitle>Sign Up</CardTitle>
<CardBody>
<Form>
<InputWithLabel id={ID_FIRT_NAME} label="First Name" type="text" onChangeValue={onHanlderChange}/>
<InputWithLabel id={ID_LAST_NAME} label="Last Name" type="text" onChangeValue={onHanlderChange}/>
<InputWithLabel id={ID_MOBILE_NUMBER} label="Mobile Number" type="number" onChangeValue={onHanlderChange}/>
<InputWithLabel id={ID_EMAIL} label="Email" type="email" onChangeValue={onHanlderChange}/>
<InputWithLabel id={ID_PASSWORD} label="Password" type="password" onChangeValue={onHanlderChange}/>
<InputWithLabel id={ID_DOB} label="Birthday" type="date" onChangeValue={onHanlderChange}/>
<FormGroup tag="fieldset">
<FormGroup check>
<Label check>
<Input type="radio" onChange={event => onHanlderChange(event,ID_SEX)} name="radio1" value="Male"/> Male
</Label>
</FormGroup>
<FormGroup check>
<Label check>
<Input type="radio" onChange={event => onHanlderChange(event,ID_SEX)} name="radio1" value="Female"/>Female
</Label>
</FormGroup>
</FormGroup>
<Button onClick={clickHandler}>Sign Up</Button>
<Button>Reset</Button>
</Form>
</CardBody>
</Card>
</div>
)
}
const mapStateToProps = (state, props) => {
return {
signUp : state
}
}
const mapDispatchToProps = (dispatch) => {
return {
onSignUp({firstName, lastName, email, password, dob, sex, mobileNumber}) {
dispatch(
signUp(firstName, lastName, email, password, dob, sex, mobileNumber)
)
}
}
}
const container = connect(mapStateToProps, mapDispatchToProps)(SignUp)
export default withRouter(container)<file_sep>const constants = {
LOGIN : 'LOGIN',
LOGGED_IN : 'LOGGED_IN',
LOGOUT : 'LOGOUT'
}
export default constants<file_sep>import React from "react";
import logo from "../../assets/images/logo.svg";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { withCookies } from "react-cookie";
import { logout } from "../../login/login-actions";
import { Badge } from 'reactstrap';
class Header extends React.Component {
constructor(props) {
super(props);
this.onLogout = this.onLogout.bind(this);
}
getLoginHeader() {
const container = (
<div>
<Link to="logIn">LogIn</Link>
<Link to="signUp">SignUp</Link>
</div>
);
return container;
}
getLoggedInHeader(user) {
const loggedContainer = (
<div>
<a>Welcome {user.firstName} </a>
<Link to="products">Products</Link>
<Link to="home">Home</Link>
<a href="" onClick={this.onLogout}>
Logout
</a>
<a href="">Cart <Badge color="secondary">0</Badge></a>
</div>
);
return loggedContainer;
}
onLogout(event) {
event.preventDefault();
this.props.cookies.remove("user");
this.props.onLogout();
}
render() {
console.log("Header..............");
let { isUserLoggedIn, user, cookies } = this.props;
if (isUserLoggedIn) {
cookies.set("user", user, { path: "/" });
} else {
const userCookie = cookies.get("user");
if (userCookie) {
isUserLoggedIn = true;
user = userCookie;
}
}
return (
<header className="App-header">
<Link to="/">
<img src={logo} className="App-logo" alt="logo" />
</Link>
<div className="menu-panel">
{isUserLoggedIn
? this.getLoggedInHeader(user)
: this.getLoginHeader()}
</div>
</header>
);
}
}
const mapStateToProps = state => ({
isUserLoggedIn: state.authUser.isAuthUser,
user: state.authUser.user
});
const mapDispatchToProps = dispatch => ({
onLogout() {
dispatch(logout());
}
});
const container = connect(mapStateToProps, mapDispatchToProps)(
withCookies(Header)
);
export default container;
<file_sep>import React from "react";
import { Card, Button, CardBody, CardTitle } from "reactstrap";
import { Form } from "reactstrap";
import { connect } from "react-redux";
import { withRouter } from "react-router";
import { login } from "./login-actions";
import InputWithLabel from "../share/components/InputWithLabel";
const LogIn = ({ onLogin = f => f }) => {
let _email, _password;
const login = () => {
onLogin(_email, _password);
};
const onEmailChangeHandler = event => {
_email = event.target.value;
};
const onPasswordChangeHandler = event => {
_password = event.target.value;
};
return (
<div className="login">
<Card>
<CardTitle>Log in</CardTitle>
<CardBody>
<Form>
<InputWithLabel
id="email"
label="Email"
type="email"
onChangeValue={onEmailChangeHandler}
/>
<InputWithLabel
id="password"
label="Password"
type="password"
onChangeValue={onPasswordChangeHandler}
/>
<Button onClick={login}>Log In</Button>
<Button>Cancel</Button>
</Form>
</CardBody>
</Card>
</div>
);
};
const mapStateToProps = () => ({});
const mapDispatchToProps = dispatch => ({
onLogin(email, password) {
dispatch(login(email, password));
}
});
const container = connect(mapStateToProps, mapDispatchToProps)(LogIn);
export default withRouter(container);
<file_sep>import React from 'react'
import { FormGroup, Label, Input } from 'reactstrap';
const InputWithLabel = ({label,id, type, onChangeValue}) =>
(
<FormGroup>
<Label for={id}>{label}</Label>
<Input
type={type}
id={id}
onChange={event => onChangeValue(event,id)}/>
</FormGroup>
)
export default InputWithLabel <file_sep>import React from "react";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import { withCookies } from "react-cookie";
import Header from "./share/components/Header";
import Footer from "./share/components/Footer";
import LogIn from "./login/LogIn";
import SignUp from "./sign-up/SignUp";
import Home from "./home/Home";
import Products from './products'
import CustomAlert from "./share/components/custom-alert/CustomAlert";
const RouterHandler = ({ isUserLoggedIn, cookies }) => {
let isLoggedIn = isUserLoggedIn;
if (!isLoggedIn) {
const userCookie = cookies.get("user");
if (userCookie) {
isLoggedIn = true;
}
}
return (
<BrowserRouter>
<div>
<CustomAlert />
<Header />
<center className="center-panel">
{isLoggedIn ? (
<Switch>
<Route exact path="/" component={Home} />
<Route path="/home" component={Home} />
<Route path="/products" component={Products} />
<Redirect from="/logIn" exact to="/" />
</Switch>
) : (
<Switch>
<Route exact path="/" component={LogIn} />
<Route exact path="/" component={LogIn} />
<Route path="/logIn" component={LogIn} />
<Route path="/signUp" component={SignUp} />
<Redirect from="/home" exact to="/" />
</Switch>
)}
</center>
<Footer />
</div>
</BrowserRouter>
);
};
const mapStateToProps = (state, props) => {
return {
isUserLoggedIn: state.authUser.isAuthUser
};
};
const container = connect(mapStateToProps)(withCookies(RouterHandler));
export default container;
<file_sep>import { combineReducers } from 'redux'
import signUp from './sign-up/sign-up-reducer'
import customAlert from './share/components/custom-alert/custom-alert-reducer'
import authUser from './login/login-reducer'
export default combineReducers({
signUp,
customAlert,
authUser
});
| b6944035eb8842b93ae90aa54ead26b9d7ff5d99 | [
"JavaScript"
] | 20 | JavaScript | DivyeshRupawala/react-firebase | f2b63ab263f22074cf28a096b177604c32cfd8ad | a2f3d32af73d71e4d60a20357c6312a6b77c79cf |
refs/heads/master | <repo_name>tomomichi549/201207_express_message<file_sep>/public/js/input.js
$(function () {
let index = 0;
//履歴削除
$('#clearBtn').on('click', function () {
$('#history').text('');
});
//フォームリクエスト
$('#form').on('submit', function () {
//HTML フォームを止める
event.preventDefault();
//Ajax データ送信
let data = $('#form').serialize();
const url = 'http://localhost:3000?id=123';
console.log(data);
$.ajax({
url: url,
type: 'post',
data: data,
dataType: 'text'
}).done(function (res) {
//結果
console.debug(res);
$('#result').text(res);
//履歴
const result = JSON.parse(res);
const date = new Date(result.datetime);
const date_string = date.toLocaleString('ja-JP');
const message = `${date_string} ${result.message}`;
index++;
let id_name = 'btn-' + index;
const li = $('<li>');
li.attr('id', id_name).addClass('list-group-item').append(message);
//delete link
const button = $('<button>');
button.attr('href', '#').addClass('btn btn-sm btn-outline-primary message-btn').text('削除');
button.on('click', function () {
$('#' + id_name).remove();
});
//btn area
const btn_area = $('<p>');
btn_area.addClass('text-right').append(button);
li.append(btn_area);
$('#history').append(li);
}).fail(function (xhr, status, error) {
//エラー
alert(status);
});
});
});
<file_sep>/server.js
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// ミドルウェア関数
// 全てのリクエスト
app.use((req, res, next) => {
console.log(`middleware: all. url: ${req.url}`);
//CROS設定: 全てのドメインに対して許可
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//次の処理
next();
});
app.post('/', (req, res) => {
// let message = req, body
let result = {
message: req.body.message,
datetime: new Date(),
};
res.send(result);
});
app.get('/', (req, res) => {
res.send('Hello Express!');
});
app.listen(3000);
console.log('Server listen:http://localhost:3000');
| ebd6186312d3f840858b633d08f03e36b2cdde50 | [
"JavaScript"
] | 2 | JavaScript | tomomichi549/201207_express_message | bda9e6426ca13637bcacda928dc647003a8cef9a | 6da9d2df5a0159c098da18be116ae07dcee78531 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 11:31:06 2020
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# storage vector for 20 trajectories
trajectories = np.zeros((20,10001))
# setting random seed
np.random.seed(6)
# stating wealth 100$ to feed the loop
w = 100
# loop that creates the trajectory
for i in range(0,20):
w = 100
for element in range(1,10001):
if (w*1.01) - w > (0.5*(w*1.5) + 0.5*(w*0.6)) - w:
w = w*1.01
trajectories[i, element] = w
else:
if np.random.randint(0, 2, 1) == 1:
w = w*1.5
trajectories[i, element] = w
else:
w = w*0.6
trajectories[i, element] = w
# 100$ at time t
trajectories[:,0] = 100
# defining expected utility factor
EU_factor = 1.05
# defining trajectory EU
trajectory_EU = list(100*(EU_factor)**(t) for t in range(0, 10001))
# plotting the trajectories
# plotting the trajectory
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.xlabel('time', fontdict=None, labelpad=None)
plt.ylabel('utility/wealth', fontdict=None, labelpad=None)
plt.yscale('log')
plt.grid()
for i in range(0,20):
plt.plot(trajectories[i,:])
plt.plot(trajectory_EU, color='red')
# saving the image
plt.savefig('thesis - linear utility 1b.pdf')
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 18:51:48 2019
@author: Lorenzo
"""
#######################################################
import numpy as np
import random
from matplotlib import pyplot as plt
#from pylab import rcParams
from collections import Counter
from scipy.interpolate import interp1d
np.seterr(divide = 'ignore')
# import pandas as pd
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#######################################################
# setting parameters
# number of trials
n = 10000
# probability of success
p = 0.5
# probability of failure
q = 0.5
# expected value
m = 5000
# standard deviation
sd = round(np.sqrt(n*p*q))
# fixed number of successes (expected value +/- a certain number of standard deviations)
successes = np.asarray([m-5*sd, round(m-4.5*sd), m-4*sd, round(m-3.5*sd), m-3*sd, round(m-2.5*sd), m-2*sd, round(m-1.5*sd), m-1*sd, round(m-0.5*sd), m, round(m+0.5*sd), m+1*sd, round(m+1.5*sd), m+2*sd, round(m+2.5*sd), m+3*sd, round(m+3.5*sd), m+4*sd, round(m+4.5*sd), m+5*sd])
coinflips = np.zeros((21,10000))
# create matrix with different streaks of successes and failures
for j in range(0,21):
ones = np.ones((1,int(successes[j,])))
zeros = np.zeros((1,int(n - successes[j,])))
x = np.concatenate((ones, zeros), axis = 1)
coinflips[j,:] = x
random.shuffle(coinflips[j,:])
# test: check that number of 1s and 0s is plausible (replace '0' with other columns' numbers to check them)
counter = Counter(coinflips[0,:])
# define interest rate
r = 0.01
# define "prior" Kelly fractions
fraction_1 = (50000/(50000+50000))*(1+r)*1/(0.4+r) - (1-(50000/(50000+50000)))*(1+r)*1/(0.5-r)
fraction_2 = (50480/(50480+49520))*(1+r)*1/(0.4+r) - (1-(50480/(50480+49520)))*(1+r)*1/(0.5-r)
fraction_3 = (49520/(50480+49520))*(1+r)*1/(0.4+r) - (1-(49520/(50480+49520)))*(1+r)*1/(0.5-r)
#####################################################
data_bayesian_kelly50k50k = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_bayesian_kelly50k50k = 100
# starting optimal fraction
f_bayesian_kelly50k50k = 0.20
# probability of winning (Beta distribution with parameters 4,4)
a = 50000
b = 50000
sum_a_b = a + b
p = a / sum_a_b
for i in range(0,10000):
if coinflips[y,i] == 1:
X_bayesian_kelly50k50k = X_bayesian_kelly50k50k*(1+f_bayesian_kelly50k50k*0.5+(1-f_bayesian_kelly50k50k)*r)
a = a + 1
sum_a_b = sum_a_b + 1
f_bayesian_kelly50k50k = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
else:
X_bayesian_kelly50k50k = X_bayesian_kelly50k50k*(1-f_bayesian_kelly50k50k*0.4+(1-f_bayesian_kelly50k50k)*r)
sum_a_b = sum_a_b + 1
f_bayesian_kelly50k50k = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
data_bayesian_kelly50k50k[y,i] = X_bayesian_kelly50k50k
starting_value_bayesian_kelly50k50k = 100*np.ones((21,1))
data_bayesian_kelly50k50k = np.append(starting_value_bayesian_kelly50k50k, data_bayesian_kelly50k50k, axis = 1)
terminal_values_bayesian_kelly50k50k = np.log(data_bayesian_kelly50k50k[:,10000])
#####################################################
data_1xkelly = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_1xkelly = 100
# starting optimal fraction
f_1xkelly = 0.2
for i in range(0,10000):
if coinflips[y,i] == 1:
X_1xkelly = X_1xkelly*(1+f_1xkelly*0.5+(1-f_1xkelly)*r)
else:
X_1xkelly = X_1xkelly*(1-f_1xkelly*0.4 +(1-f_1xkelly)*r)
data_1xkelly[y,i] = X_1xkelly
starting_value_1xkelly = 100*np.ones((21,1))
data_1xkelly = np.append(starting_value_1xkelly, data_1xkelly, axis = 1)
terminal_values_1xkelly = np.log(data_1xkelly[:,10000])
#####################################################
# interpolating the values between the chosen points
int_1 = interp1d(successes, terminal_values_bayesian_kelly50k50k)
int_2 = interp1d(successes, terminal_values_1xkelly)
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes,int_1(successes), '-', color = 'red', label = 'Bayesian Kelly 50k,50k')
plt.plot(successes,int_2(successes), '-', color = 'blue', label = 'Pure Kelly, p = .5')
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - bayesian kelly 50k-50k vs kelly.pdf')
plt.show()
#####################################################
data_bayesian_kelly_over = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_bayesian_kelly_over = 100
# starting optimal fraction
f_bayesian_kelly_over = 0.22
# probability of winning (Beta distribution with parameters 3,1)
a = 50480
b = 49520
sum_a_b = a + b
p = a / sum_a_b
for i in range(0,10000):
if coinflips[y,i] == 1:
X_bayesian_kelly_over = X_bayesian_kelly_over*(1+f_bayesian_kelly_over*0.5+(1-f_bayesian_kelly_over)*r)
a = a + 1
sum_a_b = sum_a_b + 1
f_bayesian_kelly_over = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
else:
X_bayesian_kelly_over = X_bayesian_kelly_over*(1-f_bayesian_kelly_over*0.4+(1-f_bayesian_kelly_over)*r)
sum_a_b = sum_a_b + 1
f_bayesian_kelly_over = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
data_bayesian_kelly_over[y,i] = X_bayesian_kelly_over
starting_value_bayesian_kelly_over = 100*np.ones((21,1))
data_bayesian_kelly_over = np.append(starting_value_bayesian_kelly_over, data_bayesian_kelly_over, axis = 1)
terminal_values_bayesian_kelly_over = np.log(data_bayesian_kelly_over[:,10000])
#####################################################
data_1xkelly_wo = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_1xkelly_wo = 100
# starting optimal fraction
f_1xkelly_wo = 0.22
for i in range(0,10000):
if coinflips[y,i] == 1:
X_1xkelly_wo = X_1xkelly_wo*(1+f_1xkelly_wo*0.5+(1-f_1xkelly_wo)*r)
else:
X_1xkelly_wo = X_1xkelly_wo*(1-f_1xkelly_wo*0.4 +(1-f_1xkelly_wo)*r)
data_1xkelly_wo[y,i] = X_1xkelly_wo
starting_value_1xkelly_wo = 100*np.ones((21,1))
data_1xkelly_wo = np.append(starting_value_1xkelly_wo, data_1xkelly_wo, axis = 1)
terminal_values_1xkelly_wo = np.log(data_1xkelly_wo[:,10000])
#####################################################
# interpolating the values between the chosen points
int_3 = interp1d(successes, terminal_values_bayesian_kelly_over)
int_4 = interp1d(successes, terminal_values_1xkelly_wo)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes,int_3(successes), '-', color = 'black', label = 'Bayesian Kelly 50480,49520')
plt.plot(successes,int_4(successes), '-', color = 'cyan', label = 'Pure Kelly, p = 50480/100k')
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - bayesian kelly 50k-50k vs kelly (1).pdf')
plt.show()
#####################################################
data_bayesian_kelly_under = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_bayesian_kelly_under = 100
# starting optimal fraction
f_bayesian_kelly_under = 0.18
# probability of winning (Beta distribution with parameters 3,1)
a = 49520
b = 50480
sum_a_b = a + b
p = a / sum_a_b
for i in range(0,10000):
if coinflips[y,i] == 1:
X_bayesian_kelly_under = X_bayesian_kelly_under*(1+f_bayesian_kelly_under*0.5+(1-f_bayesian_kelly_under)*r)
a = a + 1
sum_a_b = sum_a_b + 1
f_bayesian_kelly_under = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
else:
X_bayesian_kelly_under = X_bayesian_kelly_under*(1-f_bayesian_kelly_under*0.4+(1-f_bayesian_kelly_under)*r)
sum_a_b = sum_a_b + 1
f_bayesian_kelly_under = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
data_bayesian_kelly_under[y,i] = X_bayesian_kelly_under
starting_value_bayesian_kelly_under = 100*np.ones((21,1))
data_bayesian_kelly_under = np.append(starting_value_bayesian_kelly_under, data_bayesian_kelly_under, axis = 1)
terminal_values_bayesian_kelly_under = np.log(data_bayesian_kelly_under[:,10000])
#####################################################
data_1xkelly_wo1 = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_1xkelly_wo1 = 100
# starting optimal fraction
f_1xkelly_wo1 = 0.18
for i in range(0,10000):
if coinflips[y,i] == 1:
X_1xkelly_wo1 = X_1xkelly_wo1*(1+f_1xkelly_wo1*0.5+(1-f_1xkelly_wo1)*r)
else:
X_1xkelly_wo1 = X_1xkelly_wo1*(1-f_1xkelly_wo1*0.4 +(1-f_1xkelly_wo1)*r)
data_1xkelly_wo1[y,i] = X_1xkelly_wo1
starting_value_1xkelly_wo1 = 100*np.ones((21,1))
data_1xkelly_wo1 = np.append(starting_value_1xkelly_wo1, data_1xkelly_wo1, axis = 1)
terminal_values_1xkelly_wo1 = np.log(data_1xkelly_wo1[:,10000])
#####################################################
# interpolating the values between the chosen points
int_5 = interp1d(successes, terminal_values_bayesian_kelly_under)
int_6 = interp1d(successes, terminal_values_1xkelly_wo1)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes,int_5(successes), '-', color = 'black', label = 'Bayesian Kelly 49520,50480')
plt.plot(successes,int_6(successes), '-', color = 'cyan', label = 'Pure Kelly, p = 49520/100k')
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - bayesian kelly 50k-50k vs kelly (2).pdf')
plt.show()
#####################################################<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 14:34:29 2020
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# x stands for the share f
x = np.linspace(0,1)
# y stands for the long-run exponential growth rate
y = 0.5 * np.log(1-x*0.4+(1-x)*0.01) + 0.5 * np.log(1 + x*0.5 + (1-x)*0.01)
# adjusting the settings in order to properly display the function
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# displaying a vertical intercept at the maximum of the function
ax.scatter(0.2, 0.5 * np.log(1-0.2*0.4+(1-0.2)*0.01) + 0.5 * np.log(1 + 0.2*0.5 + (1-0.2)*0.01), s=80, color = 'blue', label = 'Optimum')
ax.plot([0.2, 0.2],[0, 0.5 * np.log(1-0.2*0.4+(1-0.2)*0.01) + 0.5 * np.log(1 + 0.2*0.5 + (1-0.2)*0.01)], color='blue', linestyle='dashed')
# plotting the function
plt.plot(x,y, 'r', label = 'G (long-run growth rate)')
plt.xlabel("f")
plt.ylabel("G")
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - markowitz vs kelly 2 (1).pdf')
#################################################
# returns of risk-free and risky option
return_riskfree = 0.01
expectedreturn_risky = 0.05
returns_matrix = np.array([expectedreturn_risky,return_riskfree])
# matrix with the decision-maker's fraction of wealth invested in each asset
fractions_matrix = np.array([[0,1],[0.1,0.9],[0.3,0.7],
[0.4,0.6],[0.5,0.5],[0.6,0.4],[0.7,0.3]
,[0.8,0.2],[0.9,0.1],[1,0]])
# optimum of function G
optimal_fraction = np.array([[0.2,0.8]])
# positive root of function G
first_root_fraction = np.array([[0.575,1-0.575]])
# negative root of function G
second_root_fraction = np.array([[-0.175,1+0.175]])
# EV portfolio
ev_portfolio = fractions_matrix.dot(returns_matrix)
# EV for optimum, first root and second root
ev_optimum = optimal_fraction.dot(returns_matrix)
ev_firstroot = first_root_fraction.dot(returns_matrix)
#ev_secondroot = second_root_fraction.dot(returns_matrix)
# STD of risk-free and risky options
std_riskfree = 0
std_risky = (0.5*(0.5**2) + 0.5*(0.4**2) - 0.05**2)**(1/2)
var_risky = (0.5*(0.5**2) + 0.5*(0.4**2) - 0.05**2)
# STD for optimum, first root and second root
std_optimum = (0.2**(2)*var_risky)**(1/2)
std_firstroot = (0.575**(2)*var_risky)**(1/2)
#std_secondroot = ((-0.175)**(2)*var_risky)**(1/2)
std_portfolio = np.array(np.zeros(10))
# STD for each value of the fraction invested in the risky asset
for i in range(0,10):
std_portfolio[i,]=((fractions_matrix[i,0]**2)*(var_risky))**(1/2)
# parameter-settings + plot
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.gca().yaxis.grid(True)
plt.xlabel("STD")
plt.ylabel("EV")
plt.gcf().subplots_adjust(bottom=0.25)
# plotting the function
x = np.linspace(0,0.6)
ax.plot(x,0.01 + (0.05-0.01)/0.45*x,color='black',label='Capital allocation line (CAL)')
plt.scatter(std_portfolio,ev_portfolio, s = 80, color = 'blue', label = '0<f<1')
plt.scatter(0, 0.01, marker='o', s=80, color="red", label = 'f=0 and f=1')
plt.scatter(0.45, 0.05, marker='o', s=80, color="red")
plt.scatter([std_optimum], [ev_optimum], marker='o', s=80, color="gold", label = 'optimum')
plt.scatter([std_firstroot], [ev_firstroot], marker='o', s=80, color="black", label = '0 growth')
#plt.scatter([std_secondroot], [ev_secondroot], marker='o', s=80, color="black")
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - markowitz vs kelly 2 (2).pdf')
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 15:44:59 2020
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# returns of risk-free and risky option
return_riskfree = 0.01
expectedreturn_risky = 0.05
returns_matrix = np.array([expectedreturn_risky,return_riskfree])
# matrix with the decision-maker's fraction of wealth invested in each asset
fractions_matrix = np.array([[0,1],[0.1,0.9],[0.2,0.8],[0.3,0.7],
[0.4,0.6],[0.5,0.5],[0.6,0.4],[0.7,0.3]
,[0.8,0.2],[0.9,0.1],[1,0]])
# EV of the portfolio
ev_portfolio = fractions_matrix.dot(returns_matrix)
# STD of risk-free and risky options
std_riskfree = 0
std_risky = (0.5*(0.5**2) + 0.5*(0.4**2) - 0.05**2)**(1/2)
var_risky = (0.5*(0.5**2) + 0.5*(0.4**2) - 0.05**2)
std_portfolio = np.array(np.zeros(11))
# STD for each value of the fraction invested in the risky asset
for i in range(0,11):
std_portfolio[i,]=((fractions_matrix[i,0]**2)*(var_risky))**(1/2)
# parameter-settings + plot
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.gca().yaxis.grid(True)
plt.xlabel("STD")
plt.ylabel("EV")
plt.gcf().subplots_adjust(bottom=0.25)
# plotting the function
x = np.linspace(0,0.6)
ax.plot(x,0.01 + (0.05-0.01)/0.45*x,color='black',label='Capital allocation line (CAL)')
plt.scatter(std_portfolio,ev_portfolio, s = 80, color = 'blue', label = '0<f<1')
plt.scatter(0, 0.01, marker='o', s=80, color="red", label = 'f=0 and f=1')
plt.scatter(0.45, 0.05, marker='o', s=80, color="red")
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - markowitz vs kelly 1.pdf')
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 11:31:06 2020
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# storage vector for the outcomes of choosing b
trajectory = np.zeros((1,10001))
# setting random seed
np.random.seed(6)
# starting wealth 100$ to feed the loop
w = 100
# loop that creates the trajectory
for element in range(1,10001):
if np.random.randint(0, 2, 1) == 1:
w = w*1.5
trajectory[:, element] = w
else:
w = w*0.6
trajectory[:, element] = w
# 100$ at time t
trajectory[0,0] = 100
# calculate logarithmic utility/log-wealth
trajectory = np.log(trajectory)
# defining expected utility term
EU_term = np.log(0.95)
# defining trajectory EU
trajectory_EU = list(np.log(100) +(EU_term)*(t) for t in range(0, 10001))
# plotting the trajectory
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.xlabel('time', fontdict=None, labelpad=None)
plt.ylabel('utility/logarithm of wealth', fontdict=None, labelpad=None)
plt.grid()
plt.plot(trajectory[0,:])
plt.plot(trajectory_EU, color='red')
# saving the image
plt.savefig('thesis - logarithmic utility 1a.pdf')
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 13:52:30 2019
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# storage matrix for 20 trajectories
trajectories = np.zeros((20,10001))
# setting random seed
np.random.seed(6)
# loop that creates the 20 different trajectories
for i in range(0,20):
w = 100
for element in range(1,10001):
if np.log2(w + 1) > (0.5*np.log2(w+50) + 0.5*np.log2(w-40)):
w = w + 1
trajectories[i, element] = w
else:
if np.random.randint(0, 2, 1) == 1:
w = w + 50
trajectories[i, element] = w
else:
w = w - 40
trajectories[i, element] = w
# 100$ at time t
trajectories[:,0] = 100
# calculate logarithmic utility/log-wealth
trajectories = np.log(trajectories)
# plotting the trajectories + EU trajectory
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.xlabel('time', fontdict=None, labelpad=None)
plt.ylabel('utility/logarithm of wealth', fontdict=None, labelpad=None)
plt.grid()
for i in range(0,20):
plt.plot(trajectories[i,:])
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 13:52:30 2019
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# storage matrix
trajectory = np.zeros((1,10001))
# setting random seed
np.random.seed(6)
# setting initial value for the loop
w = 100
# loop that creates the trajectory
for element in range(1,10001):
if np.log2(w + 1) > (0.5*np.log2(w+50) + 0.5*np.log2(w-40)):
w = w + 1
trajectory[:, element] = w
else:
if np.random.randint(0, 2, 1) == 1:
w = w + 50
trajectory[:, element] = w
else:
w = w - 40
trajectory[:, element] = w
# 100$ at time t
trajectory[0,0] = 100
# calculate logarithmic utility/log-wealth
trajectory = np.log(trajectory)
# plotting the trajectory
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.xlabel('time', fontdict=None, labelpad=None)
plt.ylabel('utility/logarithm of wealth', fontdict=None, labelpad=None)
plt.grid()
plt.plot(trajectory[0,:])
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 11:31:06 2020
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# storage vector for the outcomes of choosing b (20 trajectories)
trajectories = np.zeros((20,10001))
# setting random seed
np.random.seed(6)
# stating wealth 100$ to feed the loop
w = 100
# loop that creates the 20 trajectories
for i in range(0,20):
w = 100
for element in range(1,10001):
if np.random.randint(0, 2, 1) == 1:
w = w*1.5
trajectories[i, element] = w
else:
w = w*0.6
trajectories[i, element] = w
# 100$ at time t
trajectories[:,0] = 100
# calculating logarithmic utility/log-wealth
trajectories = np.log(trajectories)
# define expected utility term
EU_term = np.log(0.95)
# define trajectory EU
trajectory_EU = list(np.log(100) +(EU_term)*(t) for t in range(0, 10001))
# plotting the trajectories
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.xlabel('time', fontdict=None, labelpad=None)
plt.ylabel('utility/logarithm of wealth', fontdict=None, labelpad=None)
plt.grid()
for i in range(1, 20):
plt.plot(trajectories[i,:])
plt.plot(trajectory_EU, color='red')
# saving the image
plt.savefig('thesis - logarithmic utility 1b.pdf')
#################################################
<file_sep># MAthesis
Python simulations - Multiplicative and additive dynamics, optimal leverage and (Bayesian) Kelly criterion
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 18:51:48 2019
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
from collections import Counter
import matplotlib.pylab as pylab
#################################################
# creating array with 5 different percentages of wealth to bet (the third is the optimal share)
bet_size = np.asarray([0.05, 0.1, 0.20, 0.50, 0.65])
s = bet_size.size
# setting random seed
np.random.seed(5)
# coin flips: if 1, +50\% of wager; if 0, -40\% of wager
coinflips = np.random.randint(0, 2, 10001)
# counting the coinflips
counter = Counter(coinflips)
# creating storage matrix for six trajectories over 10000 time steps
data = np.zeros((5,10001))
# creating the trajectories
for j in range(0,5):
print(bet_size[j,])
X_0 = 100
# starting capital
r = 0.01
# risk-free return
for i in range(1,10001):
if coinflips[i,] == 1: X_0 = X_0*(1+(bet_size[j,]*0.5)+(1-bet_size[j,])*r)
else: X_0 = X_0*(1-(bet_size[j,]*0.4) +(1-bet_size[j,])*r)
#print(w)
data[j,i] = X_0
# 100 $ as a starting value for all the trajectories
data[:,0] = 100
# plotting the trajectories
# the optimal share trajectory is the magenta, dashed line
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.gca().yaxis.grid(True)
plt.xlabel("t")
plt.ylabel("wealth")
plt.yscale("log")
plt.plot((data[0,]), color='green', label="f = 0.05")
plt.plot((data[1,]), color='red', label="f = 0.1")
plt.plot((data[2,]), color='magenta', linestyle='dashed', label="f = 0.2")
plt.plot((data[3,]), color='blue', label="f = 0.5")
plt.plot((data[4,]), color='yellow', label="f = 0.65")
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - kelly criterion 2.pdf')
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 18:51:48 2019
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
from collections import Counter
import matplotlib.pylab as pylab
#################################################
# creating array with 6 different percentages of wealth to bet (the third is the optimal share)
bet_size = np.asarray([0.1, 0.15, 0.25, 0.5, 0.6])
s = bet_size.size
# setting random seed
np.random.seed(2)
# coin flips: if 1, +50\% of wager; if 0, -40\% of wager
coinflips = np.random.randint(0, 2, 10001)
# counting the coinflips
counter = Counter(coinflips)
# creating storage matrix for six trajectories over 10000 time steps
data = np.zeros((5,10001))
# creating the trajectories
for j in range(0,5):
print(bet_size[j,])
X_0 = 100
# starting capital
for i in range(1,10001):
if coinflips[i,] == 1: X_0 = X_0*(1+(bet_size[j,]*0.5))
else: X_0 = X_0*(1-(bet_size[j,]*0.4))
#print(w)
data[j,i] = X_0
# 100 $ as a starting value for all the trajectories
data[:,0] = 100
# plotting the trajectories
# the optimal share trajectory is the magenta, dashed line
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.gca().yaxis.grid(True)
plt.xlabel("t")
plt.ylabel("wealth")
plt.yscale("log")
plt.plot((data[0,]), color='green', label="f = 0.1")
plt.plot((data[1,]), color='red', label="f = 0.15")
plt.plot((data[2,]), color='magenta', linestyle='dashed', label="f = 0.25")
plt.plot((data[3,]), color='blue', label="f = 0.5")
plt.plot((data[4,]), color='yellow', label="f = 0.6")
plt.legend(loc="upper left")
# saving the first image
plt.savefig('thesis - kelly criterion.pdf')
#################################################
# x stands for the share f
x = np.linspace(-0.2,1)
# y stands for the long-run exponential growth rate
y = 0.5 * np.log(1-x*0.4) + 0.5 * np.log(1 + x*0.5)
# adjusting the settings in order to properly display the function
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# displaying a vertical intercept at the optimal value of x (i.e. of f)
ax.scatter(0.25, 0.5 * np.log(1-0.25*0.4) + 0.5 * np.log(1 + 0.25*0.5), s=80, color = 'blue', label = 'Optimum')
ax.plot([0.25, 0.25],[0, 0.5 * np.log(1-0.25*0.4) + 0.5 * np.log(1 + 0.25*0.5)], color='blue', linestyle='dashed')
# plotting the function
plt.plot(x,y, 'r',label = 'G (long-run growth rate)')
plt.xlabel("f")
plt.ylabel("G")
plt.legend(loc="upper left")
# saving the second image
plt.savefig('thesis - optimal leverage.pdf')
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 14:34:29 2020
@author: Lorenzo
"""
#################################################
import numpy as np
# import pandas as pd
from matplotlib import pyplot as plt
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# define desplayed domain
f = np.linspace(0,0.6)
# the function
p = 100 * (1 + (f*0.5)) * (1-(f*0.4)) - 100
e = 100 * (f*0.5) - 100 *(f*0.4)
l = e - p
# parameter-settings + plot
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.gca().yaxis.grid(True)
plt.xlabel("f")
plt.ylabel("W-L / Profit / (W-L) - Profit")
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.plot(f,p,'b', label = "Profit")
plt.plot(f,e,'r', label = "W-L")
plt.plot(f,l,'g', label = "(W-L) - Profit")
plt.axvline(x=0.25, linestyle='dashed')
plt.legend(loc="upper left")
# saving the figure
plt.savefig('thesis - kelly criterion 1.pdf')
#################################################
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 18:51:48 2019
@author: Lorenzo
"""
#################################################
import numpy as np
import random
from matplotlib import pyplot as plt
#from pylab import rcParams
from collections import Counter
from scipy.interpolate import interp1d
np.seterr(divide = 'ignore')
# import pandas as pd
# from pylab import rcParams
# from collections import Counter
import matplotlib.pylab as pylab
#################################################
# setting parameters
# number of trials
n = 10000
# probability of success
p = 0.5
# probability of failure
q = 0.5
# expected value
m = 5000
# standard deviation
sd = round(np.sqrt(n*p*q))
# fixed number of successes (expected value +/- a certain number of standard deviations)
successes = np.asarray([m-5*sd, round(m-4.5*sd), m-4*sd, round(m-3.5*sd), m-3*sd, round(m-2.5*sd), m-2*sd, round(m-1.5*sd), m-1*sd, round(m-0.5*sd), m, round(m+0.5*sd), m+1*sd, round(m+1.5*sd), m+2*sd, round(m+2.5*sd), m+3*sd, round(m+3.5*sd), m+4*sd, round(m+4.5*sd), m+5*sd])
coinflips = np.zeros((21,10000))
# create matrix with different streaks of successes and failures
for j in range(0,21):
ones = np.ones((1,int(successes[j,])))
zeros = np.zeros((1,int(n - successes[j,])))
x = np.concatenate((ones, zeros), axis = 1)
coinflips[j,:] = x
random.shuffle(coinflips[j,:])
# test: check that number of 1s and 0s is plausible (replace '0' with other columns' numbers to check them)
counter = Counter(coinflips[0,:])
# define interest rate
r = 0.01
# define "prior" Kelly fractions
fraction_1 = (5/(5+5))*(1+r)*1/(0.4+r) - (1-(5/(5+5)))*(1+r)*1/(0.5-r)
fraction_2 = (6/(6+4))*(1+r)*1/(0.4+r) - (1-(6/(6+4)))*(1+r)*1/(0.5-r)
fraction_3 = (4/(6+4))*(1+r)*1/(0.4+r) - (1-(4/(6+4)))*(1+r)*1/(0.5-r)
# fractions for fractional Kelly
fraction_4 = fraction_2*0.5
fraction_5 = fraction_3*0.5
#####################################################
data_bayesian_kelly55 = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_bayesian_kelly55 = 100
# starting optimal fraction
f_bayesian_kelly55 = 0.20
# probability of winning (Beta distribution with parameters 4,4)
a = 5
b = 5
sum_a_b = a + b
p = a / sum_a_b
for i in range(0,10000):
if coinflips[y,i] == 1:
X_bayesian_kelly55 = X_bayesian_kelly55*(1+f_bayesian_kelly55*0.5+(1-f_bayesian_kelly55)*r)
a = a + 1
sum_a_b = sum_a_b + 1
f_bayesian_kelly55 = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
else:
X_bayesian_kelly55 = X_bayesian_kelly55*(1-f_bayesian_kelly55*0.4+(1-f_bayesian_kelly55)*r)
sum_a_b = sum_a_b + 1
f_bayesian_kelly55 = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
data_bayesian_kelly55[y,i] = X_bayesian_kelly55
starting_value_bayesian_kelly55 = 100*np.ones((21,1))
data_bayesian_kelly55 = np.append(starting_value_bayesian_kelly55, data_bayesian_kelly55, axis = 1)
terminal_values_bayesian_kelly55 = np.log(data_bayesian_kelly55[:,10000])
#####################################################
data_1xkelly = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_1xkelly = 100
# starting optimal fraction
f_1xkelly = 0.2
for i in range(0,10000):
if coinflips[y,i] == 1:
X_1xkelly = X_1xkelly*(1+f_1xkelly*0.5+(1-f_1xkelly)*r)
else:
X_1xkelly = X_1xkelly*(1-f_1xkelly*0.4 +(1-f_1xkelly)*r)
data_1xkelly[y,i] = X_1xkelly
starting_value_1xkelly = 100*np.ones((21,1))
data_1xkelly = np.append(starting_value_1xkelly, data_1xkelly, axis = 1)
terminal_values_1xkelly = np.log(data_1xkelly[:,10000])
#####################################################
# interpolating the values between the chosen points
int_1 = interp1d(successes, terminal_values_bayesian_kelly55)
int_2 = interp1d(successes, terminal_values_1xkelly)
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes,int_1(successes), '-', color = 'red', label = 'Bayesian Kelly 5,5')
plt.plot(successes,int_2(successes), '-', color = 'blue', label = 'Pure Kelly, p = .5')
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - bayesian kelly 5-5 vs kelly.pdf')
plt.show()
#####################################################
data_bayesian_kelly64 = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_bayesian_kelly64 = 100
# starting optimal fraction
f_bayesian_kelly64 = 0.65
# probability of winning (Beta distribution with parameters 3,1)
a = 6
b = 4
sum_a_b = a + b
p = a / sum_a_b
for i in range(0,10000):
if coinflips[y,i] == 1:
X_bayesian_kelly64 = X_bayesian_kelly64*(1+f_bayesian_kelly64*0.5+(1-f_bayesian_kelly64)*r)
a = a + 1
sum_a_b = sum_a_b + 1
f_bayesian_kelly64 = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
else:
X_bayesian_kelly64 = X_bayesian_kelly64*(1-f_bayesian_kelly64*0.4+(1-f_bayesian_kelly64)*r)
sum_a_b = sum_a_b + 1
f_bayesian_kelly64 = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
data_bayesian_kelly64[y,i] = X_bayesian_kelly64
starting_value_bayesian_kelly64 = 100*np.ones((21,1))
data_bayesian_kelly64 = np.append(starting_value_bayesian_kelly64, data_bayesian_kelly64, axis = 1)
terminal_values_bayesian_kelly64 = np.log(data_bayesian_kelly64[:,10000])
#####################################################
# interpolating the values between the chosen points
data_1xkelly_wo = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_1xkelly_wo = 100
# starting optimal fraction
f_1xkelly_wo = 0.65
for i in range(0,10000):
if coinflips[y,i] == 1:
X_1xkelly_wo = X_1xkelly_wo*(1+f_1xkelly_wo*0.5+(1-f_1xkelly_wo)*r)
else:
X_1xkelly_wo = X_1xkelly_wo*(1-f_1xkelly_wo*0.4 +(1-f_1xkelly_wo)*r)
data_1xkelly_wo[y,i] = X_1xkelly_wo
starting_value_1xkelly_wo = 100*np.ones((21,1))
data_1xkelly_wo = np.append(starting_value_1xkelly_wo, data_1xkelly_wo, axis = 1)
terminal_values_1xkelly_wo = np.log(data_1xkelly_wo[:,10000])
#####################################################
# interpolating the values between the chosen points
int_3 = interp1d(successes, terminal_values_bayesian_kelly64)
int_4 = interp1d(successes, terminal_values_1xkelly_wo)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes,int_1(successes), '-', color = 'red', label = 'Bayesian Kelly 5,5')
plt.plot(successes,int_3(successes), '-', color = 'black', label = 'Bayesian Kelly 6,4')
plt.plot(successes,int_2(successes), '-', color = 'blue', label = 'Pure Kelly, p = .5')
plt.plot(successes,int_4(successes), '-', color = 'cyan', label = 'Pure Kelly, p = .6')
plt.legend(loc="lower right")
# saving the image
plt.savefig('thesis - bayesian kelly 5-5 vs kelly (1).pdf')
plt.show()
#####################################################
data_bayesian_kelly46 = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_bayesian_kelly46 = 100
# starting optimal fraction
f_bayesian_kelly46 = -0.25
# probability of winning (Beta distribution with parameters 3,1)
a = 4
b = 6
sum_a_b = a + b
p = a / sum_a_b
for i in range(0,10000):
if coinflips[y,i] == 1:
X_bayesian_kelly46 = X_bayesian_kelly46*(1+f_bayesian_kelly46*0.5+(1-f_bayesian_kelly46)*r)
a = a + 1
sum_a_b = sum_a_b + 1
f_bayesian_kelly46 = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
else:
X_bayesian_kelly46 = X_bayesian_kelly46*(1-f_bayesian_kelly46*0.4+(1-f_bayesian_kelly46)*r)
sum_a_b = sum_a_b + 1
f_bayesian_kelly46 = (a/sum_a_b)*(1+r)*1/(0.4+r) - (1-a/sum_a_b)*(1+r)*1/(0.5-r)
data_bayesian_kelly46[y,i] = X_bayesian_kelly46
starting_value_bayesian_kelly46 = 100*np.ones((21,1))
data_bayesian_kelly46 = np.append(starting_value_bayesian_kelly46, data_bayesian_kelly46, axis = 1)
terminal_values_bayesian_kelly46 = np.log(data_bayesian_kelly46[:,10000])
#####################################################
data_1xkelly_wo1 = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_1xkelly_wo1 = 100
# starting optimal fraction
f_1xkelly_wo1 = -0.25
for i in range(0,10000):
if coinflips[y,i] == 1:
X_1xkelly_wo1 = X_1xkelly_wo1*(1+f_1xkelly_wo1*0.5+(1-f_1xkelly_wo1)*r)
else:
X_1xkelly_wo1 = X_1xkelly_wo1*(1-f_1xkelly_wo1*0.4 +(1-f_1xkelly_wo1)*r)
data_1xkelly_wo1[y,i] = X_1xkelly_wo1
starting_value_1xkelly_wo1 = 100*np.ones((21,1))
data_1xkelly_wo1 = np.append(starting_value_1xkelly_wo1, data_1xkelly_wo1, axis = 1)
terminal_values_1xkelly_wo1 = np.log(data_1xkelly_wo1[:,10000])
#####################################################
# interpolating the values between the chosen points
int_5 = interp1d(successes, terminal_values_bayesian_kelly46)
int_6 = interp1d(successes, terminal_values_1xkelly_wo1)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes,int_1(successes), '-', color = 'red', label = 'Bayesian Kelly 5,5')
plt.plot(successes,int_5(successes), '-', color = 'black', label = 'Bayesian Kelly 4,6')
plt.plot(successes,int_2(successes), '-', color = 'blue', label = 'Pure Kelly, p = .5')
plt.plot(successes,int_6(successes), '-', color = 'cyan', label = 'Pure Kelly, p = .4')
plt.legend(loc="center right")
# saving the image
plt.savefig('thesis - bayesian kelly 5-5 vs kelly (2).pdf')
plt.show()
#####################################################
data_halfkelly_wo = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_halfkelly_wo = 100
# starting optimal fraction
f_halfkelly_wo = 0.65*0.5
for i in range(0,10000):
if coinflips[y,i] == 1:
X_halfkelly_wo = X_halfkelly_wo*(1+f_halfkelly_wo*0.5+(1-f_halfkelly_wo)*r)
else:
X_halfkelly_wo = X_halfkelly_wo*(1-f_halfkelly_wo*0.4 +(1-f_halfkelly_wo)*r)
data_halfkelly_wo[y,i] = X_halfkelly_wo
starting_value_halfkelly_wo = 100*np.ones((21,1))
data_halfkelly_wo = np.append(starting_value_halfkelly_wo, data_halfkelly_wo, axis = 1)
terminal_values_halfkelly_wo = np.log(data_halfkelly_wo[:,10000])
#####################################################
data_halfkelly_wo1 = np.zeros((21,10000))
for y in range(0,21):
# starting capital
X_halfkelly_wo1 = 100
# starting optimal fraction
f_halfkelly_wo1 = -0.25*0.5
for i in range(0,10000):
if coinflips[y,i] == 1:
X_halfkelly_wo1 = X_halfkelly_wo1*(1+f_halfkelly_wo1*0.5+(1-f_halfkelly_wo1)*r)
else:
X_halfkelly_wo1 = X_halfkelly_wo1*(1-f_halfkelly_wo1*0.4 +(1-f_halfkelly_wo1)*r)
data_halfkelly_wo1[y,i] = X_halfkelly_wo1
starting_value_halfkelly_wo1 = 100*np.ones((21,1))
data_halfkelly_wo1 = np.append(starting_value_halfkelly_wo1, data_halfkelly_wo1, axis = 1)
terminal_values_halfkelly_wo1 = np.log(data_halfkelly_wo1[:,10000])
#####################################################
# interpolating the values between the chosen points
int_7 = interp1d(successes, terminal_values_halfkelly_wo)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes, int_3(successes), '-', color = 'black', label = 'Bayesian Kelly 6,4')
plt.plot(successes, int_4(successes), '-', color = 'cyan', label = 'Pure Kelly, p = .6')
plt.plot(successes, int_7(successes), '-', color = 'green', label = 'Half of Pure Kelly (with p = .6)')
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - bayesian kelly 5-5 vs kelly (3).pdf')
plt.show()
#######################################################
# interpolating the values between the chosen points
int_8 = interp1d(successes, terminal_values_halfkelly_wo1)
plt.ylabel('logarithm of terminal wealth', fontdict=None, labelpad=None)
plt.xlabel('number of successes', fontdict=None, labelpad=None)
plt.grid()
plt.plot(successes,int_5(successes), '-', color = 'black', label = 'Bayesian Kelly 4,6')
plt.plot(successes,int_6(successes), '-', color = 'cyan', label = 'Pure Kelly, p = .4')
plt.plot(successes,int_8(successes), '-', color = 'green', label = 'Half of Pure Kelly (with p = .4)')
plt.legend(loc="upper left")
# saving the image
plt.savefig('thesis - bayesian kelly 5-5 vs kelly (4).pdf')
plt.show()
#######################################################
| 487e8b8c269562ee06d9c98bbcc5be7b25da816c | [
"Markdown",
"Python"
] | 13 | Python | lorenzosalvi92/MAthesis | 93ade924defe77fc5b4a46b634fd986b4f5df885 | d74deafa274e986c6794b1bc1895a73ef92e10a3 |
refs/heads/main | <file_sep>using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace MovieDBFirstLab
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Movie Mania");
Console.WriteLine();
Console.WriteLine("Movie Menu");
Console.WriteLine("1. Search by Movie Genre");
Console.WriteLine("2. Search by Movie Title");
string pick = Console.ReadLine();
if(pick == "1")
{
GenreList();
}
else if (pick == "2")
{
TitleList();
}
//MovieList();
}
static void GenreList()
{
Console.WriteLine("Enter a genre: ");
string input = Console.ReadLine();
using (var context = new MovieDBContext())
{
foreach (Movie movie in context.Movies)
{
if (input == movie.Genre)
{
Console.WriteLine(movie.Title);
}
}
}
//var genreList = context.Movies.Where(m => m.Genre == input);
}
static void TitleList()
{
Console.WriteLine("Enter a title: ");
string inputT = Console.ReadLine();
using (var context = new MovieDBContext())
foreach (Movie m in context.Movies)
{
if (m.Title.ToLower().Contains(inputT))
{
Console.WriteLine(m.Genre);
}
}
}
//using (var context = new MovieDBContext())
//{
// Console.WriteLine("What title are you are you interested in?");
// string input2 = Console.ReadLine();
// var all = context.Movies.ToList();
// foreach (Movie m in all)
// {
// if (m.Title == input2)
// {
// Console.WriteLine($"Movies {m.Genre}");
// }
// }
//}
static void MovieList()
{
using (var context = new MovieDBContext())
{
Movie movie1 = new Movie()
{
Title = "Bridesmaids",
Genre = "Comedy",
Runtime = 132
};
Movie movie2 = new Movie()
{
Title = "Pitch Perfect",
Genre = "Comedy",
Runtime = 112
};
Movie movie3 = new Movie()
{
Title = "Superbad",
Genre = "Comedy",
Runtime = 119
};
Movie movie4 = new Movie()
{
Title = "Unstoppable",
Genre = "Action",
Runtime = 99
};
Movie movie5 = new Movie()
{
Title = "Shooter",
Genre = "Action",
Runtime = 126
};
Movie movie6 = new Movie()
{
Title = "Eagle Eye",
Genre = "Action",
Runtime = 118
};
Movie movie7 = new Movie()
{
Title = "Up",
Genre = "Animation",
Runtime = 96
};
Movie movie8 = new Movie()
{
Title = "Inside Out",
Genre = "Animation",
Runtime = 102
};
Movie movie9 = new Movie()
{
Title = "Toy Story",
Genre = "Animation",
Runtime = 71
};
Movie movie10 = new Movie()
{
Title = "Wall-E",
Genre = "Comedy",
Runtime = 103
};
context.Movies.Add(movie1);
context.Movies.Add(movie2);
context.Movies.Add(movie3);
context.Movies.Add(movie4);
context.Movies.Add(movie5);
context.Movies.Add(movie6);
context.Movies.Add(movie7);
context.Movies.Add(movie8);
context.Movies.Add(movie9);
context.Movies.Add(movie10);
context.SaveChanges();
}
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
#nullable disable
namespace MovieDBFirstLab
{
public partial class Movie : DbContext
{
public int Id { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
public double? Runtime { get; set; }
}
}
| 95a7e9da5d767cf980ec9e54e49c87477b721553 | [
"C#"
] | 2 | C# | xCodeBender/MovieDBLab | f7b4b2280705a4f27cb5c9f1101abb426c8d9e49 | f8d57b66e1284202dc2cf753fdfbf6465e0e85e7 |
refs/heads/master | <file_sep>/*******************************************************************************
* Copyright IBM Corp. 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
* Do not modify this file, it will be auto-generated.
*/
import {
Category,
RenderingContextBinding,
AbstractRenderingComponent
} from '@ibm-wch-sdk/ng';
import {
Observable
} from 'rxjs/Observable';
/**
* @name Chart
* @id 2d1fd75c-6e5f-4d89-8cce-b50df45e080e
*/
export abstract class AbstractChartComponent extends AbstractRenderingComponent {
/**
* {
* "elementType": "category",
* "key": "type",
* "label": "type",
* "restrictedParents": [
* "7cac8b4b-db7d-4243-8d7b-6458af55cb5d"
* ]
* }
*/
@RenderingContextBinding('category.type')
readonly onType: Observable<Category>;
/**
* @see #onType
*/
@RenderingContextBinding()
readonly type: Category;
protected constructor() {
super();
}
}
<file_sep>/*******************************************************************************
* Copyright IBM Corp. 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
* Do not modify this file, it will be auto-generated.
*/
import {
RenderingContextBinding,
AbstractRenderingComponent
} from '@ibm-wch-sdk/ng';
import {
Observable
} from 'rxjs/Observable';
/**
* @name Youtube
* @id 4801b520-3b10-4763-ac3c-288dc52b63b3
*/
export abstract class AbstractYoutubeComponent extends AbstractRenderingComponent {
@RenderingContextBinding('text.videoid')
readonly onVideoid: Observable<string>;
/**
* @see #onVideoid
*/
@RenderingContextBinding()
readonly videoid: string;
@RenderingContextBinding('toggle.showyoutubelogo', false)
readonly onShowyoutubelogo: Observable<boolean>;
/**
* @see #onNotshowyoutubelogo
*/
@RenderingContextBinding()
readonly showyoutubelogo: boolean;
protected constructor() {
super();
}
}
<file_sep># sample-active-site-components
This repository contains a set of active sample site components to showcase how to implement custom components within Watson Content Hub Sites feature. The samples include a Youtube video integration, a charting smaple with Chart.js, and an Iframe app.
## Table of Contents
- [Table of Contents](#table-of-contents)
- [Introduction](#introduction)
- [Sample Screenshots](#sample-screenshots)
- [Prerequisites](#prerequisites)
- [Install and deploy the sample](#install-and-deploy-the-sample)
- [Configure your Wchtools](#configure-your-wchtools)
- [Install the package content-artifacts and site-application-files](#clone-and-install-the-sample-content-artifacts-and-site-application-files)
- [Build and Deploy your components](#build-and-deploy-your-components)
- [Edit your content in WCH](#edit-your-content-in-wch)
- [Samples go live](#samples-go-live)
- [Appendix - Alternative Step-by-step Tutorial without installable packages](#appendix-alternative-step-by-step-tutorial-without-installable-packages)
- [Youtube Player](#youtube-player)
- [Charts](#charts)
- [Iframe](#iframe)
- [License](#license)
## Introduction
This sample repository provides three example plugin components for your Oslo sites. It includes a Youtube component, a Chart component, and an Iframe component. With the Youtube component, you can embed your favorite Youtube videos in your Oslo sites. With the Chart component, you can create your own chart based on your customized data leveraging the ng2-charts library. With the Iframe component, you can display any websites in a customized iframe window. To enable these 3 components, you have to install the packages `content-artifacts` and package `site-application-files` by following the steps below.
There are two options to installing the samples - running a set of commands to just copy the files or following a step by step tutorial to learn how to build the samples.
You could see what example plugin components look like here:
### Youtube component

### Chart component

### Iframe component

## Prerequisites
* A WCH tenant in Trial or Standard Tier
* Latest wch-site-application source (see: https://github.com/ibm-wch/wch-site-application)
* Wchtools-cli v2.0.3 or above
* Node.js v6.11.1 or above
## Install and deploy the sample
### Configure your Wchtools
* Get your WCH tenant API URL. Open the Hub information dialog from the "About" flyout menu in the left navigation pane of the Watson Content Hub user interface. Copy the API URL for your WCH tenant.
* Run `wchtools init` in your command line. Enter your username and API URL to configure the wchtools
### Clone and install the sample content-artifacts and site-application-files
* Change the command line directory to site application's root directory (i.e. wch-site-application). If you haven't already done so, perform all of the required installation steps for the site application repo.
* Using the Git URL to the sample-active-components repository, run this command to copy the needed sample site-application-files and update the layout settings for the new component.
```
npm run install-layouts-from-git https://github.com/ibm-wch/sample-active-site-components.git
```
* Install required external modules for site-application-files. e.g: npm install ng2-charts --save
### Build and Deploy your components
* From within the wch-site-application directory run:
* Run `npm run build` to compile the project. Make sure there is no error during the build process.
* Run `npm run deploy` to your WCH tenant. After that, you can see your changes in your WCH live site.
## Edit your content in WCH
* Go to Your WCH homepage -> Content -> My Content and assets. You will see the sample content there.

* Click on one of contents. You would see our preset values in content. If you want to use your customized value in content, please click on "Create draft" to edit the content.
* For details about the meaning of each value in sample content, please refer to the Appendix tutorial.
## Samples go live
* Go to Your WCH homepage -> YOUR USERNAME on the top bar -> Hub information.
* You could view your newest site by clicking "Live site".
## Appendix - Alternative Step-by-step Tutorial without installable packages
* In this section, we will include the complete tutorial to create 3 sample components from scratch. It is not required if you choose to install packages above.
### Youtube Player
1. Find Video ID for selected Youtube video. Go to https://www.youtube.com/. Find your favorite video and get the videoID for that video. For example, if you want to play this video, https://www.youtube.com/watch?v=DC4dRht4Z9c, in your Oslo site, the video ID for this video would be `DC4dRht4Z9c` in the URL parameters.
2. Create a new content type named "Youtube" in WCH. Create elements under type "Text" in "Element palette" labeled as "videoID", and under type "Toggle" in "Element palette" labeled as "showYoutubeLogo".
The type should look like in this way:

3. Create new content with the "Youtube" content type. In the "videoID" field, input your video ID from Step1. "showYoutubeLogo" would define whether the official "Youtube" logo shows up in your customized player.
4. Create a layout in your Oslo project. In the root directory of your Oslo site, run the following commands to configure your WCH tenant info and create a layout with type "Youtube":
```
wchtools init
npm run create-layout -- --type "Youtube"
```
5. Deploy your newly created layout to WCH tenant. After you created your layout locally, you have to deploy it to WCH make it live. In the root directory of your Oslo site, run `npm run build-deploy`
6. Create a new page that contains the new layout. In your "Site manager" of your WCH site, add a "Standard page" named "Video" with content you created in Step 3.
7. Implement your code in newly created component. In `src/app/layouts/youtube/youtubeLayout.html`, replace the original code with following code:
```
<div class="ytcomponent" [id]="(onRenderingContext | async).id">
<h3>Youtube Sample Video - IBM Watson Content Hub Demo Video</h3>
<div class="video-container">
<iframe id="ytplayer" type="text/html" width="720" height="405" [src]="url" frameborder="0" allowfullscreen></iframe>
</div>
</div>
```
In `src/app/layouts/youtube/youtubeLayout.scss`, add this code:
```
.ytcomponent
{
text-align: center;
padding-top: 35px;
overflow: hidden;
}
.video-container
{
padding-bottom: 56.25%;
}
.video-container iframe {
width: 100%;
max-height: 405px;
max-width: 720px;
}
```
In `src/app/layouts/youtube/youtubeLayout.ts`, add this line in the top of file:
```
import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
```
In the "YoutubeLayoutComponent" class, please change your class to the following code:
```
export class YoutubeLayoutComponent extends TypeYoutubeComponent {
url: SafeResourceUrl;
baseURL: string;
constructor(private sanitizer: DomSanitizer) {
super();
this.safeSubscribe(this.onVideoid, (id) => {
this.safeSubscribe(this.onShowyoutubelogo, (showLogo) => {
if (showLogo === false)
{
this.baseURL = 'https://www.youtube.com/embed/' + id + '?modestbranding=1';
}
else
{
this.baseURL = 'https://www.youtube.com/embed/' + id;
}
this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.baseURL);
});
});
}
}
```
8. Test your component. After you finished the first 7 steps, you could test either locally by running `npm start`, or remotely by running `npm run build-deploy`.
### Charts
1. Install ng2-charts (https://github.com/valor-software/ng2-charts) and Chart.js packages. In your root directory of your Oslo site, run this command to install pacakges:
```
npm install ng2-charts --save
```
2. Import ChartsModule in sample.module.ts. In {root directory of Oslo project}/src/app/sample.module.ts, add ChartsModule in this way:
```
import { ChartsModule } from 'ng2-charts/ng2-charts';
export const SAMPLE_MODULE = [
ChartsModule
];
```
3. Create a new Taxonomy that contains chart type. Chart.js supports 6 different chart types. By creating a new Taxonomy named "graph", you can manage your chart type in your WCH tenant. Go to Your WCH Homepage -> Content Model -> Taxonomies -> Create taxonomy. Name the taxonomy as "graph". Add following categories, `line`, `bar`, `radar`, `pie`, `polarArea`, `doughnut`, by clicking "Add parent category". After you have finished, your "graph" taxonomy should look like this:

4. Create a new content type named "Chart" in WCH. Create an element under type "Category" in "Element palette" labeled as "type" in "Properties". In "Custom desplay", choose Select category -> Graph -> Graph.
5. Create a new content with "Chart" content type. In the "type" dropdown menu, select `bar` as our chart type.
6. Create a layout in your Oslo project. In the root directory of your Oslo site, run the following commands to configure your WCH tenant info and create a layout with type "Chart":
```
wchtools init
npm run create-layout -- --type "Chart"
```
6. Deploy your newly created layout to WCH tenant. After you created your layout locally, you have to deploy it to WCH make it live. In the root directory of your Oslo site, run `npm run build-deploy`
7. Create a new page that contains the new layout. In your "Site manager" of your WCH site, add a "Standard page" named "Chart" with content you created in Step 4.
8. Implement your code in the newly created component. In `src/app/layouts/chart/chartLayout.html`, replace the original code with following code:
```
<div class="chart-component">
<div [id]="(onRenderingContext | async).id" class="row">
<h2>Sample Radar Chart - Chart.js</h2>
<div class="chart" style="display: block;">
<canvas baseChart width="400" height="400"
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[colors]="chartColors"
[legend]="chartLegend"
[chartType]="chartType"
(chartClick)="chartClicked($event)"></canvas>
</div>
<div class="table-container" style="overflow-x:auto;">
<table class="table table-responsive table-condensed">
<tr>
<th *ngFor="let label of chartLabels">{{label}}</th>
</tr>
<tr *ngFor="let d of chartData">
<td *ngFor="let label of chartLabels; let j=index">{{d && d.data[j]}}</td>
</tr>
</table>
</div>
</div>
</div>
```
In `src/app/layouts/chart/chartLayout.scss`, add this code:
```
.row
{
padding: 30px;
text-align: center;
max-width: 800px;
margin-right: auto;
margin-left: auto;
}
.chart
{
padding-top: 50px;
}
```
In `src/app/layouts/chart/chartLayout.ts`, add these two lines in the top of file:
```
import { UtilsService } from '../../common/utils/utils.service';
import { OnInit } from '@angular/core';
```
In the "ChartLayoutComponent" class, please change your class to the following code:
```
export class ChartLayoutComponent extends TypeChartComponent implements OnInit {
public chartData:Array<any> = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'},
{data: [18, 48, 77, 9, 100, 27, 40], label: 'Series C'}
];
public chartLabels:Array<any> = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
public chartOptions:any = {
responsive: true
};
public chartLegend:boolean = true;
//If you want to set your Chart type in WCH
public chartType:string;
//If you want to set your Chart type in code
//public chartType:string = 'bar';
constructor(public utilService: UtilsService) {
super();
}
ngOnInit()
{
this.chartType = this.utilService.getFirstCategory(this.renderingContext, 'type');
}
// function called when you click on the chart
public chartClicked(e:any):void {
console.log(e);
}
}
```
`chartData` stores all the data you want to plot in your chart. `chartLabels` would label your data in your Chart. `chartLegend` defines whether you would like to show a legend in your chart. `chartType` defines the type of chart you want to use for your chart. It would be one of 6 types of charts: `line`, `bar`, `radar`, `pie`, `polarArea`, `doughnut`. You can changed your type in the content you created in the Step 5 in WCH. `chartClicked` is a function that would become active if there is mouse click action on your chart. You can customize the click event function here.
Note: If you want to customize the color of your Chart, you can insert this code in your `ChartLayoutComponent` class:
```
/* Comment out chartColors if you only want to use default colors */
public chartColors:Array<any> = [
{ // grey
backgroundColor: 'rgba(148,159,177,0.2)',
borderColor: 'rgba(148,159,177,1)',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
},
{ // dark grey
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)',
pointBackgroundColor: 'rgba(77,83,96,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(77,83,96,1)'
},
{ // grey
backgroundColor: 'rgba(148,159,177,0.2)',
borderColor: 'rgba(148,159,177,1)',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
}
];
/* Comment out chartColors if you only want to use default colors */
```
9. Test your component. After you finished the first 8 steps, you could test either locally by running `npm start`, or remotely by running `npm run build-deploy`.
You would see this chart in your Oslo site:

If you change your chart type to "line" in WCH, it will look like this:

Chart type "radar":

Chart type "pie":

Chart type "polarArea":

Chart type "doughnut":

### Iframe
This is an example of a content type you can create and add to your site. The first thing that needs to be done in order to add a new component is to the create the content type. The Iframe will have the following elements and settings:
Name: **Iframe**
Elements:
**source**: link (required)
**width**: number (required, minimum value of 0)
**height**: number (required, minimum value of 0)
After creating the content type, run the npm script in the Oslo project:
`npm run create-layout -- --type Iframe`
This will generate the template files for the new component.
Then you will find the generated **src/app/components/iframe/abstractIframeComponent.ts** file. There will be three bounded elements:
```
@RenderingContextBinding()
readonly source: Link;
@RenderingContextBinding()
readonly width: number;
@RenderingContextBinding()
readonly height: number;
```
These are the variables to use to access the content type data.
To use these in the **src/app/layouts/iframe/iframeLayout.html** file, just reference them with the angular notation. Here is the layout that will be defined:
```
<div class="iframe-component" [id]="(onRenderingContext | async).id">
<h2>Iframe component example</h2>
<iframe class="wch-iframe" [src]="source.linkURL | formattedText:'resourceUrl'" [width]="width" [height]="height">
Sorry, your browser does not support inline frames.
</iframe>
</div>
```
And the scss can be added to the **src/app/layouts/iframe/iframeLayout.scss** file:
```
.iframe-component
{
text-align: center;
padding: 30px;
}
.wch-iframe {
resize: both;
max-width: 100%;
}
```
And that is all the code that needs to be added to make a new Iframe component. The only thing left to do is build and deploy the code to the live site.
To build, run: `npm run build`
After a successful build, deploy: `npm run deploy`
To add the new component to a page, go to WCH, create a new content item from the new Iframe content type, fill in the elements with your data, and add that content item to a page of the site.
## License
See the included license file [License](license.txt) .
[back to top](#sample-active-site-components)
<file_sep>/*******************************************************************************
* Copyright IBM Corp. 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
import {
LayoutComponent
} from '@ibm-wch-sdk/ng';
import { Component } from '@angular/core';
import { TypeYoutubeComponent } from './../../components/youtube/typeYoutubeComponent';
import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
/**
* @name youtubeLayout
* @id youtube-layout
*/
@LayoutComponent({
selector: 'youtube-layout'
})
@Component({
selector: 'app-youtube-layout-component',
templateUrl: './youtubeLayout.html',
styleUrls: ['./youtubeLayout.scss']
})
export class YoutubeLayoutComponent extends TypeYoutubeComponent {
url: SafeResourceUrl;
baseURL: string;
constructor(private sanitizer: DomSanitizer) {
super();
this.safeSubscribe(this.onVideoid, (id) => {
this.safeSubscribe(this.onShowyoutubelogo, (showLogo) => {
if (showLogo === false)
{
this.baseURL = 'https://www.youtube.com/embed/' + id + '?modestbranding=1';
}
else
{
this.baseURL = 'https://www.youtube.com/embed/' + id;
}
this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.baseURL);
console.log(`!!! ${this.baseURL} ${this.url}`);
});
});
}
}
<file_sep>/*******************************************************************************
* Copyright IBM Corp. 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
* Do not modify this file, it will be auto-generated.
*/
import {
Link,
RenderingContextBinding,
AbstractRenderingComponent
} from '@ibm-wch-sdk/ng';
import {
Observable
} from 'rxjs/Observable';
/**
* @name Iframe
* @id 7b4d6587-3cfe-46d0-9249-b0a689aa98eb
*/
export abstract class AbstractIframeComponent extends AbstractRenderingComponent {
/**
* {
* "elementType": "link",
* "key": "source",
* "label": "source",
* "required": true
* }
*/
@RenderingContextBinding('link.source')
readonly onSource: Observable<Link>;
/**
* @see #onSource
*/
@RenderingContextBinding()
readonly source: Link;
/**
* {
* "elementType": "number",
* "fieldType": "integer",
* "key": "width",
* "label": "width",
* "minimum": 0,
* "required": true
* }
*/
@RenderingContextBinding('number.width')
readonly onWidth: Observable<number>;
/**
* @see #onWidth
*/
@RenderingContextBinding()
readonly width: number;
/**
* {
* "elementType": "number",
* "fieldType": "integer",
* "key": "height",
* "label": "height",
* "minimum": 0,
* "required": true
* }
*/
@RenderingContextBinding('number.height')
readonly onHeight: Observable<number>;
/**
* @see #onHeight
*/
@RenderingContextBinding()
readonly height: number;
protected constructor() {
super();
}
}
<file_sep>/*******************************************************************************
* Copyright IBM Corp. 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
//This file is used as layout components for sample-active-site-components. In default, it there is no modules here
//If you want to install sample customized components, you have to import customized modules here
// e.g. import { ChartsModule } from 'ng2-charts/ng2-charts';
import { ChartsModule } from 'ng2-charts/ng2-charts';
export const SAMPLE_MODULE = [
// e.g. ChartsModule
ChartsModule
];
| 628bae5b7bdc414a5922099a6a9f2e0d370e05c7 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | ibm-wch/sample-active-site-components | d19a1e8b46a48a4f45c6af33c5b27742b6b9b741 | d72a25cec3aa58c5185ff8bf0ac133b4140c0ea1 |
refs/heads/master | <repo_name>luickk/Apollo-Internet-controlled-rover<file_sep>/ROVER_STATION/src/de/ye/boat_client_connections/CONNECT_DIR.java
package de.ye.boat_client_connections;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import de.ye.boat_client.Main;
public class CONNECT_DIR {
static Socket client;
//Socket con;
//con = new Socket();
//con.connect(new InetSocketAddress(Main.SATELITE,8787),100);
public boolean CONNECT_DIR(String ip){
try {
client = new Socket();
client.connect(new InetSocketAddress(ip,8787),100);
} catch (UnknownHostException e) {
return false;
} catch (IOException e) {
return false;
}
System.out.println("Client gestartet!_DIR");
return true;
}
public static Socket GET_CLIENT(){
return client;
}
}
<file_sep>/README.md
Apollo
===================
The Apollo Rover is a remote controlled Rover
which can be controlled over large distances with almost no delay.
----------
How does it work?
-------------
The Raspberry on the Rover(Rover base) connects via. Java TCP Sockets, to an external Server(Rover Satellite).
When Rover is successfully connected, the Rover can be controlled
by using Rover Station software.
<file_sep>/ROVER_BASE/src/de/ye/rover_gps/GET_SEND_GPS.java
package de.ye.rover_gps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GET_SEND_GPS implements Runnable{
@Override
public void run() {
try {
while(true){
Thread.sleep(1000);
//st_gps.sh
ProcessBuilder pb = new ProcessBuilder("/home/pi/st_gps.sh");
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader reader_err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String s = null;
String s_err = null;
while((s = reader.readLine()) != null){
System.out.println(s);
THREAD_GPS.writer.println(s);
THREAD_GPS.writer.flush();
if(s==""){
THREAD_GPS.writer.println("Traceback");
THREAD_GPS.writer.flush();
}
}
while((s_err = reader_err.readLine()) != null){
//System.out.println(s);
}
reader.close();
reader_err.close();
}
} catch (IOException e){
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/ROVER_STATION/src/de/ye/rover_client/GUI.java
package de.ye.rover_client;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import de.ye.rover_client_connections.CONNECT_DIR;
import de.ye.rover_client_connections.CONNECT_ENG;
import de.ye.rover_client_connections.CONNECT_GPS;
import de.ye.rover_client_connections.CONNECT_IP;
import de.ye.rover_client_connections.CONNECT_LED;
public class GUI {
static JFrame clientFrame;
static JPanel clientPanel;
static JButton button_CONNECT;
static JLabel JOY_X_AX;
static JLabel JOY_Y_AX;
static JTextField IP_TF;
static JButton LIGHT;
static JButton pl;
static JButton cm;
static PrintWriter writer_led;
static BufferedReader reader_led;
static PrintWriter writer_dir;
static BufferedReader reader_dir;
static PrintWriter writer_eng;
static BufferedReader reader_eng;
static PrintWriter writer_ip;
static BufferedReader reader_ip;
static PrintWriter writer_gps;
static BufferedReader reader_gps;
static boolean connected=false;
static CONNECT_LED con_led = new CONNECT_LED();
static CONNECT_DIR con_dir = new CONNECT_DIR();
static CONNECT_ENG con_eng = new CONNECT_ENG();
static CONNECT_IP con_ip = new CONNECT_IP();
static CONNECT_GPS con_gps = new CONNECT_GPS();
public void CONNECT(){
if(con_led.CONNECT_LED(Main.SATELITE) == true && con_dir.CONNECT_DIR(Main.SATELITE) == true && con_eng.CONNECT_ENG(Main.SATELITE) == true && con_gps.CONNECT_GPS(Main.SATELITE) == true && con_ip.CONNECT_IP(Main.SATELITE) == true){
try {
System.out.println("Connected");
connected=true;
//Clients
Socket client_led = con_led.GET_CLIENT();
Socket client_dir = con_dir.GET_CLIENT();
Socket client_eng = con_eng.GET_CLIENT();
Socket client_ip = con_ip.GET_CLIENT();
Socket client_gps = con_gps.GET_CLIENT();
//Streams LED
OutputStream out_LED = client_led.getOutputStream();
writer_led = new PrintWriter(out_LED);
InputStream in_LED = client_led.getInputStream();
reader_led = new BufferedReader(new InputStreamReader(in_LED));
//-------------
//Streams DIR
OutputStream out_DIR = client_dir.getOutputStream();
writer_dir = new PrintWriter(out_DIR);
InputStream in_DIR = client_dir.getInputStream();
reader_dir = new BufferedReader(new InputStreamReader(in_DIR));
//-------------
//Streams ENG
OutputStream out_ENG = client_eng.getOutputStream();
writer_eng = new PrintWriter(out_ENG);
InputStream in_ENG = client_eng.getInputStream();
reader_eng = new BufferedReader(new InputStreamReader(in_ENG));
//-------------
//Streams ENG
OutputStream out_IP = client_ip.getOutputStream();
writer_ip = new PrintWriter(out_IP);
InputStream in_IP = client_ip.getInputStream();
reader_ip = new BufferedReader(new InputStreamReader(in_IP));
//-------------
//Streams GPS
OutputStream out_GPS = client_gps.getOutputStream();
writer_gps = new PrintWriter(out_GPS);
InputStream in_GPS = client_gps.getInputStream();
reader_gps = new BufferedReader(new InputStreamReader(in_GPS));
//-------------
Thread gps = new Thread(new GPS());
gps.start();
} catch (IOException e) {
}
} else {
System.out.println("NOT_CONNECTED");
connected=false;
}
}
public void createGUI() {
System.out.println("Start creating CLIENT_FRAME");
clientFrame = new JFrame("ROVER_BASE");
clientFrame.setSize(new Dimension(400,300));
clientFrame.setVisible(true);
clientPanel = new JPanel();
button_CONNECT = new JButton("CONNECT");
button_CONNECT.addActionListener(new ActionListener_CONNECT());
cm = new JButton("POWER_0");
cm.addActionListener(new ActionListener_CLEAN_MOTOR());
LIGHT = new JButton("LIGHT_ON");
LIGHT.addActionListener(new ActionListener_LIGHT());
IP_TF=new JTextField(Main.SATELITE,15);
JOY_X_AX= new JLabel("NO_JOYSTICK_X");
JOY_Y_AX= new JLabel("NO_JOYSTICK_Y");
System.out.println("Created PANEL_CLIENT_FRAME");
clientPanel.add(button_CONNECT,BorderLayout.NORTH);
clientPanel.add(IP_TF,BorderLayout.CENTER);
clientPanel.add(JOY_X_AX);
clientPanel.add(JOY_Y_AX);
clientPanel.add(LIGHT);
clientPanel.add(cm);
clientFrame.getContentPane().add(BorderLayout.CENTER, clientPanel);
clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clientFrame.setVisible(true);
System.out.println("Created CLIENT_FRAME FINISHED");
Thread UPDATE_STICK = new Thread(new Runnable() {
@Override
public void run() {
while((true)){
JOY_X_AX.setText(Integer.toString(JoyStick.X_AX));
JOY_Y_AX.setText(Integer.toString(JoyStick.Y_AX));
//System.out.println(JoyStick.Y_AX);
//System.out.println(JoyStick.X_AX);
}
}
});
UPDATE_STICK.start();
}
public static boolean isCONNECTED(){
return connected;
}
public static void all_LED_OFF(){
writer_led.println("ledoff_WARN");
writer_led.flush();
writer_led.println("ledoff_ERR");
writer_led.flush();
writer_led.println("ledoff_FINE");
writer_led.flush();
}
public class ActionListener_CONNECT implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Main.SATELITE=IP_TF.getText();
CONNECT();
}
}
public class ActionListener_LIGHT implements ActionListener {
boolean on=false;
@Override
public void actionPerformed(ActionEvent e) {
if(on==false){
on=true;
System.out.println("AN");
GUI.writer_led.println("ledon_WARN");
GUI.writer_led.flush();
} else {
on=false;
GUI.writer_led.println("ledoff_WARN");
GUI.writer_led.flush();
System.out.println("AUS");
}
}
}
public class ActionListener_CLEAN_MOTOR implements ActionListener {
boolean on=false;
@Override
public void actionPerformed(ActionEvent e) {
if(on==false){
on=true;
cm.setText("POWER_1");
System.out.println("POWER_1");
GUI.writer_led.println("power_1");
GUI.writer_led.flush();
} else {
on=false;
cm.setText("POWER_0");
GUI.writer_led.println("power_0");
GUI.writer_led.flush();
System.out.println("POWER_0");
}
}
}
public class ActionListener_pl implements ActionListener {
boolean on=false;
@Override
public void actionPerformed(ActionEvent e) {
GUI.writer_led.println("pic_load");
GUI.writer_led.flush();
}
}
public static class GPS implements Runnable{
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
<file_sep>/ROVER_BASE/src/de/ye/car_eng/ENG_CALC.java
package de.ye.car_eng;
import de.ye.car_dir.THREAD_DIR;
public class ENG_CALC implements Runnable{
public static int X_AX;
public static int Y_AX;
public static int LEFT_MOTOR=0;
public static int RIGHT_MOTOR=0;
public static String mode="0";
@Override
public void run() {
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if(!(check_alive.no_internet==false || THREAD_ENG.has_connected==false||THREAD_DIR.s==null||THREAD_ENG.s==null)){
X_AX=Integer.parseInt(THREAD_DIR.s);
Y_AX=Integer.parseInt(THREAD_ENG.s);
if(Y_AX<60&&Y_AX>40){
ENGINE.FRONT_LEFT();
ENGINE.FRONT_RIGHT();
if(X_AX<60&&X_AX>40){
LEFT_MOTOR=0;
RIGHT_MOTOR=0;
} else if(X_AX<40){
//LEFT
if(mode.equalsIgnoreCase("0")){
RIGHT_MOTOR=180;
} else if(mode.equalsIgnoreCase("1")){
RIGHT_MOTOR=210;
}
} else if(X_AX>60){
//Right
if(mode.equalsIgnoreCase("0")){
LEFT_MOTOR=180;
} else if(mode.equalsIgnoreCase("1")){
LEFT_MOTOR=210;
}
}
} else if(Y_AX>60){
if(mode.equalsIgnoreCase("0")){
LEFT_MOTOR=120;
RIGHT_MOTOR=120;
} else if(mode.equalsIgnoreCase("1")){
LEFT_MOTOR=150;
RIGHT_MOTOR=150;
}
ENGINE.BACK_LEFT();
ENGINE.BACK_RIGHT();
} else if(Y_AX<40){
if(mode.equalsIgnoreCase("0")){
LEFT_MOTOR=120;
RIGHT_MOTOR=120;
} else if(mode.equalsIgnoreCase("1")){
LEFT_MOTOR=150;
RIGHT_MOTOR=150;
}
ENGINE.FRONT_LEFT();
ENGINE.FRONT_RIGHT();
}
ENGINE.setSpeed_LEFT(LEFT_MOTOR);
ENGINE.setSpeed_RIGHT(RIGHT_MOTOR);
} else {
ENGINE.setSpeed_LEFT(0);
ENGINE.setSpeed_RIGHT(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/ROVER_BASE/src/de/ye_boat/net/TRY_CONNECT.java
package de.ye_boat.net;
import de.ye.car_con_men.CONNECT;
import de.ye.car_main.Main;
public class TRY_CONNECT implements Runnable{
@Override
public void run() {
System.out.println("TRY_CONNECT STARTED");
while(true){
try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}
if(Main.STATUS==true){
break;
} else {
Thread con = new Thread(new CONNECT());
con.start();
}
}
}
}
<file_sep>/ROVER_BASE/src/de/ye_rover/net/TRY_CONNECT.java
package de.ye_rover.net;
import de.ye.rover_con_men.CONNECT;
import de.ye.rover_main.Main;
public class TRY_CONNECT implements Runnable{
@Override
public void run() {
System.out.println("TRY_CONNECT STARTED");
while(true){
try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}
if(Main.STATUS==true){
break;
} else {
Thread con = new Thread(new CONNECT());
con.start();
}
}
}
}
<file_sep>/ROVER_BASE/src/de/ye/rover_con/THREAD_CON.java
package de.ye.rover_con;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class THREAD_CON implements Runnable {
public static Socket client;
public static boolean ALIVE=false;
public static boolean t=true;
public static int IP;
public static boolean end = false;
public static String TRACK_IP;
public static PrintWriter writer;
public static OutputStream out;
public THREAD_CON(Socket client) {
this.client = client;
}
@Override
public void run() {
try {
//Streams
out = client.getOutputStream();
writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//-------------
System.out.println("STATUS CLIENT STREAM THREAD STARTED._CON");
String s = null;
while(t=true){
}
System.out.println("STATUS CLIENT LISTENING READY._CON");
writer.close();
reader.close();
client.close();
System.out.println("STATUS CLIENT THREAD ENDED._CON");
} catch (Exception e) {
}
}
}
| 9078d1fdd18f4899fb1f6518c4f886e419ad007f | [
"Markdown",
"Java"
] | 8 | Java | luickk/Apollo-Internet-controlled-rover | 8c53a03c7abe106c9ef42968ba2b6d616735419d | 7a2103d66dc2173b4b9a44412f2cc4d25309ef18 |
refs/heads/main | <file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
== Requirements
Deploy a link:/component/network_segment[network segment].
== Providers
[cols="a,a",options="header,autowidth"]
|===
|Name |Version
|[[provider_oci]] <<provider_oci,oci>> |n/a
|[[provider_time]] <<provider_time,time>> |n/a
|[[provider_null]] <<provider_null,null>> |n/a
|===
== Module
```hcl
module "application_domain" {
source = "./component/network_domain/"
providers = { oci = oci.home }
depends_on = [ module.application_section, module.service_segment ]
config = {
service_id = local.service_id
compartment_id = module.application_section.compartment_id
vcn_id = module.service_segment.vcn_id
anywhere = module.service_segment.anywhere
defined_tags = null
freeform_tags = {"framework" = "ocloud"}
}
subnet = {
# Select the predefined name per index
domain = element(keys(module.service_segment.subnets), 0)
# Select the predefined range per index
cidr_block = element(values(module.service_segment.subnets), 0)
prohibit_public_ip_on_vnic = false
dhcp_options_id = null
route_table_id = module.service_segment.private_route_table_id
}
bastion = {
# Determine whether a bastion service will be deployed and attached
create = true
client_allow_cidr = [module.service_segment.anywhere]
max_session_ttl = 1800
}
tcp_ports = {
ingress = [
["ssh", module.service_segment.subnets.pres, 22, 22],
["http", module.service_segment.anywhere, 80, 80],
["https", module.service_segment.anywhere, 443, 443]
]
}
}
```
== Resources
[cols="a,a",options="header,autowidth"]
|===
|Name |Type
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/bastion_bastion[oci_bastion_bastion.domain] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_route_table_attachment[oci_core_route_table_attachment.domain] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_security_list[oci_core_security_list.domain] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_subnet[oci_core_subnet.domain] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/bastion_bastions[oci_bastion_bastions.domain] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_security_lists[oci_core_security_lists.domain] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_services[oci_core_services.all_services] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_subnets[oci_core_subnets.domain] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_vcn[oci_core_vcn.domain] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_compartments[oci_identity_compartments.domain] |data source
|https://registry.terraform.io/providers/hashicorp/time/latest/docs/resources/sleep[time_sleep.wait] |resource
|https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource[null_resource.previous] |resource
|===
== Inputs
[cols="a,a,a,a,a",options="header,autowidth"]
|===
|Name |Description |Type |Default |Required
|[[input_config]] <<input_config,config>>
|Settings for the network domain
|
[source]
----
object({
service_id = string,
compartment_id = string,
vcn_id = string,
defined_tags = map(any),
freeform_tags = map(any),
anywhere = string
})
----
|n/a
|yes
|[[input_subnet]] <<input_subnet,subnet>>
|Parameters for each subnet to be managed
|
[source]
----
object({
domain = string,
cidr_block = string,
prohibit_public_ip_on_vnic = bool,
dhcp_options_id = string,
route_table_id = string
})
----
|n/a
|yes
|[[input_tcp_ports]] <<input_tcp_ports,tcp_ports>>
|List of ports that will be open for the subnet
|
[source]
----
object({
ingress = list(list(any))
})
----
|n/a
|yes
|[[input_bastion]] <<input_bastion,bastion>>
|true or false, creates a bastion endpoint, usually there is just one bastion per VCN, hence default setting is false
|
[source]
----
object({
create = bool,
client_allow_cidr = list(string),
max_session_ttl = number
})
----
|n/a
|yes
|===
Parameter definitions can be found in the link:/doc/glossary.adoc[glossary]
== Outputs
[cols="a,a",options="header,autowidth"]
|===
|Name |Description
|[[output_bastion]] <<output_bastion,bastion>> |Bastion Service
|[[output_seclist]] <<output_seclist,seclist>> |Security List
|[[output_subnet]] <<output_subnet,subnet>> |Subnet
|===
<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
:ocloud-base: https://github.com/oracle-devrel/terraform-oci-ocloud-landing-zone
:ocloud-links: links.adoc
:ocloud-tf: terraform.adoc
:ocloud-net: networking.adoc
:ocloud-intro: introduction.adoc
:ocloud-name: naming.adoc
:oci-certification: https://www.oracle.com/cloud/iaas/training/architect-associate.html
:oci-cli: https://docs.oracle.com/en-us/iaas/tools/oci-cli/latest/oci_cli_docs/
:oci-cloud: https://www.oracle.com/cloud/
:oci-cloudshell: https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/cloudshellintro.htm
:oci-compartments: https://docs.cloud.oracle.com/en-us/iaas/Content/GSG/Concepts/settinguptenancy.htm#Understa
:oci-data: https://registry.terraform.io/providers/hashicorp/oci/latest/docs
:oci-freetier: http://signup.oraclecloud.com/
:oci-global: https://www.oracle.com/cloud/architecture-and-regions.html
:oci-learn: https://learn.oracle.com/ols/user-portal
:oci-learning: https://learn.oracle.com/ols/learning-path/become-oci-architect-associate/35644/75658
:oci-home: https://medium.com/oracledevs/provision-oracle-cloud-infrastructure-home-region-iam-resources-in-a-multi-region-terraform-f997a00ae7ed
:oci-homeregion: https://docs.cloud.oracle.com/en-us/iaas/Content/Identity/Tasks/managingregions.htm
:oci-identifier: https://docs.cloud.oracle.com/en-us/iaas/Content/General/Concepts/regions.htm
:oci-identity: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_availability_domains
:oci-ilom: https://www.oracle.com/servers/technologies/integrated-lights-out-manager.html
:oci-l2: https://blogs.oracle.com/cloud-infrastructure/first-principles-l2-network-virtualization-for-lift-and-shift
:oci-landing: https://docs.oracle.com/en/solutions/cis-oci-benchmark/
:oci-offbox: https://blogs.oracle.com/cloud-infrastructure/first-principles-l2-network-virtualization-for-lift-and-shift
:oci-policies: https://docs.cloud.oracle.com/en-us/iaas/Content/Identity/Concepts/commonpolicies.htm
:oci-provider: https://github.com/terraform-providers/terraform-provider-oci
:oci-reference: https://docs.oracle.com/en/solutions/multi-tenant-topology-using-terraform/
:oci-region: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_regions
:oci-regional: https://medium.com/oracledevs/provision-oracle-cloud-infrastructure-home-region-iam-resources-in-a-multi-region-terraform-f997a00ae7ed
:oci-regions: https://www.oracle.com/cloud/data-regions.html
:oci-regionmap: https://www.oracle.com/cloud/architecture-and-regions.html
:oci-sdk: https://docs.cloud.oracle.com/en-us/iaas/Content/API/SDKDocs/terraform.htm
:oci-tenancy: https://docs.oracle.com/en-us/iaas/Content/GSG/Concepts/settinguptenancy.htm
:oci-terraform: https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/terraform.htm
:oci-training: https://www.oracle.com/cloud/iaas/training/
:oci-variable: https://upcloud.com/community/tutorials/terraform-variables/#:~:text=Terraform%20variables%20can%20be%20defined,open%20the%20file%20for%20edit
:tf-boolean: https://medium.com/swlh/terraform-how-to-use-conditionals-for-dynamic-resources-creation-6a191e041857
:tf-count: https://www.terraform.io/docs/configuration/resources.html#count-multiple-resource-instances-by-count
:tf-compartment: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_compartment
:tf-cli: https://www.terraform.io/docs/commands/index.html
:tf-commands: https://www.terraform.io/docs/commands/index.html
:tf-data: https://www.terraform.io/docs/configuration/data-sources.html
:tf-data-compartments: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_compartments
:tf-data-groups: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_groups
:tf-data-policies: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_policies
:tf-data-users: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_users
:tf-doc: https://registry.terraform.io/providers/hashicorp/oci/latest/docs
:tf-foreach: https://www.terraform.io/docs/configuration/resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings
:tf-group: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_group
:tf-examples: https://github.com/terraform-providers/terraform-provider-oci/tree/master/examples
:tf-expression: https://www.terraform.io/docs/language/expressions/index.html
:tf-hcl: https://github.com/hashicorp/hcl
:tf-home: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_tenancy
:tf-input: https://www.terraform.io/docs/configuration/variables.html
:tf-intro: https://youtu.be/h970ZBgKINg
:tf-json: https://www.terraform.io/docs/internals/json-format.html
:tf-lint: https://www.hashicorp.com/blog/announcing-the-terraform-visual-studio-code-extension-v2-0-0
:tf-list: https://www.terraform.io/docs/language/values/variables.html#list-lt-type-gt-
:tf-loop: https://www.hashicorp.com/blog/hashicorp-terraform-0-12-preview-for-and-for-each/
:tf-loop-tricks: https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9
:tf-local: https://www.terraform.io/docs/configuration/locals.html
:tf-locals: https://www.terraform.io/docs/configuration/locals.html
:tf-main: https://www.terraform.io/
:tf-provider: https://www.terraform.io/docs/language/providers/configuration.html
:tf-tenancy: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_tenancy
:tf-local-exec: https://www.terraform.io/docs/language/resources/provisioners/local-exec.html
:tf-output: https://www.terraform.io/docs/configuration/outputs.html
:tf-parameterize: https://build5nines.com/use-terraform-input-variables-to-parameterize-infrastructure-deployments/
:tf-pattern: https://www.hashicorp.com/resources/evolving-infrastructure-terraform-opencredo
:tf-policy: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_policy
:tf-pwd: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_ui_password
:tf-remote-exec: https://www.terraform.io/docs/language/resources/provisioners/remote-exec.html
:tf-script: https://www.terraform.io/docs/language/expressions/for.html
:tf-sequence: https://www.terraform.io/docs/configuration/resources.html#create_before_destroy
:tf-syntax: https://www.terraform.io/docs/language/syntax/configuration.html
:tf-ternary: https://github.com/hashicorp/terraform/issues/22131
:tf-types: https://www.terraform.io/docs/language/expressions/types.html
:tf-user: https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_user
:tf-var: https://upcloud.com/community/tutorials/terraform-variables/#:~:text=Terraform%20variables%20can%20be%20defined,open%20the%20file%20for%20edit
:tf-variable: https://www.terraform.io/docs/configuration/variables.html
:tf-vcn-module: https://registry.terraform.io/modules/oracle-terraform-modules/vcn/oci/latest
:itil-application: https://wiki.en.it-processmaps.com/index.php/ITIL_Application_Management
:itil-operation: https://wiki.en.it-processmaps.com/index.php/ITIL_Service_Operation
:itil-roles: https://wiki.en.it-processmaps.com/index.php/ITIL_Roles
:itil-technical: https://wiki.en.it-processmaps.com/index.php/ITIL_Technical_Management
:itil-web: https://www.axelos.com/best-practice-solutions/itil
:cli-doc: https://docs.cloud.oracle.com/en-us/iaas/tools/oci-cli/latest/oci_cli_docs/
:iam-doc: https://docs.cloud.oracle.com/en-us/iaas/Content/Identity/Concepts/overview.htm
:network-doc: https://docs.cloud.oracle.com/en-us/iaas/Content/Network/Concepts/overview.htm
:compute-doc: https://docs.cloud.oracle.com/en-us/iaas/Content/Compute/Concepts/computeoverview.htm#Overview_of_the_Compute_Service
:storage-doc: https://docs.cloud.oracle.com/en-us/iaas/Content/Object/Concepts/objectstorageoverview.htm
:database-doc: https://docs.cloud.oracle.com/en-us/iaas/Content/Database/Concepts/databaseoverview.htm
:iam-video: https://www.youtube.com/playlist?list=PLKCk3OyNwIzuuA-wq2rVuxUE13rPTvzQZ
:network-video: https://www.youtube.com/playlist?list=PLKCk3OyNwIzvHm2E-cGrmoMes-VwanT3P
:compute-video: https://www.youtube.com/playlist?list=PLKCk3OyNwIzsAjIaUaVsKdXcfBOy6LASv
:storage-video: https://www.youtube.com/playlist?list=PLKCk3OyNwIzu7zNtt_w1dXFOUbAjheMeo
:database-video: https://www.youtube.com/watch?v=F4-sxIsnbKI&list=PLKCk3OyNwIzsfuB9kj1CTPavjgByJBXGK
:ref-cidr: https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
:ref-cli: https://docs.cloud.oracle.com/en-us/iaas/tools/oci-cli/latest/oci_cli_docs/
:ref-dgravity: https://whatis.techtarget.com/definition/data-gravity
:ref-dry: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
:ref-hostrouting: https://networkencyclopedia.com/host-routing/
:ref-iac: https://en.wikipedia.org/wiki/Infrastructure_as_code
:ref-jmespath: https://jmespath.org/tutorial.html
:ref-jq: https://stedolan.github.io/jq/
:ref-jqplay: https://jqplay.org/
:ref-json-lint: https://jsonlint.com
:ref-json: https://www.w3schools.com/js/js_json_syntax.asp
:ref-json-format: https://jsonformatter.curiousconcept.com/
:ref-l2: http://sherpainthecloud.com/en/blog/why-oci-l2-support-is-a-big-deal
:ref-logical: https://docs.oracle.com/cd/E11882_01/doc.112/e28440/logical_cdm2.htm#CDMRF1870
:ref-logresource: https://pubs.opengroup.org/architecture/togaf9-doc/arch/apdxa.html
:ref-nist: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-145.pdf
:ref-sna: https://en.wikipedia.org/wiki/Shared-nothing_architecture
:ref-vdc: https://www.techopedia.com/7/31109/technology-trends/virtualization/what-is-the-difference-between-a-private-cloud-and-a-virtualized-data-center
:ref-vsc: https://code.visualstudio.com
:rfc-1035: https://datatracker.ietf.org/doc/html/rfc1035
:linux-printenv: https://www.gnu.org/software/coreutils/manual/html_node/printenv-invocation.html
:learn-doc-iam: https://docs.cloud.oracle.com/en-us/iaas/Content/Identity/Concepts/overview.htm
:learn-doc-network: https://docs.cloud.oracle.com/en-us/iaas/Content/Network/Concepts/overview.htm
:learn-doc-compute: https://docs.cloud.oracle.com/en-us/iaas/Content/Compute/Concepts/computeoverview.htm#Overview_of_the_Compute_Service
:learn-doc-storage: https://docs.cloud.oracle.com/en-us/iaas/Content/Object/Concepts/objectstorageoverview.htm
:learn-doc-database: https://docs.cloud.oracle.com/en-us/iaas/Content/Database/Concepts/databaseoverview.htm
:learn-doc-vault: https://docs.oracle.com/en-us/iaas/Content/KeyManagement/Concepts/keyoverview.htm
:learn-video-iam: https://www.youtube.com/playlist?list=PLKCk3OyNwIzuuA-wq2rVuxUE13rPTvzQZ
:learn-video-network: https://www.youtube.com/playlist?list=PLKCk3OyNwIzvHm2E-cGrmoMes-VwanT3P
:learn-video-compute: https://www.youtube.com/playlist?list=PLKCk3OyNwIzsAjIaUaVsKdXcfBOy6LASv
:learn-video-storage: https://www.youtube.com/playlist?list=PLKCk3OyNwIzu7zNtt_w1dXFOUbAjheMeo
:learn-video-database: https://www.youtube.com/watch?v=F4-sxIsnbKI&list=PLKCk3OyNwIzsfuB9kj1CTPavjgByJBXGK
:learn-video-vault: https://www.youtube.com/watch?v=6OyrVWSL_D4
<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
== Requirements
Define an link:/init.tf[encapsulating compartment].
== Providers
[cols="a,a",options="header,autowidth"]
|===
|Name |Version
|[[provider_oci]] <<provider_oci,oci>> |n/a
|[[provider_null]] <<provider_null,null>> |n/a
|[[provider_time]] <<provider_time,time>> |n/a
|===
== Module
```hcl
module "service_segment" {
source = "./component/network_segment/"
providers = { oci = oci.home }
depends_on = [ module.network_section ]
# Define unique number per segment
segment = 1
config = {
service_id = local.service_id
display_name = lower("${local.service_name}_${var.network}")
compartment_id = module.network_section.compartment_id
source = var.code_source
freeform_tags = {
"framework" = "ocloud"
}
}
network = {
description = "virtual cloud network"
address_spaces = {
"cidr_block" = "10.0.0.0/24"
"anywhere" = "0.0.0.0/0"
"interconnect" = "192.168.0.0/16"
}
subnet_list = {
# A list with newbits for the cidrsubnet function, for subnet calculations visit http://jodies.de/ipcalc
app = 1
db = 2
pres = 2
}
create_drg = true
block_nat_traffic = false
# Alternative: "oci-${local.region_key}-objectstorage"
service_gateway_cidr = "all-${lower(local.home_region_key)}-services-in-oracle-services-network"
}
}
```
== Resources
[cols="a,a",options="header,autowidth"]
|===
|Name |Type
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_default_security_list[oci_core_default_security_list.default_security_list] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_drg[oci_core_drg.segment] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_drg_attachment[oci_core_drg_attachment.segment] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_internet_gateway[oci_core_internet_gateway.segment] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_nat_gateway[oci_core_nat_gateway.segment] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_network_security_group[oci_core_network_security_group.segment] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_route_table[oci_core_route_table.osn] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_route_table[oci_core_route_table.private] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_route_table[oci_core_route_table.public] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_service_gateway[oci_core_service_gateway.segment] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/core_vcn[oci_core_vcn.segment] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_drgs[oci_core_drgs.segment] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_internet_gateways[oci_core_internet_gateways.segment] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_nat_gateways[oci_core_nat_gateways.segment] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_network_security_groups[oci_core_network_security_groups.segment] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_route_tables[oci_core_route_tables.osn] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_route_tables[oci_core_route_tables.private] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_route_tables[oci_core_route_tables.public] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_service_gateways[oci_core_service_gateways.segment] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_services[oci_core_services.all_services] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_vcns[oci_core_vcns.segment] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_compartments[oci_identity_compartments.segment] |data source
|https://registry.terraform.io/providers/hashicorp/time/latest/docs/resources/sleep[time_sleep.wait] |resource
|https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource[null_resource.previous] |resource
|===
== Inputs
[cols="a,a,a,a,a",options="header,autowidth"]
|===
|Name |Description |Type |Default |Required
|[[input_config]] <<input_config,config>>
|Service Configuration
|
[source]
----
object({
service_id = string,
display_name = string,
compartment_id = string,
source = string,
freeform_tags = map(any)
})
----
|n/a
|yes
|[[input_network]] <<input_network,network>>
|Settings for the virtual cloud network
|
[source]
----
object({
address_spaces = map(string), # Network address prefix in CIDR notation that all of the requested subnetwork prefixes will be allocated within.
subnet_list = map(number), # A list of objects describing requested subnetwork prefixes. new_bits is the number of additional network prefix bits to add, in addition to the existing prefix on base_cidr_block.
create_drg = bool,
block_nat_traffic = bool, # Whether or not to block traffic through NAT gateway
service_gateway_cidr = string # The OSN service cidr accessible through Service Gateway"
})
----
|n/a
|yes
|[[input_segment]] <<input_segment,segment>>
|Identify the Section, use a unique number
|`number`
|n/a
|yes
|===
Parameter definitions can be found in the link:/doc/glossary.adoc[glossary]
== Outputs
[cols="a,a",options="header,autowidth"]
|===
|Name |Description
|[[output_anywhere]] <<output_anywhere,anywhere>> |Echoes back the anywhere setting for the vcn module
|[[output_cidr_block]] <<output_cidr_block,cidr_block>> |Echoes back the base_cidr_block input variable value, for convenience if passing the result of this module elsewhere as an object.
|[[output_drg_id]] <<output_drg_id,drg_id>> |Dynamic Routing Gateway
|[[output_internet_id]] <<output_internet_id,internet_id>> |Internet Gateway
|[[output_nat_id]] <<output_nat_id,nat_id>> |NAT Gateway
|[[output_osn]] <<output_osn,osn>> |Oracle Service Network
|[[output_osn_id]] <<output_osn_id,osn_id>> |Service Gateway
|[[output_osn_route_table_id]] <<output_osn_route_table_id,osn_route_table_id>> |Route traffic to the Oracle Service Network
|[[output_private_route_table_id]] <<output_private_route_table_id,private_route_table_id>> |Route traffic inside the VCN
|[[output_public_route_table_id]] <<output_public_route_table_id,public_route_table_id>> |Route traffic to the anywhere address space
|[[output_security_group]] <<output_security_group,security_group>> |Security Group
|[[output_subnets]] <<output_subnets,subnets>> |A list of objects corresponding to each of the objects in the input variable 'networks', each extended with a new attribute 'cidr_block' giving the network's allocated address prefix.
|[[output_vcn_id]] <<output_vcn_id,vcn_id>> |Virtual Cloud Network
|===
<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
ifndef::env-github[]
include::links.adoc[]
endif::[]
== Naming Conventions
Managing IT assets requires a harmonize set of identifiers accross multiple system. Cloud resources will pe represented in existing systems like the configuration management database (CMDB), the directory server (LDAP) and network management services like network information systems (NIS), dynamic host configuration protocol (DHCP), domain name service (DNS) or IP address manager (IPAM). It is necessary to adhere unique values for records such as computer names, usernames and asset tags, so operators can differentiate between them. In operations engineering we distinguish the following types of names:
* Resource Name - unique identifier for resource blocks in Terraform
* DNS Label - unique resource argument, prologuing the URL, needs to comply with {rfc-1035}[RFC 1035], up to 15 alpha numeric characters
* Name - unique resource argument to identify resource instances, up to 255 alpha numeric characters
* Display Name - freetext argument inside resource blocks refering, to resources in the console and in log files, up to 255 alpha numeric and special characters
The following guidelines should help to define names for an OCI tenancy
=== Oracle Resource Manager (ORM) stacks
[cols="1,1,1,1",options="header"]
|===
| Name | working-dir | depends on | can depend on
| base | /base | - | -
| db | /db | base | -
| app | /app | base | db
|===
=== Input Parameter
[cols="1,1,1,1,1",options="header"]
|===
| Name | Convention | Example | Limit Enforcement | Type
| service label | "owner" + "project" | dteldbas | 8 alphanumeric characters, lower letter | implicit
| service name | "owner" + _ + "project" | - | upper letter | implicit
| owner | client name | dtel | 4 alphanumeric characters max | mandatory
| project | department / project name | dbas | 4 alphanumeric characters max | mandatory
| stage | type of environment | dev/test/prd | - | optional
|===
=== Assembly Rules for Implicit Types
[cols="1,1,1",options="header"]
|===
| Type | Convention | Example
| Display Name | "service_name" + _ + "..." | dteldbas
| DNS Label | "service_name" + "..." | dbas
|===
=== Assembly Rules for Explicit Types
==== Display Name
[cols="1,1,1",options="header"]
|===
| Type | Convention | Example
| compartment | "service_name"-"resource name"-compartment | dteldbas-application-compartment
| vcn | "service_name"-"instance number"-network | dteldbas-0-network
| policy | "group name"-policy | netops-policy
|===
==== Name
an ITSM oriented setup would be the following:
**Groups**
[cols="1,1",options="header"]
|===
| Name | Function
| cloudops | Group for super user, managing the cloud tenancy
| sysops | Group for managing application infrastructure in compartment /application/
| secops | Specific sysops group with access to security services
| netops | Group for managing networking infrastrcutrue in the root compartment
| dbops | Group for managing database infrastructure in compartment /database/
| iam | Group for managing IAM resources in the tenancy.
| audit | Group for inspecting and auditing the use of a tenancy
|===
==== Resource Name
Using a consistent identifier, like the default "ocloud" and add numbers when multiple instances are possible.
{ocloud-base}[<<] | {ocloud-net}[<] | {ocloud-intro}[+] | {ocloud-net}[>] | {ocloud-links}[>>]<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
== Requirements
Define an link:/init.tf[encapsulating compartment].
== Providers
[cols="a,a",options="header,autowidth"]
|===
|Name |Version
|[[provider_oci]] <<provider_oci,oci>> |n/a
|[[provider_null]] <<provider_null,null>> |n/a
|[[provider_time]] <<provider_time,time>> |n/a
|===
== Module
```hcl
module "operation_section" {
depends_on = [ oci_identity_compartment.init ]
source = "./component/admin_section/"
providers = { oci = oci.home }
config = {
tenancy_id = var.tenancy_ocid
source = var.code_source
display_name = lower("${local.service_name}_${var.operation}")
freeform_tags = {
"framework" = "ocloud"
}
}
compartment = {
# Enable compartment delete on destroy. If true, compartment will be deleted when terraform destroy is executed
enable_delete = true
parent = local.service_id
}
roles = {
"${local.service_name}_administrator" = [
"ALLOW GROUP ${local.service_name}_administrator to read users in compartment ${local.service_name}",
"ALLOW GROUP ${local.service_name}_administrator to read groups in compartment ${local.service_name}",
"ALLOW GROUP ${local.service_name}_administrator to manage users in compartment ${local.service_name}",
"ALLOW GROUP ${local.service_name}_administrator to manage groups in compartment ${local.service_name} where target.group.name = '${local.service_name}_administrator'",
"ALLOW GROUP ${local.service_name}_administrator to manage groups in compartment ${local.service_name} where target.group.name = '${local.service_name}_secops'",
]
}
}
```
== Resources
[cols="a,a",options="header,autowidth"]
|===
|Name |Type
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_compartment[oci_identity_compartment.section] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_group[oci_identity_group.section] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/resources/identity_policy[oci_identity_policy.section] |resource
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_compartments[oci_identity_compartments.section] |data source
|https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_policies[oci_identity_policies.section] |data source
|https://registry.terraform.io/providers/hashicorp/time/latest/docs/resources/sleep[time_sleep.wait] |resource
|https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource[null_resource.previous] |resource
|===
== Inputs
[cols="a,a,a,a,a",options="header,autowidth"]
|===
|Name |Description |Type |Default |Required
|[[input_config]] <<input_config,config>>
|Settings for adminstrator section
|
[source]
----
object({
tenancy_id = string,
source = string,
display_name = string,
freeform_tags = map(any)
})
----
|n/a
|yes
|[[input_compartment]] <<input_compartment,compartment>>
|Settings for compartment
|
[source]
----
object({
enable_delete = bool,
parent = string
})
----
|n/a
|yes
|[[input_roles]] <<input_roles,roles>>
|Role definitions
|`map(list(any))`
|n/a
|yes
|===
Parameter definitions can be found in the link:/doc/glossary.adoc[glossary]
== Outputs
[cols="a,a",options="header,autowidth"]
|===
|Name |Description
|[[output_compartment_id]] <<output_compartment_id,compartment_id>> |compartment details
|[[output_compartment_name]] <<output_compartment_name,compartment_name>> |compartment details
|[[output_roles]] <<output_roles,roles>> |administrator roles
|===
<file_sep># Tenancy Configuration
Oracle Cloud Infrastructure (OCI) is a programable data center, providing dedicated infrastructure in more than 30 locations world wide. The [share-nothing design][ref_sna] allows IT operators to launch [private clouds][ref_nist] on demand and enables enterprises to adopt managed services into an existing operation. This framework is inspired by the [CIS landing zone][oci_landing] and helps ITIL oriented organizations to build and launch private or public cloud services.
<img alt="Service Delivery Framework" src="doc/image/LandingZone.png" title="Service Delivery Framework">
Customizing the framework enables application provider to manage multi-tenant services with clients shielded on the network layer. We recommend to study the following material before approaching this tutorial: Compartments, Group-, Policy- and User-Templates ([Documentation][learn_doc_iam] | [Video][learn_video_iam]), Virtual Cloud Network ([Documentation][learn_doc_network] | [Video][learn_video_network]), Key Vault ([Documentation][learn_doc_vault] | [Video][learn_video_vault]) und Object Store ([Documentation][learn_doc_storage] | [Video][learn_video_storage]).
## Code Structure
We employ [Infrastructure as Code][ref_iac] to combine dedicated resources with managed cloud- and orchestration services into [custom resources][ref_logresource]. The code is separated into multipe definiton files that Terraform merges into one deployment plan at the time of execution. The following structure uses [compartments][oci_compartments] to reflect shared service center for independent businesses or business units that are separated on the network layer.
| Nr. | Domain | File | Resources | |
|:---:|:--- |:--- | :--- |:--- |
| 1 | Applications | [app.tf](/app.tf) | Hosts (VM & BM), instance groups and container cluster | optional |
| 2 | Database Infrastructure | [db.tf](/db.tf) | CDB or PDB | optional |
| 3 | Network Topology | [net.tf](/net.tf) | Virtual Cloud Network, Layer-3 Gateways | required |
| 4 | Operations and Security | [ops.tf](/ops.tf) | Monitoring and management | required |
| 5 | Operations and Security | [global.tf](/global.tf) | Global variables, datasources and naming conventions | required |
| 6 | Operations and Security | [default.tfvars](/default.tfvars) | Default parameter for a project | required |
In the background we build on a modular code structure that uses terraform modules to employ OCI resources and services. Templates for a predefined network topology and isolated database infrastructure extend the application oriented DevOps processes with customized resources.
<img alt="Base Configuration Taxonomy" src="doc/image/taxonomy.png" title="Base Configuration Taxonomy">
Using declarative templates, provides operators with the flexibility to adjust their service delivery platform with evolving requirements. Global input parameters help to maintain readability of the code and avoid [repeating definitions][ref_dry]. We use the `~/project/default.tfvars` file to define global input parameter for an entire project.
```
variable "tenancy_ocid" { }
variable "organization" {
type = string
description = "provide a string that identifies the commercial owner of a service"
default = "org" # Define a name that identifies the project
validation {
condition = length(regexall("^[A-Za-z][A-Za-z0-9]{1,7}$", var.owner)) > 0
error_message = "The service_name variable is required and must contain alphanumeric characters only, start with a letter and 5 character max."
}
}
variable "project" {
type = string
description = "provide a string that refers to a project"
default = "name" # Define a name that identifies the project
validation {
condition = length(regexall("^[A-Za-z][A-Za-z0-9]{1,7}$", var.project)) > 0
error_message = "The service_name variable is required and must contain alphanumeric characters only, start with a letter and 8 character max."
}
}
variable "stage" {
type = string
description = "define the lifecycle status"
default = "dev" # Lifecycle stage for the code base
validation {
condition = length(regexall("^[A-Za-z][A-Za-z0-9]{1,7}$", var.stage)) > 0
error_message = "The service_name variable is required and must contain alphanumeric characters only, start with a letter and 3 character max."
}
}
variable "region" {
default = "us-ashburn-1"
validation {
condition = length(trim(var.region,"")) > 0
error_message = "The region variable is required."
}
}
variable "owner" {
type = object({
user_ocid = string
api_fingerprint = string
api_private_key_path = string
private_key_password = string
})
description = "refers to the technical owner of the tenancy"
default = {
"user_ocid" : "",
"api_fingerprint" : "",
"api_private_key_path" : "",
"private_key_password" : ""
}
}
```
The `~/project/global.tf` file contains common datasources and functions that can be utilized throughout the entire stack.
```
provider "oci" {
region = var.region
tenancy_ocid = var.tenancy_ocid
user_ocid = var.root.user_ocid
fingerprint = var.root.fingerprint
private_key_path = var.root.private_key_path
private_key_password = var.root.private_key_password
}
provider "oci" {
alias = "home"
region = local.regions_map[local.home_region_key]
tenancy_ocid = var.tenancy_ocid
user_ocid = var.root.user_ocid
fingerprint = var.root.fingerprint
private_key_path = var.root.private_key_path
private_key_password = var.root.private_key_password
}
## --- data sources ---
data "oci_identity_regions" "global" { } # Retrieve a list OCI regions
data "oci_identity_tenancy" "ocloud" { tenancy_id = var.tenancy_ocid } # Retrieve meta data for tenant
data "oci_identity_availability_domains" "ads" { compartment_id = var.tenancy_ocid } # Get a list of Availability Domains
data "oci_identity_compartments" "root" { compartment_id = var.tenancy_ocid } # List root compartments
data "oci_objectstorage_namespace" "ns" { compartment_id = var.tenancy_ocid } # Retrieve object storage namespace
data "oci_cloud_guard_targets" "root" { compartment_id = var.tenancy_ocid }
data "template_file" "ad_names" { # List AD names in home region
count = length(data.oci_identity_availability_domains.ads.availability_domains)
template = lookup(data.oci_identity_availability_domains.ads.availability_domains[count.index], "name")
}
## --- input functions ---
# Define the home region identifier
locals {
# Discovering the home region name and region key.
regions_map = {for rgn in data.oci_identity_regions.global.regions : rgn.key => rgn.name} # All regions indexed by region key.
regions_map_reverse = {for rgn in data.oci_identity_regions.global.regions : rgn.name => rgn.key} # All regions indexed by region name.
home_region = data.oci_identity_tenancy.ocloud.home_region_key # Home region key obtained from the tenancy data source
region_key = lower(local.regions_map_reverse[var.region]) # Region key obtained from the region name
# Setting network access parameters
anywhere = "0.0.0.0/0"
valid_service_gateway_cidrs = ["oci-${local.region_key}-objectstorage", "all-${local.region_key}-services-in-oracle-services-network"]
# Service label
service_name = format("%s%s%s", substr(var.owner, 0, 3), substr(var.project, 0, 5), substr(var.stage, 0, 3))
service_name = upper("${var.owner}_${var.project}_${var.stage}")
}
## --- global output parameter ---
output "account" { value = data.oci_identity_tenancy.ocloud }
output "namespace" { value = data.oci_objectstorage_namespace.ns.namespace }
output "ad_names" { value = sort(data.template_file.ad_names.*.rendered) } # List of ADs in the selected region
```
### Network Design
Before provisioning any compute or storage resources we need to setup a basic network. Therefore we start with the compartment for network operation. One of the unique features of OCI is the [virtual layer 2 network][oci_l2] design. Compared to the common network overlays in public clouds, this design provides the necessary control to create isolated data center on a shared infrastructure pool. Packet encapsulation shields private traffic on a shared network backbone to the extend of defining overlapping IP ranges. This allows for a multi-tenant design on the infrastructure layer, and prevents developers and operators to rely complex procedures building and maintaining multi-tenant applications. The following diagram exemplifies the topology in a multi data centre region.
[<img alt="Physical Network Topology" src="doc/image/topology.png" title="Physical Network Topology">][learn_doc_network]
A Virtual Cloud Network (VCN) contains a private ["Classless Inter-Domain Routing (CIDR)"][ref_cidr] and can be extend with publically addressable IP adresses.
[<img alt="Network Segementation" src="doc/image/segmentation.png" title="Network Segementation">][learn_doc_network]
Even though we need to distinguish the physical topology of single- and multi-data centre regions, the logical network layer remains the same, because the data center are connected through a close network and packet forwarding relys on [host routing mechanisms][ref_hostrouting]. Regional subnets enable operators to launch multi-data center networks for both, private and public cloud services. Beside the CIDR the VCN definition contains the Dynamic Routing Gateway (DRG) as IP peer and host for network functions like Internet Connectivity, Network Address Translation (NAT) or Private-Public Service Communication.
We start the VCN definition with the network parameter.
```
# VCN parameters
variable "create_net" { default = false }
variable "cidr" { default = "10.0.0.0/16" }
variable "enable_routing" { default = true }
variable "enable_internet" { default = false }
variable "enable_nat" { default = true }
variable "private_service" { default = false }
```
In the sources file we define a valid hostname that refers to the owner and the lifecycle stage of an infrastructure platform.
```
# Create a valid hostname
locals {
hostname = "${var.project}_${var.stage}"
}
```
We define the following resource blocks file in the *network.tf*. First we define the network compartment. A group and policy block that allows administrators to read all the resources in the tenancy and manage all the networking resources, except security lists, internet gateways, IPSec VPN connections, and customer-premises equipment. For the vcn definition, we rely on a [terraform module][tf_module_vcn] that combines the layer three gateways with the CIDR.
```
# Create a compartment network management
resource "oci_identity_compartment" "net" {
#Required
compartment_id = var.net
name = "${var.project}_network"
description = "Compartment to manage network for ${var.project}"
#Optional
enable_delete = false // true will cause this compartment to be deleted when running `terrafrom destroy`
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
# Create the network administrator role
resource "oci_identity_group" "netops" {
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}_netops"
description = "Group for the network administrator role"
#Optional
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
# Define a the administration policies for network administrators
resource "oci_identity_policy" "netops" {
name = "netops"
description = "Policies for the network administrator role"
compartment_id = var.tenancy_ocid
statements = [
"ALLOW GROUP ${oci_identity_group.netops.name} to manage vcns IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage subnets IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage route-tables IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage dhcp-options IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage drgs IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage cross-connects IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage cross-connect-groups IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage virtual-circuits IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage vnics IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage vnic-attachments IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to manage load-balancers IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to use virtual-network-family IN TENANCY",
"ALLOW GROUP ${oci_identity_group.netops.name} to read all-resources IN TENANCY",
]
}
# Launch the base network
module "vcn" {
source = "oracle-terraform-modules/vcn/oci"
version = "2.2.0"
# required inputs
compartment_id = oci_identity_compartment.net.id
drg_service_name = "${var.project}_${var.stage}_DRG"
region = local.home_region
vcn_dns_project = local.hostname
vcn_name = "${var.project}_${var.stage}_VCN"
#internet_gateway_route_rules = list(object({ destination = string destination_type = string network_entity_id = string description = string }))
#nat_gateway_route_rules = list(object({ destination = string destination_type = string network_entity_id = string description = string }))
# optional inputs
create_drg = var.enable_routing
internet_gateway_enabled = var.enable_internet
project_stage = local.hostname
lockdown_default_seclist = true
nat_gateway_enabled = var.enable_nat
service_gateway_enabled = var.private_service
vcn_cidr = var.cidr
tags = { "module": "oracle-terraform-modules/vcn/oci", "terraformed": "yes", "budget": 0, "stage": var.stage }
}
```
In the *output.tf* file we add the reference to the module output.
```
# VCN parameter returns
output "vcn_id" { value = module.vcn.vcn_id }
output "ig_route_id" { value = module.vcn.ig_route_id }
output "nat_gateway_id" { value = module.vcn.nat_gateway_id }
output "nat_route_id" { value = module.vcn.nat_route_id }
```
## Service Operation
Compartments denote a demarcation for administrator domains in OCI. A compartment membership determines the privilige to add, change or delete resources. For define our compartment structure with the [ITIL][itil_web] model in mind. The first compartment defines the working environment for [service operators][itil_operation] and enables processes like incident or problem management. While ITIL distinguishes between [technical management services][itil_technical] and [application management services][itil_application], we rely on Infrastructure as a Servce and separate network- and database-manager in distinct compartments. On the application layer we distinguish between application management and application development. The later compromises platform services and allows to define an own code chain, meanwhile application managers receive the necessary rights to deploy and manage binaries. The definitions are captured in the `~/starter/operation.tf` template.
[<img alt="Cloud Operating Model" src="doc/image/itil_cloud.png" title="Cloud Operating Model">][itil_operation]
First, we create a set of roles with priviledged access to operation data and tools. Cloud operators that make sure that services are delivered effectively and efficiently. This includes fulfilling of user requests, resolving service failures, fixing problems, as well as carrying out routine operational tasks. These roles get provisiones in form of groups. Group policies allow to define the different administrator roles on a granular level. Initially we stick to four groups: a cloud account adminstrator, security manager, user manager and "readonly" e.g. for auditors. In HCL we use a [complex variable type][tf_type], a map, to describe the different roles.
```
# the base set of operator roles
variable "operator" {
type = map
default = {
"cloudops" = [
"ALLOW GROUP tenant to read users IN TENANCY",
"ALLOW GROUP tenant to read groups IN TENANCY",
"ALLOW GROUP tenant to manage users IN TENANCY",
"ALLOW GROUP tenant to manage groups IN TENANCY where target.group.name = 'Administrators'",
"ALLOW GROUP tenant to manage groups IN TENANCY where target.group.name = 'secops'",
]
"iam" = [
"ALLOW GROUP userid to read users IN TENANCY",
"ALLOW GROUP userid to read groups IN TENANCY",
"ALLOW GROUP userid to manage users IN TENANCY",
"ALLOW GROUP userid to manage groups IN TENANCY where all {target.group.name ! = 'Administrators', target.group.name ! = 'secops'}",
]
"secops" = [
"ALLOW GROUP security to manage security-lists IN TENANCY",
"ALLOW GROUP security to manage internet-gateways IN TENANCY",
"ALLOW GROUP security to manage cpes IN TENANCY",
"ALLOW GROUP security to manage ipsec-connections IN TENANCY",
"ALLOW GROUP security to use virtual-network-family IN TENANCY",
"ALLOW GROUP security to manage load-balancers IN TENANCY",
"ALLOW GROUP security to read all-resources IN TENANCY",
]
"readonly" = [
"ALLOW GROUP read_only to read all-resources IN TENANCY"
]
}
}
```
We modify the group resource to reflect the list of roles. In a later stage we will use an own resource to assign the user accounts to one of these roles. From a terraform perspective we introduce a loop typ. With [count][tf_count] we create an ordered list and we can use the index to refer to the stored value. While \[each.key\] loops through the user list, \[0\] refers to the first group.
```
# Create a service operation compartment
resource "oci_identity_compartment" "operation" {
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}${var.stage}_ops"
description = "Compartment to manage ${var.project} ${var.stage} services"
#Optional
enable_delete = false // true will cause this compartment to be deleted when running `terrafrom destroy`
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
resource "oci_identity_group" "operators" {
provider = oci.home
for_each = var.operator
#Required
compartment_id = var.tenancy_ocid
name = each.key
description = "group for the ${each.key} role"
#Optional
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
resource "oci_identity_policy" "operation" {
provider = oci.home
for_each = var.operator
#Required
compartment_id = var.tenancy_ocid
name = each.key
description = "Policies for the ${each.key} operator"
statements = each.value
}
```
In the output file we create a map containing the name and respective OCID for the new defined roles.
```
output "operator" {
value = {
for operator in oci_identity_group.operators:
operator.name => operator.id
}
}
```
#### Key Vault
Vault is a cloud service that allows operators to manage encryption keys that protect data and secret credentials and to secure resource access. Vaults store master encryption keys and secrets that are used in configuration files and/or code. A secret is anything that requires controled access, such as API keys, passwords, certificates, or cryptographic keys.
After that we create the compartments for technical- and application manager. The tree structure is created, using the compartment_id argument. While the "resource" compartments refer to the tenancy_ocid, the service compartments refer to the parent compartment ID. This enables us to use [loops][tf_loop], counts and conditionals. Using lists helps to avoid the creation multiple blocks and allows to adjust the tree compartment structure, without rewriting the code.
```
// Create a vault to store secrets
output "key_id" {
value = oci_kms_key.main.id
}
resource "oci_kms_vault" "ops" {
compartment_id = var.compartment_id
service_name = "${var.project}ops_vault"
vault_type = "DEFAULT" # or "VIRTUAL_PRIVATE"
}
resource "oci_kms_key" "main" {
#Required
compartment_id = var.compartment_id
service_name = "${var.project}_${var.stage}_key"
management_endpoint = data.oci_kms_vault.ops.management_endpoint
key_shape {
#Required
algorithm = "AES"
length = 32
}
}
// Gets the detail of the vault.
data "oci_kms_vault" "ops" {
#Required
vault_id = oci_kms_vault.ops.id
}
data "oci_kms_keys" "ops" {
#Required
compartment_id = var.compartment_id
management_endpoint = data.oci_kms_vault.ops.management_endpoint
filter {
name = "service_name"
values = oci_kms_key.main.service_name
}
}
```
#### Management Bucket
Within the ops compartment we define a storage bucket to store files that need to be accessible to all operators. Examples are log files or terraform state file. We add the following resource blocks to the *ops.tf* template.
```
resource "oci_objectstorage_bucket" "ops" {
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}_${stage}_tfstate"
namespace = "${var.project}_${stage}_ops"
#Optional
access_type = var.bucket_access_type
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
kms_key_id = oci_objectstorage_kms_key.main.id
}
```
The complete [template][code_...] is stored in the code directory. In the compartment structure we break the technical management domain up into network and data management services. In addition, a tree structure for application management services enables operators to integrate multiple in- and external application owner, without giving up control over the main digital assets.
### Data Management
Next we define the data management domain in order to maintain [data gravity][ref_dgravity] accross the four infrastructure deployment models for application developer and service operator. A [boolean variable][tf_boolean] to enable or dsiable the creation of the "data" compartment.
```
variable "create_data" { default = false }
```
Initially, the *data.tf* contains only one resource definitions. We use the [count method][tf_count] to en- or disable the compartment creation.
```
# Create a data management compartment
resource "oci_identity_compartment" "data" {
count = var.create_data ? 1 : 0
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}_data_domain"
description = "Compartment to manage persistent data for ${var.project}"
#Optional
enable_delete = false // true will cause this compartment to be deleted when running `terrafrom destroy`
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
```
Admin policies define the tasks that a user can perform. We define groups for database administrators as well as file system manager and [assign policies][tf_data_policies]. Group memberships enable domain administrators to perform the tasks associated with these [policies][tf_policy].
```
# Create a file system administrator role
resource "oci_identity_group" "fsadmin" {
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}_${var.stage}_fs_administrator"
description = "Group for manager of network attached storage"
#Optional
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
# Define a the administration policies for storage administrators
resource "oci_identity_policy" "fsadmin" {
name = "${var.project}_${var.stage}_fs_administrator_policy"
description = "Policies for manager of network attached storage"
compartment_id = var.tenancy_ocid
statements = [
"ALLOW GROUP ${oci_identity_group.fsadmin.name} to manage object-family IN TENANCY",
"ALLOW GROUP ${oci_identity_group.fsadmin.name} to manage volume-family IN TENANCY",
"ALLOW GROUP ${oci_identity_group.fsadmin.name} to read all-resources IN TENANCY",
]
}
# Create the database administrator role
resource "oci_identity_group" "dbadmin" {
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}_${var.stage}_database_admin"
description = "Group for the network administrator role"
#Optional
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
# Define a the administration policies for database administrators
resource "oci_identity_policy" "database_admin" {
name = "${var.project}_${var.stage}_database_admin_policy"
description = "Policies for the database administrator role"
compartment_id = var.tenancy_ocid
statements = [
"ALLOW GROUP ${oci_identity_group.dbadmin.name} manage database-family IN TENANCY",
"ALLOW GROUP ${oci_identity_group.dbadmin.name} read all-resources IN TENANCY",
]
}
```
A data block that we call "trunk" creates a list of compartments attached to the root compartment.
```
# List root compartments
data "oci_identity_compartments" "trunk" {
#Required
compartment_id = var.tenancy_ocid
#Optional
access_level = "ANY" //ANY or ACCESSIBLE
# applies only when you perform listCompartments on the tenancy
#compartment_id_in_subtree = "ANY"
}
```
These data blocks are referenced in *output.tf*.
```
# Output compartment details for resource compartments
output "resources" {
value = data.oci_identity_compartments.resources
}
```
### Application Management
For the application management domain we add a [variable containing list of application domains][tf_list].
```
variable "create_app" { default = false }
```
The *app.tf* it contains two resource definitions, one for the main app compartment and one for the sub-compartments. The compartment structure is reflected using a [complex variable type][tf_variable] that enables us to create list of sub-compartments.
```
# Create a main compartment application management (https://wiki.en.it-processmaps.com/index.php/ITIL_Application_Management)
resource "oci_identity_compartment" "app" {
count = var.create_app ? 1 : 0
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}_applications"
description = "Compartment to manage applications for ${var.project}"
#Optional
enable_delete = false // true will cause this compartment to be deleted when running `terrafrom destroy`
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
# Create the system operator role
resource "oci_identity_group" "sysadmin" {
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
name = "${var.project}_${var.stage}_sysadmin"
description = "Group for the system operator role"
#Optional
# defined_tags = {"terraformed": "yes", "budget": 0, "stage": var.stage}
freeform_tags = {"source": "/code/setup", "Parent"="root"}
}
resource "oci_identity_policy" "sysadmin" {
name = "${var.platform_stage}_${var.environment_stage}_system_administrator_policy"
description = "Policies for the system operator role"
compartment_id = var.tenancy_ocid
statements = [
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to manage instance-family IN TENANCY where all {target.compartment.name=/*/, target.compartment.name!=/${var.project}_network/}",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to manage object-family IN TENANCY where all {target.compartment.name=/*/, target.compartment.name!=/${var.project}_network/}",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to manage volume-family IN TENANCY where all {target.compartment.name=/*/ , target.compartment.name!=/${var.project}_network/}",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to use load-balancers IN TENANCY where all {target.compartment.name=/*/ , target.compartment.name!=/${var.project}_network/}",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to use subnets IN TENANCY where target.compartment.name=/${var.project}_network/",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to use vnics IN TENANCY where target.compartment.name=/${var.project}_network/",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to use vnic-attachments IN TENANCY where target.compartment.name=/${var.project}_network/",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to manage compartments in Tenancy where all {target.compartment.name=/*/ , target.compartment.name!=/${var.project}_network/, target.compartment.name!=/${var.project}_applications/}",
"ALLOW GROUP ${oci_identity_group.sysadmin.name} to read all-resources IN TENANCY",
]
}
```
We loop over our platform- and the services block, using the [count method][tf_count]. *Count* refers to keys using the respective index number `[count.index]`. The `${ }` construct allows to use variables inside a string. Freeform tags provide non-harmonized context information. After that we define the data blocks in the *sources.tf* to return the identifier for the compartments that are defined in the deployment plan.
```
# List app compartments
data "oci_identity_compartments" "apps" {
#Required
compartment_id = oci_identity_compartment.app.id
#Optional
access_level = "ANY" //ANY or ACCESSIBLE
# applies only when you perform ListCompartments on the tenancy
#compartment_id_in_subtree = "ANY"
}
```
These data blocks are referenced in *output.tf*.
```
# Output compartment details for app compartments
output "apps" {
value = data.oci_identity_compartments.apps
}
```
A complete [compartment.tf][code_compartment] examle file is stored in the code directory.
## User Management
After defining the compartment structure we create the initial admin users, leveraging the *user.tf* template. with the basic [resource block][tf_user] amd the [user data block][tf_data_users]. We define a variable that represents the admin profile and insert the variable at the top of our template. Information like the name, email and description is captured in a tuple, another [complex variable type][tf_variable]. User profiles allow tenant administrators to manage user information; manage privilege, application, and service access; and grant users self-management for their own accounts and services.
```
variable "user" {
description = "user definition"
type = tuple([string, string, string, bool])
default = [ "user_name", "<EMAIL>", "ITIL Administrator", true ]
}
```
The oci_identity_user resource block creates the admin users, the oci_identity_ui_password block the password and the oci_identity_user_capabilities_management block sets the user capabilities.
```
resource "oci_identity_user" "user_name" {
provider = oci.home
#Required
compartment_id = var.tenancy_ocid
description = var.user[2]
name = var.user[0]
#Optional
#defined_tags = {"Operations.CostCenter"= "42"}
email = var.user[1]
freeform_tags = {"Framework" = "itil"}
}
resource "oci_identity_ui_password" "user_secret" {
provider = oci.home
user_id = oci_identity_user.user_name.id
}
resource "oci_identity_user_capabilities_management" "user_name" {
provider = oci.home
user_id = oci_identity_user.user_name.id
can_use_api_keys = false
can_use_auth_tokens = false
can_use_console_password = <PASSWORD>[3]
can_use_customer_secret_keys = false
can_use_smtp_credentials = false
}
```
### Assigning Roles
We defined a number of groups to manage the roles and responsibilites. A common definition of roles and responsibilites is provided by the [ITIL framework][itil_roles]. The complete model is pretty broad, our specific concern is service operation and initially created the following administrator roles
| **Group** | **Permissions** |
| :---------------- |:----------------------|
| *cloud account* | Manage users. <br> Manage the Administrators and Netsecopss groups. <br><br> **Note**: Oracle creates the Administrators group when you subscribe to Oracle Cloud. The users in this group have full access to all the resources in the tenancy, including managing users and groups. Limit the membership to this group. |
| *security* | Read all the resources in the tenancy. <br> Manage security lists, internet gateways, customer-premises equipment, IPSec VPN connections, and load balancers. <br> Use all the virtual network resources.|
| *user* | Manage users. <br> Manage all the groups except Administrators and Netsecopss.|
| *network* | Read all the resources in the tenancy. <br> Manage all the networking resources, except security lists, internet gateways, IPSec VPN connections, and customer-premises equipment. |
| *system* | Read all the resources in the tenancy. <br> Manage the compute and storage resources. <br> Manage compartments. <br> Use load balancers, subnets, and VNICs. |
| *storage* | Read all the resources in the tenancy. <br> Manage the object storage and block volume resources. |
| *database* | Read all the resources in the tenancy. <br> Manage the database resources. |
| *Auditor (ReadOnly)* | View and inspect the tenancy. This group is for users who aren't expected to create or manage any resources (for example, auditors and trainees). |
```
resource "oci_identity_user_group_membership" "operator" {
provider = oci.home
compartment_id = var.tenancy_ocid
for_each = var.user_names
user_id = oci_identity_user.admins[each.key].id
group_id = oci_identity_group.itsm[0].id
}
```
With the oci_identity_ui_password data block we retrieve all information related to the password resource before we create the output block for the user details.
```
data "oci_identity_ui_password" "user_name" {
#Required
user_id = oci_identity_user.user_name.id
}
output "user_details" {
value = oci_identity_ui_password.user_secret
}
```
The template will return the user details including the UI password. Passwords will be generated and shown at the `terraform apply` stage. When we use the `terraform output` command terraform will not return the passwords. The complete [template][code_user] is stored in the code directory.
[< provider][provider] | [+][home] | [db-infra >][db-infra]
<!--- Links -->
<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
include::links.adoc[]
= Networking
One of the unique features of OCI is the {oci-l2}[virtual layer 2 network] design. Compared to the common network overlays in public clouds, this design provides the necessary control to create isolated data center on a shared infrastructure pool. Packet encapsulation shields private traffic on a shared network backbone to the extend of defining overlapping IP ranges. This allows for a multi-tenant design on the infrastructure layer, and prevents developers and operators to rely complex procedures building and maintaining multi-tenant applications. The following diagram exemplifies the topology in a multi data centre region.
[#img-Topology]
.Network Network
image::doc/image/topology.png[Network Topology]
While network overlyas obligate VLANs on provider managed switches to connect server on networks networks, OCI launches a smart network interface with every server, exposing a Layer 3 switch for network seperation. The smart NIC operates at both Layer 2 and Layer 3, allowing devices to communicate with one another without going through a dedicated router. External traffic is still being routed and transferred between virtual cloud networks using gateways, but the internal routing is done by a private switch instead of a provider managed router. Network administrator, not the provider configure the physical device manage traffic between network segments.
== Network Segmentation
Network segmentation is the practice of splitting a computer network into independent network segment. Objectives of such split are for reflecting operational responsibilities, boosting performance and improving security.
[#img-Segementation]
.Network Segmentation
image::doc/image/segmentation.png[Network Segmentation]
=== Improve Security
When a cyber-criminal gains unauthorized access to a network, segmentation provides effective controls to limit further movement across the network. Security standards like CIS, PCI, C5 etc. provide guidance on creating clear separation of data within a network. A sound policy entails segmenting the network into multiple zones, with varying security requirements, and rigorously enforcing the policy on what is allowed to move from zone to zone.
=== Control Access
Defining segments allows to implement a set of policies that protect network nodes from unauthorized access. Using the OCI API we configure routers, switches and firewalls to work together with ID management systems and ensure the information system is operating securely.
=== Contain network problems
Separating Virtual Cloud Networks (VCN), is limiting the effect of local failures on other parts of network. Improved performance is achieved, because on a segmented network there are fewer hosts per subnetwork, thus minimizing local traffic.
Even though we need to distinguish the physical topology of single- and multi-data centre regions, the logical network layer remains the same, because the data center are connected through a close network and packet forwarding relys on {ref-hostrouting}[host routing mechanisms]. Regional subnets enable operators to launch multi-data center networks for both, private and public cloud services. Beside the CIDR the VCN definition contains the Dynamic Routing Gateway (DRG) as IP peer and host for network functions like Internet Connectivity, Network Address Translation (NAT) or Private-Public Service Communication.
== Subnetting
A subnetwork or subnet is a logical subdivision of an IP network. We break a network segement further down into smaller IP networks. Hosts that belong to the same subnet are addressed with an identical most-significant bit-group in their IP addresses. This results in the logical division of an IP address into two fields: the network number or routing prefix and the rest field or host identifier. The rest field is an identifier for a specific host or network interface.
The routing prefix is expressed in {ref-cidr}[Classless Inter-Domain Routing (CIDR)] notation, written as the first address of a network, followed by a slash character (/), and ending with the bit-length of the prefix. For example, 10.0.0.0/16 is the prefix of the Internet Protocol version 4 network starting at the given address, having 24 bits allocated for the network prefix, and the remaining 8 bits reserved for host addressing. Addresses in the range 198.51.100.0 to 198.51.100.255 belong to this network. The IPv6 address specification 2001:db8::/32 is a large address block with 296 addresses, having a 32-bit routing prefix.
In the ocloud framework we rely on Terraforms cidrsubnet function to separate a VCN into subnets. The number in the mal only refers to newbits, netnums are computed automatically.
```hcl
module "network_segment" {
address_space = {
cidr_block = "10.0.0.0/24"
}
subnets = {
# Provide a list with newbits for the cidrsubnet function
app = 1
db = 2
web = 2
}
```
The functions assigns consecutive IP address blocks to each of the requested subnets, packing them densely in the address space. The `subnet_map` output is then a map from the given `name` strings to the allocated CIDR prefixes:
```hcl
{
web = "10.0.0.0/26"
db = "10.0.0.64/26"
app = "10.0.0.128/25"
}
```
The `new_bits` values are the number of _additional_ address bits to use for numbering the new networks. Because network `web` has a `new_bits` of 2, and the base CIDR block has an existing prefix of 24, its final prefix length is 24 + 2 = 26. `app` has a `new_bits` of 1, so its final prefix length is only 24 + 1 = 25 bits.
include::cidr.adoc[]
If the order of the given subnets is significant, the alternative output `subnet_map` is a list with an object for each requested network that has the following attributes:
* `name` is the same name that was given in the request.
* `cidr_block` is the allocated CIDR prefix for the network.
If you need the CIDR block addresses in order and don't need the names, you can use `module.network_segment.subnet_map.name` to obtain that flattened list.
=== Changing Networks Later
When initially declaring your network addressing scheme, you can declare your subnets in any order. However, the positions of the subnets in the request list affects the assigned subnet numbers, so when making changes later it's important to take care to avoid implicitly renumbering other subnets.
The safest approach is to only add new subnets to the end of the list and to never remove an existing subnet or or change its `new_bits` value. If an existing allocation becomes obsolute, you can delete the "network_domain" in the respective template file and set its name explicitly to `null` in the "net" template to skip allocating it a prefix but to retain the space it previously occupied in the address space:
```hcl
module "network_segment" {
subnets = [
{
name = null # formerly "app", but no longer used
new_bits = 1
},
{
name = "db"
new_bits = 2
},
]
}
```
In the above example, the `subnet_cidr_blocks` output would have the
following value:
```
{
db = "10.0.0.0/26"
}
```
`app` has been excluded, but its former prefix `10.0.0.64/26` is now skipped altogether so `db` retains its allocation of `10.0.0.64/26`. Because the `subnets` output is a list that preserves the element indices of the requested networks, it _does_ still include the skipped networks, but with their `name` and `cidr_blocks` attributes set to null:
```
[
{
name = null
new_bits = 1
cidr_block = null
},
{
name = "db"
new_bits = 2
cidr_block = "10.0.0.64/26"
},
]
```
We don't recommend using the `subnets` output when subnets are skipped in this way, but if you _do_ need to preserve the indices while excluding the null items you could use a `for` expression to project the indices into attributes of the objects:
```
[
for i, n in module.network_segment.subnets : {
index = i
name = n.name
cidr_block = n.cidr_block
}
if n.cidr_block != null
]
```
Certain edits to existing allocations are possible without affecting subsequent allocations, as long as you are careful to ensure that the new allocation occupies the same address space as whatever replaced it. For example, it's safe to replace a single allocation anywhere in the list with a pair of consecutive allocations whose `new_bits` value is one greater. If you have an allocation with `new_bits` set to 4, you can replace it with two allocations that have `new_bits` set to 5 as long as those two new allocations retain their position in the overall list:
```hcl
networks = [
# "app-1" and "app-2" replace the former "app", taking half of the
# former address space each: 10.0.0.128/26 and 10.0.0.192/26, respectively.
{
name = "app-1"
new_bits = 2
},
{
name = "app-2"
new_bits = 2
},
# "db" is still at 10.0.0.64/26
{
name = "db"
new_bits = 2
},
]
```
When making in-place edits to existing subnets, be sure to verify that the result is as you expected using `terraform plan` before applying, to avoid disruption to already-provisioned subnets that you want to keep.
## Network Allocations in a CSV file
It may be convenient to represent your table of network definitions in a CSV file rather than writing them out as object values directly in the Terraform configuration, because CSV allows for a denser representation of such a table that might be easier to quickly scan.
You can create a CSV file `subnets.csv` containing the following and place it inside your own calling module:
```
"name","newbits"
"web","2"
"","2"
"db","2"
```
Since CSV cannot represent null, we'll use the empty string to represent an obsolete subnet that must still have reserved address space. When editing the CSV file after the resulting allocations have been used, be sure to keep in mind the restrictions under [_Changing Networks Later_](#changing-networks-later) above.
We can use Terraform's `csvdecode` function to parse this file and pass the result into the CIDR Subnets function:
```hcl
module "network_segment" {
...
subnets = [
for r in csvdecode(file("${path.module}/subnets.csv")) : {
name = r.name != "" ? r.name : null
new_bits = tonumber(r.new_bits)
}
]
}
```
{ocloud-base}[<<] | {ocloud-tf}[<] | {ocloud-intro}[+] | {ocloud-name}[>] | {ocloud-links}[>>]
<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
== Providers
[cols="1,1",options="header"]
|===
|Name
|Version
|oci
|n/a
|===
== Dependencies
* https://github.com/oracle-devrel/terraform-oci-ocloud-landing-zone/tree/main/component/admin_section[Administrator Section]
== Module
```hcl
module "application_host" {}
```
When an operator creates an application host, they can select the size of the virtual machine that is provisioned for each instance. VM sizes are simplified into T-shirt-sized service blocks, where the next-largest block is twice the size.
[cols="1,1,1,1",options="header"]
|===
| Size | oCPU | RAM (GB) | HD (GB)
| Micro | 1 | 2 | 25
| Small | 2 | 4 | 50
| Medium | 4 | 8 | 100
| Large | 8 | 16 | 200
| XL | 16 | 32 | 400
|===
== Resources
* https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/core_services[oci_core_services]
== Inputs
[cols="1,1,1,1,1",options="header"]
|===
| Name | Description | Type | Default | Required
|===
== Outputs
[cols="1,1,1",options="header"]
|===
|===
<file_sep>#!/bin/bash
# Copyright 2017, 2021 Oracle Corporation and/or affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
if [ ${ol} = 8 ]; then
dnf config-manager --enable ol8_developer && dnf -y install python3-oci-cli
else
yum -y -t update --security
yum install -y python3
pip3 install oci-cli
fi
sed -i -e "s/autoinstall\s=\sno/autoinstall = yes/g" /etc/uptrack/uptrack.conf
uptrack-upgrade -y<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
image::https://oci-resourcemanager-plugin.plugins.oci.oraclecloud.com/latest/deploy-to-oracle-cloud.svg[Deploy on Oracle Cloud, link="https://cloud.oracle.com/resourcemanager/stacks/create?zipUrl=https://github.com/oracle-devrel/terraform-oci-ocloud-landing-zone/archive/refs/heads/main.zip"]
== The OCloud Framework: Landing Zone
image:https://img.shields.io/badge/license-UPL-green[link="LICENSE"]
image:https://sonarcloud.io/api/project_badges/quality_gate?project=oracle-devrel_terraform-oci-ocloud-landing-zone[Quality gate, link="https://sonarcloud.io/dashboard?id=oracle-devrel_terraform-oci-ocloud-landing-zone"]
=== Introduction
The "ocloud" framework helps operators to set up a hosting environment for enterprise applications in Oracle Cloud Infrastructure (OCI). While launching a new resource in OCI is a matter of pressing a button, replacing on-prem infrastructure and provisioning a virtual data center or a private cloud is more challenging. Numberous services need to be configured and to be activated, which requires a deep understanding of various configuration options build into Oracle's automated infrastructure platform.
[#img-architecture]
.Base Architecture
image::doc/image/base_architecture.png[Base Architecture]
This code represents a baseline configuration for hosting three tier applications. System administrators automate the provisioning processes for infrastructure components with the link:https://docs.oracle.com/en-us/iaas/Content/ResourceManager/Concepts/resourcemanager.htm[resource manager]. A network will be setup, firewall rules defined and naming conventions are ensured accross multiple service components. The code structure reflects a separation of duties, typically found in an IT organization that works according to ITIL and allows for a multi-tenant service operation.
=== Getting Started
The code is written for the resource manager service in Oracle Cloud Infrastructure. It can either be directly link:https://cloud.oracle.com/resourcemanager/stacks/create?zipUrl=https://github.com/oracle-devrel/terraform-oci-ocloud-landing-zone/archive/refs/heads/main.zip[deployed into an existing account] or be cloned into a new repository and than be configured as dynamic code source.
=== Customizing the Framework
The first layer of code addresses the needs of system adminstrators. It is written in HCL and captures the parameters that customize the provisioning processes for OCI core resources.
[#img-structure]
.Code Structure
image::doc/image/code_structure.png[Code Structure]
The default repository separates four templates:
* link:operation.tf[Operations] prepares a working environment priviledged operators with an "ops" compartment that contains base roles like the cloud "super admin".
* link:network.tf[Network] provisions an initial network segment and creates a "presentation" domain for internet facing portals beside the "netops" compartment and role.
* link:database.tf[Database] defines the infrastructure for database hosting with access via port 1521-1522 in addition to the "db" compartment and admin role.
* link:application.tf[Application] creates an application management domain, the an app compartment, the sysops role and deploys an operator for remote scripts.
The ops and the net deployment templates are obligatory, the db and the app templates are optional. The bastion service connects to an operator in the application domain and allows to enter all domains via SSH.
==== Components
Templates refer to terraform modules, rather than addressing resource blocks directly. Platform components combine multiple resources logically into Terraform modules. These modules contain best practices collected throughout numberous projects and remain subject to change. Initially we provide the following modules:
* link:component/admin_section[Administrator Section] is the compartment block combined with groups an policies that define a working environment for cloud and security operators
* link:component/network_segment[Network Segment] defines the compart and role for network administrators together with a Virtual Cloud Network (VCN) incl. Dynamic Routing Gateway and gateways for NAT, Intenrnet and Oracle Services
* link:component/network_domain[Network Domain] the necessary subnets with portfilters and routing rules to host the application tiers
* link:component/application_host[Application Host] launches a compute node and executes the respective configuration scripts are executed
==== Resource Interfaces
Modules deploy a variety of different resources, like infrastructure components, predefined cloud services, applications or third party software products. Usually we employ the terraform service provider to provision resources, however, comand line scripts, API or SDK are additional options.
[cols="1,1,1,1,1",frame=ends,grid=rows,stripes=hover,options="header"]
|===
| | Admin Section | Network Segment | Network Domain | Application Host
| Core | Compartment | VCN, DRG | Subnet | host
| Routing | | DRG, IGW, NAT, SGW | |
| Roles | Group, Policy | | |
| Portfilter | | | Sec. List | Sec. Group
| SSH | | | Bastion | Session
|===
==== Prerequisites
Code is written in HashiCorp Configuration Language (HCL), includes data stored in JSON format and cloud init scripts. We use the OCI Resource Manager service to install, configure, and manage Terraform code in order to support a fast adoption of the "infrastructure-as-code" model.
* link:https://www.oracle.com/cloud/free/[Oracle Cloud Infrastructure (OCI) Account]
* link:https://docs.oracle.com/en-us/iaas/Content/ResourceManager/Concepts/resourcemanager.htm[Oracle Resource Manager]
* link:https://www.terraform.io[HashiCorp Terraform]
* link:https://registry.terraform.io/providers/hashicorp/oci/latest[Terraform Service Provider for OCI]
* link:https://registry.terraform.io/providers/hashicorp/time/latest[Terraform Time Service Provider]
* link:https://cloudinit.readthedocs.io/en/latest/[Cloud Init]
The script is meant for a initial tenancy setup and provisions global resources like compartments and groups. The naming should be unique though. While compartment names are constructed to avoid conflicts, groups are resources and name conflicts can be avoided to check existing groups against the link:doc/naming.adoc[naming conventions].
=== Notes/Issues
* Using Terraform 1.0 produces a warning about missing provider definitions in the module directories, which can be ignored
* It is recommended to run the first "terraform apply" without bastion session enabled. Enabling the bastion session in the first run will produce an error message. Run the "apply" a second time resolves the issue.
* Terraform destroy will an error message around missing dependencies. Repeating runs will overcome this issue.
* Destroying compartments should be an exception and can take a long time. Best practice is destroying all other resources first, before destroying the compartments in a separate run. In the default setup, the "enable_delete" flag prevent unintensional destroy of compartments
=== URLs
This repository is intended to be used with the Oracle Resource Manager. Using the "Deploy to Oracle Cloud" button requires users to link:https://www.oracle.com/cloud/sign-in.html[sign in].
=== Contributing
This project is open source. Please submit your contributions by forking this repository and submitting a pull request! Oracle appreciates any contributions that are made by the open source community.
=== License
Copyright (c) 2021 Oracle and/or its affiliates.
Licensed under the Universal Permissive License (UPL), Version 1.0.
See link:LICENSE[LICENSE] for more details.<file_sep>// Copyright (c) 2020 Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
= Glossary
== Service Configuration
[cols="1,1,1", options="header"]
|===
|Name
|Description
|Type
|tenancy_id
|The OCID of the tenancy
|`string`
|service_id
|The OCID of the encapsulating service compartment
|`string`
|service_name
|The name of the encapsulating compartment, used to define component names
|`string`
|display_name
|extends the service name with an identifier for the administrator domain
|`string`
|compartment_id
|The default compartment OCID to use for resources (unless otherwise specified), usually a child compartment to the `service_id`
|`string`
|vcn_id
|The OCID of the a vcn deployed through "network segment" component
|`string`
|anywhere
|CIDR range representing the egress traffic of a network segment or domain
|`string`
|defined_tags
|The different defined tags that are applied to each object by default
|`map(any)`
|freeform_tags
|The different freeform tags that are applied to each object by default
|`map(any)`
|source
|Source URL for the landing zone code, this URL will be exposed in resource descriptions
|`string`
|enable_delete
|true or false, determines to protect the resource against destroy or not
|`bool`
|create
|true or false, determines to create a resource or not
|`bool`
|===
== Admin Section
[cols="1,1,1,1", options="header"]
|===
|Name
|Description
|Type
|Resource
|parent
|OCID of the parent compartment
|`string`
|compartment
|roles
|Role names and policies, defined on tenancy root level, unique names are defined based on the project and owner names
|`map(list(any))`
|group, policy
|===
== Network Segment
[cols="1,1,1,1", options="header"]
|===
|Name
|Description
|Type
|Resource
|address_spaces
|Network address prefix in CIDR notation that all of the requested subnetwork prefixes will be allocated within
|`map(string)`
|VCN
|subnet_list
|A list of objects describing requested subnetwork prefixes. new_bits is the number of additional network prefix bits to add, in addition to the existing prefix on base_cidr_block
|`map(number)`
|VCN
|block_nat_traffic
|Whether or not to block traffic through NAT gateway
|`bool`
|Service Gateway
|service_gateway_cidr
|The OSN service cidr accessible through Service Gateway
|`string`
|Service Gateway
|===
== Network Domain
[cols="1,1,1,1", options="header"]
|===
|Name
|Description
|Type
|Resource
|domain
|Description
|`string`
|subnet
|cidr_block
|IP range for each subnet, a domain covers one or more contiguous IPv4 CIDR blocks
|`string`
|subnet
|prohibit_public_ip_on_vnic
|true or false, determines whether a resource can receive a public IP or not
|`bool`
|subnet
|dhcp_options_id
|n/a
|`string`
|subnet
|route_table_id
|Parameters for each route table to be managed
|`string`
|subnet
|ingress
|n/a
|`list(list(any))`
|tcp_ports
|client_allow_cidr
|CIDR for clients that are allowed to access a resource
|`list(string)`
|bastion
|max_session_ttl
|Time to live for a host or a service
|`number`
|bastion
|===
== Application Host
[cols="1,1,1,1", options="header"]
|===
|Name
|Description
|Type
|Resource
|count
|Number of identical instances to launch from a single module
|`number`
|
|timeout
|Timeout setting for creating instance
|`string`
|
|flex_memory_in_gbs
|(Updatable) The total amount of memory available to the instance, in gigabytes
|`number`
|
|flex_ocpus
|(Updatable) The total number of OCPUs available to the instance
|`number`
|
|shape
|The shape of an instance
|`string`
|
|source_type
|The source type for the instance
|`string`
|
|extended_metadata
|(Updatable) Additional metadata key/value pairs that you provide
|`map(any)`
|
|resource_platform
|Platform to create resources in
|`string`
|
|user_data
|Provide your own base64-encoded data to be used by Cloud-Init to run custom scripts or provide custom Cloud-Init configuration
|`string`
|
|timezone
|Default timezone for the server
|`string`
|
|assign_public_ip
|Whether the VNIC should be assigned a public IP address
|`bool`
|
|ipxe_script
|(Optional) The iPXE script which to continue the boot process on the instance
|`string`
|
|private_ip
|Private IP addresses of your choice to assign to the VNICs
|`list(string)`
|
|skip_source_dest_check
|Whether the source/destination check is disabled on the VNIC
|`bool`
|
|subnet_id
|The unique identifiers (OCIDs) of the subnets in which the instance primary VNICs are created
|`list(string)`
|
|vnic_name
|A user-friendly name for the VNIC
|`string`
|
|attachment_type
|(Optional) The type of volume. The only supported values are iscsi and paravirtualized
|`string`
|
|block_storage_sizes_in_gbs
|Sizes of volumes to create and attach to each instance
|`list(number)`
|
|boot_volume_size_in_gbs
|The size of the boot volume in GBs
|`number`
|
|preserve_boot_volume
|Specifies whether to delete or preserve the boot volume when terminating an instance
|`bool`
|
|use_chap
|(Applicable when attachment_type=iscsi) Whether to use CHAP authentication for the volume attachment
|`bool`
|
|=== | b07b8c1dbf53f05f12c6bdb432408ca9790b07b6 | [
"Markdown",
"AsciiDoc",
"Shell"
] | 11 | AsciiDoc | lschubert/terraform-oci-ocloud-landing-zone | c3c006ada3d0d0b61a4dc14ebfa869fe8d240f70 | 12cb33a06f684f5f69dbdaaf58b36233c2d16814 |
refs/heads/master | <repo_name>MarcoPianta/ing-sw-2019-34<file_sep>/src/main/java/Model/Colors.java
package Model;
import java.io.Serializable;
/**
* This enumeration lists the color used in the game (for example for players or squares)
*/
public enum Colors implements Serializable {
BLUE("blue"),
GREEN("green"),
WHITE("white"),
YELLOW("yellow"),
VIOLET("violet"),
RED("red"),
NULL("null"); //This value is used only from view to indicates that there is no color set
private String abbreviation;
private Colors(String abbreviation) {
this.abbreviation=abbreviation;
}
public String getAbbreviation(){
return abbreviation;
}
}
<file_sep>/src/main/java/Model/NormalSquare.java
package Model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class NormalSquare implements Serializable {
private CardAmmo ammo;
NormalSquare n;
NormalSquare e;
NormalSquare s;
NormalSquare w;
protected Colors color;
boolean spawn;
private String id;
public NormalSquare(NormalSquare sideN, NormalSquare sideE, NormalSquare sideS, NormalSquare sideW, Colors color, CardAmmo ammo) {
n = sideN;
e = sideE;
s = sideS;
w = sideW;
this.ammo = ammo;
this.color = color;
spawn = false;
}
public NormalSquare(Colors color){
n = null;
e = null;
s = null;
w = null;
ammo = null;
this.color = color;
}
public NormalSquare(){
n = null;
e = null;
s = null;
w = null;
ammo = null;
this.color = null;
}
public int setItems(Card card) {
this.ammo = (CardAmmo) card;
return 0;
}
/**
* This method is used to get the ammo on the NormalSquare(not to grab it)
* */
public CardAmmo getItem() {
if (this.ammo == null)
return null;
return ammo.copyCardAmmo();
}
private CardAmmo removeAmmo(){
if (this.getItem() == null)
return null;
CardAmmo card = ammo;
setItems(null);
return card;
}
/**
* This method Override the method of NormalSquare, it allows a BoardPlayer to grab one of the Item content by the NormalSquare
* */
public CardAmmo grabItem() {
return this.removeAmmo();
}
public boolean isSpawn() {
return spawn;
}
public NormalSquare getN() {
return n;
}
public NormalSquare getE() {
return e;
}
public NormalSquare getS() {
return s;
}
public NormalSquare getW() {
return w;
}
public Colors getColor() {
return color;
}
public List<CardWeapon> getWeapons() {
return new ArrayList<>();
}
public String getId() {
return id;
}
public void setN(NormalSquare n) {
this.n = n;
}
public void setE(NormalSquare e) {
this.e = e;
}
public void setS(NormalSquare s) {
this.s = s;
}
public void setW(NormalSquare w) {
this.w = w;
}
public void setId(String id) {
this.id = id;
}
}
<file_sep>/src/main/java/network/Server/Socket/SocketClientHandler.java
package network.Server.Socket;
import network.messages.Message;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
* This class is used to handle connection between client and server.
* It is used to read object sent from client and send object from the server to the client.
* The class implements Runnable interface because it must be run through threads created from server every time a new
* connection with a client is established.
* */
public class SocketClientHandler implements Runnable{
private Socket socket;
private Integer token;
private SocketServer server;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;
private boolean stop;
/**
* The constructor initialize the attribute of the class with the inputStream coming from the client and the
* outputStream outgoing from the server.
*
* @param socket this is the socket of which the connection must be handled
* */
public SocketClientHandler(Socket socket, Integer token, SocketServer server) {
this.socket = socket;
this.token = token;
this.server = server;
try {
this.out = new ObjectOutputStream(socket.getOutputStream());
this.in = new ObjectInputStream(socket.getInputStream());
}catch (IOException e){
//TODO logger
}
this.stop = false;
}
/**
* This method is used to send message to the server.
* @param message
*/
public void respond(Message message) {
try {
out.writeObject(message);
out.flush();
} catch (IOException e) {
//TODO catch exception, logger
}
}
/**
* This is the method run when a new instance of this class is started.
* It read the input stream to get the messages sent from the client, when a message is received is forwarded to the
* main server.
* */
@Override
public void run(){
while (!stop){
if (socket.isConnected()) {
try {
Message message = (Message) in.readObject();
if (message != null)
server.onReceive(message);
} catch (IOException | ClassNotFoundException e) {
//TODO logger
}
}
else if (socket.isClosed()){
server.removeClient(token);
}
}
}
}
<file_sep>/src/main/java/Model/PowerUpEnum.java
package Model;
import java.io.Serializable;
/**
* This enumeration contains the name's list of all weapon cards
* */
public enum PowerUpEnum implements Serializable {
NEWTON_B ("newton_B"),
NEWTON_R ("newton_R"),
NEWTON_Y ("newton_Y"),
TAGBACKGRANADE_B ("tagbackGranade_B"),
TAGBACKGRANADE_R ("tagbackGranade_R"),
TAGBACKGRANADE_Y ("tagbackGranade_Y"),
TARGETTINGSCOPE_B ("targettingScope_B"),
TARGETTINGSCOPE_R ("targettingScope_R"),
TARGETTINGSCOPE_Y ("targettingScope_Y"),
TELEPORTER_B ("teleporter_B"),
TELEPORTER_R ("teleporter_R"),
TELEPORTER_Y ("teleporter_Y");
private String abbreviation;
private PowerUpEnum(String abbreviation) {
this.abbreviation=abbreviation;
}
public String getAbbreviation(){
return abbreviation;
}
}
<file_sep>/src/main/java/network/Client/Socket/SocketClient.java
package network.Client.Socket;
import network.Client.Client;
import network.messages.Message;
import view.View;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Logger;
/**
* This class is used from the client to communicate with SocketServer when a Socket connection is used.
* */
public class SocketClient extends Client{
private String host;
private final int port;
private Socket connection;
private ObjectInputStream in; //Used to send message to server
private ObjectOutputStream out; //Used to receive message from server
private Thread networkHandler;
private static Logger logger = Logger.getLogger("Client");
/**
* The constructor only initialize the host and port attribute, it doesn't establish connection. Attributes will be
* used from init() to establish a new connection to the server.
* @param host the ip of the server to which you have to connect.
* @param port the port of the server to which you have to connect.
* */
public SocketClient(String host, int port, View view){
super(view);
this.rmi = false;
this.host = host;
this.port = port;
try {
init();
}catch (IOException e){
logger.severe(e.getMessage());
}
}
/**
* This method initialize a new socket connection and set the output and input stream used to send and receive
* message from the server.
* */
private void init() throws IOException {
connection = new Socket(host, port);
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
networkHandler = new Thread(new NetworkHandler(this, in, out));
networkHandler.start();
}
/**
* This method send a message to the server
* @param message is the message that must be sent to the server
* */
public void send(Message message) {
try {
out.writeObject(message);
out.flush();
}catch (IOException e){
logger.severe(e.getMessage());
}
}
/**
* This method is used to close connection between the client and the server. Before closing connection input and
* output streams are closed.
* */
public void close() {
try {
in.close();
out.close();
connection.close();
}catch (IOException e){
logger.severe(e.getMessage());
}
}
}
<file_sep>/src/main/java/Model/DeadRoute.java
package Model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class DeadRoute implements Serializable{
private int skulls;
private ArrayList<Player> murders;
private Game gameId;
private boolean finalTurn;
public DeadRoute(int n, Game gameId){
skulls=n;
murders=new ArrayList<>();
this.gameId=gameId;
finalTurn=false;
}
public Game getGameId() {
return gameId;
}
public int getSkulls() {
return skulls;
}
public List<Player> getMurders() {
return murders;
}
public boolean isFinalTurn() {
return finalTurn;
}
public void setFinalTurn(boolean finalTurn) {
this.finalTurn = finalTurn;
}//for test
/*
*This method adds a murder in the dead route
* */
public void addMurders(Player player, int counter){
while(counter >0){
getMurders().add(player);
counter--;
}
skulls--;
System.out.println(skulls);
if(skulls<=0){
finalTurn=true;
}
}
public void setFinalTurnPlayer(){
for(Player p:getGameId().getPlayers()){
if(p.getPlayerBoard().getHealthPlayer().getDamageBar().isEmpty()){
p.getPlayerBoard().setMaxReward(2);
p.getPlayerBoard().setFinalTurn(true);
}
}
}
//start finalTurn
}
<file_sep>/src/main/java/view/gui/ReloadGui.java
package view.gui;
import Model.CardWeapon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
/**
* This class is used to display a window for reload action
*/
public class ReloadGui extends JFrame {
private int i = 0;
public ReloadGui(List<CardWeapon> cards, MapGui mapGui, boolean finalTurn) {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
this.add(new JLabel("Choose weapon to reload"), c);
for (CardWeapon cardWeapon: cards){
if (!cardWeapon.isCharge()){
c.gridx = i;
c.gridy = 1;
JLabel label = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("GUI/weapons/" + cardWeapon.getName() + ".png")));
label.addMouseListener(new MouseListener() {
int choose = i;
@Override
public void mouseClicked(MouseEvent e) {
if (!finalTurn)
mapGui.sendReload(choose);
else{
mapGui.sendReload(choose);
new WeaponChooseGui(cards , mapGui, true);
}
dispose();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
this.add(label, c);
i++;
}
}
this.pack();
this.setVisible(true);
}
}
<file_sep>/src/main/java/view/gui/actionHandler/CreateNewGame.java
package view.gui.actionHandler;
import network.Client.Client;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CreateNewGame implements ActionListener {
private Client client;
private JComboBox<String> rmi;
private JTextField token;
private JFrame frame;
public CreateNewGame(Client client, JTextField token, JFrame frame){
this.client = client;
this.token = token;
this.frame = frame;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Ciao");
}
}
<file_sep>/src/test/java/Model/GrabTest.java
package Model;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import static org.junit.jupiter.api.Assertions.*;
public class GrabTest {
/**
* This method test all the three constructor methods
*/
@Test
public void ConstructorTest() throws FileNotFoundException {
//Test 1
Colors color = null;
Player testPlayer = new Player(243, color);
CardWeapon testWeapon = new CardWeapon (WeaponDictionary.CYBERBLADE.getAbbreviation());
Grab action = new Grab(testPlayer, testWeapon);
assertTrue(action instanceof Grab );
//Test 2
CardOnlyAmmo testOnlyAmmo= new CardOnlyAmmo (AmmoEnum.AMMO1.getAbbreviation());
action = new Grab(testPlayer, testOnlyAmmo);
assertTrue(action instanceof Grab );
//Test 3
CardNotOnlyAmmo testNotOnlyAmmo= new CardNotOnlyAmmo (AmmoEnum.AMMO1.getAbbreviation());
action = new Grab(testPlayer, testNotOnlyAmmo);
assertTrue(action instanceof Grab );
}
@Test
public void isValidTest() throws FileNotFoundException {
Colors color = null;
Player testPlayer = new Player(37834782, color);
GameBoard testGameBoard = new GameBoard("map1");
SpawnSquare testSpawnSquare = (SpawnSquare) testGameBoard.getRooms().get(0).getNormalSquares().get(2);
CardWeapon testWeapon = new CardWeapon (WeaponDictionary.CYBERBLADE.getAbbreviation());
testPlayer.newPosition(testSpawnSquare);
testSpawnSquare.setItems(testWeapon);
Grab action = new Grab(testPlayer, testWeapon);
assertTrue(action.isValid());
//Test 2
CardOnlyAmmo testOnlyAmmo = new CardOnlyAmmo (AmmoEnum.AMMO1.getAbbreviation());
action = new Grab(testPlayer, testOnlyAmmo);
assertFalse(action.isValid());
//Test 3
CardNotOnlyAmmo testNotOnlyAmmo = new CardNotOnlyAmmo (AmmoEnum.AMMO1.getAbbreviation());
action = new Grab(testPlayer, testNotOnlyAmmo);
assertFalse(action.isValid());
}
@Test
public void executeTest() throws FileNotFoundException {
Colors color = null;
Game testGame = new Game( 8,"map1");
Player testPlayer = new Player(4767745, color);
testGame.addPlayer(testPlayer);
SpawnSquare testSpawnSquare = (SpawnSquare) testGame.getMap().getRooms().get(0).getNormalSquares().get(2);
CardWeapon testWeapon = new CardWeapon (WeaponDictionary.CYBERBLADE.getAbbreviation());
testPlayer.newPosition(testSpawnSquare);
testSpawnSquare.setItems(testWeapon);
Grab action = new Grab(testPlayer, testWeapon);
assertTrue(action.execute());
assertEquals(testWeapon,testPlayer.getPlayerBoard().getHandPlayer().getPlayerWeapons().get(0));
//Test grab NotOnlyAmmo
CardNotOnlyAmmo testNotOnlyAmmo = new CardNotOnlyAmmo (AmmoEnum.AMMO11.getAbbreviation()); // (P, Yellow, Red)
action = new Grab(testPlayer, testNotOnlyAmmo);
System.out.println(testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[0] + " " + testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[1] + " " +testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[2]);
System.out.println(testPlayer.getPlayerBoard().getHandPlayer().getPlayerPowerUps());
assertTrue(action.execute());
System.out.println(testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[0] + " " + testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[1] + " " +testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[2]);
System.out.println(testPlayer.getPlayerBoard().getHandPlayer().getPlayerPowerUps());
assertEquals(1 ,testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[0]);
assertEquals(1 ,testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[1]);
assertEquals(0 ,testPlayer.getPlayerBoard().getHandPlayer().getAmmoRYB()[2]);
assertEquals(1 ,testPlayer.getPlayerBoard().getHandPlayer().getPlayerPowerUps().size());
}
}
<file_sep>/src/main/java/Model/Shoot.java
package Model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Shoot implements Action, Serializable {
private Effect shootEffect;
private Player shooterPlayer;
private List<Player> targets;
private List<NormalSquare> targetSquare;
private Colors roomColor;
private char actionType;
private List<Player> gamePlayers;
public Shoot(Effect effect, Player shooter, List<Player> target, List<NormalSquare> square, Boolean isSquare){
this.shootEffect = effect;
this.shooterPlayer = shooter;
this.targets = target;
this.targetSquare = square;
if (isSquare) {
this.actionType = 's';
this.gamePlayers = new ArrayList<>(shooterPlayer.getGameId().getPlayers());
gamePlayers.remove(shooterPlayer);
}
else
this.actionType = 'p';
}
public Shoot(Effect effect, Player shooter, Colors color){
this.shootEffect = effect;
this.shooterPlayer = shooter;
this.roomColor = color;
this.actionType = 'r';
this.gamePlayers = new ArrayList<>(shooterPlayer.getGameId().getPlayers());
gamePlayers.remove(shooterPlayer);
}
/**
* This method execute the Shoot Action
*
* @return true if the action has been executed, false otherwise
*/
public boolean execute(){
switch(actionType) {
case ('p'):
execP();
return true;
case ('s'):
execS();
return true;
case ('r'):
execR();
return true;
default:
return false;
}
}
/**
* This method is invoked by isValid
* Control the pre-condition of case P
* */
private boolean isValidP(){
if(shootEffect.getPreCondition().isConsecutive()){
return isValidTHOR();
}
List<Player> visibleTarget = targetablePlayer();
ArrayList<NormalSquare> targetListSquare = new ArrayList<>();
for (Player target : targets) {
if(!conditionControll(target, visibleTarget, targetListSquare)){
System.out.println("falso1");
return false;
}
}
if(shootEffect.getPreCondition().isCardinal()) {
targetListSquare = new ArrayList<>();
targetListSquare.add(shooterPlayer.getPosition());
for (Player target : targets) {
targetListSquare.add(target.getPosition());
}
System.out.println(cardinalControl(targetListSquare));
return cardinalControl(targetListSquare);
}
return true;
}
private boolean isValidTHOR() {
targets = new ArrayList(shooterPlayer.getGameId().getPlayers());
targets.remove(shooterPlayer);
for(int i = 0; i < targets.size(); i++){
if(i == 0){
if(!targetablePlayer().contains(targets.get(i)))
return false;
}
else{
if(!(new Shoot(shootEffect, targets.get(i-1), null, null, false).targetablePlayer()).contains(targets.get(i)))
return false;
}
}
return true;
}
/**
* This method is invoked by isValid
* Control the pre-condition of case S
* */
private boolean isValidS(){
List<NormalSquare> a = reachableSquare();
ArrayList<NormalSquare> targetListSquare;
for (NormalSquare square: targetSquare) {
if(!(a.contains(square)))
return false;
}
if(shootEffect.getPreCondition().isCardinal()) {
targetListSquare = new ArrayList<>();
targetListSquare.add(shooterPlayer.getPosition());
targetListSquare.addAll(targetSquare);
return cardinalControl(targetListSquare);
}
return true;
}
/**
* This method is invoked by isValid
* Control the pre-condition of case R
* */
private boolean isValidR(){
for (NormalSquare normalSquare : reachableSquare()){
if(normalSquare.getColor() == roomColor && normalSquare.getColor() != shooterPlayer.getPosition().getColor())
return true;
}
return false;
}
/**
* Control the Pre-condition of the Shoot Action
* This method invoke isValidP, isValidS and isValidR methods
*
* @return true if the action invocation respect the condition, false otherwise
*/
public boolean isValid(){
switch (actionType){
case ('p'):
return isValidP();
case ('s'):
return isValidS();
case ('r'):
return isValidR();
default:
return false;
}
}
/**
* When it's called by the 'p' case of the Shoot action this method returns True if the players in the List of selected targets belong to cardinals square, otherwise return false
* When it's called by the 's' case of the Shoot action this method returns True if the squares in the List of selected targets belong to cardinals square, otherwise return false
*/
private boolean cardinalControl(List<NormalSquare> square) {
int i;
int j;
int x = 0;
int y = 0;
for (j = 0,i = 1; i < square.size() && (x == 0 || y == 0); i++) {
if (square.get(i).getId().charAt(0) != square.get(j).getId().charAt(0))
x++;
if (square.get(i).getId().charAt(2) != square.get(j).getId().charAt(2))
y++;
}
return (x == 0 || y == 0);
}
/**
*
* */
private boolean conditionControll(Player target, List<Player> visibleTarget, ArrayList<NormalSquare> targetListSquare){
if (shootEffect.getPreCondition().isMelee() && shooterPlayer.getPosition() != target.getPosition()){
System.out.println("1");
return false;
}
if (shootEffect.getPreCondition().isBlind() && visibleTarget.contains(target)){
System.out.println("2");
return false;
}
if (!shootEffect.getPreCondition().isBlind() && !(visibleTarget.contains(target))){
System.out.println("3");
return false;
}
if (shootEffect.getPreCondition().isEnemiesDifferentSquare()){
if (targetListSquare.contains(target.getPosition())){
System.out.println("4");
return false;
}
else
targetListSquare.add(target.getPosition());
}
return true;
}
/**
* This method control the effect's PreCondition
* @return the list of Square reachable from the startSquare with at least movePass step
*/
public List<NormalSquare> reachableSquare() {
Effect.PreCondition preCondition = shootEffect.getPreCondition();
ArrayList<NormalSquare> reachableSquares = new ArrayList<>();
ArrayList<NormalSquare> thisStepSquare = new ArrayList<>();
ArrayList<NormalSquare> allStepSquare = new ArrayList<>();
ArrayList<Colors> colors = new ArrayList<>();
thisStepSquare.add(shooterPlayer.getPosition());
allStepSquare.add(shooterPlayer.getPosition());
int thisStep;
int range = 0;
int j;
if(preCondition.isMelee()) {
reachableSquares.add(shooterPlayer.getPosition());
return reachableSquares;
}
if (preCondition.isVision()) {
colors.add(shooterPlayer.getPosition().getColor());
if (shooterPlayer.getPosition().getN().getColor() != shooterPlayer.getPosition().getColor()){
colors.add(shooterPlayer.getPosition().getN().getColor());
}
if (shooterPlayer.getPosition().getE().getColor() != shooterPlayer.getPosition().getColor()){
colors.add(shooterPlayer.getPosition().getE().getColor());
}
if (shooterPlayer.getPosition().getS().getColor() != shooterPlayer.getPosition().getColor()){
colors.add(shooterPlayer.getPosition().getS().getColor());
}
if (shooterPlayer.getPosition().getW().getColor() != shooterPlayer.getPosition().getColor()){
colors.add(shooterPlayer.getPosition().getW().getColor());
}
}
if (0 == preCondition.getMinRange()) {
reachableSquares.add(shooterPlayer.getPosition());
}
while((preCondition.getMaxRange() == 0 && !thisStepSquare.isEmpty()) || range <= preCondition.getMaxRange()){
thisStep = thisStepSquare.size();
j = 0;
while (j < thisStep) {
isAlreadyReachable(allStepSquare, thisStepSquare, reachableSquares, thisStepSquare.get(0).getN(), colors, preCondition, range);
isAlreadyReachable(allStepSquare, thisStepSquare, reachableSquares, thisStepSquare.get(0).getE(), colors, preCondition, range);
isAlreadyReachable(allStepSquare, thisStepSquare, reachableSquares, thisStepSquare.get(0).getS(), colors, preCondition, range);
isAlreadyReachable(allStepSquare, thisStepSquare, reachableSquares, thisStepSquare.get(0).getW(), colors, preCondition, range);
thisStepSquare.remove(0);
j++;
}
range++;
}
return reachableSquares;
}
/**
* This method is invoked by reachableSquare method
*/
private void isAlreadyReachable(ArrayList<NormalSquare> allStepSquare, ArrayList<NormalSquare> thisStepSquare, ArrayList<NormalSquare> reachableSquares, NormalSquare thisSquare, ArrayList<Colors> colors, Effect.PreCondition preCondition, int range){
if (!allStepSquare.contains(thisSquare)) {
thisStepSquare.add(thisSquare);
allStepSquare.add(thisSquare);
if (!reachableSquares.contains(thisSquare)
&& (preCondition.isVision() && colors.contains((thisSquare.getColor())))
|| (!preCondition.isVision()
&& (!preCondition.isCardinal() || (thisSquare.getId().charAt(0) == shooterPlayer.getPosition().getId().charAt(0)
|| thisSquare.getId().charAt(2) == shooterPlayer.getPosition().getId().charAt(2)))))
reachableSquares.add(reachableSquares.size(), thisSquare);
}
}
/**
* This method return a List of all the square that compose the rooms reachables with the selected effect
*/
public List<NormalSquare> reachableRoom() {
ArrayList<Colors> roomList = new ArrayList<>();
List<NormalSquare> squareList = new ArrayList<>();
if(shooterPlayer.getPosition().getN().getColor() != shooterPlayer.getPosition().getColor()) {
roomList.add(shooterPlayer.getPosition().getN().getColor());
}
if(!roomList.contains(shooterPlayer.getPosition().getE().getColor()) && shooterPlayer.getPosition().getE().getColor() != shooterPlayer.getPosition().getColor()) {
roomList.add(shooterPlayer.getPosition().getE().getColor());
}
if(!roomList.contains(shooterPlayer.getPosition().getS().getColor()) && shooterPlayer.getPosition().getS().getColor() != shooterPlayer.getPosition().getColor()) {
roomList.add(shooterPlayer.getPosition().getS().getColor());
}
if(!roomList.contains(shooterPlayer.getPosition().getW().getColor()) && shooterPlayer.getPosition().getW().getColor() != shooterPlayer.getPosition().getColor()) {
roomList.add(shooterPlayer.getPosition().getW().getColor());
}
for (int i = 0; i < shooterPlayer.getGameId().getMap().getRooms().size(); i++) {
if(roomList.contains(shooterPlayer.getGameId().getMap().getRooms().get(i).getColor())){
squareList.addAll(shooterPlayer.getGameId().getMap().getRooms().get(i).getNormalSquares());
}
}
return squareList;
}
/**
* @return the list of Player that can be targeted by the actorPlayer
*/
public List<Player> targetablePlayer(){
if(shootEffect.getPreCondition().isConsecutive()){
return shooterPlayer.getGameId().getPlayers();
}
ArrayList<Player> reachablePlayer = new ArrayList<>(shooterPlayer.getGameId().getPlayers());
reachablePlayer.remove(shooterPlayer);
int i = 0;
while(i < reachablePlayer.size()){
if(!reachableSquare().contains(reachablePlayer.get(i).getPosition()))
reachablePlayer.remove(i);
else
i++;
}
return reachablePlayer;
}
/**
* @param targetPlayer The Player that is targeted in this step
* @param mark The number of mark that must be dealt to the targetPlayer
* This method mark the target
*/
private void markTarget(Player targetPlayer, int mark){
targetPlayer.getPlayerBoard().getHealthPlayer().addMark(shooterPlayer, mark);
}
/**
* @param targetPlayer The Player that is targeted in this step
* @param damage The number of mark that must be dealt to the targetPlayer
* This method damage the target
*/
private void injureTarget(Player targetPlayer, int damage){
targetPlayer.getPlayerBoard().getHealthPlayer().addDamage(shooterPlayer, damage);
}
/**
* This method is called by execute
* This method execute the Shoot Action only in 'p' case
*/
private void execP(){
for (int i = 0; i < targets.size() && i < shootEffect.getpDamage().size() ; i++) {
injureTarget(targets.get(i), shootEffect.getpDamage().get(i));
markTarget(targets.get(i), shootEffect.getpMark().get(i));
}
}
/**
* This method is called by execute
* This method execute the Shoot Action only in 's' case
*/
private void execS(){
if(shootEffect.getSquareNumber() == 4)
shootShockWave();
else if(shootEffect.getSquareNumber() == 2){
shootFlameThrower();
}
else{
for (Player target : gamePlayers) {
if (target.getPosition() == targetSquare.get(0)) {
injureTarget(target, shootEffect.getsDamage().get(0));
markTarget(target, shootEffect.getsMark().get(0));
}
}
}
}
/**
* This method is called by execS
* This method execute the Shoot Action only for FlameThrower Weapon
*/
private void shootFlameThrower() {
ArrayList<NormalSquare> flameSquares = new ArrayList<>(targetSquare);
int x = 0;
int y = 0;
int c = 0;
NormalSquare newTargetSquare = null;
if (shooterPlayer.getPosition().getId().charAt(0) == flameSquares.get(0).getId().charAt(0)) {
x = Integer.parseInt(String.valueOf(shooterPlayer.getPosition().getId().charAt(0)));
y = Integer.parseInt(String.valueOf(flameSquares.get(0).getId().charAt(2))) + Integer.parseInt(String.valueOf(flameSquares.get(0).getId().charAt(2))) - Integer.parseInt(String.valueOf(shooterPlayer.getPosition().getId().charAt(2)));
c = 1;
newTargetSquare = shooterPlayer.getGameId().getMap().getSquareFromId(x + "," + y);
} else if (shooterPlayer.getPosition().getId().charAt(2) == flameSquares.get(0).getId().charAt(2)) {
x = Integer.parseInt(String.valueOf(flameSquares.get(0).getId().charAt(0))) + Integer.parseInt(String.valueOf(flameSquares.get(0).getId().charAt(0))) - Integer.parseInt(String.valueOf(shooterPlayer.getPosition().getId().charAt(0)));
y = Integer.parseInt(String.valueOf(shooterPlayer.getPosition().getId().charAt(2)));
c = 2;
newTargetSquare = shooterPlayer.getGameId().getMap().getSquareFromId(x + "," + y);
}
if((c == 1) && flameSquares.get(0).getId().charAt(0) == newTargetSquare.getId().charAt(0) || (c == 2) && flameSquares.get(0).getId().charAt(2) == newTargetSquare.getId().charAt(2)) {
flameSquares.add(newTargetSquare);
}
for (int i = 0; i < flameSquares.size(); i++) {
for (Player target : gamePlayers) {
if (target.getPosition() == flameSquares.get(i)) {
injureTarget(target, shootEffect.getsDamage().get(i));
markTarget(target, shootEffect.getsMark().get(i));
}
}
}
}
/**
* This method is called by execS
* This method execute the Shoot Action only for ShockWave Weapon
*/
private void shootShockWave() {
ArrayList<NormalSquare> shockSquares = new ArrayList<>();
if (shooterPlayer.getPosition().getN() != shooterPlayer.getPosition())
shockSquares.add(shooterPlayer.getPosition().getN());
if (shooterPlayer.getPosition().getE() != shooterPlayer.getPosition())
shockSquares.add(shooterPlayer.getPosition().getE());
if (shooterPlayer.getPosition().getS() != shooterPlayer.getPosition())
shockSquares.add(shooterPlayer.getPosition().getS());
if (shooterPlayer.getPosition().getW() != shooterPlayer.getPosition())
shockSquares.add(shooterPlayer.getPosition().getW());
for (int i = 0; i < shockSquares.size(); i++) {
for (Player target : gamePlayers) {
if (target.getPosition() == shockSquares.get(i)) {
injureTarget(target, shootEffect.getsDamage().get(i));
markTarget(target, shootEffect.getsMark().get(i));
}
}
}
}
/**
* This method is called by execute
* This method execute the Shoot Action only in 'r' case
*/
private void execR(){
for (Player target: gamePlayers) {
if (target.getPosition().getColor() == roomColor){
injureTarget(target, shootEffect.getrDamage());
markTarget(target, shootEffect.getrMark());
}
}
}
}
<file_sep>/src/test/java/Model/DeadRouteTest.java
package Model;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import static org.junit.jupiter.api.Assertions.*;
public class DeadRouteTest {
/*
* this method tests the deadRoute's constructor
* */
@Test
public void deadRouteConstructorTest()throws FileNotFoundException {
Game game=new Game(8,"map1");
assertNotNull(game.getDeadRoute());
assertEquals(8,game.getDeadRoute().getSkulls());
}
/*
* this method tests when the deadRoute is empty and there is the calculation of points
* */
@Test
public void addMurdersTest()throws FileNotFoundException{
Game game=new Game(2,"map1");
Player player1=new Player(2830, Colors.GREEN);
Player player2=new Player(2831, Colors.BLUE);
game.addPlayer(player1);
game.addPlayer(player2);
game.getDeadRoute().addMurders(player1,1);
assertEquals(1,game.getDeadRoute().getMurders().size());
assertEquals(1,game.getDeadRoute().getSkulls());
}
}
<file_sep>/src/main/java/network/messages/ActionType.java
package network.messages;
import java.io.Serializable;
/**
* This class is an enumeration that contains names for all possible messages
*/
public enum ActionType implements Serializable {
START("Start"),
CONNECTIONREQUEST("Connection request"),
CONNECTIONRESPONSE("Connection response"),
RECONNECTIONREQUEST("Reconnection request"),
RECONNECTIONRESPONSE("Reconnection response"),
POSSIBLETARGETSHOT("Possible target shot"),
SHOT("Shot"),
POSSIBLEMOVE("Possible move"),
MOVE("Move"),
RELOAD("Reload"),
RELOADED("Reloaded"),
GRABWEAPON("Grab weapon"),
GRABWEAPONRESPONSE("Grab weapon response"),
GRABAMMO("Grab ammo"),
GRABNOTONLYAMMO("Grab notOnlyAmmo"),
GRABRESPONSE("Grab response"),
USEPOWERUP("Use powerup"),
UPDATECLIENTS("Update clients"),
PASS("Pass"),
TIMEOUT("Time out"),
FINALACTION("Final action"),
GAMESETTINGSREQUEST("Game settings request"),
GAMESETTINGSRESPONSE("Game settings response"),
STARTTURNMESSAGE("Start turn message"),
SUBSTITUTEWEAPON("Substitute weapon"),
SUBSTITUTEWEAPONRESPONSE("Substitute weapon response"),
CANUSEVENOM("Can use venom"),
CANUSESCOOP("Can use scoop"),
SCOPETARGETREQUEST("Scope target request"),
FINALTURN("Finale turn"),
SCOPETARGETRESPONSE("Scope target response"),
RECEIVETARGETSQUARE("Receive target square"),
USEPOWERUPRESPONSE("Use power up response"),
RESPAWN("Respwan"),
WINNER("Winner"),
END("End"),
SHOTRESPONSE("Shot response"),
MOVERESPONSE("Move response"),
GRABWEAPONREQUEST("Grab weapon request"),
DISCONNECT("Disconnect"),
PAYMENT("payment"),
PAYMENTRESPONSE("Payment Response"),
CANUSESCOOPRESPONSE("Can use scoop response"),
MESSAGE("Message"),
SHOOTREQUESTP("Shoot request p"),
SHOOTREQUESTS("Shoot request s"),
SHOOTREQUESTR("Shoot request r"),
TARGETMOVEREQUEST("Target move request"),
SHOOTRESPONSEP("Shoot response p"),
SHOOTRESPONSES("Shoot response s"),
SHOOTRESPONSER("Shoot response r"),
TARGETMOVERESPONSE("Target move response"),
PING("Ping");
private String abbreviation;
private ActionType(String abbreviation) {
this.abbreviation=abbreviation;
}
public String getAbbreviation(){
return abbreviation;
}
}
<file_sep>/src/test/java/Model/MoveTest.java
package Model;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import static org.junit.jupiter.api.Assertions.*;
public class MoveTest {
@Test
public void constructorTestWithoutEffect() throws FileNotFoundException {
GameBoard testGameBoard = new GameBoard("map1");
Player testMoverPlayer = new Player(2343234, null);
testMoverPlayer.newPosition(testGameBoard.getRooms().get(1).getNormalSquares().get(0));
Move action = new Move(testMoverPlayer, testGameBoard.getRooms().get(1).getNormalSquares().get(2), 2);
assertTrue(action instanceof Move);
}
@Test
public void executeTest() throws FileNotFoundException {
Colors color1 = Colors.RED, color2 = Colors.BLUE;
Game game = new Game( 8,"map1");
Player testShooterPlayer = new Player(34243432, color1);
Player testTargetPlayer = new Player(767676675, color2);
game.addPlayer(testShooterPlayer);
game.addPlayer(testTargetPlayer);
testShooterPlayer.newPosition(game.getMap().getRooms().get(1).getNormalSquares().get(0));
testTargetPlayer.newPosition(game.getMap().getRooms().get(1).getNormalSquares().get(0));
CardWeapon testWeapon = new CardWeapon (WeaponDictionary.SLEDGEHAMMER.getAbbreviation());
Effect testEffect = testWeapon.getEffects().get(1);
Move action = new Move(testTargetPlayer, game.getMap().getRooms().get(1).getNormalSquares().get(2), testEffect.getTargetMove());
assertTrue(action.execute());
}
@Test
public void isValidTest() throws FileNotFoundException {
Colors color1 = Colors.RED, color2 = Colors.BLUE;
Game game = new Game( 8,"map1");
Player testShooterPlayer = new Player(677777476, color1);
Player testTargetPlayer = new Player(6754766, color2);
game.addPlayer(testShooterPlayer);
game.addPlayer(testTargetPlayer);
testShooterPlayer.newPosition(game.getMap().getRooms().get(0).getNormalSquares().get(0));
testTargetPlayer.newPosition(game.getMap().getRooms().get(0).getNormalSquares().get(0));
CardWeapon testWeapon = new CardWeapon (WeaponDictionary.POWERGLOVE.getAbbreviation());
Effect testEffect = testWeapon.getEffects().get(1);
Move action = new Move(testShooterPlayer, game.getMap().getRooms().get(0).getNormalSquares().get(1), testEffect.getMyMove());
assertTrue(action.isValid());
//Test 2
testWeapon = new CardWeapon (WeaponDictionary.SLEDGEHAMMER.getAbbreviation());
testEffect = testWeapon.getEffects().get(1);
action = new Move(testTargetPlayer, game.getMap().getRooms().get(1).getNormalSquares().get(1), testEffect.getTargetMove());
assertTrue(action.isValid());
}
@Test
public void calculateReachableSquareTest() throws FileNotFoundException {
Colors color1 = Colors.RED, color2 = Colors.BLUE;
Game game = new Game( 8,"map1");
Player testShooterPlayer = new Player(67575, color1);
Player testTargetPlayer = new Player(67655676, color2);
game.addPlayer(testShooterPlayer);
game.addPlayer(testTargetPlayer);
testShooterPlayer.newPosition(game.getMap().getRooms().get(1).getNormalSquares().get(0));
testTargetPlayer.newPosition(game.getMap().getRooms().get(1).getNormalSquares().get(0));
CardWeapon testWeapon = new CardWeapon (WeaponDictionary.CYBERBLADE.getAbbreviation());
Effect testEffect = testWeapon.getEffects().get(1);
Move action = new Move(testTargetPlayer, game.getMap().getRooms().get(1).getNormalSquares().get(1), testEffect.getMyMove());
assertEquals(3, action.reachableSquare().size());
testShooterPlayer.newPosition(game.getMap().getRooms().get(1).getNormalSquares().get(0));
testTargetPlayer.newPosition(game.getMap().getRooms().get(1).getNormalSquares().get(0));
action = new Move(testTargetPlayer, game.getMap().getRooms().get(1).getNormalSquares().get(1), 3);
assertEquals(9, action.reachableSquare().size());
}
}
<file_sep>/src/main/java/network/messages/ShootResponser.java
package network.messages;
/**
* This message is sended by Client to Server as a response of ShootRequestr
* with this message send the ID related to a square of the selected Room for a RoomShoot
*/
public class ShootResponser extends Message{
private String targetRoom;
public ShootResponser(Integer token, String targetRoom){
this.token = token;
this.actionType = ActionType.SHOOTRESPONSER;
this.targetRoom = targetRoom;
}
public String getTargetRoom() {
return targetRoom;
}
}
<file_sep>/src/main/java/network/messages/FinalAction.java
package network.messages;
/**
* This message is used to send a message to tell the client he conclude an action
*/
public class FinalAction extends Message {
public FinalAction(Integer token){
this.token = token;
this.actionType = ActionType.FINALACTION;
}
}
<file_sep>/src/main/java/network/messages/ShootRequests.java
package network.messages;
import java.util.List;
/**
* This message is sended by GameLobby to the Client when a Shoot Action contain a 's' element in its actionSequence
* with this message send the List of ID related to the square that should be selected as target
*/
public class ShootRequests extends Message{
private Integer squareNumber;
private List<String> targetableSquare;
public ShootRequests(Integer token, List<String> targetableSquare){
this.token = token;
this.actionType = ActionType.SHOOTREQUESTS;
this.targetableSquare = targetableSquare;
}
public List<String> getTargetableSquare() {
return targetableSquare;
}
}
<file_sep>/src/test/java/Model/CardNotOnlyAmmoTest.java
package Model;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import static org.junit.jupiter.api.Assertions.*;
public class CardNotOnlyAmmoTest {
/**
* This method tests if CardNotOnlyAmmo read form json file and initialize attributes correctly.
* */
@Test
public void constructorTest() throws FileNotFoundException {
CardNotOnlyAmmo cardNotOnlyAmmo;
Deck<CardPowerUp> deck, deckCopy;
DeckCreator deckCreator = new DeckCreator();
Drawer<CardPowerUp> drawer;
cardNotOnlyAmmo = new CardNotOnlyAmmo(AmmoEnum.AMMO1.getAbbreviation());
deck = deckCreator.createDeck("POWERUP");
drawer = deck.createDrawer();
deckCopy = deck.copy();
assertEquals("A1", cardNotOnlyAmmo.getName());
assertEquals(AmmoColors.BLUE, cardNotOnlyAmmo.getItem2());
assertEquals(AmmoColors.BLUE, cardNotOnlyAmmo.getItem3());
cardNotOnlyAmmo.getItem1(drawer);
assertEquals(deck.getSize(), deckCopy.getSize()-1);
}
@Test
public void copyCardTest() throws FileNotFoundException{
CardNotOnlyAmmo cardNotOnlyAmmo, cardNotOnlyAmmoCopy;
cardNotOnlyAmmo = new CardNotOnlyAmmo(AmmoEnum.AMMO1.getAbbreviation());
cardNotOnlyAmmoCopy = cardNotOnlyAmmo.copyCardAmmo();
assertEquals(cardNotOnlyAmmo.getItem2(), cardNotOnlyAmmo.getItem2());
assertEquals(cardNotOnlyAmmo.getItem3(), cardNotOnlyAmmo.getItem3());
}
}
<file_sep>/src/main/java/view/cli/ActionCLI.java
package view.cli;
import Model.*;
import network.messages.ReceiveTargetSquare;
import network.messages.ReloadMessage;
import network.messages.UsePowerUp;
import network.messages.UsePowerUpResponse;
import view.View;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class ActionCLI {
private ViewCLI viewCLI;
private static PrintWriter out=new PrintWriter(System.out,true);
private static Scanner in=new Scanner(System.in);
public ActionCLI(ViewCLI viewCLI){
this.viewCLI=viewCLI;
}
public void actionPowerUp(){
if(viewCLI.getPowerUps().isEmpty()){
out.println("\n you have no Power up \n");
if(viewCLI.getNumberAction()==3 && !viewCLI.isFinalTurn())
viewCLI.finalActions();
else if(viewCLI.isFinalTurn())
viewCLI.finalTurnAction();
else
viewCLI.startActions();
}
else{
int i;
for ( i = 1; i <= viewCLI.getPowerUps().size(); i++)
out.println(i + ":" +viewCLI.getPowerUps().get(i - 1).getName() +" "+ viewCLI.getPowerUps().get(i - 1).getColor() + "\t");
out.println("\n choose a number from 1 to" + viewCLI.getPowerUps().size() + "or 9 to cancel\n");
boolean corrected = false;
while (!corrected) {
i = in.nextInt();
if (i >= 1 && i <= viewCLI.getPowerUps().size()) {
if (viewCLI.getPowerUps().get(i-1).getOtherMove()==2)
newtonPowerUp(i);
else if(viewCLI.getPowerUps().get(i-1).getMyMove()==-1)
teletrasporterPowerUp(i);
else{
out.println("The powerUp selected is tagBack grenade o targetting Scope, the game will tell you when to use them");
if(viewCLI.getNumberAction()==3 && !viewCLI.isFinalTurn())
viewCLI.finalActions();
else if(viewCLI.isFinalTurn())
viewCLI.finalTurnAction();
else
viewCLI.startActions();
}
corrected = true;
}
else if(i==9)
corrected=true;
else {
out.println("it's not difficult, you can do it \n");
out.println("choose a number from 1 to " + viewCLI.getPowerUps() +"or 9 to cancel"+ "\n");
}
}
}
}
private void newtonPowerUp(int posPowerUp){
//venom
ArrayList<Colors> colorsPlayer=new ArrayList<>();
ArrayList<NormalSquare> squares=new ArrayList<>();
int count=1;
out.println("Choose the TARGET for NEWTON");
for (Colors color:viewCLI.getPlayers().keySet()){
out.print(count + ":" +color + "\t");
colorsPlayer.add(color);
count++;
}
out.println(" choose a number from 1 to" + viewCLI.getPlayers().keySet().size());
boolean corrected = false;
while (!corrected) {
int target= in.nextInt();
if (target >= 1 && target <= viewCLI.getPowerUps().size()) {
out.println("Choose a square, the square must be at maximum distance 2 from the target \n" +
"and in cardinal position");
out.println(" choose a number a square id, insert string for example 0,0" );
while (!corrected) {
String square= in.next();
if (square.equals("0,0") || square.equals("0,1")||square.equals("0,2") || square.equals("1,0") ||square.equals("1,1") || square.equals("1,2")||square.equals("1,3") || square.equals("2,2")||square.equals("2,3") || square.equals("2,1")) {
viewCLI.getClient().send(new UsePowerUpResponse(viewCLI.getClient().getToken(),posPowerUp-1,viewCLI.getClient().getToken(),colorsPlayer.get(target-1),square));
corrected=true;
}
else{
out.println("it's not difficult, you can do it");
out.println("choose a string");
}
}
}
else {
out.println("it's not difficult, you can do it \n");
out.println("choose a number from 1 to " + viewCLI.getPlayers().keySet().size());
}
}
}
private void teletrasporterPowerUp(int posPowerUp){
ArrayList<NormalSquare> squares=new ArrayList<>();
out.println("choose any square where to transport yourself, have a good trip");
boolean corrected=false;
out.println(" choose a number a square id, insert string for example 1,0" );
while (!corrected) {
String square= in.next();
if (square.equals("0,1")||square.equals("0,0") ||square.equals("0,2") || square.equals("1,0") ||square.equals("1,1") || square.equals("1,2")||square.equals("1,3") || square.equals("2,2")||square.equals("2,3") || square.equals("2,1")) {
viewCLI.getClient().send(new UsePowerUpResponse(viewCLI.getClient().getToken(),posPowerUp-1,viewCLI.getClient().getToken(),Colors.BLUE,square));
corrected=true;
}
else{
out.println("it's not difficult, you can do it");
out.println("choose a string");
}
}
}
public void actionShot(){
if(viewCLI.getWeapons().isEmpty()){
out.println("\n you have no weapon \n");
if(viewCLI.getNumberAction()>=3 && !viewCLI.isFinalTurn())
viewCLI.finalActions();
else if(viewCLI.isFinalTurn())
viewCLI.finalTurnAction();
else
viewCLI.startActions();
}
int count=1;
for (CardWeapon weapon: viewCLI.getWeapons()){
out.println(count + ":" + weapon.getName() + "\t");
count++;
}
out.println("\n choose a number from 1 to" + (count-1) + "or 9 to cancel\n");
boolean corrected = false;
while (!corrected) {
int i;
int posWeapon= in.nextInt();
if (posWeapon >= 1 && posWeapon<= (count-1)) {
for ( i = 1; i <= viewCLI.getWeapons().get(posWeapon-1).getEffects().size(); i++)
out.println(i + ":" + viewCLI.getWeapons().get(posWeapon-1).getActionSequences().get(i-1)+ "\t");
out.println("\n choose a number from 1 to" + viewCLI.getWeapons().get(posWeapon-1).getEffects().size()+"\t");
while (!corrected) {
int posEffect= in.nextInt();
if (posEffect >= 1 && i <=viewCLI.getWeapons().get(posWeapon-1).getActionSequences().size()) {
viewCLI.getClient().send(new ReceiveTargetSquare(viewCLI.getClient().getToken(),"shot",posWeapon,posEffect));
corrected = true;
}
else {
out.println("it's not difficult, you can do it \n");
out.println("choose a number from 1 to " + viewCLI.getWeapons().get(posWeapon-1).getActionSequences().size()+"\t");
}
}
}
else if(posWeapon==9){
corrected=true;
if(viewCLI.getNumberAction()>=3 && !viewCLI.isFinalTurn())
viewCLI.finalActions();
else if(viewCLI.isFinalTurn())
viewCLI.finalTurnAction();
else
viewCLI.startActions();
}
else {
out.println("it's not difficult, you can do it \n");
out.println("choose a number from 1 to " + (count -1) + "or 9 to cancel\n");
}
}
}
public void shotFinalTurn(int posWeapon){
int i;
for ( i = 1; i <= viewCLI.getWeapons().get(posWeapon-1).getEffects().size(); i++)
out.println(i + ":" + viewCLI.getWeapons().get(posWeapon-1).getActionSequences().get(i-1)+ "\t");
out.println("\n choose a number from 1 to" + viewCLI.getWeapons().get(posWeapon-1).getEffects().size());
boolean corrected=false;
while (!corrected) {
int posEffect= in.nextInt();
if (posEffect >= 1 && i <=viewCLI.getWeapons().get(posWeapon-1).getActionSequences().size()) {
viewCLI.getClient().send(new ReceiveTargetSquare(viewCLI.getClient().getToken(),"shot",posWeapon,posEffect));
corrected = true;
}
else {
out.println("it's not difficult, you can do it \n");
out.println("choose a number from 1 to " + viewCLI.getWeapons().get(posWeapon-1).getActionSequences().size());
}
}
}
public int actionReload(){
if(!viewCLI.isFinalTurn())
viewCLI.setNumberAction(3);
if(viewCLI.getWeapons().isEmpty()){
out.println("\n you have no weapon for reload\n");
viewCLI.finalActions();
}
int count=1;
for (CardWeapon weapon: viewCLI.getWeapons()){
if(!weapon.isCharge()){
out.println(count + ":" + weapon.getName() + "\t");
count++;
}
}
int i;
out.println("\n choose a number from 1 to" + (count-1) + "or 9 to cancel\n");
boolean corrected=false;
while(!corrected) {
i=in.nextInt();
if(i>=1 && i<=(count-1)){
viewCLI.getClient().send(new ReloadMessage(viewCLI.getClient().getToken(),i-1));
return i-1;
}
else if(i==9)
corrected=true;
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ (count-1)+"" );
}
}
return 0;
}
}
<file_sep>/src/main/java/Model/Hand.java
package Model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Hand implements Serializable {
private ArrayList<CardWeapon> playerWeapons;
private ArrayList<CardPowerUp> playerPowerUps;
private int[] ammoRYB;
private PlayerBoard playerBoard;
public Hand(PlayerBoard playerBoard){
this.playerWeapons = new ArrayList<>();
this.playerPowerUps = new ArrayList<>();
this.ammoRYB= new int[3];
this.playerBoard=playerBoard;
}
public List<CardPowerUp> getPlayerPowerUps() {
return playerPowerUps;
}
public List<CardWeapon> getPlayerWeapons() {
return playerWeapons;
}
public int[] getAmmoRYB() {
return ammoRYB;
}
public PlayerBoard getPlayerBoard() {
return playerBoard;
}
/**
* this method add new weapon after grab cardWeapon and decrement ammo
* */
public void addWeapon(CardWeapon weapon) {
playerWeapons.add(playerWeapons.size(),weapon);
}
/**
* this method set charge true in a weapon and decrement its cost
* */
public void chargeWeapon(CardWeapon weapon,int red, int yellow, int blue){
weapon.setCharge(true);
}
/**
*this method remove an offload weapon and pay its cost with ammo and power up
* */
public void chargeWeapon(CardWeapon weapon,int red, int yellow, int blue, List<CardPowerUp> powerUp){
weapon.setCharge(true);
for(CardPowerUp p:powerUp){
if(p.getColor()==AmmoColors.RED)
red--;
else if(p.getColor()==AmmoColors.YELLOW)
yellow--;
else if(p.getColor()==AmmoColors.BLUE)
blue--;
removePowerUp(getPlayerPowerUps().indexOf(p));
}
decrementAmmo(red,yellow,blue);
}
/**
*this method substitute weapons when the player has three weapons and wants a new weapon
* */
public void substituteWeapons(int weaponPosition){
playerWeapons.remove(weaponPosition);
}
/**
* this method add a power up after when the player grabs its when he doesn't have more than three power up
* */
public void addPowerUp(CardPowerUp powerUp) {
playerPowerUps.add(powerUp);// we can delete index
}
/**
* this method use power up and remove it
* */
public void usePowerUp(CardPowerUp cardPowerUp,Player target,NormalSquare square,int pos){
if(cardPowerUp.getDamage()==1){
System.out.println("fgjngnogwourtuortuoruw uso scoop njrgoejgnoettnonte");
target.getPlayerBoard().getHealthPlayer().addDamage(getPlayerBoard().getPlayer(),1);}
else if(cardPowerUp.getMyMove()==-1){
getPlayerBoard().getPlayer().newPosition(square);}
else if(cardPowerUp.getOtherMove()==2)
new Move(target,square,2).execute();
removePowerUp(pos);
}
/**
* This method remove a power up after use its
* */
public void removePowerUp(int position){
System.out.println(getPlayerPowerUps().size());
System.out.println(position);
getPlayerPowerUps().remove(position);
}
/**
* This method add new ammo after grab cardAmmo
* */
public void addAmmo(int red, int yellow, int blue) {
ammoRYB[0]= ammoRYB[0] +red;
if(ammoRYB[0]>3)
ammoRYB[0]=3;
ammoRYB[1]=ammoRYB[1] +yellow;
if(ammoRYB[1]>3)
ammoRYB[1]=3;
ammoRYB[2]=ammoRYB[2] +blue;
if(ammoRYB[2]>3)
ammoRYB[2]=3;
}
/**
* This method decrement the value of array ammoRYB, exception by controller
* */
public void decrementAmmo(int red,int yellow,int blue){
ammoRYB[0]-=red;
ammoRYB[1]-=yellow;
ammoRYB[2]-=blue;
}
}
<file_sep>/src/test/java/Model/PlayerBoardTest.java
package Model;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class PlayerBoardTest {
/*
* This method tests the constructor
* */
@Test
public void testConstructor(){ ;
Player player=new Player(2832, Colors.GREEN);
assertNotNull(player.getPlayerBoard());
}
/**
* this method tests the decrement of max reward
* */
@Test
public void testDecrementMaxReward(){
Player player=new Player(2832, Colors.GREEN);
player.getPlayerBoard().decrementMaxReward();
assertEquals(6,player.getPlayerBoard().getMaxReward());
}
/**
* this method tests the add of points
* */
@Test
public void testAddPoints(){
Player player=new Player(2832, Colors.GREEN);
player.getPlayerBoard().addPoints(4);
assertEquals(4,player.getPlayerBoard().getPoints());
}
}
<file_sep>/src/main/java/Model/Move.java
package Model;
import java.io.Serializable;
import java.util.ArrayList;
/**
* This class implements Action
*/
public class Move implements Action, Serializable {
private Player targetPlayer;
private NormalSquare startSquare;
private NormalSquare selectedSquare;
private int movePass;
/**
* @param target the Player that is target by the action
* @param square the NormalSquare selected by the Player as the final NormalSquare for the target
* @param move the max number of pass that the Player can do
*/
public Move(Player target, NormalSquare square, int move){
targetPlayer = target;
selectedSquare = square;
startSquare = targetPlayer.getPosition();
movePass = move;
}
/**
* This method execute the Move Action
*
* @return true if the action has been executed, false otherwise
*/
public boolean execute(){
targetPlayer.newPosition(selectedSquare);
return true;
}
/**
* Control the Pre-condition of the Move Action
* This method invoke reachableSquare method
*
* @return true if the action invocation respect the condition, false otherwise
*/
public boolean isValid(){
return reachableSquare().contains(selectedSquare);
}
/**
* This method return all the reachable square from startSquare
* In reachableSquare it will be putted the Square directly connected with the Square that I take into consideration in the current step
* In reachable it will be putted all the Square reachable from startSquare with a number of step equal or less then "move"
*
* This method return the reachable square from the player
* This method is invoked to show to the Player where he can go with the view
* */
public ArrayList<NormalSquare> reachableSquare(){
ArrayList<NormalSquare> reachableSquare = new ArrayList<>();
ArrayList<NormalSquare> reachable = new ArrayList<>();
reachableSquare.add(startSquare);
reachable.add(startSquare);
int thisStep;
for(int i = 0, j; i < movePass; i++) {
thisStep = reachableSquare.size();
j = 0;
while(j < thisStep ){
isAlreadyReachable(reachableSquare.get(0).getN(), reachableSquare, reachable);
isAlreadyReachable(reachableSquare.get(0).getE(), reachableSquare, reachable);
isAlreadyReachable(reachableSquare.get(0).getS(), reachableSquare, reachable);
isAlreadyReachable(reachableSquare.get(0).getW(), reachableSquare, reachable);
reachableSquare.remove(0);
j++;
}
}
return reachable;
}
/**
* This method is invoked by reachableSquare method
*/
private void isAlreadyReachable(NormalSquare square, ArrayList<NormalSquare> reachableSquare, ArrayList<NormalSquare> reachable){
if (square != reachableSquare.get(0)) {
reachableSquare.add(square);
if(!reachable.contains(square))
reachable.add(square);
}
}
}
<file_sep>/src/test/java/Model/DeckCreatorTest.java
package Model;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import java.lang.reflect.InvocationTargetException;
import static org.junit.jupiter.api.Assertions.*;
public class DeckCreatorTest {
/**
* This method test DeckCreator class when is used to create a WeaponCard's deck
* */
@Test
public void createDeckWeaponTest() throws FileNotFoundException{
Deck<CardWeapon> deck;
DeckCreator deckCreator;
deckCreator = new DeckCreator();
deck = deckCreator.createDeck("WEAPON");
assertTrue(deckCreator.createDeck("WEAPON").getCard(0) instanceof CardWeapon); //Check if card inserted in deck are of the correct type
assertEquals(21, deck.getSize()); //Weapon card deck should be of 21 card (Now is 4 because not all json file are fixed)
assertEquals(WeaponDictionary.CYBERBLADE.getAbbreviation(), deck.getCard(0).getName()); //Deck is created in alphabetical order so first card should be cyberblade
//assertEquals(0, deck.getSize()); // After getting a card this should be removed from the deck
}
/**
* This method test DeckCreator class when is used to create a Ammo's deck
* */
@Test
public void createDeckAmmoTest() throws FileNotFoundException{
Deck<CardAmmo> deck;
DeckCreator deckCreator;
deckCreator = new DeckCreator();
deck = deckCreator.createDeck("AMMO");
assertTrue(deckCreator.createDeck("AMMO").getCard(0) instanceof CardAmmo); //Check if card inserted in deck are of the correct type
assertEquals(36, deck.getSize()); //Ammo card deck should be of 36 card
deck.getCard(0);
assertEquals(35, deck.getSize()); // After getting a card this should be removed from the deck
}
/**
* This method test DeckCreator class when is used to create a Ammo's deck
* */
@Test
public void createDeckPowerUpTest() throws FileNotFoundException{
Deck<CardPowerUp> deck;
DeckCreator deckCreator;
deckCreator = new DeckCreator();
deck = deckCreator.createDeck("POWERUP");
assertTrue(deckCreator.createDeck("POWERUP").getCard(0) instanceof CardPowerUp); //Check if card inserted in deck are of the correct type
assertEquals(12, deck.getSize()); //Ammo card deck should be of 12 card
deck.getCard(0);
assertEquals(11, deck.getSize()); // After getting a card this should be removed from the deck
}
}
<file_sep>/src/main/java/network/messages/GrabWeaponRequest.java
package network.messages;
/**
* This message send a grab request to the player
*/
public class GrabWeaponRequest extends Message{
public GrabWeaponRequest(Integer token){
this.token = token;
this.actionType = ActionType.GRABWEAPONREQUEST;
}
}
<file_sep>/src/main/java/Model/AmmoEnum.java
package Model;
import java.io.Serializable;
/**
* This enumeration is used to list the name that other classes use to refer to ammo cards
* */
public enum AmmoEnum implements Serializable {
AMMO1("A1"),
AMMO2("A2"),
AMMO3("A3"),
AMMO4("A4"),
AMMO5("A5"),
AMMO6("A6"),
AMMO7("A7"),
AMMO8("A8"),
AMMO9("A9"),
AMMO10("A10"),
AMMO11("A11"),
AMMO12("A12"),
AMMO13("A13"),
AMMO14("A14"),
AMMO15("A15"),
AMMO16("A16"),
AMMO17("A17"),
AMMO18("A18");
private String abbreviation;
private AmmoEnum(String abbreviation) {
this.abbreviation=abbreviation;
}
public String getAbbreviation(){
return abbreviation;
}
}
<file_sep>/src/main/java/network/messages/SubstituteWeaponResponse.java
package network.messages;
import Model.CardWeapon;
import java.util.List;
public class SubstituteWeaponResponse extends Message {
private int weapon;
public SubstituteWeaponResponse(Integer token, int weapon){
actionType=ActionType.SUBSTITUTEWEAPONRESPONSE;
this.token=token;
this.weapon=weapon;
}
public int getWeapon() {
return weapon;
}
}
<file_sep>/README.md
# ing-sw-2019-34
What is Adrenalina
A War Card BoardGame for 3 to 5 players that plays in about 60 minutes.
Index of the ReadMe
- How to run the game
- External libraries used
- Specification covered
Usage
The game require Java 8 or later version to run.
Client
$ java -jar client.jar [cli/gui] [ip-address]
Option
[cli/gui] - type cli or gui to chose from Command Line Interface and Graphical User Interface (default: cli)
[ip-address] - you can specify the ip address of the server (default: localhost)
Server
$ java -jar server.jar [ip-address]
External libreries used
JSON
Game-Specific met requirements:
The game is realized with the complete-rules
Game-agnostic met requirements:
Server side
Implemented rules' game with JavaSE
Instantiated only once
It supports matches with Socket and RMI simultaneously
Client side
Implemented with JavaSE
GUI implemented with Swing
On startup the player can choose the type of connection (Socket or RMI)
On startup the player can choose the type of user interface (CLI or GUI)
Match start
A new match start when almost 3 player up to 5 are connected togheter
The match starts once there are almost 3 logged players. When 3 players connect to the match, a timer is initialized. If the timer expires the game start.
During the match
The players must follow the game's rules
The disconnection is handled both when it happens automatically and manually
The game continues, skipping the disconnected player
The players must do a move within a timer's duration
If at some point the number of player in the match is less then 3, the match ends with the remaining player's victory
Advanced functionalities
Multiple matches: the server can handle more matches at a time (players are handled with queues and rooms)
Developers
$ <NAME> (https://github.com/DavidePolimi)
$ <NAME> (https://github.com/MarcoPianta)
$ <NAME> (https://github.com/FrancescoVaghi)
<file_sep>/src/main/java/network/Client/RMI/RMIClientInterface.java
package network.Client.RMI;
import network.messages.Message;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RMIClientInterface extends Remote {
void onReceive(Message message) throws RemoteException;
}
<file_sep>/src/main/java/network/messages/ConnectionResponse.java
package network.messages;
/**
* This message is used when a client connected to the server wants to connect to a new game
* */
public class ConnectionResponse extends Message{
public ConnectionResponse(Integer token){
this.actionType = ActionType.CONNECTIONRESPONSE;
this.token = token;
}
}
<file_sep>/src/main/java/Utils/JsonFileHandler.java
package Utils;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.*;
import java.net.URL;
public final class JsonFileHandler {
public static JsonObject openFile(String directory, String file) throws FileNotFoundException {
JsonObject jsonValues = null; /* this variable contains the JsonObject created from JSON file*/
URL path = JsonFileHandler.class.getClassLoader().getResource( directory + "/" + file + ".json");
try {
InputStream fis = path.openStream();
JsonReader reader = Json.createReader(fis);
jsonValues = reader.readObject();
reader.close();
return jsonValues;
}catch (IOException e){}
return jsonValues;
}
private JsonFileHandler(){}
}
<file_sep>/src/main/java/network/messages/ConnectionRequest.java
package network.messages;
/**
* This message is used when a client connected to the server wants to connect to a new game
* */
public class ConnectionRequest extends Message{
public ConnectionRequest(){
this.actionType = ActionType.CONNECTIONREQUEST;
}
}
<file_sep>/src/main/java/network/messages/Shot.java
package network.messages;
import Model.*;
import java.util.ArrayList;
import java.util.List;
public class Shot extends Message {
private List<Player> targets;
private Integer posEffect;
private ArrayList<NormalSquare> squares;
private Room room;
private int weapon;
private Integer powerUp;
private Player targetPowerUp;
public Shot(List<Player> targets, Integer posEffect, int weapon, Integer powerUp, Player targetPowerUp){
actionType=ActionType.SHOT;
this.posEffect =posEffect;
this.room=null;
this.squares=null;
this.targets =targets;
this.weapon=weapon;
this.powerUp=powerUp;
this.targetPowerUp=targetPowerUp;
}
public Shot(ArrayList<NormalSquare> square, Integer posEffect, int weapon, Integer powerUp, Player targetPowerUp){
actionType=ActionType.SHOT;
this.posEffect =posEffect;
this.room=null;
this.squares=squares;
this.targets =null;
this.weapon=weapon;
this.powerUp=powerUp;
this.targetPowerUp=targetPowerUp;
}
public Shot(Room room, Integer posEffect, int weapon, Integer powerUp, Player targetPowerUp){
actionType=ActionType.SHOT;
this.posEffect =posEffect;
this.room=room;
this.squares=null;
this.targets =null;
this.weapon=weapon;
this.powerUp=powerUp;
this.targetPowerUp=targetPowerUp;
}
public Shot(Integer token, List<Player> targets, Integer posEffect, int weapon){
this.token = token;
actionType=ActionType.SHOT;
this.posEffect =posEffect;
this.room=null;
this.squares=null;
this.targets =targets;
this.powerUp=-1;
this.weapon=weapon;
}
public Shot(Integer token, ArrayList<NormalSquare> square, Integer posEffect, int weapon){
this.token = token;
actionType=ActionType.SHOT;
this.posEffect =posEffect;
this.room=null;
this.squares=square;
this.targets =null;
this.powerUp=-1;
this.weapon=weapon;
}
public Shot(Integer token, Room room, Integer posEffect, int weapon){
this.token = token;
actionType=ActionType.SHOT;
this.posEffect =posEffect;
this.room=room;
this.squares=null;
this.targets =null;
this.powerUp=-1;
this.weapon=weapon;
}
public List<NormalSquare> getSquare() {
return squares;
}
public Room getRoom() {
return room;
}
public Player getTargetPowerUp() {
return targetPowerUp;
}
public Integer getPowerUp() {
return powerUp;
}
public int getWeapon() {
return weapon;
}
public List<Player> getTargets() {
return targets;
}
public Integer getPosEffect() {
return posEffect;
}
public void setPowerUp(Integer powerUp) {
this.powerUp = powerUp;
}
}
<file_sep>/src/test/java/Model/GameBoardTest.java
package Model;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
public class GameBoardTest {
/**
* This method tests if GameBoard constructor read the map and store it in data structures correctly.
* The method check only the second room and its side of map1.json
* */
@Test
public void constructorTest() throws FileNotFoundException {
GameBoard gameBoard = new GameBoard("map1");
assertEquals("Map1", gameBoard.getName());
assertEquals(3, gameBoard.getRooms().get(0).getNormalSquares().size());
//The following assertion check the first square
assertEquals(gameBoard.getRooms().get(0).getNormalSquares().get(0), gameBoard.getRooms().get(1).getNormalSquares().get(0).getN());
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(1), gameBoard.getRooms().get(1).getNormalSquares().get(0).getE());
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(0), gameBoard.getRooms().get(1).getNormalSquares().get(0).getS());
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(0), gameBoard.getRooms().get(1).getNormalSquares().get(0).getW());
assertEquals("1,0", gameBoard.getRooms().get(1).getNormalSquares().get(0).getId());
//The following assertion check the second square
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(1), gameBoard.getRooms().get(1).getNormalSquares().get(1).getN());
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(2), gameBoard.getRooms().get(1).getNormalSquares().get(1).getE());
assertEquals(gameBoard.getRooms().get(3).getNormalSquares().get(0), gameBoard.getRooms().get(1).getNormalSquares().get(1).getS());
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(0), gameBoard.getRooms().get(1).getNormalSquares().get(1).getW());
assertEquals("1,1", gameBoard.getRooms().get(1).getNormalSquares().get(1).getId());
//The following assertion check the third square
assertEquals(gameBoard.getRooms().get(0).getNormalSquares().get(2), gameBoard.getRooms().get(1).getNormalSquares().get(2).getN());
assertEquals(gameBoard.getRooms().get(2).getNormalSquares().get(0), gameBoard.getRooms().get(1).getNormalSquares().get(2).getE());
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(2), gameBoard.getRooms().get(1).getNormalSquares().get(2).getS());
assertEquals(gameBoard.getRooms().get(1).getNormalSquares().get(1), gameBoard.getRooms().get(1).getNormalSquares().get(2).getW());
assertEquals("1,2", gameBoard.getRooms().get(1).getNormalSquares().get(2).getId());
assertEquals(Colors.RED, gameBoard.getRooms().get(1).getColor());
}
}
<file_sep>/src/main/java/network/messages/PaymentResponse.java
package network.messages;
import java.util.ArrayList;
import java.util.List;
public class PaymentResponse extends Message{
private boolean usePowerUp;
private boolean scoop;
private List<Integer> powerUp;
private Integer [] cost;
private Integer powerUpScoop;
private String colorScoop;
/**
6 * constructor Payment response
* @param token
* @param powerUp list of powerUp to pay cost
* @param usePowerUp true indicate the payment with powerUp
* @param scoop true indicate the use of scoop powerup
*/
public PaymentResponse(Integer token,List<Integer> powerUp,boolean usePowerUp, Integer[] cost,boolean scoop){
actionType=ActionType.PAYMENTRESPONSE;
this.token=token;
this.powerUp=powerUp;
this.usePowerUp=usePowerUp;
this.cost=cost;
this.scoop=scoop;
this.powerUpScoop=null;
this.colorScoop=null;
}
public PaymentResponse(Integer token,List<Integer> powerUp,boolean usePowerUp, Integer[] cost,boolean scoop,String colorScoop, Integer powerUpScoop){
actionType=ActionType.PAYMENTRESPONSE;
this.token=token;
this.powerUp=powerUp;
this.usePowerUp=usePowerUp;
this.cost=cost;
this.scoop=scoop;
this.powerUpScoop=powerUpScoop;
this.colorScoop=colorScoop;
}
public Integer[] getCost() {
return cost;
}
public List<Integer> getPowerUp() {
return powerUp;
}
public boolean isUsePowerUp() {
return usePowerUp;
}
public boolean isScoop() {
return scoop;
}
public Integer getPowerUpScoop() {
return powerUpScoop;
}
public String getColorScoop() {
return colorScoop;
}
}
<file_sep>/src/main/java/network/Server/Socket/SocketServer.java
package network.Server.Socket;
import network.Server.Server;
import network.messages.ActionType;
import network.messages.ConnectionResponse;
import network.messages.GameSettingsRequest;
import network.messages.Message;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
/**
* This class represent the socket server; it is used to send and receive message from the client using socket
* connection.
* The default port on which the server socket is created is 10000, although is possible to change the default port.
* */
public class SocketServer {
private ServerSocket serverSocket;
private int port;
private Server server; //This variable is used to contain the main server
private HashMap<Integer, SocketClientHandler> threadHashMap;
/**
* This constructor creates a new server socket listening on the default port 10000
* @param server the main server
* */
public SocketServer(Server server) {
this.server = server;
this.port = 10000;
threadHashMap = new HashMap<>();
}
/**
* This constructor creates a new server socket listening on the port indicated as parameter
* @param server the main server
* @param port the port on which the server will listen for new connection
* */
public SocketServer(Server server, int port) {
this.server = server;
this.port = port;
threadHashMap = new HashMap<>();
}
/**
* This method initialize the server creating a new ServerSocket ready to listen for new connection on the
* indicated port.
* */
//TODO catch exception
private void init() throws IOException{
serverSocket = new ServerSocket(port);
}
/**
* This method accept a new connection from a client.
* When a new connection is accepted a new Thread running SocketClientHandler's method run is started, so that more
* than one client will be able to communicate with the server.
* To every new client is assigned a unique token which is sent to the client using a ConnectionResponse message.
* Every connected client is also added to an hash map using the token as key
* */
//TODO catch exception
public void acceptConnection() throws IOException{
while (threadHashMap.size() < 100) {
Socket socket = serverSocket.accept();
int token = server.generateToken(0,false);
SocketClientHandler clientHandler = new SocketClientHandler(socket, token, this);
Thread thread = new Thread(clientHandler);
thread.start();
threadHashMap.put(token, clientHandler);
clientHandler.respond(new ConnectionResponse(token));
send(new GameSettingsRequest(token));
}
}
/**
* This method forward the message received from the client directly to the main server
* @param message the message to be forwarded to the server
* */
public void onReceive(Message message){
if (message.getActionType().getAbbreviation().equals(ActionType.DISCONNECT.getAbbreviation()))
removeClient(message.getToken());
server.onReceive(message);
}
public void send(Message message){
threadHashMap.get(message.getToken()).respond(message);
}
/**
* This is the main method of the server.
* This method is called when the server need to be started.
* */
public void run() throws IOException{
init();
new Thread(() -> {
try {
acceptConnection();
}catch (IOException e){
//TODO log exception
}
}).start();
}
/**
* When a socket connection is closed the client is remove from the hash map containing the Thread of every
* connected client. The client is also removed from the main server
* @param token the identifier of the client to be removed.
*/
public void removeClient(Integer token){
server.removeClient(token);
threadHashMap.remove(token);
}
}
<file_sep>/src/main/java/Model/WeaponDictionary.java
package Model;
import java.io.Serializable;
/**
* This enumeration contains the name's list of all weapon cards
* */
public enum WeaponDictionary implements Serializable {
CYBERBLADE("cyberblade"),
ELECTROSCYTE("electroscyte"),
FLAMETHROWER("flamethrower"),
FURNACE("furnace"),
GRENADELAUNCHER("grenadeLauncher"),
HEATSEEKER("heatseeker"),
HELLION("hellion"),
LOCKRIFLE("lockRifle"),
MACHINEGUN("machineGun"),
PLASMAGUN("plasmaGun"),
POWERGLOVE("powerGlove"),
RAILGUN("railGun"),
ROCKETLAUNCHER("rocketLauncher"),
SHOCKWAVE("shockwave"),
SHOTGUN("shotgun"),
SLEDGEHAMMER("sledgehammer"),
THOR("thor"),
TRACTORBEAM("tractorBeam"),
WHISPER("whisper"),
ZX_2("ZX-2"),
VORTEXCANNON("vortexCannon");
private String abbreviation;
private WeaponDictionary(String abbreviation) {
this.abbreviation=abbreviation;
}
public String getAbbreviation(){
return abbreviation;
}
}<file_sep>/src/main/java/network/messages/ShootRequestr.java
package network.messages;
import java.util.List;
/**
* This message is sended by GameLobby to the Client when a Shoot Action contain a 'r' element in its actionSequence
* with this message send the List of ID related to the square that should be selected as target for a RoomShot
*/
public class ShootRequestr extends Message{
private List<String> roomTargetable;
public ShootRequestr(Integer token, List<String> roomTargetable){
this.token = token;
this.actionType = ActionType.SHOOTREQUESTR;
this.roomTargetable = roomTargetable;
}
public List<String> getRoomTargetable() {
return roomTargetable;
}
}
<file_sep>/src/main/java/network/messages/UpdateClient.java
package network.messages;
import Model.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class UpdateClient extends Message implements Serializable {
private List<Colors> damageBar; //The damageBar is made of colors to be displayed
private String squareID; //The id of the square to send in the message
private ArrayList<String> reachableSquares; //ArrayList of IDs of squares to be send
private ArrayList<String> reachableTarget; //ArrayList of possible target Players' square ID
private String type; //Type of update (position, damageBar, etc.)
private CardPowerUp powerUp;
private CardWeapon weapon;
private int posWeapon;
private CardAmmo ammo;
private List<Colors> marks;
private String textMessage;
private Colors otherColor;
private List<CardWeapon> weapons;
private List<CardPowerUp> powerUps;
private int red;
private int yellow;
private int blue;
private int points;
private void setMessageInfo(Integer token, String type){
this.actionType = ActionType.UPDATECLIENTS;
this.token = token;
this.type = type;
}
/**
* This constructor is used to build messages to update the damage bar status in clients
* @param token token of the clients who need to be updated
* @param damageBar the array which contains the new damageBar to send to the client
*/
public UpdateClient(Integer token, List<Player> damageBar,List<Player> marks){
setMessageInfo(token, DAMAGEBARUPDATE);
this.damageBar = damageBar.stream().map(Player::getColor).collect(Collectors.toList());
this.marks = marks.stream().map(Player::getColor).collect(Collectors.toList());
}
/**
* This constructor is used to build messages to update the damage bar status in clients
* @param token token of the clients who need to be updated
* @param damageBar the array which contains the new damageBar to send to the client
*/
public UpdateClient(Integer token, Colors player, List<Player> damageBar, List<Player> marks){
setMessageInfo(token, OTHERDAMAGEBAR);
this.otherColor = player;
this.damageBar = damageBar.stream().map(Player::getColor).collect(Collectors.toList());
this.marks = marks.stream().map(Player::getColor).collect(Collectors.toList());
}
/**
* This constructor is used to build messages to update the position of a player
* @param token token of the clients who need to be updated
* @param square the square which indicates the new position of the player
*/
public UpdateClient(Integer token, NormalSquare square){
setMessageInfo(token, POSITION);
this.squareID = square.getId();
}
/**
* This constructor is used to build messages to update the position of a player
* @param token token of the clients who need to be updated
* @param square the square which indicates the new position of the player
*/
public UpdateClient(Integer token, Colors otherPlayer, NormalSquare square){
setMessageInfo(token, OTHERPOSITION);
this.squareID = square.getId();
this.otherColor = otherPlayer;
}
/**
* This constructor is used to build messages to send to the client the reachable squares.
* @param token token of the clients who need to be updated
* @param squares a list that contains the reachable squares
*/
public UpdateClient(Integer token, List<NormalSquare> squares){
setMessageInfo(token, POSSIBLESQUARES);
this.reachableSquares = new ArrayList<>();
for (NormalSquare s: squares)
this.reachableSquares.add(s.getId());
}
/**
* This constructor is used to build messages to send to the client the possible target.
* @param token token of the clients who need to be updated
* @param players a list that contains the reachable squares
*/
public UpdateClient(Integer token, ArrayList<Player> players){
setMessageInfo(token, POSSIBLETARGET);
this.reachableTarget = new ArrayList<>();
for (Player p: players)
this.reachableTarget.add(p.getPosition().getId());
}
public UpdateClient(Integer token, int red,int yellow, int blue, List<CardWeapon> weapons, List<CardPowerUp> powerUps){
setMessageInfo(token, HANDPLAYER);
this.red=red;
this.yellow=yellow;
this.blue=blue;
this.weapons=weapons;
this.powerUps=powerUps;
}
public UpdateClient(Integer token){
setMessageInfo(token, RESPAWN);
}
public UpdateClient(Integer token, String squareId,CardWeapon weapon,int posWeapon){
setMessageInfo(token, FILLSPAWN);
this.squareID=squareId;
this.weapon=weapon;
this.posWeapon=posWeapon;
}
public UpdateClient(Integer token, String squareId,CardAmmo ammo){
setMessageInfo(token, FILLSQUARE);
this.squareID=squareId;
this.ammo=ammo;
}
/**
* This constructor is used to build messages to send to the client his points.
* @param token token of the clients who need to be updated
* @param points int for players points
*/
public UpdateClient(Integer token, int points){
setMessageInfo(token, POINTS);
this.points = points;
}
/**
* This constructor is used to build messages to send to the client a text message to be displayed.
* @param token token of the clients who need to be updated
* @param message a String that is the message to be sent to the client (for example to send error message)
*/
public UpdateClient(Integer token, String message){
setMessageInfo(token, MESSAGE);
this.textMessage = message;
}
public String getUpdateType() {
return type;
}
/**
* The following static values are used to distinguish the UpdateClient message type.
*/
public static final String POSSIBLETARGET = "POSSIBLETARGET";
public static final String DAMAGEBARUPDATE ="DAMAGEBAR";
public static final String POSSIBLESQUARES = "POSSIBLESQUARES";
public static final String POSITION = "POSITION";
public static final String OTHERPOSITION = "OTHERPOSITION";
public static final String OTHERDAMAGEBAR = "OTHERDAMAGEBAR";
public static final String RESPAWN = "RESPAWN";
public static final String MESSAGE = "MESSAGE";
public static final String HANDPLAYER = "HANDPLAYER";
public static final String FILLSPAWN = "FILLSPAWN";
public static final String FILLSQUARE = "FILLSQUARE";
public static final String POINTS = "POINTS";
public ArrayList<String> getReachableTarget() {
return reachableTarget;
}
public List<Colors> getDamageBar() {
return damageBar;
}
public ArrayList<String> getReachableSquares() {
return reachableSquares;
}
public String getSquareID() {
return squareID;
}
public CardPowerUp getPowerUp() {
return powerUp;
}
public String getMessage() {
return textMessage;
}
public CardAmmo getAmmo() {
return ammo;
}
public CardWeapon getWeapon() {
return weapon;
}
public int getPosWeapon() {
return posWeapon;
}
public Colors getOtherColor() {
return otherColor;
}
public List<Colors> getMarks() {
return marks;
}
public int getBlue() {
return blue;
}
public int getRed() {
return red;
}
public int getYellow() {
return yellow;
}
public List<CardPowerUp> getPowerUps() {
return powerUps;
}
public List<CardWeapon> getWeapons() {
return weapons;
}
public int getPoints() {
return points;
}
}
<file_sep>/src/main/java/view/cli/ViewCLI.java
package view.cli;
import Model.*;
import network.Client.RMI.RMIClient;
import network.Client.Socket.SocketClient;
import network.messages.*;
import view.View;
import java.io.PrintWriter;
import java.util.*;
public class ViewCLI extends View {
private static PrintWriter out=new PrintWriter(System.out,true);
private static Scanner in=new Scanner(System.in);
private int myPoint;
private HashMap<String, CardWeapon[]> spawnSquareWeapon;
private boolean finalTurn;
private boolean update=false;
private boolean grab=false;
private boolean move=false;
private boolean waitUpdate=false;
private boolean shot=false;
private ActionCLI actionCLI;
public ViewCLI(){
actionCLI=new ActionCLI(this);
out.println("what you want to use?? 1=Socket 2=RMI");
boolean corrected=false;
while(!corrected) {
int i=in.nextInt();
if(i==1){
client= new SocketClient("localhost",10000,this);
corrected=true;
}
else if(i==2){
client= new RMIClient("localhost",10000,this);
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ 3);
}
}
myPoint=0;
spawnSquareWeapon=new HashMap<>();
spawnSquareWeapon.put("0,2",new CardWeapon[3]);
spawnSquareWeapon.put("1,0",new CardWeapon[3]);
spawnSquareWeapon.put("2,3",new CardWeapon[3]);
finalTurn=false;
}
public boolean isFinalTurn() {
return finalTurn;
}
public static void main(String[] args) {
new ViewCLI();
}
@Override
public void chatMessage(String message) {
}
public void setMyTurn(boolean myTurn) {
this.myTurn=myTurn;
}
@Override
public void finalTurn() {
out.println("finally is the final turn");
finalTurn=true;
}
@Override
public void grabWeaponRequest() {
out.println("you can choose one of this weapon to grab");
int i=1;
for(CardWeapon weapon :spawnSquareWeapon.get(myPositionID)){
out.println(i+ "="+weapon.getName() +"\t");
i++;
}
out.println("choose a number from 1 to "+ 3 +"");
boolean corrected=false;
while(!corrected) {
i=in.nextInt();
if(i>=1 && i<=3){
client.send(new GrabWeapon(client.getToken(),i-1));
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ 3);
}
}
}
@Override
public void substituteWeaponRequest() {
out.println("you have a four weapon, choose the weapon that you want to eliminate");
int c=1;
for(CardWeapon weapon:weapons){
out.println(c+ "="+weapon.getName() +"\t");
c++;
}
out.println("choose a number from 1 to "+ weapons.size() +"");
boolean corrected=false;
while(!corrected) {
int i=in.nextInt();
if(i>=1 && i<=weapons.size()){
client.send(new SubstituteWeaponResponse(client.getToken(),i-1));
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ weapons.size() +"" );
}
}
}
@Override
public void showReachableSquares(List<String> squares) {
out.println("you can reach these squares: ");
int i=1;
for(String s:squares){
out.println(i+ "="+s +"\t");
i++;
}
out.println("choose a number from 1 to "+ squares.size() +"");
boolean corrected=false;
while(!corrected) {
i=in.nextInt();
if(i>=1 && i<=squares.size()){
if(move && !grab){
numberAction++;
//move=false;
client.send(new MoveResponse(client.getToken(),squares.get(i-1)));
}
else if(grab && (squares.get(i-1).equals("0,2")||squares.get(i-1).equals("1,0")||squares.get(i-1).equals("2,3"))) {
client.send(new MoveResponse(client.getToken(),squares.get(i-1)));
}
else {
numberAction++;
client.send(new MoveResponse(client.getToken(),squares.get(i-1)));
}
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ squares.size() +"" );
}
}
if(move){
if(numberAction>=3 && !finalTurn)
finalActions();
else if(finalTurn)
finalTurnAction();
else
startActions();
}
}
@Override
public void showPossibleRooms(List<String> ids) {
out.println("you can a shoot a one room, choose a square with color of room: ");
int i=1;
for(String id:ids){
out.println(i+ "="+id +"\t");
i++;
}
out.println("choose a number from 1 to "+ ids.size() +"");
boolean corrected=false;
while(!corrected) {
i=in.nextInt();
if(i>=1 && i<=ids.size()){
client.send(new ShootResponser(client.getToken(),ids.get(i-1)));
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ ids.size() +"" );
}
}
}
@Override
public void setNumberAction(int numberAction) {
this.numberAction=numberAction;
}
@Override
public void showPossibleSquares(List<String> targets) {
out.println("you can a shoot a one of this square: ");
int i=1;
for(String s:targets){
out.println(i+ "="+s+"\t");
i++;
}
out.println("choose a number from 1 to "+ targets.size() +"");
boolean corrected=false;
while(!corrected) {
i=in.nextInt();
if(i>=1 && i<=targets.size()){
client.send(new ShootResponses(client.getToken(),targets.get(i-1)));
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ targets.size() +"" );
}
}
}
@Override
public void showPossibleTarget(List<Colors> targets,int i) {
boolean esc=false;
out.println("you can shot these targets: ");
for(Colors c:targets){
out.println(c +"\t");
}
out.println(" choose a number from 0 to "+ targets.size());
out.println("choose max"+i+"target and press 9 when terminate");
int count=0;
List<Colors> targetChoose=new ArrayList();
while(count<i || !esc) {
i=in.nextInt();
if(i>=1 && i<=targets.size()){
targetChoose.add(targets.get(i-1));
count++;
}
else if(i==9){
esc=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ targets.size() +"" );
out.println("choose max"+i+"target and press 9 when terminate");
}
}
client.send(new ShootResponsep(client.getToken(),targetChoose));
}
@Override
public void payment(Payment message) {
out.println("you must pay: red= "+message.getCost()[0]+" yellow= "+message.getCost()[1]+" blue= "+message.getCost()[2]);
out.println(" PRESS 1 if you want to pay the effect with powerUp, or another number if you wan't");
ArrayList<Integer> powerUp= new ArrayList<>();
boolean corrected=false;
while(!corrected) {
int i=in.nextInt();
if(i==1){
boolean esc=false;
int count=1;
for ( CardPowerUp card: powerUps){
out.println(count + ":" +card.getName() +" "+ card.getColor() + "\t");
count++;
}
out.println("\n choose a number from 1 to" + count+ "or 9 to esc(you can use more powerUp)\n");
while(!esc) {
i=in.nextInt();
if(i>=1 && i<=powerUps.size()){
out.println("you have choose a powerUp to pay");
powerUp.add(i-1);
}
else if(i==9){
esc=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("\n choose a number from 1 to" + count + "or 9 to esc(you can use more powerUp)\n");
}
if(!esc)
System.out.println("choose another powerUp");
}
corrected=true;
}
else if(i>1)
corrected=true;
else{
out.println("it's not difficult, you can do it ");
out.println(" PRESS 1 if you want to pay the effect with powerUp, or another number if you wan't");
}
}
corrected=false;
if (message.getPowerUp()!=-1){
out.println(" PRESS 1 if you want to pay the scope with powerUp, 2 if you don't want\n");
while(!corrected) {
int i=in.nextInt();
if(i==1){
paymentWithScope(message.getPowerUp(),powerUp,message.getCost());
corrected=true;
}
else if(i==2){
paymentWithScope2(message.getPowerUp(),powerUp,message.getCost());
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println(" PRESS 1 if you want to pay the scope with powerUp, 2 if you don't want\n");
}
}
}
else {
numberAction++;
if(powerUp.isEmpty())
client.send(new PaymentResponse(client.getToken(), powerUp, false, message.getCost(), false));
else
client.send(new PaymentResponse(client.getToken(), powerUp, true, message.getCost(), false));
}
}
private void paymentWithScope(Integer posPowerUp,ArrayList<Integer> paymentPowerUp,Integer[] cost){
int count=1;
for ( CardPowerUp p:powerUps){
if((powerUps.indexOf(p)!=posPowerUp && !paymentPowerUp.contains(powerUps.indexOf(p)))) {
out.print(count + ":" + p.getName()+" " + p.getColor() + "\t");
}
else
out.print(count + ": NOPOWERUP");
count++;
}
if(count!=1) {
out.println(" choose a number from 1 to" + count);
boolean corrected=false;
while (!corrected) {
int powerUpScope = in.nextInt();
if (powerUpScope >= 1 && powerUpScope <= count) {
if(paymentPowerUp.isEmpty()) {
numberAction++;
client.send(new PaymentResponse(client.getToken(), paymentPowerUp, false, cost, true, "", powerUpScope));
}
else {
numberAction++;
client.send(new PaymentResponse(client.getToken(), paymentPowerUp, true, cost, true, "", powerUpScope));
}
corrected = true;
} else {
out.println("it's not difficult, you can do it ");
out.println(" choose a number from 1 to" + count);
}
}
}
else
paymentWithScope2(posPowerUp,paymentPowerUp,cost);
}
private void paymentWithScope2(Integer posPowerUp,ArrayList<Integer> paymentPowerUp,Integer[] cost){
out.println("You must pay scope with ammo, press r for red, y for yellow, b for blue");
boolean corrected=false;
while (!corrected) {
String ammo = in.next();
if (ammo.equals("r")||ammo.equals("y")||ammo.equals("b")) {
if(paymentPowerUp.isEmpty())
client.send(new PaymentResponse(client.getToken(), paymentPowerUp,false, cost, true,ammo,-1));
else
client.send(new PaymentResponse(client.getToken(), paymentPowerUp,true, cost, true,ammo,-1 ));
corrected = true;
} else {
out.println("it's not difficult, you can do it ");
out.println("You must pay scope with ammo, press r for red, y for yellow, b for blue");
}
}
}
@Override
public void showTargetMove(List<String> targets) {
out.println("you can move the the target in a one of this square: ");
int i=1;
for(String s:targets){
out.println(i+ "="+s+"\t");
i++;
}
out.println("choose a number from 1 to "+ targets.size() +"");
boolean corrected=false;
while(!corrected) {
i=in.nextInt();
if(i>=1 && i<=targets.size()){
client.send(new TargetMoveResponse(client.getToken(),targets.get(i-1)));
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ targets.size() +"" );
}
}
}
public void updateEnemiesDamageBar(List<Colors> damageBar,List<Colors> marks, Colors player) {
out.println(player+"was attacked and his damagedBar was changed:" );
for(Colors color:damageBar)
out.println(color+",");
out.println("");
}
@Override
public void addMarks(ArrayList<Colors> marks, Colors player) {
out.println(player+"was attacked and his mark list was changed:" );
for(Colors color:damageBar)
out.println(color+",");
out.println("");
}
@Override
public void showPowerUpChooseRespawn() {
out.println("\nchoose the power up to discard to spawn in that color:");
int c=1;
for(CardPowerUp p:powerUps){
out.println(c +":"+p.getName()+", "+p.getColor()+ "\t");
c++;
}
out.println(" choose a number from 1 to "+ powerUps.size() +"" );
boolean corrected=false;
while(!corrected) {
int i=in.nextInt();
if(i>=1 && i<=powerUps.size()){
waitUpdate=true;
client.send(new RespawnMessage(client.getToken(),i-1));
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to "+ powerUps.size() +"" );
}
}
}
@Override
public void showMessage(String message) {
out.println("\n"+message);
if(message.equals("Action not done") && myPositionID!=null && !(grab && (myPositionID.equals("0,2")||myPositionID.equals("1,0")||myPositionID.equals("2,3")))){
if(numberAction>=3 && !finalTurn)
finalActions();
else if(finalTurn)
finalTurnAction();
else
startActions();
}
}
@Override
public void showScoopRequest() {
out.println("You can use Scope's powerUp press 1 to use scope or any key to cancel.");
if(in.nextInt()==1){
int i;
for (i = 1; i <= powerUps.size(); i++)
out.println(i + ":" + powerUps.get(i - 1) + "\t");
out.println(" choose a number from 1 to" + powerUps.size() + "");
boolean corrected = false;
while (!corrected) {
i = in.nextInt();
if (i >= 1 && i <= powerUps.size()) {
client.send(new CanUseScoopResponse(client.getToken(), true,i-1));
corrected = true;
} else {
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to " + powerUps.size() + "");
}
}
}
else{
client.send(new CanUseScoopResponse(client.getToken(), false,-1));
}
}
@Override
public void chooseScopeTarget(ArrayList<Colors> targets){
out.println("choose a target for scope");
int i;
for (i = 1; i <= targets.size(); i++)
out.println(i + ":" + targets.get(i - 1) + "\t");
out.println(" choose a number from 1 to" + targets.size() + "");
boolean corrected = false;
while (!corrected) {
i = in.nextInt();
if (i >= 1 && i <= targets.size()) {
client.send(new ScopeTargetResponse(client.getToken(), targets.get(i-1)));
corrected = true;
} else {
out.println("it's not difficult, you can do it ");
out.println("choose a number from 1 to " + targets.size() + "");
}
}
}
@Override
public void showVenomRequest(Colors player){
ArrayList<Integer> powerUp=new ArrayList<>();
out.println(""+ player+"attacked you, do you want revenge ?? press 1 to use grenade or any key to cancel.");
if (in.nextInt()==1){
int i;
for(i=0; i<powerUps.size();i++){
if(powerUps.get(i).getWhen().equals("deal")) {
powerUp.add(i);
}
}
if(powerUp.size()==1){
client.send(new UsePowerUpResponse(client.getToken(),powerUp.get(0),client.getToken(),player,null));
}
else{
for(i=1;i<=powerUp.size();i++){
out.println(i+"="+powerUps.get(powerUp.get(i-1))+"\t");
}
out.println(" choose a number or 9 to cancel");
boolean corrected=false;
i=in.nextInt();
while(!corrected){
if(i==1 || (i==2 && powerUp.size()==2)||(i==3 && powerUp.size()==3)){
client.send(new UsePowerUpResponse(client.getToken(),powerUp.get(i-1),client.getToken(),player,null));
corrected=true;
}
else if(i==9){
in.close();
corrected=true;
}
else
out.println(" choose a correct number or 9 to cancel");
}
}
}
}
@Override
public void showGameSettingsRequest() {
}
@Override
public void endGame(boolean winner) {
if(winner)
out.println("The game is over.Congratulation, you won!");
else
out.println("The game is over.You didn't win!");
}
@Override
public void startGame(String map) {
out.println("The game started, GOOD LUCK!!");
}
@Override
public void startTurn() {
out.println("it's officially your turn ");
myTurn=true;
numberAction=1;
if(myPositionID!=null){
if(finalTurn)
finalTurnAction();
else
startActions();
}
}
@Override
public void showToken() {
out.println(client.getToken());
}
public void startActions(){
if(myTurn){
update=false;
grab=false;
move=false;
shot=false;
out.println("\nyou can choose:");
out.println("1:Move, 2:Shoot, 3:Grab, 4:Use power up 5:Reload and pass, 6:Pass type a number from 1 to 6 ");
boolean corrected=false;
while(!corrected){
int i=in.nextInt();
if(i==1){
move=true;
client.send(new ReceiveTargetSquare(client.getToken(),"move"));
corrected=true;
}
else if(i==2){
shot=true;
actionCLI.actionShot();
corrected=true;
}
else if(i==3){
grab=true;
client.send(new ReceiveTargetSquare(client.getToken(),"grab"));
corrected=true;
}
else if(i==4){
actionCLI.actionPowerUp();
corrected=true;
}
else if(i==5){
actionCLI.actionReload();
corrected=true;
}
else if(i==6){
client.send(new Pass(client.getToken()));
setMyTurn(false);
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("1:Move, 2:Shoot, 3:Grab, 4:Use power up 5:Reload and pass, 6:Pass type a number from 1 to 6 ");
}
}
}
}
public void finalActions(){
if (myTurn){
update=false;
grab=false;
move=false;
shot=false;
out.println("\nyou have finished your turn you can recharge using some powerUp or pass");
out.println("1:Use power up 2:Reload, 3:Pass type a number from 1 to 3 ");
boolean corrected=false;
while(!corrected) {
int i = in.nextInt();
if (i == 1) {
actionCLI.actionPowerUp();
corrected = true;
} else if (i == 2) {
actionCLI.actionReload();
corrected = true;
} else if (i == 3) {
client.send(new Pass(client.getToken()));
setMyTurn(false);
corrected = true;
} else {
out.println("it's not difficult, you can do it ");
out.println("1:Use power up 2:Reload, 3:Pass type a number from 1 to 3 ");
}
}
}
}
public void finalTurnAction(){
if(myTurn){
grab=false;
update=false;
move=false;
shot=false;
out.println("\nyou can choose: ");
out.println("1:Move(don't press if you play after first player), 2:Shoot, 3:Grab, 4:Use power up 5:Pass type a number from 1 to 5 ");
boolean corrected=false;
while(!corrected){
int i=in.nextInt();
if(i==1){
move=true;
client.send(new ReceiveTargetSquare(client.getToken(),"move"));
corrected=true;
}
else if(i==2){
shot=true;
out.println("you can reload this weapon for shot");
int posWeapon=actionCLI.actionReload();
if(posWeapon==0)
actionCLI.actionShot();
else
actionCLI.shotFinalTurn(posWeapon);
corrected=true;
}
else if(i==3){
grab=true;
client.send(new ReceiveTargetSquare(client.getToken(),"grab"));
corrected=true;
}
else if(i==4){
actionCLI.actionPowerUp();
corrected=true;
}
else if(i==5){
client.send(new Pass(client.getToken()));
setMyTurn(false);
corrected=true;
}
else{
out.println("it's not difficult, you can do it ");
out.println("1:Move(don't press if you play after first player), 2:Shoot, 3:Grab, 4:Use power up 5:Pass type a number from 1 to 5 ");
}
}
}
update=false;
}
@Override
public void updateEnemyPosition(Colors player, String position) {
out.println(player +"has moved in"+position +"" );
}
@Override
public void fillSquare(String squareID, CardAmmo ammo){
out.print(squareID+":"+ammo.getName()+"\t");
}
@Override
public void fillSpawn(String squareID, int position, CardWeapon weapon){
out.print(squareID+":"+"position " +position+ " "+weapon.getName()+"\t" );
spawnSquareWeapon.get(squareID)[position] = weapon;
}
@Override
public void setOtherPosition(Colors player, String position) {
out.println(player+"position:" +position+"" );
}
@Override
public void setPoints(int points) {
myPoint+=points;
out.println("you have gained "+points+" points han you have "+myPoint+"points");
}
@Override
public void setMyPositionID(String myPositionID) {
this.myPositionID=myPositionID;
out.println("your new Position is " +myPositionID);
if(!update){
update=true;
setWeapons(weapons);
}
}
@Override
public void setBlueAmmo(int blueAmmo) {
this.blueAmmo =blueAmmo;
out.print("\n You have ammo blue="+blueAmmo);
waitUpdate=false;
grab=false;
shot=false;
}
@Override
public void setRedAmmo(int redAmmo) {
this.redAmmo=redAmmo;
out.print("\n You have ammo red="+redAmmo);
}
@Override
public void setPowerUps(ArrayList<CardPowerUp> powerUps) {
this.powerUps=powerUps;
out.print("\n Yours powerUp are: \t");
for(CardPowerUp powerUp:powerUps)
out.print(powerUp.getName()+"\t");
}
@Override
public void setWeapons(ArrayList<CardWeapon> weapons) {
if(!update){
update=true;
setMyPositionID(myPositionID);
}
this.weapons=weapons;
out.print("\n Yours weapons are: \t");
for(CardWeapon weapon :weapons)
out.print(weapon.getName() +"\n");
if(myPositionID!=null && !grab && !shot && !move &&!waitUpdate){
if(numberAction>=3 && !finalTurn)
finalActions();
else if(finalTurn)
finalTurnAction();
else
startActions();
}
}
@Override
public void setYellowAmmo(int yellowAmmo) {
this.yellowAmmo=yellowAmmo;
out.print("\n You have ammo yellow="+yellowAmmo);
}
}
<file_sep>/src/test/java/Controller/FinalTurnHandlerTest.java
package Controller;
import Model.CardWeapon;
import Model.NormalSquare;
import Model.Player;
import Model.WeaponDictionary;
import network.messages.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class FinalTurnHandlerTest {
@Test
public void isFirstPlayerTest()throws FileNotFoundException {
ArrayList<Integer> players=new ArrayList<>();
players.add(32413);
players.add(4324525);
GameHandler gameHandler=new GameHandler(5,players,"map1",null);
gameHandler.getGame().setCurrentPlayer(gameHandler.getGame().getFirstPlayer());
gameHandler.getGame().incrementCurrentPlayer();
gameHandler.getFinalTurnHandler().getEndFinalTurnChecks().isFirstPlayer();
assertFalse(gameHandler.getFinalTurnHandler().isAlreadyFirstPlayer());
gameHandler.getGame().incrementCurrentPlayer();
gameHandler.getFinalTurnHandler().getEndFinalTurnChecks().isFirstPlayer();
assertTrue(gameHandler.getFinalTurnHandler().isAlreadyFirstPlayer());
}
@Test
public void finalTurnIsEndTest() throws FileNotFoundException{
ArrayList<Integer> players=new ArrayList<>();
players.add(32413);
players.add(4324525);
GameHandler gameHandler=new GameHandler(5,players,"map1",null);
gameHandler.getGame().setCurrentPlayer(gameHandler.getGame().getFirstPlayer());
gameHandler.getFinalTurnHandler().setFirstFinalTurnPlayer(gameHandler.getGame().getFirstPlayer());
assertTrue(gameHandler.getFinalTurnHandler().getEndFinalTurnChecks().finalTurnIsEnd());
gameHandler.getGame().incrementCurrentPlayer();
assertFalse(gameHandler.getFinalTurnHandler().getEndFinalTurnChecks().finalTurnIsEnd());
}
@Test
public void actionFinalTurnTest()throws FileNotFoundException{
ArrayList<Integer> players=new ArrayList<>();
List<NormalSquare> squares;
players.add(32413);
players.add(4324525);
GameHandler gameHandler=new GameHandler(5,players,"map1",null);
PossibleMove possibleMove=new PossibleMove(gameHandler.getGame().getPlayers().get(0).getPlayerID(),4);
gameHandler.getGame().getDeadRoute().setFinalTurn(true);
gameHandler.getGame().setCurrentPlayer(gameHandler.getGame().getPlayers().get(0));
gameHandler.getFinalTurnHandler().setAlreadyFirsPlayer(false);
//move test no firstPlayer
//squares=gameHandler.receiveSquare(possibleMove);
//NormalSquare newSquare= squares.get(squares.size()-1);
//MoveMessage message=new MoveMessage(gameHandler.getGame().getPlayers().get(0).getPlayerID(),newSquare);
//assertTrue(gameHandler.receiveServerMessage(message));
String file= WeaponDictionary.ELECTROSCYTE.getAbbreviation();
CardWeapon cardWeapon=new CardWeapon(file);
gameHandler.getGame().getCurrentPlayer().getPlayerBoard().getHandPlayer().addAmmo(3,3,3);
gameHandler.getGame().getCurrentPlayer().getPlayerBoard().getHandPlayer().addWeapon(cardWeapon);
//shot test no firstPlayer
PossibleTargetShot shotMessage= new PossibleTargetShot(gameHandler.getGame().getPlayers().get(0).getPlayerID(),gameHandler.getGame().getCurrentPlayer().getPlayerBoard().getHandPlayer().getPlayerWeapons().get(0).getEffects().get(0));
gameHandler.getGame().getPlayers().get(1).newPosition(gameHandler.getGame().getCurrentPlayer().getPosition());
ArrayList<Player> playersTarget;
playersTarget=gameHandler.receiveTarget(shotMessage);
gameHandler.getGame().getCurrentPlayer().getPlayerBoard().getHandPlayer().getPlayerWeapons().get(0).setCharge(true);
//errror effetto è dato a pezzi
//Shot shot=new Shot(playersTarget,gameHandler.getGame().getCurrentPlayer().getPlayerBoard().getHandPlayer().getPlayerWeapons().get(0).getEffects().get(0),0);
//assertTrue(gameHandler.getTurnHandler().actionState(shot));
//test Grab firstPlayer
gameHandler.getFinalTurnHandler().setAlreadyFirsPlayer(true);
gameHandler.getGame().getCurrentPlayer().setState(StateMachineEnumerationTurn.ACTION1);
GrabNotOnlyAmmo grabNotOnlyAmmo=new GrabNotOnlyAmmo(gameHandler.getGame().getCurrentPlayer().getPlayerID());
//assertTrue(gameHandler.receiveServerMessage(grabNotOnlyAmmo));
}
}
<file_sep>/src/main/java/view/gui/SpawnGui.java
package view.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
/**
* This class is used to display a window for spawn
*/
public class SpawnGui extends JFrame {
private int position;
public SpawnGui(ArrayList<String> powerUps, MapGui mapGui){
super("Spawn");
this.setLayout(new FlowLayout());
position = 0;
for (String s: powerUps){
JLabel label = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("GUI/powerups/" + s + ".png")));
label.addMouseListener(new MouseListener() {
int pos = position;
@Override
public void mouseClicked(MouseEvent e) {
mapGui.sendSpawnMessage(pos);
System.out.println(pos);
dispose();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
position++;
this.add(label);
}
this.pack();
this.setVisible(true);
}
}
<file_sep>/src/main/java/network/messages/ScopeTargetResponse.java
package network.messages;
import Model.Colors;
public class ScopeTargetResponse extends Message {
private Colors target;
public ScopeTargetResponse(Integer token, Colors target){
this.token = token;
this.actionType = ActionType.SCOPETARGETRESPONSE;
this.target = target;
}
public Colors getTarget() {
return target;
}
}
<file_sep>/src/main/java/Model/Deck.java
package Model;
import java.io.Serializable;
import java.util.ArrayList;
/**
* This class is a collection of card, cards are collected in a deterministic order, the Drawer class then will randomly
* extract card from cardDeck
* */
public class Deck<T extends Card> implements Serializable {
private ArrayList<T> cardDeck;
private ArrayList<T> trashDeck;
private boolean mix;
public Deck(boolean mix) {
cardDeck = new ArrayList<>();
this.mix = mix;
if(mix)
trashDeck = new ArrayList<>();
}
/**
* This method is used to add a cart to the cardDeck, it returns true if the operation end successfully
* */
public void add(T t){
cardDeck.add(t);
}
/**
* This method allow the caller to get a card from the cardDeck using an index, when cardDeck is empty if cardDeck type allow
* mixing a new cardDeck is created to simulate mixing
* */
public T getCard(int index) {
T returned = null;
if(!cardDeck.isEmpty()) {
if (index > cardDeck.size())
throw new IndexOutOfBoundsException();
else{
returned = remove(index);
}
}
else{
if (mix) {
cardDeck = getTrashDeck(); //Refill cardDeck
if (index > cardDeck.size())
throw new IndexOutOfBoundsException();
else {
returned = remove(index);
}
}
}
return returned;
}
/**
* Returns the cardDeck size
* */
public int getSize(){
return cardDeck.size();
}
/**
* This method returns a copy of the trash cardDeck
* */
private ArrayList<T> getTrashDeck() {
return new ArrayList<>(trashDeck);
}
/**
* This method copy the current cardDeck in trashDeck if, and only if, the cardDeck type allow mixing and trash cardDeck is empty.
* This method should be used only when cardDeck is created to create a copy of the original cardDeck that can be used to
* simulate mixing
* */
public void setTrashDeck() {
if(mix && trashDeck.isEmpty())
this.trashDeck = new ArrayList<>(cardDeck);
}
/**
* This method returns the iterator used to extract cards from cardDeck
* */
public Drawer<T> createDrawer(){
return new Drawer<>(this);
}
/**
* This method remove the card specified by the index and return a copy of it
* */
private T remove(int index){
T copy = cardDeck.get(index);
cardDeck.remove(index);
return copy;
}
public Deck<T> copy(){
Deck<T> copy = new Deck<>(mix);
copy.cardDeck = new ArrayList<>(this.cardDeck);
copy.mix = this.mix;
if (mix)
copy.trashDeck = new ArrayList<>(this.trashDeck);
return copy;
}
}
<file_sep>/src/main/java/network/messages/GameSettingsRequest.java
package network.messages;
/**
* This Class is a message used to ask the client which Game configuration want to use, Map, number of skulls.
*/
public class GameSettingsRequest extends Message{
public GameSettingsRequest(Integer token){
actionType = ActionType.GAMESETTINGSREQUEST;
this.token = token;
}
}
<file_sep>/src/main/java/view/gui/ViewMap.java
package view.gui;
import java.util.Arrays;
import java.util.List;
/**
* This class contains x and y coordinates of some component of the gui
*/
public abstract class ViewMap {
private static final String[] ids = {"0,0", "0,1", "0,2", "0,3", "1,0", "1,1", "1,2", "1,3", "2,0", "2,1", "2,2", "2,3"};
private static final int[][] xCoord = {{490, 905, 1335, 1770},{490, 905, 1335, 1770}, {490, 905, 1335, 1770}};
private static final int[][] yCoord = {{470, 470, 470, 470} ,{900 ,900 ,900 ,900}, {1350, 1350, 1350, 1350}};
private static final int[][] xWeapon = {{1350, 1625, 1905},{10, 10, 10}, {2198, 2198, 2198, 2198}};
private static final int[][] yWeapon = {{1,1,1},{702, 981, 1258}, {1096, 1373, 1652}};
private static final int[] xWeaponIncrement = {240, 350, 350};
private static final int[] yWeaponIncrement = {350, 240, 240};
private static final String[] notInMap1 = {"0,4", "2,1"};
private static final String[] notInMap2 = {"2,1"};
private static final String[] notInMap3 = {};
private static final String[] notInMap4 = {"0,4"};
public static int getXCoordinates(String id){
return xCoord[Character.getNumericValue(id.charAt(0))][Character.getNumericValue(id.charAt(2))];
}
public static int getYCoordinates(String id){
return yCoord[Character.getNumericValue(id.charAt(0))][Character.getNumericValue(id.charAt(2))];
}
public static String[] getIds() {
return ids;
}
public static int getSquareNumber(String id){
return Arrays.asList(ids).indexOf(id);
}
public static int getxWeapon(String id, int i){
return xWeapon[Character.getNumericValue(id.charAt(0))][i];
}
public static int getyWeapon(String id, int i){
return yWeapon[Character.getNumericValue(id.charAt(0))][i];
}
public static int getxWeaponIncrement(String id){
return xWeaponIncrement[Character.getNumericValue(id.charAt(0))];
}
public static int getyWeaponIncrement(String id){
return yWeaponIncrement[Character.getNumericValue(id.charAt(0))];
}
public static List<String> getNotInMap1(){
return Arrays.asList(notInMap1);
}
public static List<String> getNotInMap2(){
return Arrays.asList(notInMap1);
}
public static List<String> getNotInMap3(){
return Arrays.asList(notInMap1);
}
public static List<String> getNotInMap4(){
return Arrays.asList(notInMap1);
}
}
<file_sep>/src/test/java/Model/ReloadTest.java
package Model;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ReloadTest {
@Test
public void constructorTest() throws FileNotFoundException {
Player testPlayer = new Player(564347347, null);
CardWeapon testWeapon = new CardWeapon(WeaponDictionary.CYBERBLADE.getAbbreviation());
testPlayer.getPlayerBoard().getHandPlayer().addWeapon(testWeapon);
testPlayer.getPlayerBoard().getHandPlayer().addAmmo(testWeapon.getRedCost(), testWeapon.getYellowCost(), testWeapon.getBlueCost());
Reload action = new Reload(testPlayer, testWeapon);
assertTrue(action instanceof Reload);
ArrayList<CardPowerUp> testPowerUps = new ArrayList<>();
CardPowerUp testPowerUp1 = new CardPowerUp("newton_R");
CardPowerUp testPowerUp2 = new CardPowerUp("newton_Y");
testPowerUps.add(testPowerUp1);
testPowerUps.add(testPowerUp2);
}
@Test
public void isValidTest() throws FileNotFoundException {
Player testPlayer = new Player(76586485, null);
CardWeapon testWeapon = new CardWeapon(WeaponDictionary.CYBERBLADE.getAbbreviation());
testPlayer.getPlayerBoard().getHandPlayer().addWeapon(testWeapon);
testPlayer.getPlayerBoard().getHandPlayer().addAmmo(testWeapon.getRedCost(), testWeapon.getYellowCost(), testWeapon.getBlueCost());
Reload action = new Reload(testPlayer, testWeapon, 1, 1, 1);
assertTrue(action.isValid());
}
@Test
public void executeTest() throws FileNotFoundException {
Player testPlayer = new Player(56485, null);
CardWeapon testWeapon = new CardWeapon(WeaponDictionary.CYBERBLADE.getAbbreviation());
testPlayer.getPlayerBoard().getHandPlayer().addWeapon(testWeapon);
testPlayer.getPlayerBoard().getHandPlayer().addAmmo(testWeapon.getRedCost(), testWeapon.getYellowCost(), testWeapon.getBlueCost());
Reload action = new Reload(testPlayer, testWeapon);
assertTrue(action.execute());
assertTrue(testWeapon.isCharge());
}
}
<file_sep>/src/test/java/Controller/GameHandlerTest.java
package Controller;
import Model.Player;
import network.Server.GameLobby;
import network.Server.Server;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class GameHandlerTest {
@Test
public void winnerTest() throws FileNotFoundException {
List<Player> winners;
ArrayList<Integer> players=new ArrayList<>();
players.add(1233);
players.add(3525);
players.add(235555);
players.add(235235);
players.add(53325);
GameHandler gameHandler=new GameHandler(8,players,"map1",null);
gameHandler.getGame().getPlayers().get(0).getPlayerBoard().addPoints(32);
gameHandler.getGame().getPlayers().get(1).getPlayerBoard().addPoints(32);
gameHandler.getGame().getPlayers().get(2).getPlayerBoard().addPoints(22);
gameHandler.getGame().getPlayers().get(3).getPlayerBoard().addPoints(30);
gameHandler.getGame().getPlayers().get(4).getPlayerBoard().addPoints(17);
gameHandler.getGame().getDeadRoute().addMurders(gameHandler.getGame().getPlayers().get(0),2);
gameHandler.getGame().getDeadRoute().addMurders(gameHandler.getGame().getPlayers().get(1),1);
gameHandler.getGame().getDeadRoute().addMurders(gameHandler.getGame().getPlayers().get(3),2);
assertEquals(1,gameHandler.countPlayer(gameHandler.getGame().getPlayers().get(1)));
assertEquals(2,gameHandler.countPlayer(gameHandler.getGame().getPlayers().get(0)));
}
}
<file_sep>/src/main/java/view/gui/GameSettingsChoose.java
package view.gui;
import network.Client.Client;
import network.messages.GameSettingsResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import static view.gui.MainGuiView.GOLDENRATIO;
/**
* This class is used to display a window for game setting choose
*/
public class GameSettingsChoose extends JFrame{
private Client client;
private JPanel mainPanel;
private JLabel map;
private JComboBox<String> maps;
JCheckBox use8Skulls;
private String currentMap;
private static final Object lock = new Object();
private static final int INITIALWINDOWHEIGHT = 600;
public GameSettingsChoose(Client client){
super("Game settings");
this.client = client;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(new BorderLayout());
JPanel comboAndText = new JPanel(new BorderLayout());
String[] mapsName = {"Map 1", "Map 2", "Map 3", "Map 4"};
maps = new JComboBox<>(mapsName);
currentMap = "map1";
comboAndText.add(maps, BorderLayout.LINE_START);
JLabel explanation = new JLabel("Choose your game settings");
comboAndText.add(explanation, BorderLayout.CENTER);
use8Skulls = new JCheckBox("Use 8 skulls (if not selected 5 skulls are used)");
comboAndText.add(use8Skulls, BorderLayout.LINE_END);
mainPanel.add(comboAndText, BorderLayout.PAGE_START);
ImageIcon mapImage = new ImageIcon(getClass().getClassLoader().getResource("GUI/mappe/map1.png"));
map = new JLabel(mapImage);
mainPanel.add(map, BorderLayout.CENTER);
JPanel bottomPage = new JPanel(new BorderLayout());
JButton confirm = new JButton("Continue");
bottomPage.add(confirm, BorderLayout.LINE_END);
mainPanel.add(bottomPage, BorderLayout.PAGE_END);
confirm.addActionListener(e -> {
client.send(new GameSettingsResponse(client.getToken(), getSkullsNumber(), maps.getSelectedIndex()+1));
});
mainPanel.addComponentListener(new ResizeMaps());
maps.addActionListener(new ChangeMap());
int panelWidth = (int)(INITIALWINDOWHEIGHT *GOLDENRATIO);
add(mainPanel);
setMinimumSize(new Dimension(panelWidth, INITIALWINDOWHEIGHT));
setSize(panelWidth, INITIALWINDOWHEIGHT);
setVisible(true);
}
class ChangeMap implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
new Thread(() -> {
currentMap = "map" + (maps.getSelectedIndex()+1);
setImageMap();
}).start();
}
}
class ResizeMaps implements ComponentListener{
@Override
public void componentResized(ComponentEvent e) {
new Thread(GameSettingsChoose.this::setImageMap).start();
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
}
private void setImageMap(){
synchronized (lock) {
ImageIcon im = new ImageIcon(new ImageIcon(getClass().getClassLoader().getResource("GUI/mappe/" + currentMap + ".png")).getImage().getScaledInstance(map.getWidth(), map.getHeight(), Image.SCALE_DEFAULT));
map.setIcon(im);
}
}
private int getSkullsNumber(){
if (use8Skulls.isSelected())
return 8;
else
return 5;
}
} | 272e551a8ea2b33e57df261ca6b9e7139bea38f4 | [
"Markdown",
"Java"
] | 47 | Java | MarcoPianta/ing-sw-2019-34 | 39fd7bb14fe0459a766d7f288c592bba9a3f8666 | 03ed397cebe8a114617b62b027d5f1eaefd2b404 |
refs/heads/master | <repo_name>d11-a2/javarush<file_sep>/booksGRUD/src/main/resources/standard.properties
styleSheet=styles/mystyle.css
<file_sep>/booksGRUD/src/main/java/com/bookscrud/BookDao.java
package com.bookscrud;
import java.util.List;
public interface BookDao {
Book create(Book book);
Book read(Book book);
Book changeEdition(Book book);
void delete(Book book);
List<Book> findAll();
public List<Book> findByTitle(String title);
public List<Book> findByYear(Integer year);
public List<Book> findByAuthor(String author);
public Book findById(long id);
public List<Book> findByISBN(String ISBN);
public List<Book> searchByReadAlready(Boolean readAlready);
class Paginator {
private int paging;
private int pageCount;
private int lastPageEntryCount;
private List<Book> bookList;
public Paginator(int paging, List<Book> bookList) {
this.paging = paging;
this.bookList = bookList;
lastPageEntryCount = paging;
pageCount = bookList.size() / paging;
if (bookList.size() % paging > 0) {
pageCount++;
lastPageEntryCount = bookList.size() % paging;
}
}
public List<Book> getNextEntryListForPage(int nextPage) {
if (nextPage < 1)
nextPage = 1;
if (nextPage > pageCount)
nextPage = pageCount;
int beginIndex = (nextPage - 1) * paging;
if (nextPage == pageCount)
return bookList.subList(beginIndex, beginIndex + lastPageEntryCount);
return bookList.subList(beginIndex, beginIndex + paging);
}
public int getPageCount() {
return pageCount;
}
}
}
<file_sep>/booksGRUD/src/main/webapp/WEB-INF/i18n/application.properties
application_name=booksCRUD
header_text=Bookshelf application
home_text=Home
menu_header_text=Menu
label_welcome=Welcome
label_login=Login
label_logout=Logout
label_book_list=Book Listing
label_book_info=Book Info
label_book_id=ID
label_book_title=Title
label_book_author=Author
label_book_year=Print year
label_book_description=Description
label_book_read_already=Read already
label_book_isbn=ISBN
label_book_update=Edit book
label_book_save=Save
label_book_save_changes=Save
label_book_reset=Reset
label_book_cancel=Cancel
label_book_add=Add new book
label_book_cancel_search=Reset search
text_no_books_found=No books found
label_en_US=English (US)
label_zh_HK=Chinese (HK)
<file_sep>/booksGRUD/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>books</groupId>
<artifactId>books</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring-framework-version>5.0.0.RELEASE</spring-framework-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework-version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons-core</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
</dependencies>
</project><file_sep>/README.md
# javarush
This repository contains my test task for javaRush intership.
My nik name for javaRush is Viktor. Приложение запускается через томкат.При заполнении форм выполняется проверка на вводимые данные. ISBN должен содержать 20 цифр, Ввод предусмотрен только латиницей. Имя Фамилия должны начинаться с прописной буквы без сокращений и точек. Год издания книги начиная с 1142 по 2017 год. Название книги без ограничений.
<file_sep>/booksGRUD/src/main/resources/META-INF/sql/schema.sql
USE test;
DROP TABLE IF EXISTS book;
CREATE TABLE book (
id INT NOT NULL AUTO_INCREMENT
, title VARCHAR(100) NOT NULL
, description VARCHAR(255)
, author VARCHAR(100) NOT NULL
, isbn VARCHAR(20) NOT NULL
, printyear INT NOT NULL
, readalready BOOL NOT NULL
, PRIMARY KEY (ID)
)
DEFAULT CHARACTER SET = utf8;
<file_sep>/booksGRUD/src/main/webapp/WEB-INF/i18n/messages.properties
welcome_titlepane=Welcome to {0}
welcome_h3=Welcome to {0}
book_save_success=Book saved successfully
book_save_fail=Failed saving book
validation.title.NotEmpty.message=Title is required
validation.title.Size.message=Title must be between {min} and {max}
validation.author.NotEmpty.message=Author name is required
validation.author.Size.message=author name must be between {min} and {max}
validation.year.NotEmpty.message=Print year is required
validation.year.Size.message=Print year must be {min}
validation.description.NotEmpty.message=Description is required
validation.description.Size.message=Description must be between {min} and {max}
validation.isbn.NotEmpty.message=ISBN is required
validation.isbn.Size.message=ISBN must be {min}
message_login_fail=Login failed, please try again
<file_sep>/booksGRUD/src/main/resources/META-INF/sql/test-data.sql
insert into book (title, description, author, isbn, printyear, readalready) values (
'Information graphics: a comprehensive illustrated reference','Networks','Harris','56785432678965345600','1996'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'A first look at communication theory (4th edition)','Communication, Theory','Griffin','56785432678965345600','2000'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'A measure of freedom','Political thought','Carter','56785432678965345601','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Analyzing everyday texts: discourse, rhetoric and social perspectives','Social Theory','Stillar','56785432678965345602','1998'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Applied data communications: a business oriented approach (2nd edition)','Communication, Data Mining','Goldman','56785432678965345603','1998'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Artificial intelligence and statistics 99: 7th international workshop on artificial intelligence','Artificial Intelligence, Statistics','Heckerman (editor)','56785432678965345604','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Beyond calculation: the next fifty years of computing','Complexity,Computational','Denning','56785432678965345605','1997'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Cataloging and classification: an introduction (2nd edition)','Others','Chan','56785432678965345606','1994'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Complexity and postmodernism: understanding complex systems','Complexity','Cilliers','56785432678965345607','1998'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Computer concepts (3rd edition-CD)','Computer basics','Parsons','56785432678965345608','1998'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Computing essentials','Computational','O’Leary','56785432678965345609','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Designing communication and collaboration support systems','Information Systems','Matsushita','56785432678965345610','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Dictionary of semiotics','Others','Martin','56785432678965345611','2000'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Economic complexity: chaos, sunspots, bubbles and nonlinearity','Complexity','Shell (editor)','56785432678965345612','1988'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Elements of graph design','Networks','Kosslyn','56785432678965345613','1993'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Encyclopedia of social and cultural anthropology','Social Theory','Barnard (editor)','56785432678965345614','1998'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Executive’s guide to information technology: shrinking the IT gap','Information Systems','Cox','56785432678965345615','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Fuzzy cluster analysis: methods for classification, data analysis and image recognition','Statistics','Hoppner et al','56785432678965345616','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Handbook of technology in financial services','Finance','Keyes (editor)','56785432678965345617','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Information graphics: a comprehensive illustrated reference','Networks','Harris','56785432678965345618','1996'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Knowledge representation: logical, philosophical and computational foundations','Artificial Intelligence, Computational, Knowledge Management','Sowa','56785432678965345619','2000'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Logic, language and computation (VOL 1)','Artificial Intelligence,Programming','Seligman (editor)','56785432678965345620','1996'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Marketing engineering: computer assisted market analysis and planning (Vol 1)','Others','Lilien','56785432678965345621','1998'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Mastering the digital market place: practical strategies for competitiveness in the new economy','E-Commerce, Economics','Aldrich','56785432678965345622','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'OFFICE 2000 for busy people','Computer basics','Weverka','56785432678965345623','1999'
,0);
insert into book (title, description, author, isbn, printyear, readalready) values (
'Questioning technology','Communication, Information Systems','Feenberg','56785432678965345624','1999'
,0);
<file_sep>/booksGRUD/src/main/java/com/bookscrud/BookSample.java
package com.bookscrud;
import org.springframework.context.support.GenericXmlApplicationContext;
import java.util.List;
public class BookSample {
public static void main(String[] args) {
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load("/META-INF/spring/app-context.xml");
context.refresh();
BookDao bookService = context.getBean("bookDao", BookDao.class);
System.out.println("by id " + bookService.findById(2L));
List<Book> books = bookService.findAll();
for (Book book : books) {
System.out.println(book.toString());
}
System.out.println("__________________________________________________________________");
Book book = new Book();
book.setId(26);
book.setTitle("new book");
book.setDescription("nothing");
book.setAuthor("noname");
book.setIsbn("1221");
book.setPrintYear(1990);
// bookService.update(book);
// bookService.create(book);
//bookService.delete(book);
//bookService.read(book);
//books = bookService.findAll();
}
}
| 49702e927c3973a8f6bec2e8a849fa84812da8e9 | [
"SQL",
"Markdown",
"Maven POM",
"INI",
"Java"
] | 9 | INI | d11-a2/javarush | 1fbcc9e4d8d8acc07749732f78f6c29b3fe9faa2 | d95b6e0e87c326755a767f2b7e49482d2c43afc1 |
refs/heads/master | <repo_name>kaephas/jsreading<file_sep>/README.md
# jsreading
Files from Eloquent JavaScript assignments
<file_sep>/json-search.js
/*
* <NAME>
* 5-1-2019
* json-search.js
*
* load json file, compare input to contents, display on web page
*/
// get elements
let input = document.getElementById("name");
let button = document.getElementById("search");
let output = document.getElementById("display");
// to store people found in json file
let people = [];
// get all the people from the json file
let requestURL = "people.json";
let request = new XMLHttpRequest();
request.open("GET", requestURL);
request.responseType = 'json';
request.send();
// store the request in people
request.onload = function() {
people = request.response;
};
// clicking search button
button.onclick = function() {
// get matching names
let found = checkName();
// reset display
output.innerHTML = "";
// if none found
if(found.length === 0) {
output.innerHTML = "<p>No person found.</p>";
} else { // if >= 1 found
for(let person of found) {
// paragraph for each person
output.innerHTML += "<p>";
// for each field in person object -- also make sure that person object has the property
// -- feels redundant but doesn't run without
for(let field in person) if (person.hasOwnProperty(field)) {
output.innerHTML += field.replace(field[0], field[0].toUpperCase()) + ": " + person[field] + "<br>";
}
output.innerHTML += "</p>";
}
}
};
// check if search value is in any of the names
function checkName() {
let results = [];
// compare value to the name field of each person
for(let person of people) {
// add to results if string is found in name field
if(person.name.toLowerCase().includes(input.value.toLowerCase())) {
results.push(person);
}
}
return results;
}
<file_sep>/chapter2.js
/*
* Script for Chapter 2 assignment
*
* <NAME>
* 4-10-19
* chapter2.js
*/
// hee haw 3 & 5
function heeHaw() {
for (let i = 1; i <= 100; i++) {
let output = "";
// mod 3 = hee
if (i % 3 == 0) {
output += "Hee";
// if not mod 5, end line with !
if (!(i % 5 == 0)) {
output += "!";
} else {
output += " ";
}
}
// mod 5 == haw -- add space first if also mod 3
if (i % 5 == 0) {
output += "Haw!";
}
console.log(i + ": " + output);
}
} | 45705a210f584fd71473eaf65696d3adf68b81a2 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | kaephas/jsreading | 53bfcc801f9fbc4445ad2d722802cc964e648a45 | 96f880820a89b21ec9cc98c17f3065d3b99aeec9 |
refs/heads/master | <repo_name>FulyaDemirkan/RockPaperScissors<file_sep>/README.md
# Rock Paper Scissors - version 1.0
This program is a Rock-Paper-Scissors game which can be played against computer.
Player can see or reset current play session's scores.
## Prerequisities ##
This application requires Oracle JDK8 (Windows) or OpenJDK+OpenJFX (Linux).
## Installation ##
No installation is required.
## How to Run ##
java -jar RockPaperScissors.jar
## Technologies Used ##
Java, JavaFX
## Authors ##
<NAME> <file_sep>/src/demirkaf/A4_demirkaf.java
package demirkaf;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/*
Name: <NAME>
Assignment: Assignment 4
Program: Computer Programmer
This program is a Rock-Paper-Scissors game which can be played against computer.
Player can see or reset current play session's scores.
*/
/**
* This program is a Rock-Paper-Scissors game which can be played against
* computer. Player can see or reset current play session's scores.
*
* @author <NAME>
*/
public class A4_demirkaf extends Application
{
@Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load(getClass().getResource("FXMLRps.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Play Rock-Paper-Scissors");
stage.setScene(scene);
stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
<file_sep>/src/demirkaf/FXMLRpsController.java
package demirkaf;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.binding.NumberBinding;
import javafx.beans.property.IntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
/*
Name: <NAME>
File: FXMLRpsController.java
Other Files in this Project:
- Rps.java
- Player.java
- FXMLRps.fxml
- main.css
Main class: A4_demirkaf
*/
/**
* FXMLRpsController manages the game play of Rock Paper Scissors game.
*
* @author <NAME>
*/
public class FXMLRpsController implements Initializable
{
@FXML
private Label lblwinner, lblPlayerScore, lblCompScore;
@FXML
private ImageView imgRock, imgPaper, imgScissors, imgComp;
@FXML
private FlowPane rockToken, paperToken, scissorsToken;
@FXML
private Player player = new Player();
@FXML
private Player computer = new Player();
/**
* When an image is clicked, sets move for player, changes the background
* color of chosen token and initiates gamePlay method with passing move
* parameter of player. Also changes the background color of each image to
* the default color with each new click.
*
* @param event Mouse click event for images.
*/
@FXML
private void imgClicked(MouseEvent event)
{
//change bg-color to default with each click.
rockToken.setStyle("-fx-background-color: #87ceeb;");
paperToken.setStyle("-fx-background-color: #87ceeb;");
scissorsToken.setStyle("-fx-background-color: #87ceeb;");
//send token name to move parameter of player and change bg-color of
//image
if (event.getSource() == imgRock)
{
rockToken.setStyle("-fx-background-color: orange;");
player.makeMove("ROCK");
} else if (event.getSource() == imgPaper)
{
paperToken.setStyle("-fx-background-color: orange;");
player.makeMove("PAPER");
} else if (event.getSource() == imgScissors)
{
scissorsToken.setStyle("-fx-background-color: orange;");
player.makeMove("SCISSORS");
}
//generate a random computer move
Rps compPlay = computer.makeRandomMove();
//change computer token image with the randomly generated token's image
Image img = new Image(getClass().getResource("res/" +
compPlay.getName() + ".png").toExternalForm());
imgComp.setImage(img);
//check if there is a tie or win. Increment player or computer score
//after every win
if ((player.move).tie(compPlay))
{
lblwinner.setText("It's a tie!");
} else if ((player.move).win(compPlay))
{
lblwinner.setText("Player Wins!");
player.incrementScore();
} else
{
lblwinner.setText("Computer Wins!");
computer.incrementScore();
}
}
@Override
public void initialize(URL url, ResourceBundle rb)
{
//Binds player and computer scores to appropriate labels.
lblPlayerScore.textProperty().bind(player.scoreProperty().asString());
lblCompScore.textProperty().bind(computer.scoreProperty().asString());
}
/**
* Resets the game to default values and styles. Sets scores to zero, styles
* to default bg-color, winner label to empty and computer token image to
* question.
*/
@FXML
public void resetGame()
{
player.setScore(0);
computer.setScore(0);
rockToken.setStyle("-fx-background-color: #87ceeb;");
paperToken.setStyle("-fx-background-color: #87ceeb;");
scissorsToken.setStyle("-fx-background-color: #87ceeb;");
lblwinner.setText("");
Image img = new
Image(getClass().getResource("res/question.png").toExternalForm());
imgComp.setImage(img);
}
/**
* Exits the game.
*/
public void exitGame()
{
System.exit(0);
}
}
| d84675c6c2c727eb3966016de0853e658ddad794 | [
"Markdown",
"Java"
] | 3 | Markdown | FulyaDemirkan/RockPaperScissors | bfe0ae7d90c00ec0adf08391da62ae854bab3d81 | 5621ffc541fac5bd09a316a22ec025020897553b |
refs/heads/main | <repo_name>not-varram/advanced-example-discord-bot<file_sep>/commands/flip.js
require('dotenv').config();
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const {
MessageEmbed
} = require('discord.js')
module.exports = {
name: 'flip',
description: '"flip"',
aliases: [],
async execute(client, message, args, Discord) {
function send(a) {
message.channel.send(a);
}
function checkrole(role) {
return message.member.roles.cache.some(r => r.name === role);
}
function addRoleMSGS(ole) {
//adds role to message sender
let role = message.guild.roles.cache.find(r => r.name === ole);
message.member.roles.add(role).catch(console.error);
}
function firstMentioned() {
var returnedobj = message.mentions.users.first();
if (returnedobj == undefined) {
return "asd";
}
return returnedobj.username;
}
function httpGet(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false); // false for synchronous request
xmlHttp.send(null);
return xmlHttp.responseText;
}
var a = httpGet("https://no-api-key.com/api/v1/coin-flip");
var b = JSON.parse(a);
const embed = new MessageEmbed()
.setImage(b.gif);
await message.channel.send(embed);
await message.channel.send("it landed on: " + b.coin);
}
}<file_sep>/commands/help.js
const profileModel = require("../models/profileSchema");
module.exports = {
name: "help",
aliases: [],
description: "give a list of all commands",
async execute(client, message, args, Discord, cmd, profileData) {
if (args[0] == 'currency') {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.addFields({
name: 'balance/bal/bl',
value: 'shows how much money you have'
})
.addFields({
name: 'give',
value: 'only people with the "botperms" role can use this. give money to someone'
})
.addFields({
name: 'deposit',
value: 'puts your money from wallet to bank'
})
.addFields({
name: 'withdraw',
value: 'gets money back from bank'
}).setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001');
message.channel.send(exampleEmbed);
} else if (args[0] == 'music') {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.addFields({
name: 'play/add',
value: 'MUSIC BOT. join voice channel and starts playing music'
})
.addFields({
name: 'leave',
value: 'MUSIC BOT COMMAND leave he voice channel'
}).setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001');
message.channel.send(exampleEmbed);
} else if (args[0] == "mod") {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.setDescription('__***only people with the role "botperms" can use these commands***__')
.addFields({
name: 'ban',
value: 'bans a person only works with people who have OWNER ROLE contact bot dev to add more roles'
})
.addFields({
name: 'clear',
value: 'clears a specific amout of amount of messages'
})
.addFields({
name: 'kick',
value: 'kicks members. only works with people who have the "owner role" '
}).setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001');
message.channel.send(exampleEmbed);
} else if (args[0] == 'misc') {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.addFields({
name: 'help',
value: 'sends a list of all the commands'
})
.addFields({
name: 'minecraft',
value: 'checks staus of servers. and gives info'
})
.addFields({
name: 'nuke',
value: 'deletes all message in a server'
})
.addFields({
name: 'ping',
value: 'sends back pong'
})
.addFields({
name: 'suggestions',
value: 'sends suggestions to #suggestions channel'
})
.addFields({
name: 'youtube',
value: 'sends my yt. pls sub :)'
})
.setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001')
message.channel.send(exampleEmbed);
}
else if (args[0] == 'image') {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.addFields({
name: '8ball',
value: 'bacically magic 8 ball'
})
.addFields({
name: 'image',
value: 'send a image of anything you type.'
})
.addFields({
name: 'doggo/dog',
value: 'send an image of a epic doggo with a cool fact (i like dogs better than cats).'
})
.addFields({
name: 'cat',
value: 'send an image of a cat with a fact (i like dogs better than cats).'
})
.addFields({
name: 'bear',
value: 'send an image of a bear with a fact.'
})
.addFields({
name: 'panda',
value: 'send an image of a panda with a fact'
})
.addFields({
name: 'meme',
value: 'send an image of a meme. what do you expect HUH'
})
.setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001');
message.channel.send(exampleEmbed);
}
else if(args[0] == 'no-api-key') {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.addFields({
name: 'doggo/dog',
value: 'send an image of a epic doggo with a cool fact (i like dogs better than cats).'
})
.addFields({
name: 'cat',
value: 'send an image of a cat with a fact (i like dogs better than cats).'
})
.addFields({
name: 'bear',
value: 'send an image of a bear with a fact.'
})
.addFields({
name: 'panda',
value: 'send an image of a panda with a fact'
})
.addFields({
name: 'meme',
value: 'send an image of a meme. what do you expect HUH'
})
.addFields({
name: 'quote',
value: 'gives a epic quote from a person'
})
.addFields({
name: 'flip',
value: 'flips a coin for you'
})
.setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001');
message.channel.send(exampleEmbed);
}
else {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.addFields({
name: '```!help currency```',
value: 'shows currency commands'
})
.addFields({
name: '```!help music```',
value: 'shows music commands'
})
.addFields({
name: '```!help mod```',
value: 'shows mod commands'
})
.addFields({
name: '```!help misc```',
value: 'shows misalanius commands'
})
.addFields({
name: '```!help no-api-key```',
value: 'a bunch of cool commands like trashing stuff and other stuff (my fav commands)'
})
.setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001');
message.channel.send(exampleEmbed);
}
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#7300ff')
.setTitle('COMMANDS HELP')
.setAuthor('varram#0001')
.setTimestamp()
.setFooter('contact me for any errors on from my discord bot. varram#0001')
}
};<file_sep>/README.md
# advanced-example-discord-bot
# how to use
open the .env file and change the discord bot token to your token.
also you will need mongo dn but you mongo db url where it tells you to put it
after that do
```npm i```
then
```node .```
and your discord bot will be ready.
# music commands
for music commands for will need ffmpeg installed
<file_sep>/commands/balance.js
module.exports = {
name: "balance",
aliases: ["bal", "bl"],
description: "Check the user balance",
execute(client, message, args, Discord, cmd, profileData) {
message.channel.send(`Your wallet bal is ${profileData.coins}, you banks bal is ${profileData.bank}`);
},
};<file_sep>/commands/kick.js
require('dotenv').config();
module.exports = {
name: 'kick',
description: 'kicks user',
execute(client, message, args, Discord) {
function send(a) {
message.channel.send(a);
}
function checkrole(role) {
return message.member.roles.cache.some(r => r.name === role);
}
function addRoleMSGS(ole) {
//adds role to message sender
let role = message.guild.roles.cache.find(r => r.name === ole);
message.member.roles.add(role).catch(console.error);
}
function firstMentioned() {
var returnedobj = message.mentions.users.first();
if (returnedobj == undefined) {
return "asd";
}
return returnedobj.username;
}
if(checkrole(process.env.ADMIN_ROLE) !== true) send("you dont have perms to do that NERRRRDD");
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.kick();
message.channel.send("User has been kicked");
} else {
message.channel.send(`You coudn't kick that member!`);
}
}
}<file_sep>/commands/roleall.js
module.exports = {
name: 'roleall',
description: 'this is a basic ping command',
execute(client, message, args, Discord, cmd, profileData) {
function send(a) {
message.channel.send(a);
}
function checkrole(role) {
return message.member.roles.cache.some(r => r.name === role);
}
function addRoleMSGS(ole) {
//adds role to message sender
let role = message.guild.roles.cache.find(r => r.name === ole);
message.member.roles.add(role).catch(console.error);
}
function firstMentioned() {
var returnedobj = message.mentions.users.first();
if (returnedobj == undefined) {
return "asd";
}
return returnedobj.username;
}
let role = message.guild.roles.cache.find(r => r.name == args[0]);
// if role doesn't exist, notify the author of command that the role couldn't be found
if (!role) return message.channel.send(`**${message.author.username}**, role not found`)
// find all guild members that aren't bots, and add the "Community" role to each
message.guild.members.cache.filter(m => !m.user.bot).forEach(member => member.cache.addRole(role))
// notify the author of the command that the role was successfully added to all members
message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
}
}<file_sep>/events/guild/guildMemberAdd.js
const profileModel = require("../../models/profileSchema");
module.exports = async (Discord, client, member) => {
let profile = await profileModel.create({
userID: member.id,
serverID: member.guild.id,
coins: 1000,
bank: 0,
});
member.send("Thanks for joining this server if you ever get kicked or if the server gets raided here is the invite link to join the server back: https://discord.gg/X4dUAs4YXQ. IF THE SERVER GETS RAIDED JUST WAIT 2 DAYS AND TRY TO JOIN BACK!! :)");
profile.save();
};<file_sep>/commands/youtube.js
module.exports = {
name: 'youtube',
description: 'this is to get my yt channel name',
execute(client, message, args, Discord){
function send(a) {
message.channel.send(a);
}
function checkrole(role) {
return message.member.roles.cache.some(r => r.name === role);
}
function addRoleMSGS(ole) {
//adds role to message sender
let role = message.guild.roles.cache.find(r => r.name === ole);
message.member.roles.add(role).catch(console.error);
}
function firstMentioned() {
var returnedobj = message.mentions.users.first();
if(returnedobj == undefined) {
return "asd";
}
return returnedobj.username;
}
send(`${message.author}` + " here is the yt: https://www.youtube.com/channel/UC6FTMFf_1vMdbJK9nNY6HaA");
}
}<file_sep>/events/client/ready.js
module.exports = () =>{
console.log("THE YE BOT IS ONLINE!!")
}<file_sep>/commands/clear.js
module.exports = {
name: 'clear',
description: 'clears messages',
execute(client, message, args, Discord){
function send(a) {
message.channel.send(a);
}
function checkrole(role) {
return message.member.roles.cache.some(r => r.name === role);
}
function addRoleMSGS(ole) {
//adds role to message sender
let role = message.guild.roles.cache.find(r => r.name === ole);
message.member.roles.add(role).catch(console.error);
}
function firstMentioned() {
var returnedobj = message.mentions.users.first();
if(returnedobj == undefined) {
return "asd";
}
return returnedobj.username;
}
if(!args[0]) return send("please enter the amount of messages you want to clear");
if(isNaN(args[0])) return send("please enter a real number!");
if(args[0] < 1) return send("at least delete one message");
if(args[0] > 100) return send("only until 100");
async function m() {
await message.channel.messages.fetch({limit: args[0]}).then(messages => {
message.channel.bulkDelete(messages)
})}
m();
}
} | 0241f50ec2dca0c8e1f7512ccdc369be85451aba | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | not-varram/advanced-example-discord-bot | 2a92a7eb1cadb83d290e89359dc3bb12194d4b31 | e848f328a35f5389df5d741d1eb5cdb5506f0fdb |
refs/heads/master | <repo_name>mayank-a93/Form_Validation<file_sep>/src/js/data.js
function getData() {
var data = JSON.parse(localStorage.getItem('Users'));
var table = document.getElementById("userTable");
for (var i = 1 ; i <= Object.keys(data).length ; i++)
{
table.innerHTML+= "<tr>"+
"<td>"+data[i].Name+"</td>"+
"<td>"+data[i].Phone+"</td>"+
"<td>"+data[i].Email+"</td>"+
"</tr>"
}
}
<file_sep>/README.md
# Form_Validation
Form validation using JS and JSON
<file_sep>/src/js/validation.js
function val_number(num){
return(num.match(/\d/g).length!=10);
}
function val_name(name){
return(/[^a-zA-Z]/.test(name));
}
function pass_len(pass) {
return(pass.length<6);
}
function pass_alpha_num(pass) {
return(pass.match(/\d/g)==null || pass.match(/[^a-zA-Z]/)==null);
}
function pass_match(pass1,pass2) {
return(pass1!=pass2);
}
function data_init(user) {
var data = {};
data["1"] = user;
localStorage.setItem('Users', JSON.stringify(data));
}
function add_to_data(user) {
var data = JSON.parse(localStorage.getItem('Users'));
var temp = user;
if(data==null)
data_init(temp);
else {
var len = Object.keys(data).length
data[""+(len+1)] = user;
window.alert(Object.keys(data).length)
localStorage.setItem('Users', JSON.stringify(data));
}
}
function val(form) {
if(val_name(form.name.value)){
window.alert("Name can only contain characters.");
return false;
}
if(val_number(form.phno.value)){
window.alert("Invalid Phone Number.");
return false;
}
if(pass_len(form.pass.value)){
window.alert("Password too short.");
return false;
}
if(pass_alpha_num(form.pass.value)){
window.alert("Password must be alpha-numeric.");
return false;
}
if(pass_match(form.pass.value,form.cpass.value)){
window.alert("Passwords don't match.");
return false;
}
var user = {
'Name' : form.name.value,
'Phone' : form.phno.value,
'Email' : form.email.value,
'Password' : <PASSWORD>
};
//localStorage.clear();
add_to_data(user);
window.location = "users.html";
} | a50fb5278acf3ca4e2af4146af09e66427434414 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | mayank-a93/Form_Validation | 4a680d1b5df417d06d5031dac7072f6aa13341ae | 827ff6c97b16c2f948cdd9ce5ee316e602e96c06 |
refs/heads/master | <file_sep>package com.example.rabbitmqproducer.config;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitmqConfig {
/**
* 创建队列*/
@Bean
public Queue testQueue() {
return new Queue("test_queue");
}
@Bean
public Queue testQueue2() {
return new Queue("test_queue2");
}
}
<file_sep>package com.example.rabbitmqconsumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Arrays;
@SpringBootApplication
public class RabbitmqConsumerApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(RabbitmqConsumerApplication.class, args);
String[] beans = run.getBeanDefinitionNames();
Arrays.sort(beans);
for (String bean : beans) {
System.out.println(bean);
}
}
}
<file_sep>package com.example.rabbitmqconsumer;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "test_queue")
public class consumer {
@RabbitHandler
public void process(String message) throws InterruptedException {
System.out.println("1接受消息:" + message);
//Thread.sleep(300);
//return true;
}
}
<file_sep>package com.example.rabbitmqproducer;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class ProducerTopic {
@Autowired
private AmqpTemplate rabbitTemplate;
/**
* 发送消息到指定交换机;
*
* 交换机通过routingKey的值来模糊匹配将这条消息发送给匹配到的队列,#表示0个或若干个关键字,*表示一个关键字
*
* 消费者监听队列来接受消息
*/
public void sendMessage(int i) {
/**
* 队列test_queue绑定交换机myexchange时指定的routingKey是 topic.message
* 队列test_queue2绑定交换机myexchange时指定的routingKey是 topic.#
*
* 所以该消息会被这2个队列一起接受到
*/
rabbitTemplate.convertAndSend("myTopicExchange","topic.message","一条消息routingKey=topic.message" + "--------" + i);
// (交换机名称,routingKey,消息内容)
}
/**
* 队列test_queue绑定交换机myexchange时指定的routingKey是 topic.message
* 队列test_queue2绑定交换机myexchange时指定的routingKey是 topic.#
*
* 所以该消息会被test_queue2这个队列接受到
*/
public void sendMessage2(int i) {
rabbitTemplate.convertAndSend("myTopicExchange","topic.hanghang","一条消息routingKey=topic.hanghang" + "--------" + i);
}
}
<file_sep>/*
package com.example.rabbitmqproducer.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitmqConfigFanout {
*/
/**
* 创建队列*//*
@Bean
public Queue testQueue() {
return new Queue("test_queue");
}
@Bean
public Queue testQueue2() {
return new Queue("test_queue2");
}
*/
/**
* 声明一个Fanout类型的交换机*//*
@Bean
FanoutExchange fanoutExchange() {
return new FanoutExchange("myFanoutExchange");
}
*/
/**
* 绑定队列到交换机*//*
@Bean
Binding bindingExchangeA(Queue testQueue, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(testQueue).to(fanoutExchange);
}
@Bean
Binding bindingExchangeB(Queue testQueue2, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(testQueue2).to(fanoutExchange);
}
}
*/
<file_sep>package com.example.rabbitmqproducer;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class Producer {
@Autowired
private AmqpTemplate rabbitTemplate;
/**
* 发送消息到指定队列
*
* 消费者监听队列来接受消息
*/
public void sendMessage(int i) {
//①rabbitTemplate.send(); void 发送的消息必须为Message对象
//②rabbitTemplate.sendAndReceive(); Object 发送的消息必须为Message对象
//③rabbitTemplate.convertAndSend(); void 发送的消息任意类型,自动转换Message对象
//④rabbitTemplate.convertSendAndReceive() Object 发送的消息任意类型,自动转换Message对象
//1、3无返回值直接将所有消息发送出去(无时间间隔),不会因为消费者处理慢而阻塞线程
//2、4有返回值等待消费者处理完这条消息后才发送下一条(有时间间隔,等待消费者处理完毕) ≠ 消息确认机制
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//Object test_queue = rabbitTemplate.convertSendAndReceive("test_queue", "hello " + new Date() + "--------" + i);
rabbitTemplate.convertAndSend("test_queue", "hello " + new Date() + "--------" + i);
//System.out.println(simpleDateFormat.format(new Date()) + test_queue.toString());
System.out.println(simpleDateFormat.format(new Date()));
}
public void sendMessage2(int i) {
rabbitTemplate.convertAndSend("test_queue2", "hello " + new Date() + "--------" + i);
}
}
<file_sep>package com.example.rabbitmqproducer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Arrays;
@SpringBootApplication
public class RabbitmqProducerApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(RabbitmqProducerApplication.class, args);
String[] beans = run.getBeanDefinitionNames();
Arrays.sort(beans);
for (String bean : beans) {
System.out.println(bean);
}
}
}
<file_sep>/*
package com.example.rabbitmqproducer.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitmqConfigTopic {
*/
/**
* 创建队列*//*
@Bean
public Queue testQueue() {
return new Queue("test_queue");
}
@Bean
public Queue testQueue2() {
return new Queue("test_queue2");
}
*/
/**
* 声明一个Topic类型的交换机*//*
@Bean
TopicExchange exchange() {
return new TopicExchange("myTopicExchange");
}
*/
/**
* 绑定队列到交换机,并且指定routingKey*//*
@Bean
Binding bindingExchangeMessage(Queue testQueue, TopicExchange exchange) {
return BindingBuilder.bind(testQueue).to(exchange).with("topic.message");
}
@Bean
Binding bindingExchangeMessages(Queue testQueue2, TopicExchange exchange) {
return BindingBuilder.bind(testQueue2).to(exchange).with("topic.#");
}
}
*/
| a1e90a90db15d3f9fcb71a76d7c50372fd9e9466 | [
"Java"
] | 8 | Java | zhh0524/RabbitMQ-demo | ff954816a0a924472ff2ecc8f16e9d5db6bf4b9d | 8178bdc8e091b832236e206a866d6ac29abaed72 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>
#include <sys/time.h>
double wtime()
{
struct timeval t;
gettimeofday(&t, NULL);
return (double) t.tv_sec + (double) t.tv_usec * 1E-6;
}
int min(int a, int b)
{
return (a < b) ? a : b;
}
void get_chunk(int a, int b, int commsize, int rank, int *lb, int *ub)
{
int n = b - a + 1;
int q = n / commsize;
if (n % commsize)
q++;
int r = commsize * q - n;
/* Compute chunk size for the process */
int chunk = q;
if (rank >= commsize - r) chunk = q - 1;
*lb = a; /* Determine start item for the process */
if (rank > 0) { /* Count sum of previous chunks */
if (rank <= commsize - r)
*lb += q * rank;
else
*lb += q * (commsize - r) + (q - 1) * (rank - (commsize - r));
}
*ub = *lb + chunk - 1;
}
static inline void infinitize(int n, int *g)
{
for (int i = 0; i < n * n; ++i)
if (g[i] == 0)
g[i] = 10000;
}
static inline void deinfinitize(int n, int *g)
{
for (int i = 0; i < n * n; ++i)
if (g[i] == 10000)
g[i] = 0;
}
int *gen_graph(int n)
{
int *g = calloc(n * n, sizeof(int));
for (int j = 0; j < n; ++j) {
for (int i = 0; i < n; ++i)
if (j > i)
g[j * n + i] = (rand() % 100);
else
g[j * n + i] = -1;
}
for (int j = 0; j < n; ++j) {
for (int i = 0; i < n; ++i)
if (i > j)
g[j * n + i] = g[i * n + j];
g[j * n + j] = 0;
}
return g;
}
void write_matrix(const char *fname, int n, int *a)
{
FILE *fp = fopen(fname, "w+");
if (fp == NULL) {
fprintf(stderr, "Could not open output file: %s\n", fname);
exit(EXIT_FAILURE);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j)
fprintf(fp, "%d ", a[j * n + i]);
fprintf(fp, "\n");
}
fclose(fp);
}
void copy(int *p_beg, int *p_end, int *rows)
{
int *p = p_beg;
for (int i = 0; p < p_end; i++, p++)
rows[i] = *p;
}
// функция для рассылки строки всем процессам
void raw_distribution(int *proc_raws, int n, int raw_num, int k, int *raw, int commsize, int rank)
{
int proc_raw_rank; //ранг процесса, которому принадлежит k-я строка
int proc_raw_num; //номер k-й строки в полосе матрицы
//нахождение ранга процесса - владельца k-й строки
/*
int rest_raws = n;
int ind = 0;
int num = n / commsize;
for (proc_raw_rank = 1; proc_raw_rank < commsize + 1; proc_raw_rank++) {
if (k < ind + num)
break;
rest_raws -= num;
ind += num;
num = rest_raws / (commsize - proc_raw_rank);
}
*/
int lb, ub;
for (int i = 0; i < commsize; i++) {
get_chunk(0, n - 1, commsize, i, &lb, &ub);
if (k >= lb && k <= ub) {
proc_raw_rank = i;
break;
}
}
//копирование строки в массив raw
if (proc_raw_rank == rank) {
int need_row = k - lb;
copy(&proc_raws[need_row * n], &proc_raws[(need_row + 1) * n], raw);
}
//распределение k-й строки между процессами
MPI_Bcast(raw, n, MPI_INT, proc_raw_rank, MPI_COMM_WORLD);
}
void floyd_mpi(int *proc_raws, int n, int raw_num, int commsize, int rank)
{
int *raw = (int *) malloc(sizeof(*raw) * n);
int t1, t2;
for (int k = 0; k < n; k++) {
//распределение k-й строки среди процессов
raw_distribution(proc_raws, n, raw_num, k, raw, commsize, rank);
// обновление элементов матрицы смежности
for (int i = 0; i < raw_num; i++) {
for (int j = 0; j < n; j++) {
if( (proc_raws[i * n + k] != -1) && (raw[j] != -1)) {
t1 = proc_raws[i * n + j];
t2 = proc_raws[i * n + k] + raw[j];
proc_raws[i * n + j] = min(t1, t2);
}
}
}
}
free(raw);
}
int main(int argc, char **argv)
{
int n = (argc > 1) ? atoi(argv[1]) : 100;
const char *genname = (argc > 2) ? argv[2] : NULL;
const char *parname = (argc > 3) ? argv[3] : NULL;
double t = wtime();
if (n < 1) {
fprintf(stderr, "Invalid size of graph");
exit(EXIT_FAILURE);
}
int *g = gen_graph(n);
int rank, commsize;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &commsize);
//if (genname && !rank)
//write_matrix(genname, n, g);
MPI_Bcast(g, n * n, MPI_INT, 0, MPI_COMM_WORLD);
/*if (rank == 0) {
for (int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
printf("%d ", g[i * n + j]);
printf("\n");
}
}*/
int lb, ub;
get_chunk(0, n - 1, commsize, rank, &lb, &ub);
int raw_num = ub - lb + 1; //чисто строк для текущего процесса
//строки матрицы смежности текущего процесса
int *proc_raws = malloc(sizeof(*proc_raws) * raw_num * n);
for (int i = 0; i < raw_num; i++)
for (int j = 0; j < n; j++)
proc_raws[i * n + j] = (g[(i + lb) * n + j] == 0) ? 10000 : g[(i + lb) * n + j];
floyd_mpi(proc_raws, n, raw_num, commsize, rank);
if (!rank) {
for (int i = 0; i < n * n; i++)
g[i] = 0;
int *recvcnt = malloc(sizeof(*recvcnt) * commsize);
int *displs = malloc(sizeof(*displs) * commsize);
for (int i = 0; i < commsize; i++) {
int lb, ub;
get_chunk(0, n - 1, commsize, i, &lb, &ub);
recvcnt[i] = (ub - lb + 1) * n;
displs[i] = (i > 0) ? displs[i - 1] + recvcnt[i - 1] : 0;
//printf("cnt = %d, displs = %d\n", recvcnt[i], displs[i]);
}
MPI_Gatherv(proc_raws, raw_num * n, MPI_INT, g, recvcnt, displs, MPI_INT, 0, MPI_COMM_WORLD);
} else
MPI_Gatherv(proc_raws, raw_num * n, MPI_INT, NULL, NULL, NULL, MPI_INT, 0, MPI_COMM_WORLD);
for (int i = 0; i < n * n; i += n + 1)
g[i] = 0;
t = wtime() - t;
double tmax;
MPI_Reduce(&t, &tmax, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if (!rank) {
printf("n: %d\n", n);
printf("Time for %d proc: %.6f\n", commsize, tmax);
}
/*if (rank == 0) {
printf("----\n");
for (int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
printf("%d ", g[i * n + j]);
printf("\n");
}
}
//if (parname)
// write_matrix(parname, n, gp);
*/
free(g);
free(proc_raws);
MPI_Finalize();
return 0;
}
<file_sep># algo_FloydWarshall
Алгоритм Флойда-Уоршелла. Serial, MPI OpenMP C
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
double ts, tp;
void floyd(int *g, int n, int threads)
{
for (int k = 0; k < n; ++k) {
#pragma omp parallel for num_threads(threads)
for (int i = 0; i < n; ++i) {
int v = g[i * n + k];
for (int j = 0; j < n; ++j) {
int val = v + g[k * n + j];
if (g[i * n + j] > val) {
g[i * n + j] = val;
}
}
}
}
}
static inline void infinitize(int n, int *g)
{
for (int i = 0; i < n * n; ++i)
if (g[i] == 0)
g[i] = 10000;
}
static inline void deinfinitize(int n, int *g)
{
for (int i = 0; i < n * n; ++i)
if (g[i] == 10000)
g[i] = 0;
}
int *shortest_paths_p(int n, int *restrict g)
{
int *restrict gnew = (int *) calloc(n * n, sizeof(int));
memcpy(gnew, g, n * n * sizeof(int));
infinitize(n, gnew);
tp = omp_get_wtime();
floyd(gnew, n, omp_get_max_threads());
tp = omp_get_wtime() - tp;
for (int i = 0; i < n * n; i += n + 1)
gnew[i] = 0;
deinfinitize(n, gnew);
return gnew;
}
int *shortest_paths_s(int n, int *restrict g)
{
int *restrict gnew = (int *) calloc(n * n, sizeof(int));
memcpy(gnew, g, n * n * sizeof(int));
infinitize(n, gnew);
ts = omp_get_wtime();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++) {
if (gnew[j * n + k] > gnew[j * n + i] + gnew[i * n + k])
gnew[j * n + k] = gnew[j * n + i] + gnew[i * n + k];
}
}
ts = omp_get_wtime() - ts;
for (int i = 0; i < n * n; i += n + 1)
gnew[i] = 0;
deinfinitize(n, gnew);
return gnew;
}
int *gen_graph(int n)
{
int *g = calloc(n * n, sizeof(int));
for (int j = 0; j < n; ++j) {
for (int i = 0; i < n; ++i)
if (j > i)
g[j * n + i] = (rand() % 100);
else
g[j * n + i] = -1;
}
for (int j = 0; j < n; ++j) {
for (int i = 0; i < n; ++i)
if (i > j)
g[j * n + i] = g[i * n + j];
g[j * n + j] = 0;
}
return g;
}
void write_matrix(const char *fname, int n, int *a)
{
FILE *fp = fopen(fname, "w+");
if (fp == NULL) {
fprintf(stderr, "Could not open output file: %s\n", fname);
exit(EXIT_FAILURE);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j)
fprintf(fp, "%d ", a[j * n + i]);
fprintf(fp, "\n");
}
fclose(fp);
}
int main(int argc, char **argv)
{
int n = (argc > 1) ? atoi(argv[1]) : 100;
const char *genname = (argc > 2) ? argv[2] : NULL;
const char *sername = (argc > 3) ? argv[3] : NULL;
const char *parname = (argc > 4) ? argv[4] : NULL;
if (n < 1) {
fprintf(stderr, "Invalid size of graph");
exit(EXIT_FAILURE);
}
int *g = gen_graph(n);
if (genname)
write_matrix(genname, n, g);
int *gs = shortest_paths_s(n, g);
printf("OpenMP with %d threads\n", omp_get_max_threads());
printf("n: %d\n", n);
printf("Time ser (sec): %.6f\nTime parallel (sec): %.6f\nS(n): %.6f\n", ts, tp, ts / tp);
if (sername)
write_matrix(sername, n, gs);
if (parname)
write_matrix(parname, n, gp);
free(g);
free(gs);
free(gp);
return 0;
}
| 8ef19512fd3ed04cf5f388166f420a22e1ed44ea | [
"Markdown",
"C"
] | 3 | C | u7er/algo_FloydWarshall | c2a77914f8a2386adb32f123e7e472d130ab17fc | 857c1015e7dfc96734ca4e7ed8f627b4a64e4fc7 |
refs/heads/master | <file_sep>import { IProject } from '../IProject'
const img6 = process.env.REACT_APP_IMAGE_URL + 'Turkey/1.jpg'
const img7 = process.env.REACT_APP_IMAGE_URL + 'Turkey/2.jpg'
const img8 = process.env.REACT_APP_IMAGE_URL + 'Turkey/3.jpg'
const img9 = process.env.REACT_APP_IMAGE_URL + 'Turkey/4.jpg'
const img10 = process.env.REACT_APP_IMAGE_URL + 'Turkey/5.jpg'
const img11 = process.env.REACT_APP_IMAGE_URL + 'Turkey/6.jpg'
const img12 = process.env.REACT_APP_IMAGE_URL + 'Turkey/7.jpg'
const img13 = process.env.REACT_APP_IMAGE_URL + 'Turkey/8.jpg'
const img14 = process.env.REACT_APP_IMAGE_URL + 'Turkey/9.jpg'
const img15 = process.env.REACT_APP_IMAGE_URL + 'Turkey/10.jpg'
const img16 = process.env.REACT_APP_IMAGE_URL + 'Turkey/11.jpg'
const img17 = process.env.REACT_APP_IMAGE_URL + 'Turkey/12.jpg'
const img18 = process.env.REACT_APP_IMAGE_URL + 'Turkey/13.jpg'
const img19 = process.env.REACT_APP_IMAGE_URL + 'Turkey/14.jpg'
const img20 = process.env.REACT_APP_IMAGE_URL + 'Turkey/16.jpg'
const img21 = process.env.REACT_APP_IMAGE_URL + 'Turkey/17.jpg'
const img22 = process.env.REACT_APP_IMAGE_URL + 'Turkey/19.jpg'
const img23 = process.env.REACT_APP_IMAGE_URL + 'Turkey/20.jpg'
const img24 = process.env.REACT_APP_IMAGE_URL + 'Turkey/21.jpg'
const img25 = process.env.REACT_APP_IMAGE_URL + 'Turkey/22.jpg'
const img26 = process.env.REACT_APP_IMAGE_URL + 'Turkey/23.jpg'
const img27 = process.env.REACT_APP_IMAGE_URL + 'Turkey/24.jpg'
const img28 = process.env.REACT_APP_IMAGE_URL + 'Turkey/25.jpg'
const img29 = process.env.REACT_APP_IMAGE_URL + 'Turkey/26.jpg'
const img30 = process.env.REACT_APP_IMAGE_URL + 'Turkey/27.jpg'
const img31 = process.env.REACT_APP_IMAGE_URL + 'Turkey/28.jpg'
const img32 = process.env.REACT_APP_IMAGE_URL + 'Turkey/30.jpg'
const img33 = process.env.REACT_APP_IMAGE_URL + 'Turkey/31.jpg'
const img34 = process.env.REACT_APP_IMAGE_URL + 'Turkey/32.jpg'
const img35 = process.env.REACT_APP_IMAGE_URL + 'Turkey/obelisk_1_kellygorr.jpg'
export const turkey: IProject = {
title: 'Turkey',
photos: [
{
title: 'Istanbul',
thumbnail: img35,
img: img35,
},
{
title: 'Blue Mosque',
thumbnail: img6,
img: img6,
},
{
title: 'Turkey',
thumbnail: img7,
img: img7,
},
{
title: 'Turkey',
thumbnail: img8,
img: img8,
},
{
title: 'Turkey',
thumbnail: img9,
img: img9,
},
{
title: 'Turkey',
thumbnail: img10,
img: img10,
},
{
title: 'Turkey',
thumbnail: img11,
img: img11,
},
{
title: 'Turkey',
thumbnail: img12,
img: img12,
},
{
title: '<NAME>',
thumbnail: img13,
img: img13,
},
{
title: 'Turkey',
thumbnail: img14,
img: img14,
},
{
title: 'Istanbul',
thumbnail: img15,
img: img15,
},
{
title: 'Turkey',
thumbnail: img16,
img: img16,
},
{
title: 'Blue Mosque',
thumbnail: img17,
img: img17,
},
{
title: 'Blue Mosque',
thumbnail: img18,
img: img18,
},
{
title: 'Istanbul',
thumbnail: img19,
img: img19,
},
{
title: 'Ephesus',
thumbnail: img20,
img: img20,
},
{
title: 'Pamukkale',
thumbnail: img21,
img: img21,
},
{
title: 'Cappadocia',
thumbnail: img22,
img: img22,
},
{
title: 'Blue Mosque',
thumbnail: img23,
img: img23,
},
{
title: 'Turkey',
thumbnail: img24,
img: img24,
},
{
title: 'Turkey',
thumbnail: img25,
img: img25,
},
{
title: 'Turkey',
thumbnail: img26,
img: img26,
},
{
title: 'Turkey',
thumbnail: img27,
img: img27,
},
{
title: 'Turkey',
thumbnail: img28,
img: img28,
},
{
title: 'Turkey',
thumbnail: img29,
img: img29,
},
{
title: 'Turkey',
thumbnail: img30,
img: img30,
},
{
title: 'Turkey',
thumbnail: img31,
img: img31,
},
{
title: 'Cappadocia',
thumbnail: img32,
img: img32,
},
{
title: 'Cappadocia',
thumbnail: img33,
img: img33,
},
{
title: 'Cappadocia',
thumbnail: img34,
img: img34,
},
],
}
<file_sep>import { IProject } from '../IProject'
const img1 = process.env.REACT_APP_IMAGE_URL + 'Spain/madrid_street_kellygorr.jpg'
const img2 = process.env.REACT_APP_IMAGE_URL + 'Spain/Sinagoga_La_Blanca_kellygorr.jpg'
const img3 = process.env.REACT_APP_IMAGE_URL + 'Spain/toledo_cathedral_kellygorr.jpg'
export const spain: IProject = {
title: 'Spain',
photos: [
{
title: 'Toledo',
thumbnail: img3,
img: img3,
},
{
title: 'Madrid',
thumbnail: img1,
img: img1,
},
{
title: 'Sinagoga La Blanca',
thumbnail: img2,
img: img2,
},
],
}
<file_sep>import { IProject } from '../IProject'
const img1 = process.env.REACT_APP_IMAGE_URL + 'Beach/Beach_driftwood_kellygorr.jpg'
const img2 = process.env.REACT_APP_IMAGE_URL + 'Washington/nw_treck_1_kellygorr.jpg'
const img3 = process.env.REACT_APP_IMAGE_URL + 'Washington/nw_treck_2_kellygorr.jpg'
const img4 = process.env.REACT_APP_IMAGE_URL + 'Washington/nw_treck_kellygorr.jpg'
export const washington: IProject = {
title: 'Washington',
photos: [
{
title: 'Camano Island',
thumbnail: img1,
img: img1,
},
{
title: 'NW Treck - Sheep',
thumbnail: img2,
img: img2,
},
{
title: 'NW Treck - Snowy Owl',
thumbnail: img3,
img: img3,
},
{
title: 'NW Treck',
thumbnail: img4,
img: img4,
},
],
}
<file_sep>import { IProject } from '../IProject'
const img2 = process.env.REACT_APP_IMAGE_URL + 'France/france_paris_1_kellygorr.jpg'
export const france: IProject = {
title: 'France',
photos: [
{
title: 'Paris',
thumbnail: img2,
img: img2,
},
],
}
<file_sep>import { IProject } from '../IProject'
const img1 = process.env.REACT_APP_IMAGE_URL + 'Flowers/bee_lavender_3_kellygorr.jpg'
const img2 = process.env.REACT_APP_IMAGE_URL + 'Flowers/crocus_duo_kellygorr.jpg'
const img3 = process.env.REACT_APP_IMAGE_URL + 'Flowers/dandelion_2_kellygorr.jpg'
const img4 = process.env.REACT_APP_IMAGE_URL + 'Flowers/dandelion_seeds_kellygorr.jpg'
const img5 = process.env.REACT_APP_IMAGE_URL + 'Flowers/crocus_1_kellygorr.jpg'
const img6 = process.env.REACT_APP_IMAGE_URL + 'Flowers/rain_drop_1_kellygorr.jpg'
const img7 = process.env.REACT_APP_IMAGE_URL + 'Flowers/white_flower_5_kellygorr.jpg'
const img8 = process.env.REACT_APP_IMAGE_URL + 'Flowers/snow_flowers_kellygorr.jpg'
const img9 = process.env.REACT_APP_IMAGE_URL + 'Flowers/daisies_flowers_kellygorr.jpg'
const img10 = process.env.REACT_APP_IMAGE_URL + 'Flowers/butterfly_1_kellygorr.jpg'
const img11 = process.env.REACT_APP_IMAGE_URL + 'Flowers/butterfly_2_kellygorr.jpg'
const img12 = process.env.REACT_APP_IMAGE_URL + 'Flowers/butterfly_3_kellygorr.jpg'
const img13 = process.env.REACT_APP_IMAGE_URL + 'Flowers/daisies_2_kellygorr.jpg'
export const flowers: IProject = {
title: 'Flowers',
photos: [
{
title: 'Bee',
thumbnail: img1,
img: img1,
},
{
title: '<NAME>',
thumbnail: img2,
img: img2,
},
{
title: 'Dandelion',
thumbnail: img3,
img: img3,
},
{
title: 'Dandelion',
thumbnail: img4,
img: img4,
},
{
title: 'Crocus',
thumbnail: img5,
img: img5,
},
{
title: 'Coneflower',
thumbnail: img6,
img: img6,
},
{
title: 'Clover',
thumbnail: img7,
img: img7,
},
{
title: 'Snow',
thumbnail: img8,
img: img8,
},
{
title: 'Daisies',
thumbnail: img9,
img: img9,
},
{
title: 'Butterfly',
thumbnail: img10,
img: img10,
},
{
title: 'Butterfly',
thumbnail: img11,
img: img11,
},
{
title: 'Butterfly',
thumbnail: img12,
img: img12,
},
{
title: 'Daisies',
thumbnail: img13,
img: img13,
},
],
}
<file_sep>import { IProject } from '../IProject'
const img1 = process.env.REACT_APP_IMAGE_URL + 'Seattle/seattle_kellygorr.jpg'
const img2 = process.env.REACT_APP_IMAGE_URL + 'Seattle/uw_kellygorr.jpg'
const img8 = process.env.REACT_APP_IMAGE_URL + 'Seattle/seattle_1_kellygorr.jpg'
const img9 = process.env.REACT_APP_IMAGE_URL + 'Seattle/seattle_2_kellygorr.jpg'
const img10 = process.env.REACT_APP_IMAGE_URL + 'Seattle/seattle_3_kellygorr.jpg'
const img11 = process.env.REACT_APP_IMAGE_URL + 'Seattle/seattle_4_kellygorr.jpg'
const img12 = process.env.REACT_APP_IMAGE_URL + 'Seattle/seattle_5_kellygorr.jpg'
export const seattle: IProject = {
title: 'Seattle',
photos: [
{
title: 'Seattle',
thumbnail: img1,
img: img1,
camera: 'Canon',
lens: 'Canon',
date: '1/1/11',
},
{
title: 'University of Washington',
thumbnail: img2,
img: img2,
camera: 'Canon',
lens: 'Canon',
date: '1/1/11',
},
{
title: 'Gas Works Park',
thumbnail: img8,
img: img8,
camera: 'Canon',
lens: 'Canon',
date: '1/1/11',
},
{
title: 'Gas Works Park',
thumbnail: img9,
img: img9,
camera: 'Canon',
lens: 'Canon',
date: '1/1/11',
},
{
title: 'Gas Works Park',
thumbnail: img10,
img: img10,
camera: 'Canon',
lens: 'Canon',
date: '1/1/11',
},
{
title: 'Ballard locks',
thumbnail: img11,
img: img11,
camera: 'Canon',
lens: 'Canon',
date: '1/1/11',
},
{
title: 'Ballard locks',
thumbnail: img12,
img: img12,
camera: 'Canon',
lens: 'Canon',
date: '1/1/11',
},
],
}
<file_sep>import { IProject } from '../IProject'
const img1 = process.env.REACT_APP_IMAGE_URL + 'Pets/kody_kellygorr.jpg'
const img2 = process.env.REACT_APP_IMAGE_URL + 'Pets/cat_portrait_1_kellygorr.jpg'
const img3 = process.env.REACT_APP_IMAGE_URL + 'Pets/corgi_dog_1_kellygorr.jpg'
const img4 = process.env.REACT_APP_IMAGE_URL + 'Pets/pygmy_goat_1_kellygorr.jpg'
const img5 = process.env.REACT_APP_IMAGE_URL + 'Pets/pygmy_goat_2_kellygorr.jpg'
const img6 = process.env.REACT_APP_IMAGE_URL + 'Pets/pygmy_goat_6_kellygorr.jpg'
const img7 = process.env.REACT_APP_IMAGE_URL + 'Pets/yellow_labrador_retriever_kellygorr.jpg'
const img8 = process.env.REACT_APP_IMAGE_URL + 'Pets/pygmy_goat_4_kellygorr.jpg'
const img9 = process.env.REACT_APP_IMAGE_URL + 'Pets/corgi_dog_2_kellygorr.jpg'
export const pets: IProject = {
title: 'Pets',
photos: [
{
title: 'Kody',
thumbnail: img1,
img: img1,
},
{
title: 'Basil',
thumbnail: img4,
img: img4,
},
{
title: 'Basil',
thumbnail: img5,
img: img5,
},
{
title: 'Basil',
thumbnail: img6,
img: img6,
},
{
title: 'Comet',
thumbnail: img7,
img: img7,
},
{
title: 'Rocky',
thumbnail: img2,
img: img2,
},
{
title: 'Cory',
thumbnail: img3,
img: img3,
},
{
title: 'Basil',
thumbnail: img8,
img: img8,
},
{
title: 'Hasil',
thumbnail: img9,
img: img9,
},
],
}
<file_sep>import { IProject } from './IProject'
import { flowers } from './projects/flowers'
import { washington } from './projects/washington'
import { turkey } from './projects/turkey'
import { seattle } from './projects/seattle'
import { france } from './projects/france'
import { pets } from './projects/pets'
import { spain } from './projects/spain'
export const projects: IProject[] = [turkey, spain, flowers, pets, france, seattle, washington]
| d1ebb097376e31e85c00815c175a90bf81ff2ed7 | [
"TypeScript"
] | 8 | TypeScript | kellygorr/gallery-website-react | b4d5d75481991f7415ae86d33cfd43bec1486eb3 | 203d0fd484bc933ceefcbf3beda4cab1343be431 |
refs/heads/master | <file_sep>namespace SE2_Oefentoets
{
public class Beker : IVoorraad
{
public Beker(string naam, int milliliter, bool warmeDrankMogelijk)
{
Naam = naam;
Milliliter = milliliter;
WarmeDrankMogelijk = warmeDrankMogelijk;
}
public int Milliliter { get; set; }
public bool WarmeDrankMogelijk { get; set; }
public string Naam { get; set; }
public int Voorraad { get; set; }
public override string ToString()
=> $"Naam: {Naam}, Voorraad: {Voorraad}, Milliliter: {Milliliter}, WarmeDrankMogelijk: {WarmeDrankMogelijk}";
}
}<file_sep>namespace SE2_Oefentoets
{
public class Soep : Drank
{
public Soep(string naam, decimal prijs, int milliliter) : base(naam, prijs, milliliter, true)
{
}
public override string ToString() => $"{base.ToString()}";
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace SE2_Oefentoets
{
public class Voorraad
{
public readonly List<IVoorraad> HuidigeVoorraad = new List<IVoorraad>();
public readonly List<Verkoop> Verkopen = new List<Verkoop>();
/// <summary>
/// Voeg een nieuwe drank aan het systeem toe.
/// </summary>
/// <param name="drank">De toe te voegen drank.</param>
/// <returns>True als het toevoegen gelukt is.</returns>
public bool NieuwProduct(Drank drank)
{
if (HuidigeVoorraad.Contains(drank)) return false;
HuidigeVoorraad.Add(drank);
return true;
}
/// <summary>
/// Voeg een nieuwe beker aan het systeem toe.
/// </summary>
/// <param name="beker">De toe te voegen beker.</param>
/// <returns>True als het toevoegen gelukt is.</returns>
public bool NieuwProduct(Beker beker)
{
if (HuidigeVoorraad.Contains(beker)) return false;
HuidigeVoorraad.Add(beker);
return true;
}
/// <summary>
/// Een kopie van de lijst met beschikbare producten. Elementen die toegevoegd of verwijderd worden, worden niet
/// automatisch bijgewerkt in de originele lijst.
/// </summary>
/// <returns>Een kopie van de lijst met beschikbare producten.</returns>
public List<IVoorraad> BeschikbareProducten()
{
return HuidigeVoorraad.ToList();
}
/// <summary>
/// Een kopie van de lijst met alle dranken die op voorraad zijn. Elementen die toegevoegd of verwijderd worden, worden
/// niet
/// automatisch bijgewerkt in de originele lijst.
/// </summary>
/// <returns>Een kopie van de lijst met alle dranken die op voorraad zijn.</returns>
public List<Drank> VoorradigeDranken() => HuidigeVoorraad.OfType<Drank>()
.Where(drank => drank.Voorraad > 0).ToList();
/// <summary>
/// Voeg nieuwe voorraad toe aan een product.
/// </summary>
/// <param name="product">Het product om bij te vullen.</param>
/// <param name="aantal">Het aantal bij te vullen producten.</param>
public void VulBij(IVoorraad product, int aantal)
{
product.Voorraad += aantal;
}
/// <summary>
/// Serveer een drank en registreer dit in het logboek.
/// <para />
/// <para />
/// De drank wordt alleen geserveerd als:
/// <para />
/// - De inworp minstens gelijk is aan de prijs.
/// <para />
/// - Er een beker op voorraad is.
/// <para />
/// - De beker geschikt is voor het type drank.
/// <para />
/// - De inhoud van de beker groot genoeg is.
/// </summary>
/// <param name="drank"></param>
/// <param name="inworp"></param>
/// <returns></returns>
public bool KoopDrank(Drank drank, decimal inworp)
{
if (!VoorradigeDranken().Contains(drank)) return false; // Drank niet beschikbaar
if (drank.Prijs > inworp) return false; // Niet genoeg geld
try
{
Beker gevondenBeker = BeschikbareProducten()
// Alle bekers...
.OfType<Beker>()
// ...die op voorraad zijn...
.Where(beker => beker.Voorraad > 0)
// ...en geschikt zijn voor de drank...
.Where(beker => !drank.WarmeDrank || beker.WarmeDrankMogelijk)
// ...en groot genoeg zijn...
.Where(beker => beker.Milliliter >= drank.Milliliter)
// ...gesorteerd van klein naar groot. Hierdoor worden eerst alle kleine bekers op gemaakt.
.OrderBy(beker => beker.Milliliter)
.First();
gevondenBeker.Voorraad--;
drank.Voorraad--;
// Log
Verkopen.Add(new Verkoop(drank));
return true;
}
catch (InvalidOperationException)
{
throw new OnvoldoendeBekersException();
}
}
/// <summary>
/// Schrijf alle verkopen op omgekeerd chronologische volgorde naar het aangegeven bestand.
/// </summary>
/// <param name="bestandsnaam">Het bestand waar de logs naar toe geschreven moeten worden.</param>
public void ExporteerLogbestand(string bestandsnaam)
{
Verkopen.Sort();
Verkopen.Reverse();
File.WriteAllLines(bestandsnaam, Verkopen.Select(verkoop => verkoop.Tijdstip + " - " + verkoop.Drank.Naam));
}
public override string ToString() => $"HuidigeVoorraad: {HuidigeVoorraad.Count}, Verkopen: {Verkopen.Count}";
}
}<file_sep>namespace SE2_Oefentoets
{
public class Koffie : Drank
{
public Koffie(string naam, decimal prijs, int milliliter, int milligramCafeine)
: base(naam, prijs, milliliter, true)
{
MilligramCafeine = milligramCafeine;
}
public int MilligramCafeine { get; set; }
public override string ToString() => $"{base.ToString()}, MilligramCafeine: {MilligramCafeine}";
}
}<file_sep>namespace SE2_Oefentoets
{
public interface IVoorraad
{
string Naam { get; set; }
int Voorraad { get; set; }
}
}<file_sep>using System;
namespace SE2_Oefentoets
{
public class Verkoop : IComparable<Verkoop>
{
public Verkoop(Drank drank)
{
Tijdstip = DateTime.Now;
Drank = drank;
}
public DateTime Tijdstip { get; set; }
public Drank Drank { get; set; }
public int CompareTo(Verkoop other) => Tijdstip.CompareTo(other.Tijdstip);
public override string ToString() => $"Tijdstip: {Tijdstip}, Drank: {Drank}";
}
}<file_sep>namespace SE2_Oefentoets
{
public class Frisdrank : Drank
{
public Frisdrank(string naam, decimal prijs, int milliliter, int gramSuiker)
: base(naam, prijs, milliliter, false)
{
GramSuiker = gramSuiker;
}
public int GramSuiker { get; set; }
public override string ToString() => $"{base.ToString()}, GramSuiker: {GramSuiker}";
}
}<file_sep>using System;
namespace SE2_Oefentoets
{
public class OnvoldoendeBekersException : Exception
{
public OnvoldoendeBekersException() : base("Niet genoeg bekers beschikbaar")
{
}
}
}<file_sep>namespace SE2_Oefentoets
{
public abstract class Drank : IVoorraad
{
protected Drank(string naam, decimal prijs, int milliliter, bool warmeDrank)
{
Naam = naam;
Prijs = prijs;
Milliliter = milliliter;
WarmeDrank = warmeDrank;
}
public decimal Prijs { get; set; }
public int Milliliter { get; set; }
public bool WarmeDrank { get; set; }
public string Naam { get; set; }
public int Voorraad { get; set; }
public override string ToString()
=> $"Naam: {Naam}, Voorraad: {Voorraad}, Prijs: {Prijs}, Milliliter: {Milliliter}, WarmeDrank: {WarmeDrank}";
}
}<file_sep>using System;
using System.Windows.Forms;
namespace SE2_Oefentoets
{
public partial class MainForm : Form
{
private readonly Voorraad _voorraad = new Voorraad();
private decimal _inworp = new decimal(7.50);
public MainForm()
{
InitializeComponent();
// Event handlers
btnEuro020.Click += btnInworp_click;
btnEuro050.Click += btnInworp_click;
btnEuro100.Click += btnInworp_click;
btnEuro200.Click += btnInworp_click;
RefreshData();
}
private void btnInworp_click(object sender, EventArgs eventArgs)
{
if (sender == btnEuro020)
{
_inworp += (decimal) 0.20;
}
else if (sender == btnEuro050)
{
_inworp += (decimal) 0.50;
}
else if (sender == btnEuro100)
{
_inworp += (decimal) 1.00;
}
else if (sender == btnEuro200)
{
_inworp += (decimal) 2.00;
}
RefreshData();
}
private void btnServeer_Click(object sender, EventArgs e)
{
Drank drank = lbDranken.SelectedItem as Drank;
try
{
// Koop een drank als deze geselecteerd is
if (drank != null)
{
if (_voorraad.KoopDrank(drank, _inworp))
{
// Schrijf geld af als het kopen gelukt is
_inworp -= drank.Prijs;
}
else
{
MessageBox.Show("Niet genoeg geld");
}
}
else
{
MessageBox.Show("Geen drank geselecteerd");
}
}
catch (OnvoldoendeBekersException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
MessageBox.Show(ex.Message);
}
RefreshData();
}
private void btnDrankToevoegen_Click(object sender, EventArgs e)
{
string naam = tbDrankNaam.Text;
decimal prijs = nudDrankPrijs.Value;
int milliliter = Convert.ToInt32(nudDrankMilliliter.Value);
int voedingswaarde = Convert.ToInt32(nudDrankVoedingswaarde.Value);
switch (cbDrankSoort.Text)
{
case "Frisdrank":
if (naam != "" && prijs >= 0 && milliliter > 0 && voedingswaarde >= 0)
{
_voorraad.NieuwProduct(new Frisdrank(naam, prijs, milliliter, voedingswaarde));
}
else
{
MessageBox.Show("Ongeldige data");
}
break;
case "Koffie":
if (naam != "" && prijs >= 0 && milliliter > 0 && voedingswaarde >= 0)
{
_voorraad.NieuwProduct(new Koffie(naam, prijs, milliliter, voedingswaarde));
}
else
{
MessageBox.Show("Ongeldige data");
}
break;
case "Soep":
if (naam != "" && prijs >= 0 && milliliter > 0)
{
_voorraad.NieuwProduct(new Soep(naam, prijs, milliliter));
}
else
{
MessageBox.Show("Ongeldige data");
}
break;
default:
MessageBox.Show("Geen product geselecteerd");
break;
}
RefreshData();
}
private void btnVoorraadToevoegen_Click(object sender, EventArgs e)
{
int aantal = Convert.ToInt32(nudVoorraadAantal.Value);
IVoorraad voorraad = lbVoorraad.SelectedItem as IVoorraad;
if (voorraad != null)
{
_voorraad.VulBij(voorraad, aantal);
}
else
{
MessageBox.Show("Geen voorraad geselecteerd");
}
RefreshData();
}
private void btnBekerToevoegen_Click(object sender, EventArgs e)
{
string naam = tbBekerNaam.Text;
int milliliters = Convert.ToInt32(nudBekerMilliliter.Value);
bool warmeDrankMogelijk = chkBekerWarmeDrank.Checked;
if (naam != "" && milliliters > 0)
{
_voorraad.NieuwProduct(new Beker(naam, milliliters, warmeDrankMogelijk));
}
else
{
MessageBox.Show("Ongeldige data");
}
RefreshData();
}
private void btnExporteerLogbestand_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog
{
DefaultExt = "log",
Filter = "Log bestand|*.log"
};
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
_voorraad.ExporteerLogbestand(dialog.FileName);
}
}
private void RefreshData()
{
object selectedVoorraad = lbVoorraad.SelectedItem;
lbVoorraad.Items.Clear();
_voorraad.BeschikbareProducten().ForEach(voorraad => lbVoorraad.Items.Add(voorraad));
if (selectedVoorraad != null && lbVoorraad.Items.Contains(selectedVoorraad))
{
lbVoorraad.SelectedItem = selectedVoorraad;
}
object selectedDrank = lbDranken.SelectedItem;
lbDranken.Items.Clear();
_voorraad.VoorradigeDranken().ForEach(drank => lbDranken.Items.Add(drank));
if (selectedDrank != null && lbDranken.Items.Contains(selectedDrank))
{
lbDranken.SelectedItem = selectedDrank;
}
lblInworp.Text = _inworp.ToString("##.00");
}
}
} | a6289efeb70c2a2399565203b9682c9c89e77499 | [
"C#"
] | 10 | C# | SvenDub/se2-oefentoets | ebc4af58832b5a60cc5c939fd450f36e8b534ec7 | a9af4b2e18eead9c6990bc0e63769f8698d2e8b5 |
refs/heads/master | <file_sep>#include<Servo.h>
Servo test;
int pot = 0;
int val = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
test.attach(3);
test.writeMicroseconds(1000);
}
void loop() {
// put your main code here, to run repeatedly:
pot = analogRead(A0);
val = map(pot, 0, 1024, 1000,2000);
Serial.print(val);
test.writeMicroseconds(val);
}
<file_sep># Arduino-Hexacopter-Control
SCHEMATICS WILL COME
After not being able to find a good hexacopter PID controller or anything that I could work off of, I decided to make my own from scratch. I'll try to make this just one file so it is easy for beginners to use as well. Follow along
<file_sep>#include <Wire.h>
#include <Servo.h>
Servo left_prop;
Servo right_prop;
/*
This is mainly pseudo-code. I am mapping and putting everything in place before
actually using the needed values from the sensors, putting out the values to motors, and etc.
*/
double kP = 3.55, kI = 0.005, kD = 2.05; //all the constant
double desVal=0, error, prevError; //the value that you want(usually the input from RC), error/difference
double oP, oI, oD, total; //the outputs and final needed value
double difSum; //the sum of all differences (for integral control)
double angleInput; //the angle that you get from the gyroscope
double elapsedTime, time, prevTime;
double angleX, angleY;
long accelRaw_X, accelRaw_Y, accelRaw_Z;
float accel_X, accel_Y, accel_Z;
float pwmLeft, pwmRight;
double throttle = 1300;
long gyroRaw_X, gyroRaw_Y, gyroRaw_Z;
float gyro_X, gyro_Y, gyro_Z;
float accelAngleX, accelAngleY;
float rad_to_deg = 180/3.141592654;
void setup() {
//set stuff
Serial.begin(9600);
Wire.begin();
setupMPU();
time = millis(); //starts couting
left_prop.attach(3);
right_prop.attach(5);
left_prop.writeMicroseconds(1000);
right_prop.writeMicroseconds(1000);
delay(5000);
}
void loop() {
getAccelData();
accelAngleX = atan(accel_Y/sqrt(pow((accel_Y),2)+ pow((accel_Z),2)))*rad_to_deg;
accelAngleY = atan(-1*accel_X/sqrt(pow((accel_Y),2)+ pow((accel_Z),2)))*rad_to_deg;
//use accel data to calculate angle
getGyroData();
prevTime = time;
time = millis(); //counting
elapsedTime = (time - prevTime) / 1000;
//final angleX made with The Complementary Filter, using both angle datas
angleX = 0.98 *(angleX + gyro_X*elapsedTime)+ 0.02*accelAngleX;
error = desVal - angleX;
difSum += error;
oP = kP * error; //Proportional controller
//oI = oI + (kI * error); //Integral controller
if(-3<error<3) {
oI = oI+(kI*error);
}
oD = kD * ((error - prevError) / elapsedTime); //Derivative controller
//Serial.print(oP);
//Serial.println(oI);
//Serial.println(oD);
total = oP + oI + oD; //Final PID value
if (total<-1000) {
total=-1000;
}
if (total>1000) {
total=1000;
}
Serial.println(total);
pwmLeft = throttle + total;
pwmRight = throttle - total;
if (pwmRight<1000) {
pwmRight=1000;
}
if (pwmRight>2000) {
pwmRight=2000;
}
if (pwmLeft<1000) {
pwmLeft=1000;
}
if (pwmLeft>2000) {
pwmLeft=2000;
}
left_prop.writeMicroseconds(pwmLeft);
right_prop.writeMicroseconds(pwmRight);
//Serial.println(elapsedTime);
prevError = error;
//Serial.println(pwmLeft);
}
void setupMPU() {
Wire.beginTransmission(0b1101000); //the I2C address of the mpu6050
Wire.write(0x6B); //register 6B- Power Managment
Wire.write(0b00000000); //Set SLEEP(bit6)(2nd left) register to 0 so that it's not in "off" mode upon boot
//0b notifies that you are writing in bit mode
Wire.endTransmission();
Wire.beginTransmission(0b1101000); //I2C adress of the mpu
Wire.write(0x1B); //register 1B- Gyroscope
Wire.write(0b00000000); //set gyro to
Wire.endTransmission(); //set gyro to +/- 250*/sec mode
//the 3rd and 4th bits are the ones for setting the values
Wire.beginTransmission(0b1101000);
Wire.write(0x1C); //register 1C- Accelerometer
Wire. write(0b00000000); //set accel to +/- 2g mode
//the 3rd and 4th bits are the ones for setting the values
Wire.endTransmission();
}
void getAccelData() {
Wire.beginTransmission(0b1101000);
Wire.write(0x3B); //register for accel readings
Wire.endTransmission();
Wire.requestFrom(0b1101000,6);
while(Wire.available()<6);
accelRaw_X = Wire.read()<<8|Wire.read(); //first two bites
accelRaw_Y = Wire.read()<<8|Wire.read(); //middle two bites
accelRaw_Z = Wire.read()<<8|Wire.read(); //last two bites
accel_X = accelRaw_X / 16384.0;
accel_Y = accelRaw_Y / 16384.0;
accel_Z = accelRaw_Z / 16384.0; //raw to useful data. (in +/-2g mode, 1g=16384.0)
}
void getGyroData() {
Wire.beginTransmission(0b1101000);
Wire.write(0x43);
Wire.endTransmission();
Wire.requestFrom(0b1101000,6);
while(Wire.available()<6);
gyroRaw_X = Wire.read()<<8|Wire.read(); //first
gyroRaw_Y = Wire.read()<<8|Wire.read(); //middle
gyroRaw_Z = Wire.read()<<8|Wire.read(); //last two bites
gyro_X = gyroRaw_X / 131.0;
gyro_Y = gyroRaw_Y / 131.0;
gyro_Z = gyroRaw_Z / 131.0; //raw to useful data. (in +/-250*/sec mode, 1*/sec=131.0)
}
| 59388591fb2bd6289142bdb8d7287227bb57b59f | [
"Markdown",
"C++"
] | 3 | C++ | Runkli/Arduino-Hexacopter-Control | 925f61d87271bb2c4a1f21edad34247810e8ab2e | b1d89e0e7bd3f17fe1e7cb5ad3e7f3c91b196c21 |
refs/heads/main | <file_sep>import java.util.Scanner;
public class CRC {
public static void main(String args [])
{
Scanner scanner = new Scanner(System.in);
//Enter the message
System.out.print("Enter the message:");
String input = scanner.nextLine();
//Enter the generator
System.out.print("Enter the polynomial generator:");
String generator = scanner.nextLine();
//created int message variable as the size of input
int message[] = new int[input.length()+generator.length()-1];
//created int divisor as the size of the generator
int remainder[] = new int[generator.length()];
//the input bits copied to the message as int
for(int i=0; i<input.length(); i++) {
message[i] = Integer.parseInt(input.charAt(i)+"");
}
//the generator bits copied to the divisor as int
for(int i=0; i<generator.length(); i++) {
remainder[i] = Integer.parseInt(generator.charAt(i)+"");
}
//the input and divisor xor
for(int i=0; i<input.length(); i++)
{
if(message[i]==1) {
for(int j=0; j<remainder.length; j++)
message[i+j]^=remainder[j];
}
}
System.out.print("The CRC code is:");
for(int i=0; i<input.length(); i++)
message[i]=Integer.parseInt(input.charAt(i)+"");
for(int i= 0; i<message.length; i++)
System.out.print(message[i]);
System.out.println();
//the message with remainder
System.out.print("Enter the message you want to send:");
input = scanner.nextLine();
message = new int[input.length()+generator.length()-1];
remainder = new int[generator.length()];
for(int i=0; i<input.length(); i++)
message[i] = Integer.parseInt(input.charAt(i)+"");
for(int i=0; i<generator.length(); i++)
remainder[i] = Integer.parseInt(generator.charAt(i)+"");
//the message and generator xor
for(int i=0; i<input.length(); i++)
{
if(message[i]==1) {
for(int j=0; j<remainder.length; j++)
message[i+j]^=remainder[j];
}
}
boolean alter = true;
for(int i=0; i<message.length; i++) {
if(message[i]==1) {
alter= false;
break;
}
}
if(alter==true)
System.out.println("The message sent successfully. There is no error.");
else
System.out.print("The message has changed. There is an error in the message.");
}
}
| c2612cb4b1cf2c0fd7a83e2b6ec1a4d64862a37d | [
"Java"
] | 1 | Java | gul-cincik/CRC-Algorithm | 296a73e8b6db522b209b486e94688f98bb300b79 | 71f957b1ea47b1d90a50f9a29d16677fd2a0810c |
refs/heads/master | <repo_name>g33kcentric/site-check-list<file_sep>/index.php
<?php
require_once 'vendor/autoload.php';
use App\Commands\Check404;
use App\Commands\GenerateSitemap;
use App\Commands\GooglePageSpeed;
use App\Commands\LiveUrl;
use App\Commands\PrivacyPolicy;
use App\Commands\RunAll;
use App\Commands\HasSitemap;
use Symfony\Component\Console\Application;
$application = new Application();
$application->add(new LiveUrl());
$application->add(new PrivacyPolicy());
$application->add(new HasSitemap());
$application->add(new GooglePageSpeed());
$application->add(new GenerateSitemap());
$application->add(new Check404());
$application->add(new RunAll());
$application->run();<file_sep>/app/Commands/PrivacyPolicy.php
<?php
namespace App\Commands;
use App\Results;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
final class PrivacyPolicy extends Command
{
protected function configure()
{
$this
->setName('app:privacy-policy')
->setDescription('Checks to see if the site has a privacy policy.')
->addArgument('url', InputArgument::REQUIRED, 'The url of the site.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->write('3) Does the site have a privacy policy page? ');
if (@file_get_contents(sprintf('%s/privacy-policy', (string)$input->getArgument('url'))) or
@file_get_contents(sprintf('%s/privacypolicy', (string)$input->getArgument('url')))
) {
(new SymfonyStyle($input, $output))->success('There is a privacy policy present.');
} else {
(new SymfonyStyle($input, $output))->error('There is not a privacy policy present.');
}
}
}
<file_sep>/app/Crawlers/Broken.php
<?php
namespace App\Crawlers;
use Spatie\Crawler\CrawlObserver;
use Spatie\Crawler\Url;
final class Broken implements CrawlObserver
{
private $error = [];
private $file;
private $sitemap;
private $url;
private $output;
public function __construct($file, $sitemap, $url, $output)
{
$this->file = $file;
$this->sitemap = $sitemap;
$this->url = $url;
$this->output = $output;
}
/**
* Called when the crawler will crawl the url.
*
* @param \Spatie\Crawler\Url $url
*/
public function willCrawl(Url $url)
{
}
/**
* Called when the crawler has crawled the given url.
*
* @param \Spatie\Crawler\Url $url
* @param \Psr\Http\Message\ResponseInterface|null $response
*/
public function hasBeenCrawled(Url $url, $response)
{
$statusCode = $response ? $response->getStatusCode() : 404;
if (404 == $statusCode) {
$reason = $response ? $response->getReasonPhrase() : '';
$timestamp = date('Y-m-d H:i:s');
$this->output->error("[{$timestamp}] {$statusCode} {$reason} - {$url}");
$this->error[] = $url;
}
}
/**
* Called when the crawl has ended.
*/
public function finishedCrawling()
{
if (0 === count($this->error)) {
$this->output->success('There are no broken links!');
}
}
}
<file_sep>/app/Commands/RunAll.php
<?php
namespace App\Commands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
final class RunAll extends Command
{
private $commands = [
'url-live',
'has-sitemap',
'privacy-policy',
//'google-page-speed',
'broken-links'
];
protected function configure()
{
$this
->setName('app:run-all')
->setDescription('Run all commands.')
->addArgument('url', InputArgument::REQUIRED, 'The url of the site.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
(new SymfonyStyle($input, $output))->title('Welcome to the G33kcentric basic site checker.');
$arguments = [
'url' => $input->getArgument('url')
];
$input = new ArrayInput($arguments);
array_walk($this->commands, function ($command) use ($input, $output) {
$this->getApplication()->find(sprintf('app:%s', $command))->run($input, $output);
});
}
}
<file_sep>/app/Commands/GooglePageSpeed.php
<?php
namespace App\Commands;
use App\Results;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Yaml\Yaml;
final class GooglePageSpeed extends Command
{
protected function configure()
{
$this
->setName('app:google-page-speed')
->setDescription('Runs good page speed on the url.')
->addArgument('url', InputArgument::REQUIRED, 'The url of the site.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->write('4) Grabbing google page speed results. ');
$file = new Filesystem();
$results = file_get_contents(
sprintf(
'https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=%s&key=%s',
urlencode($input->getArgument('url')),
'<KEY>'
)
);
try {
$file->dumpFile(
__DIR__.'/../../data/page-speed-'.date('d-m-Y-H:i:s').'.yml',
Yaml::dump(json_decode($results, true))
);
$output->writeln('<info>✓</info>');
} catch (IOExceptionInterface $e) {
$output->writeln('<error>✕</error>');
(new ConsoleLogger($output))->log(sprintf('[%s] %s', date('d-m-Y H:i:s'), $e->getMessage()));
} catch (Exception $e) {
(new ConsoleLogger($output))->log(sprintf('[%s] %s', date('d-m-Y H:i:s'), $e->getMessage()));
}
}
}
<file_sep>/app/Crawlers/Sitemap.php
<?php
namespace App\Crawlers;
use Spatie\Crawler\CrawlObserver;
use Spatie\Crawler\Url;
final class Sitemap implements CrawlObserver
{
private $crawledUrls = [];
private $file;
private $sitemap;
private $url;
private $output;
public function __construct($file, $sitemap, $url, $output)
{
$this->file = $file;
$this->sitemap = $sitemap;
$this->url = $url;
$this->output = $output;
}
/**
* Called when the crawler will crawl the url.
*
* @param \Spatie\Crawler\Url $url
*/
public function willCrawl(Url $url)
{
}
/**
* Called when the crawler has crawled the given url.
*
* @param \Spatie\Crawler\Url $url
* @param \Psr\Http\Message\ResponseInterface|null $response
*/
public function hasBeenCrawled(Url $url, $response)
{
$this->crawledUrls[] = (string)$url;
}
/**
* Called when the crawl has ended.
*/
public function finishedCrawling()
{
$map = $this->sitemap;
array_walk($this->crawledUrls, function ($url) use ($map) {
$this->sitemap->add($url, date('Y-m-d'));
});
// @todo add all this stuff to a static class function
try {
$this->file->dumpFile(
__DIR__.'/../../data/sitemap.xml',
(string)$this->sitemap
);
$this->output->writeln('<info>✓</info>');
} catch (IOExceptionInterface $e) {
$this->output->writeln('<error>✕</error>');
(new ConsoleLogger($this->output))->log(sprintf('[%s] %s', date('d-m-Y H:i:s'), $e->getMessage()));
} catch (Exception $e) {
$this->output->writeln('<error>✕</error>');
(new ConsoleLogger($this->output))->log(sprintf('[%s] %s', date('d-m-Y H:i:s'), $e->getMessage()));
}
}
}
<file_sep>/app/Commands/LiveUrl.php
<?php
namespace App\Commands;
use App\Results;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
final class LiveUrl extends Command
{
protected function configure()
{
$this
->setName('app:url-live')
->setDescription('Checks to see if the URL is live.')
->addArgument('url', InputArgument::REQUIRED, 'The url of the site.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->write('1) Is URL Live? ');
if (@file_get_contents((string)$input->getArgument('url'))) {
(new SymfonyStyle($input, $output))->success('URL is live.');
} else {
(new SymfonyStyle($input, $output))->error('URL is not live.');
}
}
}
<file_sep>/README.md
# Site List Checker
A small console program to check some basic things before a new site launch.<file_sep>/app/Commands/Check404.php
<?php
namespace App\Commands;
use App\Crawlers\Broken;
use App\Results;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Filesystem;
use Spatie\Crawler\Crawler;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Tackk\Cartographer\Sitemap;
/**
* Class Sitemap
*
* @package App\Commands
* @category
* @author
*/
final class Check404 extends Command
{
protected function configure()
{
$this
->setName('app:broken-links')
->setDescription('Checks 404 links')
->addArgument('url', InputArgument::REQUIRED, 'The url of the site.');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @throws \Spatie\Crawler\Exceptions\InvalidBaseUrl
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('5) Checking broken links, this could take a while');
$file = new Filesystem();
$sitemap = new Sitemap();
$url = $input->getArgument('url');
$observer = new Broken($file, $sitemap, $url, new SymfonyStyle($input, $output));
Crawler::create()
->setCrawlObserver($observer)
->startCrawling($url);
}
}
<file_sep>/app/Commands/HasSitemap.php
<?php
namespace App\Commands;
use App\Results;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Class Sitemap
*
* @package App\Commands
* @category
* @author
*/
final class HasSitemap extends Command
{
protected function configure()
{
$this
->setName('app:has-sitemap')
->setDescription('Checks to see if the site has a sitemap.')
->addArgument('url', InputArgument::REQUIRED, 'The url of the site.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->write('2) Does the site have a sitemap? ');
if (@file_get_contents(sprintf('%s/sitemap.xml', (string)$input->getArgument('url')))) {
(new SymfonyStyle($input, $output))->success('There is a sitemap present.');
} else {
(new SymfonyStyle($input, $output))->error('There is no sitemap present.');
}
}
}
| b6a0525ba9e5ee586144571fe486dcc625345e0f | [
"Markdown",
"PHP"
] | 10 | PHP | g33kcentric/site-check-list | 5d26daa502cef4ec4c03744943c851740e0b896f | 0d4629d9e025653fdb90e8a41f5ec219bd29f1d0 |
refs/heads/main | <file_sep>#!/usr/bin/python3
import flask
import flask_login as fl
import argparse
from pages_standard import standardPages
from pages_api import pagesApi
from subpages_dashboard import subpagesDashboard
from pages_loginmanagement import pagesLoginManagement
import database as db
app = flask.Flask("OH-MY-Nemesis")
app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'
loginManager = fl.LoginManager()
@loginManager.user_loader
def load_user(userName):
'''Setup the user/login manager'''
return db.getUserByName(userName)
<EMAIL>('/static/<path:path>')
#def static(path):
# '''Configure sending of static files'''
# return flask.send_from_directory('static', path)
@app.before_first_request
def init():
'''Do nessesary initialization jobs'''
loginManager.init_app(app)
app.register_blueprint(standardPages)
app.register_blueprint(pagesApi)
app.register_blueprint(subpagesDashboard)
app.register_blueprint(pagesLoginManagement)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='None',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--interface', default="localhost",
help='Interface on which flask (this server) will take requests on')
parser.add_argument('--port', default="5000",
help='Port on which flask (this server) will take requests on')
args = parser.parse_args()
app.run(host=args.interface, port=args.port)
<file_sep>
import flask
import smtplib
import jsonConfig as jc
pagesApi = flask.Blueprint('simple_page', __name__, template_folder='templates')
@pagesApi.route("/contact-api", methods=['POST'])
def contactAPI():
email = flask.request.form["email"]
name = flask.request.form["name"]
subject = "Subject: {} ({})\n\n".format(flask.request.form["subject"], name)
message = subject + flask.request.form["message"]
smtpTarget = smtplib.SMTP(jc.mainConfig().smtp)
smtpTarget.sendmail(email, jc.mainConfig().target_email , message)
smtpTarget.quit()
return flask.redirect("/thanks")<file_sep>import jsonConfig as jc
import flask
import flask_login as fl
import database as db
import collections
import os
subpagesDashboard = flask.Blueprint('subpagesDashboard', __name__, template_folder='templates')
@subpagesDashboard.route("/dashboard/self-analysis")
@fl.login_required
def selfMatchHistory():
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("dashboardSubpages/self_analysis.html",
config=jc.mainConfig(),
currentUser=user,
champs=jc.champs())
@subpagesDashboard.route("/dashboard/self_matchups")
@fl.login_required
def selfMatchups():
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("dashboardSubpages/self_matchups.html",
config=jc.mainConfig(), currentUser=user, champs=jc.champs())
@subpagesDashboard.route("/dashboard/team-match-history")
@fl.login_required
def teamMatchHistory():
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("dashboardSubpages/subpage_team_history.html",
config=jc.mainConfig(), currentUser=user, champs=jc.champs())
@subpagesDashboard.route("/team_champselect", methods=['GET', 'POST'])
@fl.login_required
def teamChampSelect():
teamid = "example"
roles = collections.OrderedDict()
roles["Top"] = None
roles["Jungle"] = None
roles["Mid"] = None
roles["Bottom"] = None
roles["Support"] = None
if flask.request.method == "POST":
role = flask.request.args.get("role")
champ = flask.request.args.get("champ")
action = flask.request.args.get("action")
if action == "remove":
db.teamChampSelectRemove(teamid, champ, role)
elif action == "add":
db.teamChampSelectAdd(teamid, champ, role)
else:
flask.abort(500)
return ("", 204)
for key in roles:
path = "config/teams/{}/roles/{}.json".format(teamid, key)
if not os.path.isfile(path):
with open(path, "w") as f:
f.write('{ "champions": [] }')
roles[key] = jc.readJsonFile(path)
allChampions = jc.readJsonDir("config/champions")
return flask.render_template("team_champselect.html", roles=roles,
allChampions=allChampions, config=jc.readJsonFile("config/config.json"), currentUser=fl.current_user)
@subpagesDashboard.route("/team_composition_overview")
@fl.login_required
def teamCompositionOverview():
username = fl.current_user
user = jc.readJsonFile(os.path.join("data/users/", "{}.json".format(username)))
teamComps = jc.readJsonDir(os.path.join("config/teams/{}/compositions/".format("example")))
return flask.render_template("team_composition_overview.html", config=jc.readJsonFile("config/config.json"), currentUser=fl.current_user,
userInDatabase=user, teamComps=teamComps)
@subpagesDashboard.route("/team_composition_single")
@fl.login_required
def teamCompositionSingle():
roles = collections.OrderedDict()
roles["Top"] = None
roles["Jungle"] = None
roles["Mid"] = None
roles["Bottom"] = None
roles["Support"] = None
allChampions = jc.readJsonDir("config/champions")
return flask.render_template("team_composition_single.html", roles=roles,
teamChamps=allChampions,
config=jc.readJsonFile("config/config.json"),
currentUser=fl.current_user)
<file_sep>import flask_login as fl
import jsonConfig as jc
class User(fl.UserMixin):
def __init__(self, name):
self.id = name
self.name = "user" + str(id)
self.password = <PASSWORD>"
self.single = True
self.accounts = ["Sheppy", "TheArmCommander"]
self.selectedChampions = ["Lulu", "Aatrox", "Brand"]
self.matchhistoryEntries = []
def __repr__(self):
return self.id
def __str__(self):
return str(self.id)
def allowedFeatures(self):
'''Dynamicly return the features this user is allowed to use'''
allFeatures = jc.readJsonDir("config/tables/")
allowedFeatures = []
if not allowedFeatures:
allowedFeatures = allFeatures
else:
allowedFeatures = filter(lambda x: x["title"] in allowedFeatures,
allFeatures)
return sorted(allowedFeatures, key=lambda x: x["title"])
<file_sep>class Composition:
def __init__(self, name):
self.goodAgainst = []
self.badAgainst = []
self.name = name
def isGoodAgainst(self, compositions):
self.goodAgainst = compositions
def isBadAgainst(self, compositions):
self.badAgainst = Composition
def __eq__(self, other):
return self.name == other.name
ATTACK = Composition("ATTACK")
PROTECT = Composition("PROTECT")
CATCH = Composition("CATCH")
SIEGE = Composition("SIEGE")
SPLIT = Composition("SPLIT")
ATTACK.isGoodAgainst([SPLIT, SIEGE])
PROTECT.isGoodAgainst([CATCH, ATTACK])
CATCH.isGoodAgainst([ATTACK, SPLIT])
SIEGE.isGoodAgainst([PROTECT, CATCH])
SPLIT.isGoodAgainst([SIEGE, PROTECT])
ATTACK.isBadAgainst([CATCH, PROTECT])
PROTECT.isBadAgainst([SPLIT, SIEGE])
CATCH.isBadAgainst([SIEGE, PROTECT])
SIEGE.isBadAgainst([ATTACK, SPLIT])
SPLIT.isBadAgainst([CATCH, ATTACK])<file_sep>
import flask
import flask_login as fl
import database as db
import jsonConfig as jc
pagesLoginManagement = flask.Blueprint('pagesLoginManagement', __name__, template_folder='templates')
@pagesLoginManagement.route("/login", methods=['GET', 'POST'])
def login():
if flask.request.method == 'POST':
username = flask.request.form['username']
password = flask.request.form['password']
print(username, password)
acceptedUser = db.safeCheckLogin(username, password)
if acceptedUser:
fl.login_user(acceptedUser)
return flask.redirect(flask.url_for("standardPages.dashboard"))
else:
return flask.abort(401)
else:
return flask.render_template("standard/login.html",
config=jc.mainConfig())
@pagesLoginManagement.route("/logout")
@fl.login_required
def logout():
fl.logout_user()
return flask.redirect("/")
<file_sep># Setup
## Python
pip install -r req.txt
## CSS/JS/Assets
Download the following into the `static/` directory.
- [bootstrap>=4.3](https://getbootstrap.com/docs/4.3/getting-started/download/)
- [fontawesome-free](https://fontawesome.com) (unpacked directory must be called `fontawesome`)
## Directories
mkdir -p data/users/
## User-Schema
{
name : "name of user",
accounts : [ "list", "of", "account", "names" ],
single : "true/false, depending if user has team",
selectedChampions: ["list of champions", "this user can play"]
allowedFeatures: ["list of allowed features", "or empty list to allow all"]
}
<file_sep>import json
import os
import usermanagement
import flask_login as fl
userDb = {
"sheppy" : { "password" : "" }
}
DEAULT_DIR = "data/"
def saveTable(tableId, jsonData):
with open(DEAULT_DIR + tableId + ".json" , "w") as f:
print(jsonData)
f.write(json.dumps(jsonData))
def loadTable(tableId):
with open(DEAULT_DIR + tableId + ".json") as f:
return json.loads(f.read())
def teamChampSelectAdd(teamid, champ, role):
path = "config/teams/{}/roles/{}.json".format(teamid, role)
if not os.path.isfile(path):
with open(path, "w") as f:
f.write('{ "champions": [%s]] }' % champ)
else:
data = None
with open(path, "r") as f:
data = json.loads(f.read())
if champ not in data["champions"]:
data["champions"] += [champ]
with open(path, "w") as f:
f.write(json.dumps(data))
def teamChampSelectRemove(teamid, champ, role):
path = "config/teams/{}/roles/{}.json".format(teamid, role)
if not os.path.isfile(path):
raise ValueError("No information about this role exists, so nothing can be removed.")
else:
data = None
with open(path, "r") as f:
data = json.loads(f.read())
data["champions"].remove(champ)
with open(path, "w") as f:
f.write(json.dumps(data))
def getUserByFlaskLoginId(flId):
if not flId.is_active:
return None
return usermanagement.User(flId)
def safeCheckLogin(username, password):
return usermanagement.User(username)
def getUserByName(name):
return usermanagement.User(name)
<file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Leauge of Legends Coaching">
<title>Nemesis Coaching</title>
<!-- Bootstrap core CSS -->
{% include 'partials/header.html' %}
</head>
<body>
{% include 'partials/navbar.html' %}
<div class="jumbotron text-center">
<h1 class="display-3">Thank You!</h1>
<p class="lead"><strong>Your contact request has been send!</strong> We will answer you as soon as possible.</p>
<hr>
<p>
Still having trouble? <a href="/contact">Contact us</a>
</p>
<p class="lead">
<a class="btn btn-primary btn-sm" href="/" role="button">Return to Homepage</a>
</p>
</div>
{% include 'partials/footer.html' %}
</body>
</html><file_sep>import re
import os
import json
import types
def readJsonFile(filename):
'''Return a single json file as a dictionary object'''
with open(filename) as f:
return json.load(f)
def readJsonDir(basedir):
'''Return an array of dictionary objects in a directory'''
# important safety check #
udata = basedir.encode("utf-8")
asciidata = udata.decode("ascii", "ignore")
if re.match(r'^[\w-]+$', asciidata) or basedir != asciidata:
raise RuntimeError("Unsafe path")
# load json files from projects/ dir #
jsonDictList = []
for root, dirs, files in os.walk(basedir):
root = dirs
dirs = root
for filename in files:
if filename.endswith(".json"):
jsonDictList += [readJsonFile(os.path.join(basedir, filename))]
return jsonDictList
def priceSection(section):
'''Get a prices sections by it's identifier'''
prices = readJsonDir(os.path.join("config/prices/", section))
allFeatures = []
for p in prices:
allFeatures += p["features"]
for p in prices:
p["disabledFeatures"] = set(allFeatures) - set(p["features"])
return prices
def pricesSections():
return [ priceSection("section-1"), priceSection("section-2")]
def mainConfig():
'''Get main configuration'''
ret = types.SimpleNamespace()
ret.__dict__.update(readJsonFile("config/config.json"))
return ret
def services():
'''Get Services configuration'''
return readJsonDir("config/services/")
def getOfferById(strId):
'''Get an offer in prices sections by it's id'''
d1 = readJsonDir("config/prices/section-1")
d2 = readJsonDir("config/prices/section-1")
for el in d1 + d2:
if el.get(strId):
return el
return None
def champs():
'''Read champ directory and return a list of champions'''
return [ x["name"] for x in readJsonDir("config/champions/")]
<file_sep>import flask
class CellContainer:
def __init__(self, tableConfig):
self.columns = tableConfig.get("columns")
self.rows = tableConfig["rows"]
self.headerRow = tableConfig["header-row"]
if not self.columns:
self.columns = len(self.headerRow)
self.headerColumn = tableConfig["header-column"]
self.currentCellId = 0
self.contents = tableConfig.get("contents")
self.colors = tableConfig.get("colors")
self.help = tableConfig.get("help")
self.hasHeaderColumn = bool(tableConfig.get("hasHeaderColumn"))
self.hasHeaderRow = bool(tableConfig.get("hasHeaderRow"))
def setContents(self, contents):
self.contents = contents
def getView(self):
innerHTML = ""
startAtRow = 0
if self.headerRow or self.hasHeaderRow:
innerHTML += flask.Markup(flask.render_template("entities/row.html", cells=self.getHeaderRow()))
startAtRow = 1
for rowNr in range(startAtRow, self.rows):
innerHTML += flask.Markup(flask.render_template("entities/row.html", cells=self.getRowHTML(rowNr)))
return flask.Markup(flask.render_template("entities/table.html", tableContent=innerHTML))
def getHeaderRow(self):
rowHTML = ""
array = None
if self.contents:
array = self.contents[:self.columns]
else:
array = self.headerRow
for rowStr in array:
rowHTML += flask.Markup(flask.render_template("entities/cell.html",
cellId=self.currentCellId, classes="cell header", cellContent=rowStr))
self.currentCellId += 1
return rowHTML
def getCellWidth(self):
return "{:.2f}%".format(100/self.columns)
def getRowHTML(self, curRow):
'''Get HTML for individual rows'''
rowHTML = ""
for col in range(0, self.columns):
# handle header fields in rows #
classes = ["cell"]
cellContent = ""
cellColor = ""
if self.headerColumn and col == 0:
classes += ["header"]
cellContent = self.headerColumn[curRow]
elif self.hasHeaderColumn and col == 0:
classes += ["header"]
if self.contents:
cellContent = self.contents[curRow*self.columns+col]
if self.colors:
cellColor = self.colors[curRow*self.columns+col]
# add single cell #
rowHTML += flask.Markup(flask.render_template("entities/cell.html", cellId=self.currentCellId, cellContent=cellContent, classes=" ".join(classes), enableEdit=True, cellColor=cellColor))
self.currentCellId += 1
# return HTML for row #
return rowHTML
<file_sep>import database as db
import jsonConfig as jc
import flask
import flask_login as fl
import os
standardPages = flask.Blueprint('standardPages', __name__, template_folder='templates')
@standardPages.route('/')
def index():
'''Landing page/index page/root page'''
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("standard/index.html",
services=jc.services(),
pricesSections=jc.pricesSections(),
config=jc.mainConfig(),
currentUser=user)
@standardPages.route("/dashboard")
@fl.login_required
def dashboard():
'''Logged in user dashboard'''
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("standard/user_dashboard.html",
config=jc.mainConfig(),
currentUser=user)
@standardPages.route("/shop")
def shop():
'''Shop to buy shit'''
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("standard/shop.html",
config=jc.mainConfig(),
currentUser=user)
@standardPages.route("/about")
def about():
'''About Page'''
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("standard/about.html",
config=jc.mainConfig(),
currentUser=user)
@standardPages.route("/impressum")
def impressum():
'''About Page'''
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("standard/impressum.html",
config=jc.mainConfig(),
currentUser=user)
@standardPages.route("/contact")
def contact():
'''Contact Page'''
offer = jc.getOfferById(flask.request.args.get("offerId"))
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("standard/contact.html",
conf=jc.mainConfig(),
currentUser=user, selectedOffer=offer)
@standardPages.route("/thanks")
def thanks():
'''Post Contact thanks page'''
user = db.getUserByFlaskLoginId(fl.current_user)
return flask.render_template("standard/thanks.html", config=jc.mainConfig(),
currentUser=user)
| f697473de486346dd5a15fec87505a907ba1fa6f | [
"Markdown",
"Python",
"HTML"
] | 12 | Python | FAUSheppy/oh-my-nemesis | ac930185574bc64c02b2333be5cb13f4001cb1f6 | d9c5c975d186598ed5ac49b0efaaf43b5a7fba4f |
refs/heads/master | <repo_name>jonunezg/advent-of-code-2020<file_sep>/src/day_05/missing_seats.py
import sys
import os
def get_dec(pattern, encoded_1):
n = 0
for c in pattern:
n = (n << 1) | (1 if c == encoded_1 else 0)
return n
def get_id(line):
return get_dec(line[:7], 'B') * 8 + get_dec(line[7:], 'R')
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Get the only available seat, must be between two used seats')
occupied = [False] * 128 * 8
for seat in [get_id(a.strip('\n')) for a in f.readlines()]:
occupied[seat] = True
for i in range(1, len(occupied) - 1):
if occupied[i - 1] and occupied[i + 1] and not occupied[i]:
print('Seat: {0}, row: {1}, col: {2}'.format(i, i // 8, i % 8))
<file_sep>/src/day_06/answer_sum.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Count the number of unique responses on each group')
groups = []
answers = {}
for line in [a.strip('\n') for a in f.readlines()]:
if len(line) == 0:
groups.append(answers)
answers = {}
else:
for c in line:
answers[c] = True
print('Sum of group sizes: {0}'.format(sum([len(entry) for entry in groups])))
<file_sep>/src/day_01/sum2020.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print("Find 2 numbers (a, b) that sum 2020, get its product, a * b")
seen = {}
target = 2020
for line in f.readlines():
n = int(line)
if target - n in seen:
print('{0} * {1} = {2}'.format(n, target - n, n * (target - n)))
seen[n] = 1<file_sep>/src/day_22/play_game.py
from os import path
with open(path.dirname(__file__) + '/input.txt') as f:
print('Play the game and print the winning score')
d1, d2 = [[int(a) for a in cards.strip().split('\n')[1:]] for cards in f.read().split('\n\n')]
while len(d1) and len(d2):
top1, top2 = d1[0], d2[0]
d1, d2 = d1[1:], d2[1:]
if top1 >= top2:
d1.append(top1)
d1.append(top2)
else:
d2.append(top2)
d2.append(top1)
winner = d1 if d1 else d2
print(sum([(i + 1) * x for i, x, in enumerate(winner[::-1])]))
<file_sep>/src/day_13/first_bus.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Get the ID of the first bus you can take times the minutes that you will have to wait')
lines = f.readlines()
arrive_time = int(lines[0])
current, id = 999999999, 0
for bus in [int(bus) for bus in lines[1].strip('\n').split(',') if bus != 'x']:
time_to_wait = bus - arrive_time % bus
time_to_wait = 0 if time_to_wait == bus else time_to_wait
if current > time_to_wait:
current, id = time_to_wait, bus
print("Bus {0}, wait {1} minutes, result: {2}".format(id, current, id * current))<file_sep>/README.md
# advent-of-code-2020
Some coding challenges from Advent of code 2020 calendar, made in python so far.
<file_sep>/src/day_23/crab_game_large.py
from os import path
def next(candidate, exclusions, max_value):
while candidate in exclusions:
candidate = candidate - 1 if candidate > 1 else max_value
return candidate
def play(s, cur):
next_3 = [s[cur], s[s[cur]], s[s[s[cur]]]] # Get 3 elements to move
s[cur] = s[next_3[2]] # Move them out of the list
i = next(cur, next_3 + [cur], len(s) - 1) # Find the destination
s[i], s[next_3[2]] = next_3[0], s[i] # Move 3 elements to destination
return s[cur] # Return right neighbor of current value
with open(path.dirname(__file__) + '/input.txt') as f:
print('Play the game and print the product of the two numbers to the right of 1')
sequence = [max(10, i + 1) for i in range(1000001)]
input = f.read().strip('\n')
for i, c in enumerate(input[:-1]):
sequence[int(c)] = int(input[i + 1])
sequence[-1] = int(input[0])
current = int(input[0])
for i in range(10000000):
current = play(sequence, current)
print(sequence[1] * sequence[sequence[1]])<file_sep>/src/day_10/number_of_combinations.py
import sys
import os
def count_combinations(mem, n, adapters):
if n not in mem:
mem[n] = sum([count_combinations(mem, i, adapters) for i in range(n + 1, n + 4) if i in adapters])
return mem[n]
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Number of combinations in which the adapters can be used from 0 to the largest adapter (adapter can be chained with another 1, 2 or 3 numbers lower)')
numbers = [0] + [int(line) for line in f.readlines()]
print('Result: {0}'.format(count_combinations({max(numbers) : 1}, 0, numbers)))<file_sep>/src/day_14/address_mask.py
import sys
import os
def gen_combinations(base, rest, addresses):
if rest == '':
addresses.append(base)
else:
if rest[0] == 'X':
gen_combinations(base + '0', rest[1:], addresses)
gen_combinations(base + '1', rest[1:], addresses)
else:
gen_combinations(base + rest[0], rest[1:], addresses)
def address_to_int(address_string):
address = 0
for c in address_string:
address = (address << 1) + (1 if c == '1' else 0)
return address
def get_addresses(base, mask):
onebit = 1 << 35
res = ''
for c in mask:
res = res + (('1' if base & onebit != 0 else '0') if c == '0' else ('1' if c == '1' else 'X'))
onebit >>= 1
addresses = []
gen_combinations('', res, addresses)
for m in addresses:
yield address_to_int(m)
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Sum values on memory left behind after applying asignment with masks')
instructions = [line.replace('mask = ', '').replace('mem[', '').replace('] = ', ',').strip('\n').split(',') for line in f.readlines()]
mask = ''
mem = {}
for ins in instructions:
if len(ins) == 1:
mask = ins[0]
else:
base_address, value = int(ins[0]), int(ins[1])
for address in get_addresses(base_address, mask):
mem[address] = value
print('Sum: {0}'.format(sum([value for value in mem.values()])))<file_sep>/src/day_16/ticket_fields.py
import sys
import os
categories_zone = 0
ticket_zone = 1
nearby_zone = 2
def in_range(n, r):
return n >= r[0] and n <= r[1]
def is_n_invalid(n, ranges):
return True if len([True for r in ranges if in_range(n, r)]) == 0 else False
def is_ticket_valid(ticket, ranges):
return len([True for n in ticket if is_n_invalid(n, ranges)]) == 0
lines = []
with open(os.path.dirname(__file__) + '/input.txt') as f:
lines = f.readlines()
print('Fit each category to its column according to the valid ranges, and')
print('multiply the value of all categories that start with "departure" in your ticket')
zone = categories_zone
categories = {}
all_ranges = []
tickets = []
valid_counts = {}
my_ticket = []
for line in lines:
line = line.strip('\n')
if line == '':
continue
if line in ('your ticket:', 'nearby tickets:'):
zone += 1
continue
if zone == categories_zone:
category, ranges = line.split(': ')
ranges = [[int(a) for a in pair.split('-')] for pair in ranges.split(' or ')]
categories[category] = ranges
all_ranges += ranges
else:
ticket = [int(v) for v in line.split(',')]
if zone == ticket_zone:
my_ticket = ticket
elif zone == nearby_zone:
if is_ticket_valid(ticket, all_ranges):
tickets.append(ticket)
for ticket in tickets:
for col, n in enumerate(ticket):
for k in categories:
if not is_n_invalid(n, categories[k]):
# For each ticket, count if current column is valid on each category
valid_counts[(k, col)] = valid_counts.get((k, col), 0) + 1
found = {}
while len(found) < len(my_ticket):
# Find one category which can only fit in only one column
for category in categories:
counts = [valid_counts.get((category, col), 0) for col in range(len(my_ticket))]
if counts.count(len(tickets)) == 1:
# Choose this category
index = counts.index(len(tickets))
found[category] = index
for k in categories:
# Discard all categories that might fit in this column
valid_counts[(k, index)] = valid_counts.get((k, index), 0) - 1
break
result = 1
for k, value in found.items():
if k.startswith('departure'):
result *= my_ticket[value]
print(result)
<file_sep>/src/day_09/continues_range_to_sum.py
import sys
import os
def two_sum(target, numbers):
seen = {}
for n in numbers.keys():
if target - n in seen and n != target - n:
return True
seen[n] = 1
return False
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Add the min and max numbers of a continous range in the list that adds to the first invalid number')
numbers = [int(line) for line in f.readlines()]
preamble = {}
window = 25
invalid = 0
for elem in numbers[:window]:
preamble[elem] = preamble.get(elem, 0) + 1
for i, elem in enumerate(numbers[window:]):
if not two_sum(elem, preamble):
print('Number: {0}'.format(elem))
invalid = elem
break
preamble[numbers[i]] -= 1
if preamble[numbers[i]] == 0:
preamble.pop(numbers[i])
preamble[elem] = preamble.get(elem, 0) + 1
i = j = current = 0
while True:
if current < invalid:
current += numbers[j]
j += 1
elif current > invalid:
current -= numbers[i]
i += 1
else:
break
print('Sum: {0}'.format(min(numbers[i:j]) + max(numbers[i:j])))<file_sep>/src/day_18/calc.py
from os import path
def insert(q, n):
if not q or q[-1] == '(':
q.append(n)
else:
op = q.pop()
m = q.pop()
q.append(n + m if op == '+' else n * m)
def evaluate(tokens):
q = []
for token in tokens:
if token in ('+', '*', '('):
q.append(token)
elif token == ')':
n = q.pop()
q.pop()
insert(q, n)
else:
insert(q, int(token))
return sum(q)
with open(path.dirname(__file__) + '/input.txt') as f:
print('Print sum of evaluating expressions, + and * have the same precedence, evaluate left to right')
result = 0
for line in f.readlines():
tokens = line.strip('\n').replace('(', '( ').replace(')', ' )').split(' ')
result += evaluate(tokens)
print(result)<file_sep>/src/day_14/memory_mask.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Sum values on memory left behind after applying asignment with masks')
instructions = [line.replace('mask = ', '').replace('mem[', '').replace('] = ', ',').strip('\n').split(',') for line in f.readlines()]
onemask, zeromask, mem = 0, 1, {}
for ins in instructions:
if len(ins) == 1:
onemask, zeromask = 0, 1
for c in ins[0]:
onemask <<= 1
zeromask <<= 1
onemask |= 1 if c == '1' else 0
zeromask |= 0 if c == '0' else 1
else:
address, value = int(ins[0]), int(ins[1])
if (1 << 36) - 1 < (value | onemask) & zeromask:
print('Error', (value | onemask) & zeromask, ins, value, onemask, zeromask)
break
mem[address] = (value | onemask) & zeromask
print('Sum: {0}'.format(sum([v for v in mem.values()])))<file_sep>/src/day_17/game_of_life_3d.py
import sys
import os
def gen_neighbours(coords):
x, y, z = coords
for i in range(27):
if i != 13:
yield (x + i // 9 % 3 - 1, y + i // 3 % 3 - 1, z + i % 3 - 1)
def count_active_neighbours(coords, active):
return sum([1 for neighbour in gen_neighbours(coords) if neighbour in active])
print('Do 6 iterations of game of life, Activate if 3 neighbours are active, do not deactivate if 2 or 3 neighbours are active')
active = {}
with open(os.path.dirname(__file__) + '/input.txt') as f:
for y, line in enumerate([line.strip('\n') for line in f.readlines()]):
for x, c in enumerate(line):
if c == '#':
active[(x, y, 0)] = True
for _ in range(6):
next_gen = {}
for cube in active:
if count_active_neighbours(cube, active) in(2, 3):
next_gen[cube] = True
processed = {}
for neighbour in gen_neighbours(cube):
if neighbour not in processed and neighbour not in active:
if count_active_neighbours(neighbour, active) == 3:
next_gen[neighbour] = True
processed[neighbour] = True
active = next_gen
print(len(active))<file_sep>/src/day_12/waypoint.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Get the Manhattan distance traveled')
pos = (0, 0)
waypoint = (10, 1)
for k, value in [(line[0], int(line.strip('\n')[1:])) for line in f.readlines()]:
if k in ('L', 'R'):
rotation = value % 360
if k == 'L':
rotation = 360 - rotation
for _ in range(rotation // 90):
waypoint = (waypoint[1], -waypoint[0])
if k == 'F':
pos = (pos[0] + value * waypoint[0], pos[1] + value * waypoint[1])
if k in ('N', 'S', 'W', 'E'):
waypoint = (waypoint[0] + value * (1 if k == 'E' else (-1 if k == 'W' else 0)), waypoint[1] + value * (1 if k == 'N' else (-1 if k == 'S' else 0)))
print(k, value, pos, waypoint)
print('Result: {0}'.format(sum([abs(a) for a in pos])))<file_sep>/src/day_04/strict_validate.py
import sys
import os
import string
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Validate passports have 7 mandatory fields')
lines = f.readlines()
current = {}
documents = []
for line in lines:
line = line.strip('\n')
if len(line) == 0:
documents.append(current)
current = {}
else:
for key, value in [entry.split(':') for entry in line.split(' ')]:
current[key] = value
# byr (Birth Year) - four digits; at least 1920 and at most 2002.
# iyr (Issue Year) - four digits; at least 2010 and at most 2020.
# eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
# hgt (Height) - a number followed by either cm or in:
# If cm, the number must be at least 150 and at most 193.
# If in, the number must be at least 59 and at most 76.
# hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
# ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
# pid (Passport ID) - a nine-digit number, including leading zeroes.
# cid (Country ID) - ignored, missing or not
expected = {'byr':0, 'iyr':0, 'eyr':0, 'hgt':0, 'hcl':0, 'ecl':0, 'pid':0}
valid = 0
for document in documents:
present = 0
for key, value in document.items():
if (key == 'byr' and len(value) == 4 and value.isnumeric() and int(value) >= 1920 and int(value) <= 2002) or \
(key == 'iyr' and len(value) == 4 and value.isnumeric() and int(value) >= 2010 and int(value) <= 2020) or \
(key == 'eyr' and len(value) == 4 and value.isnumeric() and int(value) >= 2020 and int(value) <= 2030) or \
(key == 'hgt' and ((len(value) == 5 and value[:3].isnumeric() and int(value[:3]) >= 150 and int(value[:3]) <= 193 and value[3:] == "cm") or (len(value) == 4 and value[:2].isnumeric() and int(value[:2]) >= 59 and int(value[:2]) <= 76 and value[2:] == "in"))) or \
(key == 'hcl' and len(value) == 7 and value[0] == '#' and all(c in string.hexdigits for c in value[1:])) or \
(key == 'ecl' and value in ('amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth')) or \
(key == 'pid' and len(value) == 9 and value.isnumeric()):
present += 1
valid += 1 if present == 7 else 0
print('Valid: {0}'.format(valid))<file_sep>/src/day_25/encryption_key.py
from os import path
def update(n, subject):
return (n * subject) % 20201227
with open(path.dirname(__file__) + '/input.txt') as f:
print('Get the encryption_key')
n, encryption_key, public_keys = 1, 1, [int(line.strip('\n')) for line in f.readlines()]
while n != public_keys[0]:
n, encryption_key = update(n, 7), update(encryption_key, public_keys[1])
print(encryption_key)<file_sep>/src/day_09/first_non_valid_number.py
import sys
import os
def two_sum(target, numbers):
seen = {}
for n in numbers.keys():
if target - n in seen and n != target - n:
return True
seen[n] = 1
return False
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Find the first number which is not the sum of two of the previous 25 numbers')
numbers = [int(line) for line in f.readlines()]
preamble = {}
window = 25
for elem in numbers[:window]:
preamble[elem] = preamble.get(elem, 0) + 1
for i, elem in enumerate(numbers[window:]):
if not two_sum(elem, preamble):
print('Number: {0}'.format(elem))
break
preamble[numbers[i]] -= 1
if preamble[numbers[i]] == 0:
preamble.pop(numbers[i])
preamble[elem] = preamble.get(elem, 0) + 1<file_sep>/src/day_23/crab_game.py
from os import path
def play(sequence):
current, next_3, rest = sequence[0], sequence[1:4], sequence[4:]
for i in range(1, 9):
cup = int(current) - i
cup += 9 if cup < 1 else 0
cup = rest.find(str(cup))
if cup != -1:
return rest[:cup + 1] + next_3 + (rest[cup + 1:] if cup + 1 < len(rest) else '') + current
with open(path.dirname(__file__) + '/input.txt') as f:
print('Play the game and print the sequence')
sequence = f.read().strip('\n')
for i in range(100):
sequence = play(sequence)
i = sequence.find('1')
print((sequence[i + 1:] if i + i < len(sequence) else '') + sequence[:i])
<file_sep>/src/day_08/correct_infinite_loop.py
import sys
import os
def run_program(program):
acc = pc = 0
executed = {}
while True:
if pc in executed or pc == len(program):
return (acc, True if pc in executed else False) # Loop or EOF
executed[pc] = True
mnemonic, value = program[pc]
acc += value if mnemonic == 'acc' else 0
pc += value if mnemonic == 'jmp' else 1
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Change just 1 jmp to nop or nop to jmp until program reaches end and print Acc')
program = [(line.split(' ')[0], int(line.split(' ')[1])) for line in f.readlines()]
for i in range(len(program)):
mnemonic, value = program[i]
if mnemonic == 'jmp' or mnemonic == 'nop':
old, program[i] = program[i], ('nop' if mnemonic == 'jmp' else 'jmp', value)
acc, loop = run_program(program)
if not loop:
print('Acc: {0}'.format(acc))
break
program[i] = old # Restore program<file_sep>/src/day_05/ticket_ids.py
import sys
import os
def get_dec(pattern, encoded_1):
n = 0
for c in pattern:
n = (n << 1) | (1 if c == encoded_1 else 0)
return n
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Get boarding pass Id, row * 8 + column, which are encoded using binary')
lines = f.readlines()
max_id = 0
for line in lines:
line = line.strip('\n')
row = get_dec(line[:7], 'B')
col = get_dec(line[7:], 'R')
max_id = max(max_id, row * 8 + col)
print('Max id: {0}'.format(max_id))
<file_sep>/src/day_15/numbers_spoken.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Print the 2020th and 30000000th numbers spoken, next number is 0 if the last number has never been spoken or the difference in turns from when it was last spoken')
initial, seen, turn = [int(e) for e in f.readline().split(',')], {}, 1
for n in initial[:len(initial) - 1]:
seen[n], turn = turn, turn + 1
cur = initial[-1]
while turn < 30000000:
seen[cur], turn, cur = turn, turn + 1, 0 if cur not in seen else turn - seen[cur]
if turn in (2020, 30000000):
print('Turn: {0}, number: {1}'.format(turn, cur))<file_sep>/src/day_04/validate_passports.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Validate passports have 7 mandatory fields')
lines = f.readlines()
current = {}
documents = []
for line in lines:
line = line.strip('\n')
if len(line) == 0:
documents.append(current)
current = {}
else:
for key, value in [entry.split(':') for entry in line.split(' ')]:
current[key] = value
expected = {'byr':0, 'iyr':0, 'eyr':0, 'hgt':0, 'hcl':0, 'ecl':0, 'pid':0}
valid = 0
for document in documents:
present = 0
for key in document:
present += 1 if key in expected else 0
valid += 1 if present == 7 else 0
print('Valid: {0}'.format(valid))
<file_sep>/src/day_06/answer2_sum.py
import sys
import os
def common_responses(group):
return sum([1 for answer_count in group.values() if answer_count == group['members']]) - 1
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Count the number of common responses on each group')
groups = []
answers = {}
for line in [a.strip('\n') for a in f.readlines()]:
if len(line) == 0:
groups.append(answers)
answers = {}
else:
answers['members'] = answers.get('members', 0) + 1
for c in line:
answers[c] = answers.get(c, 0) + 1
print('Sum of group sizes: {0}'.format(sum([common_responses(entry) for entry in groups])))
<file_sep>/src/day_12/navigation.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Get the Manhattan distance traveled')
pos = (0, 0)
heading = 90
for k, value in [(line[0], int(line.strip('\n')[1:])) for line in f.readlines()]:
if k in ('L', 'R'):
heading += value * (1 if k == 'R' else -1)
heading += 360 * (abs(heading) // 360 + 1)
heading %= 360
if k == 'F':
pos = (pos[0] + value * (1 if heading == 90 else (-1 if heading == 270 else 0)), pos[1] + value * (1 if heading == 0 else (-1 if heading == 180 else 0)))
if k in ('N', 'S', 'W', 'E'):
pos = (pos[0] + value * (1 if k == 'E' else (-1 if k == 'W' else 0)), pos[1] + value * (1 if k == 'N' else (-1 if k == 'S' else 0)))
print(k, value, pos, heading)
print('Result: {0}'.format(sum([abs(a) for a in pos])))<file_sep>/src/day_02/second_validation.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print("Validate passwords and print the number of valid passwords")
valid = 0
for line in f.readlines():
r, l, p = line.replace(':', '').split() # 1-3 f: eafeaw
r = [int(a) for a in r.split('-')] # r l p
# Exactly one of the positions (1 indexed) in 'p' marked by 'r' should be equal to 'l'
if sum([1 for pos in r if pos - 1 < len(p) and p[pos - 1] == l]) == 1:
valid += 1
print(r, l, p, valid)<file_sep>/src/day_10/differences.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Number of 1 jolt diffrences times number of 3 jolt differences')
numbers = [int(line) for line in f.readlines()]
numbers = [0] + numbers + [max(numbers) + 3]
numbers.sort()
differences = [numbers[i] - numbers[i - 1] for i in range(1, len(numbers))]
print('Result: {0}'.format(differences.count(1) * differences.count(3)))<file_sep>/src/day_01/3sum2020.py
import sys
import os
def two_sum(target, numbers):
seen = {}
for n in numbers:
if target - n in seen:
return (target - n, n)
seen[n] = 1
return None
with open(os.path.dirname(__file__) + '/input.txt') as f:
print("Find 3 numbers (a, b, c) that sum 2020, get its product, a * b * c")
target = 2020
numbers = []
for line in f.readlines():
numbers.append(int(line))
for i, n in enumerate(numbers):
if i + 1 > len(numbers) - 2: # Avoid invalid index
break
result = two_sum(target - n, numbers[i + 1:])
if result is not None:
print('{0} * {1} * {2} = {3}'.format(n, result[0], result[1], n * result[0] * result[1]))<file_sep>/src/day_16/invalid_values.py
import sys
import os
fields_zone = 0
ticket_zone = 1
nearby_zone = 2
def in_range(n, r):
#print(n,r,n >= r[0] and n <= r[1])
return n >= r[0] and n <= r[1]
def is_invalid(n, ranges):
return True if len([True for r in ranges if in_range(n, r)]) == 0 else False
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('From nearby tickets, add those values which do not match any of the valid ranges')
lines = f.readlines()
zone = fields_zone
fields = {}
all_ranges = []
invalid = []
for line in lines:
line = line.strip('\n')
if line == '':
continue
if line == 'your ticket:':
zone = ticket_zone
continue
elif line == 'nearby tickets:':
zone = nearby_zone
continue
if zone == fields_zone:
category, ranges = line.split(': ')
ranges = [[int(a) for a in pair.split('-')] for pair in ranges.split(' or ')]
fields[category] = ranges
all_ranges += ranges
elif zone == ticket_zone:
continue
elif zone == nearby_zone:
invalid += [int(v) for v in line.split(',') if is_invalid(int(v), all_ranges)]
print(sum(invalid), invalid)<file_sep>/src/day_21/non_allergenic.py
from os import path
with open(path.dirname(__file__) + '/input.txt') as f:
print('Count the number of times ingredients that cannot have allergens appear')
recipes = [(entry[0].strip().split(' '), entry[1].strip().split(' ')) for entry in [line.strip('\n').replace('(', '').replace(')', '').replace(',', '').split('contains') for line in f.readlines()]]
candidates = {}
for ingredients, allergens in recipes:
for allergen in allergens:
candidates[allergen] = [ingredient for ingredient in candidates.get(allergen, ingredients) if ingredient in ingredients]
all_candidates = {}
for ingredients in candidates.values():
for ingredient in ingredients:
all_candidates[ingredient] = True
print('Number of ingredient mentions with no possible allergen: {0}'.format(sum([sum([1 for ingredient in ingredients if ingredient not in all_candidates]) for ingredients, _ in recipes])))
matched = {}
while True: # Reduce found combinations of ingredient-allergen and try to find new ones
current = len(matched)
for allergen, ingredients in candidates.items():
candidates[allergen] = [ingredient for ingredient in ingredients if ingredient not in matched] # Removed known ingredients from which the allergen is known
if len(candidates[allergen]) == 1:
matched[candidates[allergen][0]] = allergen
if len(matched) == current: # No other ingredient-allergen unique combination found, finished or not enough data to decide on the rest
break
print('Ingredients sorted by their allergen (alphabetical order):', ','.join([ingredient for ingredient, _ in sorted(matched.items(), key = lambda x : x[1])]))
<file_sep>/src/day_03/multiple_count_trees.py
import sys
import os
def count_trees(lines, right, down):
trees = 0
column = 0
row = 0
while row < len(lines):
line = lines[row].strip('\n')
trees += 1 if line[column] == '#' else 0
column = (column + right) % len(line)
row += down
print('Number of trees: {0}'.format(trees))
return trees
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Count the number of trees #, while going 1,1 3,1 5,1 7,1 and 1,2 right and down and multiply')
lines = f.readlines()
print('Total: {0}'.format(count_trees(lines, 1, 1) * count_trees(lines, 3, 1) * count_trees(lines, 5, 1) * count_trees(lines, 7, 1) * count_trees(lines, 1, 2)))<file_sep>/src/day_03/count_trees.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print("Count the number of trees #, while going 1 down 3 right")
trees = 0
column = 0
for line in f.readlines():
line = line.strip('\n')
trees += 1 if line[column] == '#' else 0
print(line, column, trees)
column = (column + 3) % len(line)
print('Number of trees: {0}'.format(trees))<file_sep>/src/day_02/validate_passwords.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print("Validate passwords and print the number of valid passwords")
valid = 0
for line in f.readlines():
r, l, p = line.replace(':', '').split() # 1-3 f: eafeaw
r = [int(a) for a in r.split('-')] # r l p
c = p.count(l)
# 'l' must appear at least 'r[0]' and at most 'r[1]' times in 'p'
if (c >= r[0] and c <= r[1]):
valid += 1
print(r, l, p, valid)<file_sep>/src/day_07/fit_gold_suitcase.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('How many colors can hold a gold bag')
rules = {}
for parent, children in [(rule.split(' bags')[0], rule.strip(' .\n').split('contain ')[1].split(', ')) for rule in f.readlines()]:
for child in children:
if child == "no other bags":
break
words = child.split(' ')
color = ' '.join((words[1:3]))
rules[color] = rules.get(color, [])
rules[color].append(parent)
seen = ['shiny gold']
colors = ['shiny gold']
while colors:
color = colors.pop()
new_colors = [parent for parent in rules.get(color, []) if parent not in seen]
colors.extend(new_colors)
seen.extend(new_colors)
print("Shiny gold bags can be held by {0} other color bags".format(len(seen) - 1))<file_sep>/src/day_20/tiles.py
from os import path
def get_edges(data):
left = right = ''
for row in data:
left += row[0]
right += row[-1]
return [data[0], data[-1], left, right]
with open(path.dirname(__file__) + '/input.txt') as f:
print('Assemble image by rotating tiles, get the result of multiplying the ID of the corners')
tiles = [tile for tile in f.read().split('\n\n') if tile != '']
edges = {}
matches = {}
for tile in tiles:
id, data = tile.split('\n')[0].split(' ')[1].strip(':'), tile.split('\n')[1:]
for edge in get_edges(data):
if edge in edges:
matches[edges[edge]] = matches.get(edges[edge], 0) + 1
matches[id] = matches.get(id, 0) + 1
else:
edges[edge] = id
edges[edge[::-1]] = id
res = 1
for corner in [tile for tile in matches if matches[tile] == 2]:
res *= int(corner)
print(res)<file_sep>/src/day_19/parser.py
from os import path
def parse(rules, index, data):
matched = []
for rule in rules[index]:
if rule[0][0] == '"' and rule[0][2] == '"': # Check for terminal character
return [data[1:]] if data and data[0] == rule[0][1] else []
else:
next = [data]
for p in rule: # Parse sequentially each member of the rule
parsed = []
for n in next:
parsed += parse(rules, p, n)
next = parsed # The new options are the successfully parsed remaining strings in each step
matched += next
return matched
with open(path.dirname(__file__) + '/input.txt') as f:
print('Evaluate each expression with the production rules, count the number of valid expressions')
rules = {}
rules_text, expressions = f.read().split('\n\n')
for line in rules_text.split('\n'):
rules[line.split(': ')[0]] = [rule.split(' ') for rule in line.split(': ')[1].split(' | ')]
print(sum([1 if [True for match in parse(rules, '0', exp + '$') if match == '$'] else 0 for exp in expressions.split('\n')]))<file_sep>/src/day_20/sea_monsters.py
from os import path
def get_edges(data):
left = right = ''
for row in data:
left += row[0]
right += row[-1]
return [data[0], data[-1], left, right]
def print_pic(data):
for row in data:
print(row)
print('')
def rotate(data):
new_rows = [''] * len(data)
for row in data[::-1]:
for i, c in enumerate(row):
new_rows[i] += c
return new_rows
def flip(data):
return [row[::-1] for row in data]
def get_neighbour(tiles, tile, matches, my_edge, edge_to_match):
f = lambda data : data if get_edges(tiles[tile])[my_edge] == get_edges(data)[edge_to_match] else None
for match in matches[tile]:
new_data = apply_function_to_rotated_data(tiles[match], f)
if new_data is not None:
tiles[match] = new_data
return match
return None
def get_ids_in_row(tiles, tile, matches):
row = [tile]
while True:
actual = len(row)
new_element = get_neighbour(tiles, row[-1], matches, 3, 2)
if new_element:
row.append(new_element)
if actual == len(row):
return row
def orient_corner(tiles, corner, matches):
for __ in range(2):
for _ in range(4):
if get_neighbour(tiles, corner, matches, 3, 2) is not None and get_neighbour(tiles, corner, matches, 1, 0) is not None:
return
tiles[corner] = rotate(tiles[corner])
tiles[corner] = flip(tiles[corner])
def clear_edges(tiles):
for tile, data in tiles.items():
tiles[tile] = [row[1:-1] for row in data][1:-1]
def make_image(tiles, corner, matches):
orient_corner(tiles, corner, matches)
left = corner
image = []
ids = []
while left is not None:
ids.append(get_ids_in_row(tiles, left, matches))
left = get_neighbour(tiles, left, matches, 1, 0)
clear_edges(tiles)
print(ids)
for row in ids:
image += stitch_pics(tiles, row)
return(image)
def stitch_pics(tiles, row):
data = []
for i in range(len(tiles[row[0]])):
r = ''
for tile in [tiles[c] for c in row]:
r += tile[i]
data.append(r)
return data
def clean_sea_monsters(data):
for i, string in enumerate(data):
data[i] = string.replace('O', '#')
sea_monster = [ ' # ', \
'# ## ## ###', \
' # # # # # # ']
def paint_sea_monster(data, i, j, r, c):
points = [(r + n // 20, c + n % 20) for n in range(60) if sea_monster[n // 20][n % 20] == '#' and data[r + n // 20][c + n % 20] == '#']
if len(points) != 15:
return
for i, j in points:
data[i] = data[i][:j] + 'O' + data[i][j + 1:]
def apply_function_to_rotated_data(data, f):
for __ in range(2):
for _ in range(4):
result = f(data)
if result is not None:
return result
data = rotate(data)
data = flip(data)
def look_for_monsters(image):
for r in range(len(image) - 2):
for c in range(len(image[0]) - 19):
paint_sea_monster(image, 0, 0, r, c)
#print_pic(image)
print(sum([row.count('#') for row in image]))
clean_sea_monsters(image)
with open(path.dirname(__file__) + '/input.txt') as f:
print('Assemble image by rotating tiles and removing edges, identify the monster pattern and count the number of # left without monsters in the image')
tiles_text = [tile for tile in f.read().split('\n\n') if tile != '']
edges = {}
matches = {}
tiles = {}
for tile in tiles_text:
id, data = tile.split('\n')[0].split(' ')[1].strip(':'), tile.split('\n')[1:]
tiles[id] = data
for edge in get_edges(data):
if edge in edges:
matches[edges[edge]] = matches.get(edges[edge], []) + [id]
matches[id] = matches.get(id, []) + [edges[edge]]
else:
edges[edge] = id
edges[edge[::-1]] = id
corners = [tile for tile in matches if len(matches[tile]) == 2]
image = make_image(tiles, corners[0], matches)
apply_function_to_rotated_data(image, look_for_monsters)
<file_sep>/src/day_11/game_of_life_2.py
import sys
import os
def is_valid_pos(layout, pos):
x, y = pos
return x >= 0 and x < len(layout) and y >= 0 and y < len(layout[0])
def is_direction_occupied(layout, pos, dir):
while True:
pos = [sum(e) for e in zip(pos, dir)]
if not is_valid_pos(layout, pos):
return False
if layout[pos[0]][pos[1]] in ['L', '#']:
return layout[pos[0]][pos[1]] == '#'
def occupied_neighbours(layout, seat):
directions = [(1, 1), (1, 0), (1, - 1), (0, 1), (0, - 1), (- 1, 1), (- 1, 0), (- 1, - 1)]
return sum([1 for n in directions if is_direction_occupied(layout, seat, n)])
def update_chairs(layout):
updated = False
occupied = 0
update_map = [[False for _ in range(len(layout[0]))] for _ in range(len(layout))]
for x in range(len(layout)):
for y in range(len(layout[0])):
update_map[x][y] = True if (layout[x][y] == 'L' and occupied_neighbours(layout, (x, y)) == 0) or (layout[x][y] == '#' and occupied_neighbours(layout, (x, y)) >= 5) else False
for x in range(len(layout)):
for y in range(len(layout[0])):
if update_map[x][y]:
layout[x][y] = 'L' if layout[x][y] == '#' else '#'
updated = True
occupied += 1 if layout[x][y] == '#' else 0
return (updated, occupied)
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Simulate chair usage until stable and print number of used seats')
layout = [list(line.strip('\n')) for line in f.readlines()]
updated = True
occupied = 0
while updated:
updated, occupied = update_chairs(layout)
print(updated, occupied)<file_sep>/src/day_13/offsets.py
import sys
import os
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('Find the earliest T at which the first bus departs and each bus not X departs Y minutes after T according to their offset on the list')
t, step = 0, 1
for offset, freq in [(offset, int(freq)) for offset, freq in enumerate([e for e in f.readlines()[1].strip('\n').split(',')]) if freq != 'x']:
while (t + offset) % freq != 0:
t += step
step *= freq # Step becomes least common multiple of matched frequencies, just multiply as they are all prime numbers
print ('Matched freq: {0}, new step: {1}, at t: {2}'.format(freq, step, t))<file_sep>/src/day_22/play_recursive_game.py
from os import path
def play(decks, mem, depth):
original = tuple([deck[:] for deck in decks])
if original not in mem:
previous = {}
while not [True for deck in decks if len(deck) == 0]:
if decks in mem:
return mem[decks]
if decks in previous:
return (0, decks)
previous[decks] = True
cards = [deck[0] for deck in decks]
decks = [deck[1:] for deck in decks]
i = play(tuple([deck[:cards[i]] for i, deck in enumerate(decks)]), mem, depth + 1)[0] if len([True for i, deck in enumerate(decks) if cards[i] <= len(deck)]) == len(decks) else cards.index(max(cards))
decks[i] = decks[i] + (cards[i], cards[i - 1])
decks = tuple(decks)
for p in previous:
mem[p] = (0 if len(decks[0]) else 1, decks)
return mem[original]
with open(path.dirname(__file__) + '/input.txt') as f:
print('Play the game with the recursive set of rules and print the winning score')
decks = tuple([tuple([int(a) for a in cards.strip().split('\n')[1:]]) for cards in f.read().split('\n\n')])
winner, result = play(decks, {}, 0)
print(sum([(i + 1) * card for i, card in enumerate(result[winner][::-1])]))<file_sep>/src/day_18/calc2.py
from os import path
def insert(q, n):
if not q or q[-1] in ('(', '*'): #
q.append(n)
else:
q.pop()
m = q.pop()
q.append(n + m) #
def mult(q):
while len(q) > 1:
n = q.pop()
op = q.pop()
if op == '(':
insert(q, n)
break
else:
m = q.pop()
q.append(n * m) #
def evaluate(tokens):
q = []
for token in tokens:
if token in ('+', '*', '('):
q.append(token)
elif token == ')':
mult(q)
else:
insert(q, int(token))
mult(q)
return sum(q)
with open(path.dirname(__file__) + '/input.txt') as f:
print('Print sum of evaluating expressions, + has precence over *, evaluate left to right')
print(sum([evaluate(line.strip('\n').replace('(', '( ').replace(')', ' )').split(' ')) for line in f.readlines()]))
<file_sep>/src/day_07/bags_needed.py
import sys
import os
def bags_needed(rules, color):
return 1 + sum([n * bags_needed(rules, child) for n, child in rules.get(color, [])])
with open(os.path.dirname(__file__) + '/input.txt') as f:
print('How many bags are needed in total')
rules = {}
for parent, children in [(rule.split(' bags')[0], rule.strip(' .\n').split('contain ')[1].split(', ')) for rule in f.readlines()]:
rules[parent] = [(int(child.split(' ')[0]), ' '.join((child.split(' ')[1:3]))) for child in children if child != "no other bags"]
print('Need {0} bags'.format(bags_needed(rules, 'shiny gold') - 1))<file_sep>/src/day_24/hex_path.py
from os import path
def generate_neighbors(coord):
for neighbor in [[-1, 0], [1, 0], [-1, 1], [0, 1], [0, -1], [1, -1]]:
yield tuple([a + b for a, b in zip(coord, neighbor)])
def count_black_neighbors(tiles, coord):
return sum([1 for neighbor in generate_neighbors(coord) if tiles.get(neighbor, False)])
def next_black_tiles(tiles):
processed, new_black = {}, {}
for tile in tiles:
if tiles[tile]:
if count_black_neighbors(tiles, tile) in (1, 2):
new_black[tile] = True
for neighbor in generate_neighbors(tile):
if neighbor not in processed and not tiles.get(neighbor, False) and count_black_neighbors(tiles, neighbor) == 2:
new_black[neighbor] = True
processed[neighbor] = True
return new_black
with open(path.dirname(__file__) + '/input.txt') as f:
print('Flip tiles by following directions')
lines = [line.strip('\n') for line in f.readlines()]
black_tiles = {}
offsets = { 'w' : [-1, 0], 'e' : [1, 0], 'nw' : [-1, 1], 'ne' : [0, 1], 'sw' : [0, -1], 'se' : [1, -1] }
for line in lines:
coord = [0, 0]
while line:
if line[0] in ('e', 'w'):
coord = [a + b for a, b in zip(coord, offsets[line[0]])]
line = line[1:]
else:
coord = [a + b for a, b in zip(coord, offsets[line[0:2]])]
line = line[2:]
black_tiles[tuple(coord)] = not black_tiles.get(tuple(coord), False)
print(sum([1 for tile in black_tiles if black_tiles[tile] == True]))
print('Now do 100 generations of game of life and print the number of black tiles afterwards')
for i in range(100):
black_tiles = next_black_tiles(black_tiles)
print(sum([1 for tile in black_tiles if black_tiles[tile] == True]))
| babe1de4e8226a63069fb3c2031aa57f7c3f96a4 | [
"Markdown",
"Python"
] | 43 | Python | jonunezg/advent-of-code-2020 | 8f4d6e9a41e35458146431952d7ef03ccefbc54e | 1dfc645ff19dca2ee510bfe4c04b6d0f06b752fd |
refs/heads/master | <file_sep>import net.proteanit.sql.DbUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class Storage extends JFrame{
private JFrame frame;
private JPanel rootPanel;
private JTabbedPane tabbedPane1;
private JButton aktualizaceSkladuButton;
private JTable tableSkladDily;
private JTable tableDily;
private JButton aktualizaceSeznamuDily;
private JButton pridatPolozkuButton;
private JTextArea kodTextArea;
private JTextArea vyrobceTextArea;
private JTextArea dodavatelTextArea;
private JPanel Dily;
private JComboBox comboBox1;
private JButton button1;
private JTextArea textArea1;
private String id_dilu;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
Storage okno = new Storage();
okno.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
public void naplnCombobox() {
try {
String query = "SELECT id_dilu FROM dily";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()) {
comboBox1.addItem(rs.getString("id_dilu"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Storage() {
connection = SQLConnection.dbConnector();
setContentPane(rootPanel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50,50,1000,450);
rootPanel.setBorder(new EmptyBorder(5,5,5,5));
aktualizaceSeznamuDily.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String query = "SELECT id_dilu, kod AS Kód, dodavatel AS Dodavatel, vyrobce AS Výrobce FROM dily";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
tableDily.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
aktualizaceSkladuButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String query = "SELECT id_dilu_ve_skladu, id_dilu, id_zakazky, id_skladu, sklady.popis, dily.kod FROM dily_ve_skladu " +
"LEFT JOIN sklady USING(id_skladu)" +
"LEFT JOIN dily USING(id_dilu) " +
"WHERE id_zakazky IS NULL";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
tableSkladDily.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
pridatPolozkuButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String query = "INSERT INTO dily (id_dilu, kod, dodavatel, vyrobce) VALUES((SELECT (MAX(id_dilu) + 1) FROM dily), ?, ?, ?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, kodTextArea.getText());
pst.setString(2, dodavatelTextArea.getText());
pst.setString(3, vyrobceTextArea.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Data vložena");
pst.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
comboBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String query = "SELECT id_dilu FROM dily WHERE id_dilu = ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, (String)comboBox1.getSelectedItem());
ResultSet rs = pst.executeQuery();
textArea1.setText(rs.getString("id_dilu"));
id_dilu = rs.getString("id_dilu");
pst.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String query = "INSERT INTO dily_ve_skladu (id_dilu_ve_skladu, id_dilu, id_skladu) " +
"VALUES((SELECT (MAX(id_dilu_ve_skladu) + 1) FROM dily_ve_skladu), ?, ?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, id_dilu);
String idSkladu = JOptionPane.showInputDialog(frame, "Zadej id_skladu");
pst.setString(2, idSkladu);
pst.execute();
JOptionPane.showMessageDialog(null, "Data vložena");
pst.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
naplnCombobox();
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
}
<file_sep>rootProject.name = 'svanstorage'
<file_sep>= <NAME> - Semestrální projekt
== Scénář
//Objedání zakázky
Zákazník nám předá své údaje (jméno, přijmení, název firmy (údaje spojené s firmou) a kontaktní údaje).
Dále nám popíše o jaké služby má zájem. Například z výběru z níže napsaných:
* Samostatné podvozky k dostavbě určené pro nejrůznější nástavby (provedení podle požadavků zákazníka)
* Nosiče pro všechny typy kontejnerů
** DIN 30722 + vanové kontejnery
** vanové kontejnery + ISO kontejnery
** přeprava kontejnerů + valník
** přeprava kontejnerů + přepravník strojů
* Sklápěčkové podvozky
** Tandemové, točnicové nebo návěsové sklápěcí přívěsy
* Návěsy a přívěsy pro přepravu dřeva
* Odtahovky a přepravníky strojů
* Podvozky pod cisterny
* Traktorové přívěsy
* Speciální přívěsy podle přání zákazníka
Prodejce tyto informace zpracuje a podle požadavků zákazníka zpracuje objednávku. Vytvoří plán objednávky s předběžnou
informační cenou. Poté tuto zpracovanou objednávku přeloží zákazníkovi.
Zákazník tento návrh může přijmout i nemusí. Popřípadě se dořeší další nesrovnalosti.
Do určité výše ceny zakázky je zákazník povinen zaplatit část z této částky předem.
Podle zpracované zakázky prodejce zjistí, které díly je potřeba objednat od dodavatele. Některé díly mouhou být
evidované ve skladu, tyto díly nejsou potřebné obejdnat.
// vyzvedávání dílu od dodavatele
Díly, které jsou dodavatelem dodány, jsou zaevidovány do skladu. Je možno evidovat více dílů/výrobků. Každý z těchto
dílů/výrobků má informace, které ho popisují a charakterizují.
//Dodání dílů
Jakmile jsou všechny díly dostupné, objednávka míří k technikovi, kterou postupem času zpracovává. Prodejce ze skladu
díly, které jsou použity pro stavbů návěsu. Nepoužité skladové zásoby jsou zpetně doplněny do systému. Prodejce má po
celu dobu přehled jak práce na objednávce probíhají.
// technik začne pracovat na objednávce
// požádání o zaplacení zbylé částky
Po vyhotovení práce se předá zákazníkovi požadavek o zplacení.
== Diagramy
=== Sequence diagram
----
@startuml
participant Zákazník
Zákazník -> Prodejce: objednej zakázku
activate Prodejce
Prodejce --> Zákazník: zpracování objednávky
|||
Prodejce -> Zákazník: návrh objednávky
Zákazník --> Prodejce: potvrď objednávku
alt
Prodejce -> Zákazník: požadavek na zaplacení zálohy
Zákazník --> Prodejce: zaplať zálohu
|||
end
alt
Prodejce -> Dodavatel: kup díly
activate Dodavatel
Dodavatel --> Prodejce: objednávka zpracována
|||
|||
Dodavatel -> Prodejce: vyzvedni si díly
deactivate Dodavatel
|||
end
|||
Prodejce -> Skladník: začni pracovat
activate Skladník
Skladník --> Prodejce: začal jsem pracovat
deactivate Prodejce
|||
|||
Skladník -> Prodejce: hotová práce
deactivate Skladník
activate Prodejce
Prodejce -> Zákazník: zaplať zbytek
Zákazník --> Prodejce: zaplacení
Prodejce -> Zákazník: vyzvedni si zakázku
deactivate Prodejce
@enduml
----
.Sequence diagram
image::img/seq_diagram.png[seq_diagram]
=== Use case diagram
----
@startuml
left to right direction
skinparam packageStyle rectangle
actor Zákazník
actor Prodejce
actor Dodavatel
actor Technik
rectangle {
Zákazník --> (Vyvoření objednávky)
Zákazník --> (Potvrzení objednávky)
Zákazník --> (Platba)
(Zaplacení zálohy) ..> (Platba) : <<extends>>
(Zaplacení zbylé částky) ..> (Platba) : <<extends>>
(Zpracování objednávky) <-- Prodejce
Prodejce -> (Návrh objednávky)
(výzva k platbě) <-- Prodejce
(Zálohy) ..> (výzva k platbě) : <<extends>>
(Zbylá částka) ..> (výzva k platbě) : <<extends>>
(Nákup dílů) ..> (Zpracování objednávky) : <<extends>>
(Přiřadit technika k práci) ..> (Zpracování objednávky) : <<extends>>
(Výdej zakázky) ..> (Zpracování objednávky) : <<extends>>
Dodavatel --> (Dodání dílů)
(Práce na zakázce) <-- Technik
(Hotová zakázka) ..> (Práce na zakázce) : <<extends>>
@enduml
----
.Use case diagram
image::img/uc_diagram.png[uc_diagram]
== Návrh grafického rozhraní
.Grafické rozhraní: Skladu subdodávek
image::img/sklad_subdodavky.jpeg[uc_diagram]
.Grafické rozhraní: Skladu subdodávek/barev/povrchových úprav
image::img/sklad_uni.jpeg[uc_diagram]
.Grafické rozhraní: Vytvoření nové zakázky
image::img/nova_zakazka.jpeg[uc_diagram]
.Grafické rozhraní: Vytvoření zakázky a přidávání položek na zakázku
image::img/vytvoreni_zakazky_pridavani.jpeg[uc_diagram]
| b360fceac7116d0fc7c0b0cdb8700c0ca7a8ab3b | [
"Java",
"AsciiDoc",
"Gradle"
] | 3 | Java | JanTikal/svanstorage | 5ec5094a2f4861c8419f44591b31fb1138af6e4b | ea88cc56f1797de9ce3afc9231bfa367e9fa23e4 |
refs/heads/master | <repo_name>leitstandjs/leitstand<file_sep>/lib/action.js
import _ from 'lodash';
export default class Action {
constructor(instance, widget, leitstand) {
this.instance = instance;
this.widget = widget;
this.logger = widget.logger;
this.leitstand = leitstand;
this.name = instance.name;
this.key = instance.key;
const plugin = instance.plugin || this.widget.plugin;
this.plugin = this.leitstand.plugins[plugin];
if (!this.plugin) {
throw new Error(`Plugin "${instance.plugin}" not found`);
}
var promise;
const settings = _.get(this.widget, ['settings', this.plugin.id], this.widget.settings);
if (instance.settings) {
promise = new Promise((resolve, reject) => {
this.spec = this.plugin.api(instance.settings, resolve, reject);
})
.then(client => {
this.client = client;
});
} else if (settings) {
if (!this.widget.clients[this.plugin.id]) {
promise = this.widget.clients[this.plugin.id] = new Promise((resolve, reject) => {
this.spec = this.plugin.api(settings, resolve, reject);
})
.then(client => {
this.widget.clients[this.plugin.id] = client;
});
}
Object.defineProperty(this, 'client', {
get: function () {
return this.widget.clients[this.plugin.id];
}
});
} else {
if (!this.plugin.client) {
promise = this.plugin.client = new Promise((resolve, reject) => {
this.spec = this.plugin.api(this.plugin.settings, resolve, reject);
})
.then(client => {
this.plugin.client = client;
});
}
Object.defineProperty(this, 'client', {
get: () => {
return this.plugin.client;
}
});
}
if (promise) {
this.leitstand.promises.push(promise);
}
}
method(name, type) {
return this.instance[name] ||
_.get(this.widget, [name, this.plugin.id, type]) ||
_.get(this.widget, [name, this.plugin.id], this.widget[name]) ||
_.get(this.plugin, [name, type], this.plugin[name]) ||
this[name];
}
callback(error, values) {
if (error instanceof Error) {
this.logger.error('Widget "%s", method "%s":', this.widget.id, this.name, error);
} else {
if (error !== null) {
values = error;
}
if (!this.key && Array.isArray(values)) {
this.key = this.name.replace('.', '-');
}
if (this.filter instanceof Function) {
values = this.filter(values);
}
this.widget.set(values, this.key);
}
}
}
<file_sep>/lib/dashboard.js
export default class Dashboard {
constructor(id, leitstand) {
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this.logger = leitstand.logger;
this.view = 'dashboards/' + this.id;
this.leitstand = leitstand;
this.widgetFilter = '';
}
get widgets() {
return Object.keys(this.leitstand.widgets).filter(id => {
return [...this.widgetFilter].some(regexp => id.match(new RegExp(regexp, 'i')));
}).reduce((result, id) => {
result[id] = this.leitstand.widgets[id];
return result;
}, {});
}
set widgets(filter) {
this.widgetFilter = filter;
}
}
<file_sep>/lib/event.js
import _ from 'lodash';
import Action from './action';
export default class Event extends Action {
start() {
if (this.running) {
return false;
}
this.callback = this.method('callback', 'events');
this.filter = this.method('filter', 'events');
this.logger.debug('Binding on widget "%s", plugin "%s" for event "%s"', this.widget.id, this.plugin.id, this.name);
this.client.on(this.name, this.callback.bind(this));
this.running = true;
return true;
}
stop() {
if (!this.running) {
return false;
}
this.logger.debug('Binding off widget "%s", plugin "%s" for event "%s"', this.widget.id, this.plugin.id, this.name);
this.client.off(this.name, this.callback);
this.running = false;
return true;
}
}
<file_sep>/test/index.js
import assert from 'assert';
import Leitstand from '../lib/leitstand';
describe('leitstand', function () {
var leitstand;
before(function () {
leitstand = new Leitstand({
plugins: {
load: false
}
});
});
it('should have unit test!', function () {
assert(true, leitstand instanceof Leitstand);
});
});
<file_sep>/lib/plugin.js
export default class Plugin {
constructor(id, leitstand) {
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this.logger = leitstand.logger;
this.leitstand = leitstand;
}
}
<file_sep>/README.md
# Leitstand [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url]
> Leitstand core for creating (interactive) dashboards. Please see [leistand-cli][leistand-cli-url] for easily scaffolding and running Leistand apps and plugins.
## Installation
```bash
npm install leitstand --save
```
## Usage
```js
var Leitstand = require('leitstand');
var leistand = new Leitstand();
```
## TODO
- Documentation
- Tests
## License
MIT © [<NAME>](http://theblackestbox.net)
[npm-image]: https://badge.fury.io/js/leitstand.svg
[npm-url]: https://npmjs.org/package/leitstand
[travis-image]: https://travis-ci.org/leitstandjs/leitstand.svg?branch=master
[travis-url]: https://travis-ci.org/leitstandjs/leitstand
[daviddm-image]: https://david-dm.org/leitstandjs/leitstand.svg?theme=shields.io
[daviddm-url]: https://david-dm.org/leitstandjs/leitstand
[leistand-cli-url]: https://npmjs.org/leitstandjs/leitstand-cli
<file_sep>/lib/widget.js
import EventEmitter from 'events';
import _ from 'lodash';
import Event from './event';
import Method from './method';
export default class Widget extends EventEmitter {
constructor(id, leitstand) {
super();
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this.logger = leitstand.logger;
this.leitstand = leitstand;
this.values = {};
this.schedule = {};
this.clients = {};
this._events = [];
this._methods = [];
}
set events(events) {
if (!events) {
return;
} else if (!Array.isArray(events)) {
events = [events];
}
this._events.forEach(event => event.stop());
this._events = events.map(event => {
if (typeof event === 'string' || event instanceof String) {
event = {
name: event,
widget: this
};
}
return new Event(event, this, this.leitstand);
});
}
set methods(methods) {
if (!methods) {
return;
} else if (!Array.isArray(methods)) {
methods = [methods];
}
this._methods.forEach(method => method.stop());
this._methods = methods.map(method => {
if (typeof method === 'string' || method instanceof String) {
method = {
name: method
};
}
return new Method(method, this, this.leitstand);
});
}
get methods() {
return this._methods;
}
set(values, key) {
const val = _.cloneDeep(this.get());
if (key) {
_.set(val, key, values);
} else {
Object.assign(val, values);
}
if (!_.isEqual(val, this.get())) {
this.values = val;
this.emit('set', this);
return true;
}
return false;
}
get() {
return this.values;
}
listen() {
this._events.forEach(event => {
event.start();
});
}
work() {
this._methods.forEach(method => {
method.start();
});
}
toJSON() {
return _.assign({}, this.values, {id: this.id});
}
}
| 288957215d0f41e9dfffdb3a454c7923a3952fdc | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | leitstandjs/leitstand | d94d385cb420aa354b9f2e7cb3db71bf05064df7 | 721d138042299352f2e6d5f05df2e87e091c40db |
refs/heads/master | <repo_name>m4a1grant/ExcelAndMail<file_sep>/src/main/java/logic/entity/DailyExchangeRate.java
package logic.entity;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* @author Serhiy.K.Dubovenko
*/
public class DailyExchangeRate {
@SerializedName("date")
@Expose
private String date;
@SerializedName("bank")
@Expose
private String bank;
@SerializedName("baseCurrency")
@Expose
private int baseCurrency;
@SerializedName("baseCurrencyLit")
@Expose
private String baseCurrencyLit;
@SerializedName("exchangeRate")
@Expose
private List<ExchangeRate> exchangeRate;
public DailyExchangeRate(String date, String bank, int baseCurrency, String baseCurrencyLit, List<ExchangeRate> exchangeRate) {
this.date = date;
this.bank = bank;
this.baseCurrency = baseCurrency;
this.baseCurrencyLit = baseCurrencyLit;
this.exchangeRate = exchangeRate;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getBank() {
return bank;
}
public void setBank(String bank) {
this.bank = bank;
}
public int getBaseCurrency() {
return baseCurrency;
}
public void setBaseCurrency(int baseCurrency) {
this.baseCurrency = baseCurrency;
}
public String getBaseCurrencyLit() {
return baseCurrencyLit;
}
public void setBaseCurrencyLit(String baseCurrencyLit) {
this.baseCurrencyLit = baseCurrencyLit;
}
public List<ExchangeRate> getExchangeRate() {
return exchangeRate;
}
public void setExchangeRate(List<ExchangeRate> exchangeRate) {
this.exchangeRate = exchangeRate;
}
@Override
public String toString() {
return "DailyExchangeRate{" +
"date='" + date + '\'' +
", bank='" + bank + '\'' +
", baseCurrency=" + baseCurrency +
", baseCurrencyLit='" + baseCurrencyLit + '\'' +
", exchangeRate=" + exchangeRate +
'}';
}
}
<file_sep>/src/main/java/logic/Main.java
package logic;
import logic.excel.CreatorXLS;
import logic.mail.MailSender;
import javax.mail.MessagingException;
import java.io.IOException;
/**
* @author <NAME>
*/
public class Main {
private static final String FIRST_DATE = "01.01.2016";
private static final String LAST_DATE = "31.12.2017";
private static final String SENDER_SETTINGS = "settings\\SenderSettings.xml";
private static final String RECIPIENTS = "settings\\Recipients.xml";
private static final String FILE = "Result.xls";
public static void main(String[] args) throws MessagingException, IOException {
CreatorXLS creator = new CreatorXLS();
creator.createXLS(FIRST_DATE, LAST_DATE, FILE);
MailSender.sendMail(SENDER_SETTINGS, RECIPIENTS, FILE);
}
}
| 6cdce135efa18a7dcf036a5b22b088764dd69ead | [
"Java"
] | 2 | Java | m4a1grant/ExcelAndMail | fe97dd95debb1b4ab540f412ebc35eccef705feb | 630e882e6e0200669a6403a32527fbf6de69a250 |
refs/heads/master | <file_sep>#ifndef BINARY_SEARCH_HPP
#define BINARY_SEARCH_HPP
int binary_search(vector<int> array, int value)
{
int low = 0;
int high = array.size() - 1;
sort(array.begin(), array.end());
while (low <= high) {
int mid = (low + high) / 2;
if (array[mid] == value) {
return mid;
} else if (array[mid] > value) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
#endif
<file_sep>#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
#include "../include/prim.hpp"
int main(void)
{
init_graph(graph);
print_graph(graph);
cout << "minmum spanning tree:\n";
prim(graph);
return 0;
}
<file_sep>#ifndef SHELL_SORT_HPP
#define SHELL_SORT_HPP
void print(vector<int> array)
{
for (vector<int>::iterator p = array.begin(); p != array.end(); p++)
cout << *p << " ";
cout << "\n";
}
void shell_sort(vector<int> &array, vector<int>::size_type N)
{
vector<int>::size_type step, i, j;
for (step = N / 2; step > 0; step /= 2) {
for (i = step; i < N; i++) {
vector<int>::size_type temp = array[i];
for (j = i; j >= step; j -= step) {
if (temp < array[j - step])
array[j] = array[j - step];
else
break;
}
array[j] = temp;
print(array);
}
}
}
#endif
<file_sep>A set of basic algorithm
=========
+ heap sort
+ quick sort
+ insert sort
+ shell sort
+ radix sort
+ binary search
+ hash search
+ DFS search
+ soundex
+ prim
<file_sep>#ifndef INSERT_SORT_HPP
#define INSERT_SORT_HPP
void print_sort(vector<int> array)
{
for (vector<int>::iterator p = array.begin(); p != array.end(); p++) {
cout << *p << " ";
}
cout << "\n";
}
void insert_sort(vector<int> &array)
{
int i, j;
for (i = 1; i < array.size(); i++) {
int temp = array[i];
for (j = i - 1; j >= 0 && array[j] > temp; j--) {
array[j + 1] = array[j];
}
array[j + 1] = temp;
print_sort(array);
}
}
#endif
<file_sep>#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
#include "../include/quick_sort.hpp"
int main(void)
{
vector<int> array;
int num;
cout << "Before sort:\n";
while (cin >> num) {
array.push_back(num);
if (cin.get() == '\n')
break;
}
random_quick_sort(array, 0, array.size() - 1);
cout << "\nAfter sort:\n";
print_sort(array);
return 0;
}
<file_sep>#include <iostream>
#include <vector>
using namespace std;
#include "../include/shell_sort.hpp"
int main(int argc, char *argv[])
{
vector<int> array;
int num;
cout << "Before sort:\n";
while (cin >> num) {
array.push_back(num);
if (cin.get() == '\n')
break;
}
shell_sort(array, array.size());
cout << "\nAfter sort:\n";
print(array);
return 0;
}
<file_sep>#ifndef QUICK_SORT_HPP
#define QUICK_SORT_HPP
void print_sort(vector<int> array)
{
for (vector<int>::iterator p = array.begin(); p != array.end(); p++) {
cout << *p << " ";
}
cout << "\n";
}
int adjust_array(vector<int> &array, int l, int r)
{
int i = l;
int j = r;
int x = array[i];
while (i < j) {
while (i < j && array[j] >= x)
j--;
if (i < j) {
array[i] = array[j];
i++;
}
while (i < j && array[i] < x)
i++;
if (i < j) {
array[j] = array[i];
j--;
}
}
array[i] = x;
return i;
}
int random_adjust_array(vector<int> &array, int l, int r)
{
srand(time(NULL));
int i = rand() % (r-l+1) + l;
int x;
x= array[i];
cout << x << " | ";
array[i] = array[l];
array[l] = x;
return adjust_array(array, l, r);
}
void quick_sort(vector<int> array, int l, int r)
{
if (l < r) {
int i = adjust_array(array, l, r);
print_sort(array);
quick_sort(array, l, i - 1);
quick_sort(array, i + 1, r);
}
}
void random_quick_sort(vector<int> &array, int l, int r)
{
if (l < r) {
int i = random_adjust_array(array, l, r);
print_sort(array);
random_quick_sort(array, l, i - 1);
random_quick_sort(array, i + 1, r);
}
}
#endif
<file_sep>#ifndef HASH_SEARCH_HPP
#define HASH_SEARCH_HPP
void build_hash(vector<int> &array, vector<int> &hash_table)
{
vector<int>::iterator p;
for (p = array.begin(); p < array.end(); p++) {
int hash_address = *p % HASH_LEN;
while (hash_table.at(hash_address) != 0) {
hash_address = (++hash_address) % HASH_LEN;
}
hash_table.at(hash_address) = *p;
}
}
int hash_search(vector<int> &hash_table, int value)
{
int hash_address = value % HASH_LEN;
while (hash_table.at(hash_address) != 0 &&
hash_table.at(hash_address) != value) {
hash_address = (++hash_address) % HASH_LEN;
}
if (hash_table.at(hash_address) == 0)
return -1;
return 1;
}
#endif
<file_sep>#include <iostream>
#include <vector>
using namespace std;
#include "../include/radix_sort.hpp"
int main(void)
{
vector<int> array;
int num;
cout << "Before sort:\n";
while (cin >> num) {
array.push_back(num);
if (cin.get() == '\n')
break;
}
radix_sort(array, array.size());
cout << "\nAfter sort:\n";
print(array);
return 0;
}
<file_sep>#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
#include "../include/binary_search.hpp"
int main(void)
{
vector<int> array;
int num;
int value;
while (cin >> num) {
array.push_back(num);
if (cin.get() == '\n')
break;
}
cin >> value;
if (binary_search(array, value) != -1)
cout << "found" << endl;
else
cout << "no found" << endl;
return 0;
}
<file_sep>#include <vector>
#include <iostream>
#define HASH_LEN 137
using namespace std;
#include "../include/hash_search.hpp"
int main(void)
{
int num;
int value;
vector<int> array;
while (cin >> num) {
array.push_back(num);
if (cin.get() == '\n')
break;
}
vector<int> hash_table(HASH_LEN);
build_hash(array, hash_table);
cin >> value;
if (hash_search(hash_table, value) == 1) {
cout << "found" << endl;
} else {
cout << "no found" << endl;
}
return 0;
}
<file_sep>#ifndef SOUNDEX_HPP
#define SOUNDEX_HPP
char encode(char c)
{
if ((c == 'B') || (c == 'F') || (c == 'P') || (c == 'V'))
return '1';
if ((c == 'C') || (c == 'G') || (c == 'J') || (c == 'K') ||
(c == 'Q') || (c == 'S') || (c == 'X') || (c == 'Z'))
return '2';
if ((c == 'D') || (c == 'T'))
return '3';
if ((c == 'M') || (c == 'N'))
return '5';
if ((c == 'R'))
return '6';
if ((c == 'L'))
return '4';
return '0';
}
string soundex(const string str)
{
string code = "0000";
int i = 0, j = 1;
char tmp;
code[i] = str[i];
for (i = 1; i < str.length(); i++){
tmp = toupper(str[i]);
if (encode(tmp) != '0') {
code[j++] = encode(tmp);
}
}
return code;
}
#endif
<file_sep>#ifndef HEAP_SORT_HPP
#define HEAP_SORT_HPP
void print_sort(vector<int> array)
{
for (vector<int>::iterator p = array.begin(); p != array.end(); p++)
cout << *p << " ";
cout << "\n";
}
void heap_adjust(vector<int> &array, int i, int size)
{
int lchild = 2 * i;
int rchild = 2 * i + 1;
int max = i;
if (i <= size / 2) {
if (lchild <= size && array[lchild] > array[max]) {
max = lchild;
}
if (rchild <= size && array[rchild] > array[max]) {
max = rchild;
}
if (max != i) {
swap(array[i], array[max]);
heap_adjust(array, max, size);
}
}
}
void build_heap(vector<int> &array, int size)
{
int i;
for (i = size / 2; i >= 1; i--)
heap_adjust(array, i, size);
}
void heap_sort(vector<int> &array, int size)
{
int i;
build_heap(array, size);
for (i = size; i >= 1; i--) {
swap(array[1], array[i]);
heap_adjust(array, 1, i - 1);
print_sort(array);
}
}
#endif
<file_sep>#ifndef RADIX_SORT_HPP
#define RADIX_SORT_HPP
void print(vector<int> array)
{
for (vector<int>::iterator p = array.begin(); p != array.end(); p++)
cout << *p << " ";
cout << "\n";
}
int max_bit(vector<int> &array, int n)
{
int d = 1;
int p = 10;
for (int i = 0; i < n; i++) {
while (array[i] >= p) {
p *= 10;
d++;
}
}
return d;
}
void radix_sort(vector<int> &array, int n)
{
int d = max_bit(array, n);
int *tmp = new int[n];
int *count = new int[10];
int k = 0;
int radix = 1;
for (int i = 1; i <= d; i++) {
for (int j = 0; j < 10; j++)
count[j] = 0;
for (int j = 0; j < n; j++) {
k = (array[j] / radix) % 10;
count[k]++;
}
for (int j = 1; j < 10; j++)
count[j] = count[j-1] + count[j];
for (int j = n-1; j >= 0; j--) {
k = (array[j] / radix) % 10;
tmp[count[k]-1] = array[j];
count[k]--;
}
for (int j = 0; j < n; j++)
array[j] = tmp[j];
print(array);
radix = radix * 10;
}
delete [] tmp;
delete [] count;
}
#endif
<file_sep>#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
#include "../include/soundex.hpp"
int main(int argc, char *argv[])
{
string test1, test2;
cin >> test1 >> test2;
string code1 = soundex(test1);
string code2 = soundex(test2);
cout << "soundex for " << test1 << " is " << code1 << endl;
cout << "soundex for " << test2 << " is " << code2 << endl;
return 0;
}
| 5c868d34aa997cfc864d794fd75e3845915d9e72 | [
"Markdown",
"C++"
] | 16 | C++ | qs8607a/algorithm-31 | 46476d01666d82d76c3aa70baaf90450be104506 | ad373dd07004328accc2949a1ce414762cfaa3f9 |
refs/heads/main | <repo_name>ImLordImpaler/crm-1<file_sep>/basic/views.py
from django.shortcuts import render , redirect
from django.http import HttpResponse
from .models import Enquiry , Product , Employee
from .forms import ProductForm , EnquiryForm , EmployeForm , SignUpForm
from django.contrib.auth import login , logout , authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# Create your views here.
from django.contrib.auth.decorators import login_required
@login_required(login_url='loginPage')
def cover(request):
return render(request , 'basic/cover.html')
def loginPage(request):
if request.method == 'POST':
uname = request.POST.get('uname')
pwd = request.POST.get('pwd')
user = authenticate(username=uname , password = pwd)
if user is not None:
login(request , user)
return redirect('dashboard')
else:
return HttpResponse("Kon hai bai tu")
else :
pass
return render(request , 'basic/login.html')
def register(request):
form = SignUpForm()
if request.method=='POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('<PASSWORD>')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('dashboard')
else:
return HttpResponse("Nai hua bhau")
else :
form = SignUpForm()
params = {
'form': form
}
return render(request , 'basic/register.html' , params )
def logoutPage(request):
logout(request)
return redirect('loginPage')
@login_required(login_url='loginPage')
def home(request):
enq = Enquiry.objects.all()
pro = Product.objects.all().order_by('quantity')
params = {
'enq': enq ,
'pro' : pro
}
return render(request , 'basic/dashboard.html' , params)
@login_required(login_url='loginPage')
def enquiry(request):
enq = Enquiry.objects.all()
form = EnquiryForm()
if request.method == 'POST':
form = EnquiryForm(request.POST)
if form.is_valid():
form.save()
return redirect('dashboard')
else :
return HttpResponse('<h3> Try again </h3>')
else :
form = EnquiryForm()
params = {
'form' : form ,
'pro' : enq
}
return render(request , 'basic/enquiry.html' , params)
@login_required(login_url='loginPage')
def enquiryUpdate(request , pk):
enq = Enquiry.objects.get(id = pk)
if request.method == 'POST':
form = EnquiryForm(request.POST , instance=enq)
if form.is_valid():
form.save()
return redirect('dashboard')
else:
return HttpResponse('not found')
else:
form = EnquiryForm(instance= enq)
params = {
'form' : form
}
return render(request , 'basic/enquiryForm.html' , params)
@login_required(login_url='loginPage')
def product(request):
enq = Product.objects.all()
form = EnquiryForm()
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return redirect('dashboard')
else :
return HttpResponse('<h3> Try again </h3>')
else :
form = ProductForm()
params = {
'form' : form ,
'pro' : enq
}
return render(request , 'basic/product.html' , params)
@login_required(login_url='loginPage')
def productEnquiry(request , pk):
enq = Product.objects.get(id = pk)
if request.method == 'POST':
form = ProductForm(request.POST , instance=enq)
if form.is_valid():
form.save()
return redirect('dashboard')
else:
return HttpResponse('not found')
else:
form = ProductForm(instance= enq)
params = {
'form' : form
}
return render(request , 'basic/productForm.html' , params)
@login_required(login_url='loginPage')
def employee(request):
emp = Employee.objects.all()
if request.method == 'POST':
form = EmployeForm(request.POST)
if form.is_valid():
form.save()
return redirect('dashboard')
else :
return HttpResponse('kya hai reh halkat. Tereko likhne ka nai atta kya?')
else:
form = EmployeForm()
params = {
'form': form,
'pro': emp
}
return render(request , 'basic/employee.html' , params)
@login_required(login_url='loginPage')
def employeeUpdate(request , pk):
enq = Employee.objects.get(id = pk)
if request.method == 'POST':
form = EmployeForm(request.POST , instance=enq)
if form.is_valid():
form.save()
return redirect('dashboard')
else:
return HttpResponse('not found')
else:
form = EmployeForm(instance= enq)
params = {
'form' : form
}
return render(request , 'basic/empForm.html' , params)
@login_required(login_url='loginPage')
def stock(request):
pro = Product.objects.all()
params = {
'stock': pro
}
return render(request , 'basic/album.html' , params)
@login_required(login_url='loginPage')
def clients(request):
params = {
}
return render(request , 'basic/clients.html' , params)
@login_required(login_url='loginPage')
def deleteEmployee(request , pk):
Emp = Employee.objects.get(id=pk)
if request.method == 'POST':
Emp.delete()
return redirect('employee')
params = {
'item': Emp
}
return render(request, 'basic/deleteEmployee.html' , params)
@login_required(login_url='loginPage')
def deleteProduct(request , pk):
pro = Product.objects.get(id=pk)
if request.method=='POST':
pro.delete()
return redirect('product')
params = {
'item': pro
}
return render(request , 'basic/deleteProduct.html' , params)
@login_required(login_url='loginPage')
def deleteEnquiry(request , pk):
pro = Enquiry.objects.get(id=pk)
if request.method=='POST':
pro.delete()
return redirect('enquiry')
params = {
'item': pro
}
return render(request , 'basic/deleteEnquiry.html' , params )<file_sep>/basic/forms.py
from django.forms import ModelForm
from basic.models import Product , Enquiry , Employee
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ('username','email', '<PASSWORD>', '<PASSWORD>', )
class ProductForm(ModelForm):
class Meta:
model = Product
fields = '__all__'
class EnquiryForm(ModelForm):
class Meta:
model = Enquiry
fields = '__all__'
class EmployeForm(ModelForm):
class Meta:
model = Employee
fields = '__all__'<file_sep>/basic/admin.py
from django.contrib import admin
# Register your models here.
from .models import Enquiry , Product , Service , Category , Employee , Customer
admin.site.register(Employee)
admin.site.register(Enquiry)
admin.site.register(Product)
admin.site.register(Service)
admin.site.register(Category)
admin.site.register(Customer) | bf91584bd650087bb85b9abe438ae6209e612059 | [
"Python"
] | 3 | Python | ImLordImpaler/crm-1 | c65bd7cdcd0f31a44969ebfadc0c20aae1205e8f | 30dbd831b1ab254215f012361ceb70f40e75ee76 |
HEAD | <file_sep>using System;
using System.IO;
using ExcelDataReader.Core.BinaryFormat;
namespace ExcelDataReader
{
/// <summary>
/// The ExcelReader Factory
/// </summary>
public static class ExcelReaderFactory
{
/// <summary>
/// Creates an instance of <see cref="ExcelBinaryReader"/> or <see cref="ExcelOpenXmlReader"/>
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <param name="convertOADates">If <see langword="true"/> convert OA dates to <see cref="DateTime"/>. Only applicable to binary (xls) files.</param>
/// <param name="readOption">The read option to use for binary (xls) files.</param>
/// <returns>The excel data reader.</returns>
public static IExcelDataReader CreateReader(Stream fileStream, bool convertOADates = true, ReadOption readOption = ReadOption.Strict)
{
var probe = new byte[8];
fileStream.Read(probe, 0, probe.Length);
fileStream.Seek(0, SeekOrigin.Begin);
if (!XlsDocument.CheckRawBiffStream(probe, out int version))
{
version = -1;
}
// MUST be set to the value 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1.
if (version != -1 || (probe[0] == 0xD0 && probe[1] == 0xCF))
{
return new ExcelBinaryReader(fileStream, convertOADates, readOption);
}
// zip files start with 'PK'
if (probe[0] == 0x50 && probe[1] == 0x4B)
{
return CreateOpenXmlReader(fileStream);
}
throw new NotSupportedException("Unknown file format");
}
/// <summary>
/// Creates an instance of <see cref="ExcelBinaryReader"/>
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <returns>The excel data reader.</returns>
public static IExcelDataReader CreateBinaryReader(Stream fileStream)
{
return CreateBinaryReader(fileStream, true, ReadOption.Strict);
}
/// <summary>
/// Creates an instance of <see cref="ExcelBinaryReader"/>
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <param name="option">The read option.</param>
/// <returns>The excel data reader.</returns>
public static IExcelDataReader CreateBinaryReader(Stream fileStream, ReadOption option)
{
return CreateBinaryReader(fileStream, true, option);
}
/// <summary>
/// Creates an instance of <see cref="ExcelBinaryReader"/>
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <param name="convertOADate">If true oa dates will be converer to <see cref="DateTime"/>.</param>
/// <returns>The excel data reader.</returns>
public static IExcelDataReader CreateBinaryReader(Stream fileStream, bool convertOADate)
{
return CreateBinaryReader(fileStream, convertOADate, ReadOption.Strict);
}
/// <summary>
/// Creates an instance of <see cref="ExcelBinaryReader"/>
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <param name="convertOADate">If true oa dates will be converer to <see cref="DateTime"/>.</param>
/// <param name="readOption">The read option.</param>
/// <returns>The excel data reader.</returns>
public static IExcelDataReader CreateBinaryReader(Stream fileStream, bool convertOADate, ReadOption readOption)
{
return new ExcelBinaryReader(fileStream, convertOADate, readOption);
}
/// <summary>
/// Creates an instance of <see cref="ExcelOpenXmlReader"/>
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <returns>The excel data reader.</returns>
public static IExcelDataReader CreateOpenXmlReader(Stream fileStream)
{
return new ExcelOpenXmlReader(fileStream);
}
}
}
<file_sep>ExcelDataReader
===============
Lightweight and fast library written in C# for reading Microsoft Excel files.
Please feel free to fork and submit pull requests.
If you are reporting an issue it is really useful if you can supply an example Excel file as this makes debugging much easier and without it we may not be able to resolve any problems.
This project is using a git-flow style workflow so please submit pull requests to the develop branch if possible.
[](https://ci.appveyor.com/project/andersnm/exceldatareader/branch/master) [](https://ci.appveyor.com/project/andersnm/exceldatareader/branch/develop)
## Finding the binaries
It is recommended to use Nuget. F.ex through the VS Package Manager Console `Install-Package <package>` or using the VS "Manage NuGet Packages..." extension.
As of ExcelDataReader version 3.0, the project was split into multiple packages:
Install the `ExcelDataReader` base package to use the "low level" reader interface. Compatible with net20, net45 and netstandard 1.3.
Install the `ExcelDataReader.DataSet` extension package to use the AsDataSet() method and load spreadsheets into System.Data.DataSet. This will also pull in the base package. Compatible with net20 and net45.
## How to use
### C# code :
```c#
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
// Choose one of either 1 or 2
// 1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
// 2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
// Choose one of either 3, 4, or 5
// 3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
// 4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
// 5. Data Reader methods
while (excelReader.Read()) {
// excelReader.GetInt32(0);
}
// 6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
```
### VB.NET Code:
```vb.net
Dim stream As FileStream = File.Open(filePath, FileMode.Open, FileAccess.Read)
' 1. Reading from a binary Excel file ('97-2003 format; *.xls)
Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateBinaryReader(stream)
' 2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateOpenXmlReader(stream)
' 3. DataSet - The result of each spreadsheet will be created in the result.Tables
Dim result As DataSet = excelReader.AsDataSet()
' 4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = True
Dim result As DataSet = excelReader.AsDataSet()
' 5. Data Reader methods
While excelReader.Read()
' excelReader.GetInt32(0);
End While
' 6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close()
```
### Tips
* SQL reporting services. Set ReadOption.Loose in the CreateBinaryReader factory method to skip some bounds checking which was causing SSRS generated xls to fail. (Only on changeset >= 82970)
<file_sep>using System.Globalization;
namespace ExcelDataReader.Core
{
public static class ReferenceHelper
{
/// <summary>
/// Logic for the Excel dimensions. Ex: A15
/// </summary>
/// <param name="value">The value.</param>
/// <param name="column">The column, 1-based.</param>
/// <param name="row">The row, 1-based.</param>
public static void ParseReference(string value, out int column, out int row)
{
// INFO: Check for a simple Solution
int index = ParseReference(value, out column);
row = int.Parse(value.Substring(index), NumberStyles.None, CultureInfo.InvariantCulture);
}
/// <summary>
/// Logic for the Excel dimensions. Ex: A15
/// </summary>
/// <param name="value">The value.</param>
/// <param name="column">The column, 1-based.</param>
/// <returns>The index of the row.</returns>
public static int ParseReference(string value, out int column)
{
int index = 0;
column = 0;
const int offset = 'A' - 1;
for (; index < value.Length; index++)
{
char c = value[index];
if (char.IsDigit(c))
break;
column *= 26;
column += c - offset;
}
return index;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace ExcelDataReader.Core.OpenXmlFormat
{
internal class XlsxWorkbook
{
public XlsxWorkbook(List<XlsxWorksheet> sheets, XlsxSST sst, XlsxStyles styles)
{
Sheets = sheets;
SST = sst;
Styles = styles;
}
public List<XlsxWorksheet> Sheets { get; set; }
public XlsxSST SST { get; }
public XlsxStyles Styles { get; }
}
}
<file_sep>using System;
using System.Text;
namespace ExcelDataReader.Core.BinaryFormat
{
/// <summary>
/// Represents a cell containing formula
/// </summary>
internal class XlsBiffFormulaCell : XlsBiffNumberCell
{
internal XlsBiffFormulaCell(byte[] bytes, uint offset)
: base(bytes, offset)
{
}
[Flags]
public enum FormulaFlags : ushort
{
AlwaysCalc = 0x0001,
CalcOnLoad = 0x0002,
SharedFormulaGroup = 0x0008
}
/// <summary>
/// Gets the formula flags
/// </summary>
public FormulaFlags Flags => (FormulaFlags)ReadUInt16(0xE);
/// <summary>
/// Gets the formula string length.
/// </summary>
public byte FormulaLength => ReadByte(0xF);
public byte FormulaValueByte1 => ReadByte(0x6);
public byte FormulaValueByte2 => ReadByte(0x7);
public byte FormulaValueByte3 => ReadByte(0x8);
public byte FormulaValueByte4 => ReadByte(0x9);
public byte FormulaValueByte5 => ReadByte(0xA);
public byte FormulaValueByte6 => ReadByte(0xB);
public ushort FormulaValueExprO => ReadUInt16(0xC);
/// <summary>
/// Gets a value indicating whether a string value is stored in a String record that immediately follows this record. See [MS-XLS] 2.5.133 FormulaValue
/// </summary>
public bool IsString => FormulaValueExprO == 0xFFFF && FormulaValueByte1 == 0x00;
/// <summary>
/// Gets a value indicating whether the BooleanValue property is valid.
/// </summary>
public bool IsBoolean => FormulaValueExprO == 0xFFFF && FormulaValueByte1 == 0x01;
/// <summary>
/// Gets a value indicating whether the ErrorValue property is valid.
/// </summary>
public bool IsError => FormulaValueExprO == 0xFFFF && FormulaValueByte1 == 0x02;
/// <summary>
/// Gets a value indicating whether the XNumValue property is valid.
/// </summary>
public bool IsXNum => FormulaValueExprO != 0xFFFF;
/// <summary>
/// Gets a value indicating whether the formula value is an empty string.
/// </summary>
public bool IsEmptyString => FormulaValueExprO == 0xFFFF && FormulaValueByte1 == 0x03;
public bool BooleanValue => FormulaValueByte3 != 0;
public FORMULAERROR ErrorValue => (FORMULAERROR)FormulaValueByte3;
public double XNumValue => ReadDouble(0x6);
public string Formula
{
get
{
byte[] bts = ReadArray(0x10, FormulaLength);
return Encoding.Unicode.GetString(bts, 0, bts.Length);
}
}
}
}<file_sep>// ReSharper disable InconsistentNaming
namespace ExcelDataReader.Core.OpenXmlFormat
{
internal class XlsxWorksheet
{
public const string NDimension = "dimension";
public const string NWorksheet = "worksheet";
public const string NRow = "row";
public const string NCol = "col";
public const string NC = "c"; // cell
public const string NV = "v";
public const string NT = "t";
public const string ARef = "ref";
public const string AR = "r";
public const string AT = "t";
public const string AS = "s";
public const string NSheetData = "sheetData";
public const string NInlineStr = "inlineStr";
public XlsxWorksheet(string name, int id, string rid, string visibleState)
{
Name = name;
Id = id;
Rid = rid;
VisibleState = string.IsNullOrEmpty(visibleState) ? "visible" : visibleState.ToLower();
}
public bool IsEmpty { get; set; }
public XlsxDimension Dimension { get; set; }
public int ColumnsCount => IsEmpty ? 0 : (Dimension?.LastCol ?? -1);
public int RowsCount => Dimension == null ? -1 : Dimension.LastRow - Dimension.FirstRow + 1;
public string Name { get; }
public string VisibleState { get; }
public int Id { get; }
public string Rid { get; set; }
public string Path { get; set; }
}
}
<file_sep>// #define DEBUGREADERS
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using ExcelDataReader.Core;
using ExcelDataReader.Core.OpenXmlFormat;
namespace ExcelDataReader
{
public partial class ExcelOpenXmlReader : IExcelDataReader
{
private const string ElementSheet = "sheet";
private const string ElementT = "t";
private const string ElementStringItem = "si";
private const string ElementCellCrossReference = "cellXfs";
private const string ElementNumberFormats = "numFmts";
private const string AttributeSheetId = "sheetId";
private const string AttributeVisibleState = "state";
private const string AttributeName = "name";
private const string AttributeRelationshipId = "r:id";
private const string ElementRelationship = "Relationship";
private const string AttributeId = "Id";
private const string AttributeTarget = "Target";
private readonly List<int> _defaultDateTimeStyles;
private XlsxWorkbook _workbook;
private bool _isFirstRead;
private int _resultIndex;
private int _emptyRowCount;
private ZipWorker _zipWorker;
private XmlReader _xmlReader;
private Stream _sheetStream;
private string[] _cellsNames;
private object[] _cellsValues;
private object[] _savedCellsValues;
private string _namespaceUri;
public ExcelOpenXmlReader(Stream stream)
{
_isFirstRead = true;
_defaultDateTimeStyles = new List<int>(new[]
{
14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47
});
_zipWorker = new ZipWorker(stream);
ReadGlobals();
}
private static List<XlsxWorksheet> ReadWorkbook(Stream xmlFileStream)
{
var sheets = new List<XlsxWorksheet>();
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == ElementSheet)
{
sheets.Add(new XlsxWorksheet(
reader.GetAttribute(AttributeName),
int.Parse(reader.GetAttribute(AttributeSheetId)),
reader.GetAttribute(AttributeRelationshipId),
reader.GetAttribute(AttributeVisibleState)));
}
}
}
return sheets;
}
private static void ReadWorkbookRels(Stream xmlFileStream, List<XlsxWorksheet> sheets)
{
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == ElementRelationship)
{
string rid = reader.GetAttribute(AttributeId);
for (int i = 0; i < sheets.Count; i++)
{
XlsxWorksheet tempSheet = sheets[i];
if (tempSheet.Rid == rid)
{
tempSheet.Path = reader.GetAttribute(AttributeTarget);
sheets[i] = tempSheet;
break;
}
}
}
}
}
}
private static XlsxSST ReadSharedStrings(Stream xmlFileStream)
{
if (xmlFileStream == null)
return null;
var sst = new XlsxSST();
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
// Skip phonetic string data.
bool bSkipPhonetic = false;
// There are multiple <t> in a <si>. Concatenate <t> within an <si>.
bool bAddStringItem = false;
string sStringItem = string.Empty;
while (reader.Read())
{
// There are multiple <t> in a <si>. Concatenate <t> within an <si>.
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == ElementStringItem)
{
// Do not add the string item until the next string item is read.
if (bAddStringItem)
{
// Add the string item to XlsxSST.
sst.Add(sStringItem);
}
else
{
// Add the string items from here on.
bAddStringItem = true;
}
// Reset the string item.
sStringItem = string.Empty;
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == ElementT)
{
// Skip phonetic string data.
if (!bSkipPhonetic)
{
// Append to the string item.
sStringItem += reader.ReadElementContentAsString();
}
}
if (reader.LocalName == "rPh")
{
// Phonetic items represents pronunciation hints for some East Asian languages.
// In the file 'xl/sharedStrings.xml', the phonetic properties appear like:
// <si>
// <t>(a japanese text in KANJI)</t>
// <rPh sb="0" eb="1">
// <t>(its pronounciation in KATAKANA)</t>
// </rPh>
// </si>
if (reader.NodeType == XmlNodeType.Element)
bSkipPhonetic = true;
else if (reader.NodeType == XmlNodeType.EndElement)
bSkipPhonetic = false;
}
}
// Do not add the last string item unless we have read previous string items.
if (bAddStringItem)
{
// Add the string item to XlsxSST.
sst.Add(sStringItem);
}
}
return sst;
}
private static XlsxStyles ReadStyles(Stream xmlFileStream)
{
var styles = new XlsxStyles();
if (xmlFileStream == null)
return styles;
bool rXlsxNumFmt = false;
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
while (reader.Read())
{
if (!rXlsxNumFmt && reader.NodeType == XmlNodeType.Element && reader.LocalName == ElementNumberFormats)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1)
break;
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == XlsxNumFmt.NNumFmt)
{
styles.NumFmts.Add(
new XlsxNumFmt(
int.Parse(reader.GetAttribute(XlsxNumFmt.ANumFmtId)),
reader.GetAttribute(XlsxNumFmt.AFormatCode)));
}
}
rXlsxNumFmt = true;
}
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == ElementCellCrossReference)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1)
break;
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == XlsxXf.NXF)
{
var xfId = reader.GetAttribute(XlsxXf.AXFId);
var numFmtId = reader.GetAttribute(XlsxXf.ANumFmtId);
styles.CellXfs.Add(
new XlsxXf(
xfId == null ? -1 : int.Parse(xfId),
numFmtId == null ? -1 : int.Parse(numFmtId),
reader.GetAttribute(XlsxXf.AApplyNumberFormat)));
}
}
break;
}
}
}
return styles;
}
private void ReadGlobals()
{
List<XlsxWorksheet> sheets;
XlsxSST sst;
XlsxStyles styles;
using (var stream = _zipWorker.GetWorkbookStream())
{
sheets = ReadWorkbook(stream);
}
using (var stream = _zipWorker.GetWorkbookRelsStream())
{
ReadWorkbookRels(stream, sheets);
}
using (var stream = _zipWorker.GetSharedStringsStream())
{
sst = ReadSharedStrings(stream);
}
using (var stream = _zipWorker.GetStylesStream())
{
styles = ReadStyles(stream);
}
_workbook = new XlsxWorkbook(sheets, sst, styles);
CheckDateTimeNumFmts(_workbook.Styles.NumFmts);
}
private void CheckDateTimeNumFmts(List<XlsxNumFmt> list)
{
if (list.Count == 0)
return;
foreach (XlsxNumFmt numFmt in list)
{
if (string.IsNullOrEmpty(numFmt.FormatCode))
continue;
string fc = numFmt.FormatCode.ToLower();
int pos;
while ((pos = fc.IndexOf('"')) > 0)
{
int endPos = fc.IndexOf('"', pos + 1);
if (endPos > 0)
fc = fc.Remove(pos, endPos - pos + 1);
}
// it should only detect it as a date if it contains
// dd mm mmm yy yyyy
// h hh ss
// AM PM
// and only if these appear as "words" so either contained in [ ]
// or delimted in someway
// updated to not detect as date if format contains a #
var formatReader = new FormatReader { FormatString = fc };
if (formatReader.IsDateFormatString())
{
_defaultDateTimeStyles.Add(numFmt.Id);
}
}
}
private void ReadSheetGlobals(XlsxWorksheet sheet)
{
((IDisposable)_xmlReader)?.Dispose();
_sheetStream?.Dispose();
_sheetStream = _zipWorker.GetWorksheetStream(sheet.Path);
if (_sheetStream == null)
return;
_xmlReader = XmlReader.Create(_sheetStream);
// count rows and cols in case there is no dimension elements
int rows = 0;
int cols = 0;
bool foundDimension = false;
_namespaceUri = null;
int biggestColumn = 0; // used when no col elements and no dimension
int cellElementsInRow = 0;
while (_xmlReader.Read())
{
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.NWorksheet)
{
// grab the namespaceuri from the worksheet element
_namespaceUri = _xmlReader.NamespaceURI;
}
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.NDimension)
{
string dimValue = _xmlReader.GetAttribute(XlsxWorksheet.ARef);
var dimension = new XlsxDimension(dimValue);
if (dimension.IsRange)
{
sheet.Dimension = dimension;
foundDimension = true;
break;
}
}
// removed: Do not use col to work out number of columns as this is really for defining formatting, so may not contain all columns
/*if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_col)
cols++;*/
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.NRow)
{
biggestColumn = Math.Max(biggestColumn, cellElementsInRow);
cellElementsInRow = 0;
rows++;
}
// check cells so we can find size of sheet if can't work it out from dimension or col elements (dimension should have been set before the cells if it was available)
// ditto for cols
if (cols == 0 && _xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.NC)
{
cellElementsInRow++;
var refAttribute = _xmlReader.GetAttribute(XlsxWorksheet.AR);
if (refAttribute != null)
{
int column;
ReferenceHelper.ParseReference(refAttribute, out column);
if (column > biggestColumn)
biggestColumn = column;
}
}
}
biggestColumn = Math.Max(biggestColumn, cellElementsInRow);
// if we didn't get a dimension element then use the calculated rows/cols to create it
if (!foundDimension)
{
if (cols == 0)
cols = biggestColumn;
if (rows == 0 || cols == 0)
{
sheet.IsEmpty = true;
return;
}
sheet.Dimension = new XlsxDimension(rows, cols);
// we need to reset our position to sheet data
((IDisposable)_xmlReader).Dispose();
_sheetStream.Dispose();
_sheetStream = _zipWorker.GetWorksheetStream(sheet.Path);
_xmlReader = XmlReader.Create(_sheetStream);
}
// read up to the sheetData element. if this element is empty then there aren't any rows and we need to null out dimension
_xmlReader.ReadToFollowing(XlsxWorksheet.NSheetData, _namespaceUri);
if (_xmlReader.IsEmptyElement)
{
sheet.IsEmpty = true;
}
}
private bool ReadSheetRow(XlsxWorksheet sheet)
{
if (_xmlReader == null)
return false;
if (_emptyRowCount != 0)
{
_cellsValues = new object[sheet.ColumnsCount];
_emptyRowCount--;
Depth++;
return true;
}
if (_savedCellsValues != null)
{
_cellsValues = _savedCellsValues;
_savedCellsValues = null;
Depth++;
return true;
}
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.NRow ||
_xmlReader.ReadToFollowing(XlsxWorksheet.NRow, _namespaceUri))
{
_cellsValues = new object[sheet.ColumnsCount];
int rowIndex;
if (!int.TryParse(_xmlReader.GetAttribute(XlsxWorksheet.AR), out rowIndex))
rowIndex = Depth + 1;
if (rowIndex != (Depth + 1))
{
_emptyRowCount = rowIndex - Depth - 1;
}
bool hasValue = false;
string aS = string.Empty;
string aT = string.Empty;
string aR = string.Empty;
int col = 0;
while (_xmlReader.Read())
{
if (_xmlReader.Depth == 2)
break;
if (_xmlReader.NodeType == XmlNodeType.Element)
{
hasValue = false;
if (_xmlReader.LocalName == XlsxWorksheet.NC)
{
aS = _xmlReader.GetAttribute(XlsxWorksheet.AS);
aT = _xmlReader.GetAttribute(XlsxWorksheet.AT);
aR = _xmlReader.GetAttribute(XlsxWorksheet.AR);
if (aR != null)
{
ReferenceHelper.ParseReference(aR, out col);
}
else
{
++col;
}
}
else if (_xmlReader.LocalName == XlsxWorksheet.NV || _xmlReader.LocalName == XlsxWorksheet.NT)
{
hasValue = true;
}
}
if (_xmlReader.NodeType == XmlNodeType.Text && hasValue)
{
double number;
object o = _xmlReader.Value;
const NumberStyles style = NumberStyles.Any;
var culture = CultureInfo.InvariantCulture;
if (double.TryParse(o.ToString(), style, culture, out number))
o = number;
if (aT != null && aT == XlsxWorksheet.AS) //// if string
{
o = Helpers.ConvertEscapeChars(_workbook.SST[int.Parse(o.ToString())]);
} // Requested change 4: missing (it appears that if should be else if)
else if (aT != null && aT == XlsxWorksheet.NInlineStr) //// if string inline
{
o = Helpers.ConvertEscapeChars(o.ToString());
}
else if (aT == "b") //// boolean
{
o = _xmlReader.Value == "1";
}
else if (aS != null) //// if something else
{
XlsxXf xf = _workbook.Styles.CellXfs[int.Parse(aS)];
if (o != null && o.ToString() != string.Empty && IsDateTimeStyle(xf.NumFmtId))
o = Helpers.ConvertFromOATime(number);
else if (xf.NumFmtId == 49)
o = o.ToString();
}
if (col - 1 < _cellsValues.Length)
_cellsValues[col - 1] = o;
}
}
if (_emptyRowCount > 0)
{
_savedCellsValues = _cellsValues;
return ReadSheetRow(sheet);
}
Depth++;
return true;
}
((IDisposable)_xmlReader).Dispose();
_sheetStream?.Dispose();
return false;
}
private bool InitializeSheetRead()
{
if (ResultsCount <= 0)
return false;
ReadSheetGlobals(_workbook.Sheets[_resultIndex]);
if (_workbook.Sheets[_resultIndex].Dimension == null)
return false;
_isFirstRead = false;
Depth = 0;
_emptyRowCount = 0;
return true;
}
private bool IsDateTimeStyle(int styleId)
{
return _defaultDateTimeStyles.Contains(styleId);
}
}
public partial class ExcelOpenXmlReader
{
~ExcelOpenXmlReader()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
Close();
}
}
public partial class ExcelOpenXmlReader
{
public bool IsFirstRowAsColumnNames { get; set; }
public bool ConvertOaDate { get; set; }
public ReadOption ReadOption { get; set; }
public Encoding Encoding => null;
public string Name => _resultIndex >= 0 && _resultIndex < ResultsCount ? _workbook.Sheets[_resultIndex].Name : null;
public string VisibleState => _resultIndex >= 0 && _resultIndex < ResultsCount ? _workbook.Sheets[_resultIndex].VisibleState : null;
public int Depth { get; private set; }
public int ResultsCount => _workbook?.Sheets.Count ?? -1;
public bool IsClosed { get; private set; }
public int FieldCount => _resultIndex >= 0 && _resultIndex < ResultsCount ? _workbook.Sheets[_resultIndex].ColumnsCount : -1;
public int RecordsAffected => throw new NotSupportedException();
public object this[int i] => _cellsValues[i];
public object this[string name] => throw new NotSupportedException();
public void Reset()
{
_resultIndex = 0;
_isFirstRead = true;
_savedCellsValues = null;
}
public void Close()
{
if (IsClosed)
return;
((IDisposable)_xmlReader)?.Dispose();
_sheetStream?.Dispose();
_zipWorker?.Dispose();
_zipWorker = null;
_xmlReader = null;
_sheetStream = null;
_workbook = null;
_cellsValues = null;
_savedCellsValues = null;
IsClosed = true;
}
public bool NextResult()
{
if (_resultIndex >= ResultsCount - 1)
return false;
_resultIndex++;
_isFirstRead = true;
_savedCellsValues = null;
return true;
}
public bool Read()
{
if (_isFirstRead)
{
var initializeSheetRead = InitializeSheetRead();
if (!initializeSheetRead)
return false;
if (IsFirstRowAsColumnNames)
{
if (ReadSheetRow(_workbook.Sheets[_resultIndex]))
{
_cellsNames = new string[_cellsValues.Length];
for (var i = 0; i < _cellsValues.Length; i++)
{
var value = _cellsValues[i]?.ToString();
if (!string.IsNullOrEmpty(value))
_cellsNames[i] = value;
}
}
else
{
return false;
}
}
else
{
_cellsNames = null;
}
}
return ReadSheetRow(_workbook.Sheets[_resultIndex]);
}
public bool GetBoolean(int i)
{
return !IsDBNull(i) && bool.Parse(_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i))
return DateTime.MinValue;
try
{
return (DateTime)_cellsValues[i];
}
catch (InvalidCastException)
{
return DateTime.MinValue;
}
}
public decimal GetDecimal(int i)
{
return IsDBNull(i) ? decimal.MinValue : decimal.Parse(_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
return IsDBNull(i) ? double.MinValue : double.Parse(_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
return IsDBNull(i) ? float.MinValue : float.Parse(_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
return IsDBNull(i) ? short.MinValue : short.Parse(_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
return IsDBNull(i) ? int.MinValue : int.Parse(_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
return IsDBNull(i) ? long.MinValue : long.Parse(_cellsValues[i].ToString());
}
public string GetString(int i)
{
return IsDBNull(i) ? null : _cellsValues[i].ToString();
}
public object GetValue(int i)
{
return _cellsValues[i];
}
public bool IsDBNull(int i)
{
return _cellsValues[i] == null;
}
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
if (_cellsValues[i] == null)
return null;
return _cellsValues[i].GetType();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
return _cellsNames?[i];
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
/// <inheritdoc />
public DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using ExcelDataReader.Core.BinaryFormat;
using ExcelDataReader.Exceptions;
using ExcelDataReader.Misc;
namespace ExcelDataReader
{
/// <summary>
/// Strict is as normal, Loose is more forgiving and will not cause an exception if a record size takes it beyond the end of the file. It will be trunacted in this case (SQl Reporting Services)
/// </summary>
public enum ReadOption
{
Strict,
Loose
}
/// <summary>
/// ExcelDataReader Class
/// </summary>
public partial class ExcelBinaryReader : IExcelDataReader
{
private const string Workbook = "Workbook";
private const string Book = "Book";
private Stream _file;
private XlsDocument _document;
private XlsWorkbook _workbook;
private bool _isFirstRead;
private string[] _cellsNames;
private IEnumerator<XlsWorksheet> _worksheetIterator = null;
private IEnumerator<object[]> _rowIterator = null;
public ExcelBinaryReader(Stream stream)
: this(stream, true, ReadOption.Strict)
{
}
public ExcelBinaryReader(Stream stream, ReadOption readOption)
: this(stream, true, readOption)
{
}
public ExcelBinaryReader(Stream stream, bool convertOADate, ReadOption readOption)
{
_file = stream;
ReadOption = readOption;
_document = new XlsDocument(stream);
_workbook = ReadWorkbook(convertOADate);
// By default, the data reader is positioned on the first result.
Reset();
}
private object[] CellsValues => _rowIterator?.Current;
private XlsWorkbook ReadWorkbook(bool convertOADate)
{
XlsDirectoryEntry workbookEntry = _document.FindEntry(Workbook) ?? _document.FindEntry(Book);
if (workbookEntry == null)
{
throw new ExcelReaderException(Errors.ErrorStreamWorkbookNotFound);
}
if (workbookEntry.EntryType != STGTY.STGTY_STREAM)
{
throw new ExcelReaderException(Errors.ErrorWorkbookIsNotStream);
}
var bytes = _document.ReadStream(_file, workbookEntry.StreamFirstSector, (int)workbookEntry.StreamSize, workbookEntry.IsEntryMiniStream);
return new XlsWorkbook(bytes, convertOADate, ReadOption);
}
private void ResetSheetData()
{
_isFirstRead = true;
Depth = -1;
}
}
// IDisposable implementation
public partial class ExcelBinaryReader
{
~ExcelBinaryReader()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
Close();
}
}
// IExcelDataReader implementation.
public partial class ExcelBinaryReader
{
public bool IsFirstRowAsColumnNames { get; set; }
public ReadOption ReadOption { get; }
public Encoding Encoding => _workbook.Encoding;
public string Name => _worksheetIterator?.Current?.Name;
public string VisibleState => _worksheetIterator?.Current?.VisibleState;
public int Depth { get; private set; }
public int ResultsCount => _workbook.Sheets.Count;
public bool IsClosed { get; private set; }
public int FieldCount => _worksheetIterator?.Current?.FieldCount ?? 0;
public int RecordsAffected => throw new NotSupportedException();
public object this[int i] => CellsValues[i];
public object this[string name] => throw new NotSupportedException();
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
return CellsValues[i]?.GetType();
}
public string GetName(int i)
{
return _cellsNames?[i];
}
/// <inheritdoc />
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
/// <inheritdoc />
public DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public void Reset()
{
_worksheetIterator?.Dispose();
_rowIterator?.Dispose();
_worksheetIterator = null;
_rowIterator = null;
ResetSheetData();
if (_workbook != null) {
_worksheetIterator = _workbook.ReadWorksheets().GetEnumerator();
if (!_worksheetIterator.MoveNext())
{
_worksheetIterator.Dispose();
_worksheetIterator = null;
return;
}
_rowIterator = _worksheetIterator.Current.ReadRows().GetEnumerator();
}
}
public void Close()
{
if (IsClosed)
return;
_worksheetIterator?.Dispose();
_rowIterator?.Dispose();
_file?.Dispose();
_worksheetIterator = null;
_rowIterator = null;
_workbook = null;
_document = null;
_file = null;
IsClosed = true;
}
public bool NextResult()
{
if (_worksheetIterator == null)
{
return false;
}
ResetSheetData();
_rowIterator?.Dispose();
_rowIterator = null;
if (!_worksheetIterator.MoveNext())
{
_worksheetIterator.Dispose();
_worksheetIterator = null;
return false;
}
_rowIterator = _worksheetIterator.Current.ReadRows().GetEnumerator();
return true;
}
public bool Read()
{
if (_worksheetIterator == null || _rowIterator == null)
{
return false;
}
if (!_rowIterator.MoveNext())
{
_rowIterator.Dispose();
_rowIterator = null;
return false;
}
if (_isFirstRead)
{
_isFirstRead = false;
if (IsFirstRowAsColumnNames)
{
_cellsNames = new string[CellsValues.Length];
for (var i = 0; i < CellsValues.Length; i++)
{
var value = CellsValues[i]?.ToString();
if (!string.IsNullOrEmpty(value))
{
_cellsNames[i] = value;
}
}
if (!_rowIterator.MoveNext())
{
_rowIterator.Dispose();
_rowIterator = null;
return false;
}
}
else
{
_cellsNames = null; // no columns
}
}
Depth++;
return true;
}
public bool GetBoolean(int i)
{
return !IsDBNull(i) && bool.Parse(CellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i))
return DateTime.MinValue;
// requested change: 3
object val = CellsValues[i];
if (val is DateTime)
{
// if the value is already a datetime.. return it without further conversion
return (DateTime)val;
}
// otherwise proceed with conversion attempts
string valString = val.ToString();
double dVal;
try
{
dVal = double.Parse(valString);
}
catch (FormatException)
{
return DateTime.Parse(valString);
}
return DateTimeHelper.FromOADate(dVal);
}
public decimal GetDecimal(int i)
{
return IsDBNull(i) ? decimal.MinValue : decimal.Parse(CellsValues[i].ToString());
}
public double GetDouble(int i)
{
return IsDBNull(i) ? double.MinValue : double.Parse(CellsValues[i].ToString());
}
public float GetFloat(int i)
{
return IsDBNull(i) ? float.MinValue : float.Parse(CellsValues[i].ToString());
}
public short GetInt16(int i)
{
return IsDBNull(i) ? short.MinValue : short.Parse(CellsValues[i].ToString());
}
public int GetInt32(int i)
{
return IsDBNull(i) ? int.MinValue : int.Parse(CellsValues[i].ToString());
}
public long GetInt64(int i)
{
return IsDBNull(i) ? long.MinValue : long.Parse(CellsValues[i].ToString());
}
public string GetString(int i)
{
return IsDBNull(i) ? null : CellsValues[i].ToString();
}
public object GetValue(int i)
{
return CellsValues[i];
}
public bool IsDBNull(int i)
{
return CellsValues[i] == null;
}
}
} | e2b641203578421cdda7bf9cc0ad96631dd176ec | [
"Markdown",
"C#"
] | 8 | C# | jonathanmorley/ExcelDataReader | 710d26ff698cb0f0a66f2669a13219de4da1347a | 43ab85ef00c641a6c39e62ea92a77e3ef119cf76 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(575, 680)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_uno = QtWidgets.QPushButton(self.centralwidget)
self.btn_uno.setGeometry(QtCore.QRect(10, 10, 61, 51))
self.btn_uno.setText("")
self.btn_uno.setObjectName("btn_uno")
self.btn_uno.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_due = QtWidgets.QPushButton(self.centralwidget)
self.btn_due.setGeometry(QtCore.QRect(80, 10, 61, 51))
self.btn_due.setText("")
self.btn_due.setObjectName("btn_due")
self.btn_due.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_tre = QtWidgets.QPushButton(self.centralwidget)
self.btn_tre.setGeometry(QtCore.QRect(150, 10, 61, 51))
self.btn_tre.setText("")
self.btn_tre.setObjectName("btn_tre")
self.btn_tre.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quattro = QtWidgets.QPushButton(self.centralwidget)
self.btn_quattro.setGeometry(QtCore.QRect(220, 10, 61, 51))
self.btn_quattro.setText("")
self.btn_quattro.setObjectName("btn_quattro")
self.btn_quattro.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinque = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinque.setGeometry(QtCore.QRect(290, 10, 61, 51))
self.btn_cinque.setText("")
self.btn_cinque.setObjectName("btn_cinque")
self.btn_cinque.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sei = QtWidgets.QPushButton(self.centralwidget)
self.btn_sei.setGeometry(QtCore.QRect(360, 10, 61, 51))
self.btn_sei.setText("")
self.btn_sei.setObjectName("btn_sei")
self.btn_sei.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sette = QtWidgets.QPushButton(self.centralwidget)
self.btn_sette.setGeometry(QtCore.QRect(430, 10, 61, 51))
self.btn_sette.setText("")
self.btn_sette.setObjectName("btn_sette")
self.btn_sette.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_otto = QtWidgets.QPushButton(self.centralwidget)
self.btn_otto.setGeometry(QtCore.QRect(500, 10, 61, 51))
self.btn_otto.setText("")
self.btn_otto.setObjectName("btn_otto")
self.btn_otto.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_nove = QtWidgets.QPushButton(self.centralwidget)
self.btn_nove.setGeometry(QtCore.QRect(10, 70, 61, 51))
self.btn_nove.setText("")
self.btn_nove.setObjectName("btn_nove")
self.btn_nove.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_dieci = QtWidgets.QPushButton(self.centralwidget)
self.btn_dieci.setGeometry(QtCore.QRect(80, 70, 61, 51))
self.btn_dieci.setText("")
self.btn_dieci.setObjectName("btn_dieci")
self.btn_dieci.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_undici = QtWidgets.QPushButton(self.centralwidget)
self.btn_undici.setGeometry(QtCore.QRect(150, 70, 61, 51))
self.btn_undici.setText("")
self.btn_undici.setObjectName("btn_undici")
self.btn_undici.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_dodici = QtWidgets.QPushButton(self.centralwidget)
self.btn_dodici.setGeometry(QtCore.QRect(220, 70, 61, 51))
self.btn_dodici.setText("")
self.btn_dodici.setObjectName("btn_dodici")
self.btn_dodici.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_tredici = QtWidgets.QPushButton(self.centralwidget)
self.btn_tredici.setGeometry(QtCore.QRect(290, 70, 61, 51))
self.btn_tredici.setText("")
self.btn_tredici.setObjectName("btn_tredici")
self.btn_tredici.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quattordici = QtWidgets.QPushButton(self.centralwidget)
self.btn_quattordici.setGeometry(QtCore.QRect(360, 70, 61, 51))
self.btn_quattordici.setText("")
self.btn_quattordici.setObjectName("btn_quattordici")
self.btn_quattordici.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quindici = QtWidgets.QPushButton(self.centralwidget)
self.btn_quindici.setGeometry(QtCore.QRect(430, 70, 61, 51))
self.btn_quindici.setText("")
self.btn_quindici.setObjectName("btn_quindici")
self.btn_quindici.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sedici = QtWidgets.QPushButton(self.centralwidget)
self.btn_sedici.setGeometry(QtCore.QRect(500, 70, 61, 51))
self.btn_sedici.setText("")
self.btn_sedici.setObjectName("btn_sedici")
self.btn_sedici.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_diciassette = QtWidgets.QPushButton(self.centralwidget)
self.btn_diciassette.setGeometry(QtCore.QRect(10, 130, 61, 51))
self.btn_diciassette.setText("")
self.btn_diciassette.setObjectName("btn_diciassette")
self.btn_diciassette.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_diciotto = QtWidgets.QPushButton(self.centralwidget)
self.btn_diciotto.setGeometry(QtCore.QRect(80, 130, 61, 51))
self.btn_diciotto.setText("")
self.btn_diciotto.setObjectName("btn_diciotto")
self.btn_diciotto.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_diciannove = QtWidgets.QPushButton(self.centralwidget)
self.btn_diciannove.setGeometry(QtCore.QRect(150, 130, 61, 51))
self.btn_diciannove.setText("")
self.btn_diciannove.setObjectName("btn_diciannove")
self.btn_diciannove.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_venti = QtWidgets.QPushButton(self.centralwidget)
self.btn_venti.setGeometry(QtCore.QRect(220, 130, 61, 51))
self.btn_venti.setText("")
self.btn_venti.setObjectName("btn_venti")
self.btn_venti.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventuno = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventuno.setGeometry(QtCore.QRect(290, 130, 61, 51))
self.btn_ventuno.setText("")
self.btn_ventuno.setObjectName("btn_ventuno")
self.btn_ventuno.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventidue = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventidue.setGeometry(QtCore.QRect(360, 130, 61, 51))
self.btn_ventidue.setText("")
self.btn_ventidue.setObjectName("btn_ventidue")
self.btn_ventidue.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventitre = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventitre.setGeometry(QtCore.QRect(430, 130, 61, 51))
self.btn_ventitre.setText("")
self.btn_ventitre.setObjectName("btn_ventitre")
self.btn_ventitre.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventiquattro = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventiquattro.setGeometry(QtCore.QRect(500, 130, 61, 51))
self.btn_ventiquattro.setText("")
self.btn_ventiquattro.setObjectName("btn_ventiquattro")
self.btn_ventiquattro.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_venticinque = QtWidgets.QPushButton(self.centralwidget)
self.btn_venticinque.setGeometry(QtCore.QRect(10, 190, 61, 51))
self.btn_venticinque.setText("")
self.btn_venticinque.setObjectName("btn_venticinque")
self.btn_venticinque.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventisei = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventisei.setGeometry(QtCore.QRect(80, 190, 61, 51))
self.btn_ventisei.setText("")
self.btn_ventisei.setObjectName("btn_ventisei")
self.btn_ventisei.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventisette = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventisette.setGeometry(QtCore.QRect(150, 190, 61, 51))
self.btn_ventisette.setText("")
self.btn_ventisette.setObjectName("btn_ventisette")
self.btn_ventisette.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventotto = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventotto.setGeometry(QtCore.QRect(220, 190, 61, 51))
self.btn_ventotto.setText("")
self.btn_ventotto.setObjectName("btn_ventotto")
self.btn_ventotto.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_ventinove = QtWidgets.QPushButton(self.centralwidget)
self.btn_ventinove.setGeometry(QtCore.QRect(290, 190, 61, 51))
self.btn_ventinove.setText("")
self.btn_ventinove.setObjectName("btn_ventinove")
self.btn_ventinove.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trenta = QtWidgets.QPushButton(self.centralwidget)
self.btn_trenta.setGeometry(QtCore.QRect(360, 190, 61, 51))
self.btn_trenta.setText("")
self.btn_trenta.setObjectName("btn_trenta")
self.btn_trenta.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentuno = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentuno.setGeometry(QtCore.QRect(430, 190, 61, 51))
self.btn_trentuno.setText("")
self.btn_trentuno.setObjectName("btn_trentuno")
self.btn_trentuno.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentadue = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentadue.setGeometry(QtCore.QRect(500, 190, 61, 51))
self.btn_trentadue.setText("")
self.btn_trentadue.setObjectName("btn_trentadue")
self.btn_trentadue.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentatre = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentatre.setGeometry(QtCore.QRect(10, 250, 61, 51))
self.btn_trentatre.setText("")
self.btn_trentatre.setObjectName("btn_trentatre")
self.btn_trentatre.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentaquattro = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentaquattro.setGeometry(QtCore.QRect(80, 250, 61, 51))
self.btn_trentaquattro.setText("")
self.btn_trentaquattro.setObjectName("btn_trentaquattro")
self.btn_trentaquattro.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentacinque = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentacinque.setGeometry(QtCore.QRect(150, 250, 61, 51))
self.btn_trentacinque.setText("")
self.btn_trentacinque.setObjectName("btn_trentacinque")
self.btn_trentacinque.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentasei = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentasei.setGeometry(QtCore.QRect(220, 250, 61, 51))
self.btn_trentasei.setText("")
self.btn_trentasei.setObjectName("btn_trentasei")
self.btn_trentasei.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentasette = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentasette.setGeometry(QtCore.QRect(290, 250, 61, 51))
self.btn_trentasette.setText("")
self.btn_trentasette.setObjectName("btn_trentasette")
self.btn_trentasette.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentotto = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentotto.setGeometry(QtCore.QRect(360, 250, 61, 51))
self.btn_trentotto.setText("")
self.btn_trentotto.setObjectName("btn_trentotto")
self.btn_trentotto.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_trentanove = QtWidgets.QPushButton(self.centralwidget)
self.btn_trentanove.setGeometry(QtCore.QRect(430, 250, 61, 51))
self.btn_trentanove.setText("")
self.btn_trentanove.setObjectName("btn_trentanove")
self.btn_trentanove.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quaranta = QtWidgets.QPushButton(self.centralwidget)
self.btn_quaranta.setGeometry(QtCore.QRect(500, 250, 61, 51))
self.btn_quaranta.setText("")
self.btn_quaranta.setObjectName("btn_quaranta")
self.btn_quaranta.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantuno = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantuno.setGeometry(QtCore.QRect(10, 310, 61, 51))
self.btn_quarantuno.setText("")
self.btn_quarantuno.setObjectName("btn_quarantuno")
self.btn_quarantuno.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantadue = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantadue.setGeometry(QtCore.QRect(80, 310, 61, 51))
self.btn_quarantadue.setText("")
self.btn_quarantadue.setObjectName("btn_quarantadue")
self.btn_quarantadue.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantatre = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantatre.setGeometry(QtCore.QRect(150, 310, 61, 51))
self.btn_quarantatre.setText("")
self.btn_quarantatre.setObjectName("btn_quarantatre")
self.btn_quarantatre.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantaquattro = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantaquattro.setGeometry(QtCore.QRect(220, 310, 61, 51))
self.btn_quarantaquattro.setText("")
self.btn_quarantaquattro.setObjectName("btn_quarantaquattro")
self.btn_quarantaquattro.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantacinque = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantacinque.setGeometry(QtCore.QRect(290, 310, 61, 51))
self.btn_quarantacinque.setText("")
self.btn_quarantacinque.setObjectName("btn_quarantacinque")
self.btn_quarantacinque.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantasei = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantasei.setGeometry(QtCore.QRect(360, 310, 61, 51))
self.btn_quarantasei.setText("")
self.btn_quarantasei.setObjectName("btn_quarantasei")
self.btn_quarantasei.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantasette = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantasette.setGeometry(QtCore.QRect(430, 310, 61, 51))
self.btn_quarantasette.setText("")
self.btn_quarantasette.setObjectName("btn_quarantasette")
self.btn_quarantasette.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantotto = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantotto.setGeometry(QtCore.QRect(500, 310, 61, 51))
self.btn_quarantotto.setText("")
self.btn_quarantotto.setObjectName("btn_quarantotto")
self.btn_quarantotto.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_quarantanove = QtWidgets.QPushButton(self.centralwidget)
self.btn_quarantanove.setGeometry(QtCore.QRect(10, 370, 61, 51))
self.btn_quarantanove.setText("")
self.btn_quarantanove.setObjectName("btn_quarantanove")
self.btn_quarantanove.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquanta = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquanta.setGeometry(QtCore.QRect(80, 370, 61, 51))
self.btn_cinquanta.setText("")
self.btn_cinquanta.setObjectName("btn_cinquanta")
self.btn_cinquanta.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantuno = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantuno.setGeometry(QtCore.QRect(150, 370, 61, 51))
self.btn_cinquantuno.setText("")
self.btn_cinquantuno.setObjectName("btn_cinquantuno")
self.btn_cinquantuno.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantadue = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantadue.setGeometry(QtCore.QRect(220, 370, 61, 51))
self.btn_cinquantadue.setText("")
self.btn_cinquantadue.setObjectName("btn_cinquantadue")
self.btn_cinquantadue.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantatre = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantatre.setGeometry(QtCore.QRect(290, 370, 61, 51))
self.btn_cinquantatre.setText("")
self.btn_cinquantatre.setObjectName("btn_cinquantatre")
self.btn_cinquantatre.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantaquattro = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantaquattro.setGeometry(QtCore.QRect(360, 370, 61, 51))
self.btn_cinquantaquattro.setText("")
self.btn_cinquantaquattro.setObjectName("btn_cinquantaquattro")
self.btn_cinquantaquattro.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantacinque = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantacinque.setGeometry(QtCore.QRect(430, 370, 61, 51))
self.btn_cinquantacinque.setText("")
self.btn_cinquantacinque.setObjectName("btn_cinquantacinque")
self.btn_cinquantacinque.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantasei = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantasei.setGeometry(QtCore.QRect(500, 370, 61, 51))
self.btn_cinquantasei.setText("")
self.btn_cinquantasei.setObjectName("btn_cinquantasei")
self.btn_cinquantasei.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantasette = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantasette.setGeometry(QtCore.QRect(10, 430, 61, 51))
self.btn_cinquantasette.setText("")
self.btn_cinquantasette.setObjectName("btn_cinquantasette")
self.btn_cinquantasette.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantotto = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantotto.setGeometry(QtCore.QRect(80, 430, 61, 51))
self.btn_cinquantotto.setText("")
self.btn_cinquantotto.setObjectName("btn_cinquantotto")
self.btn_cinquantotto.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_cinquantanove = QtWidgets.QPushButton(self.centralwidget)
self.btn_cinquantanove.setGeometry(QtCore.QRect(150, 430, 61, 51))
self.btn_cinquantanove.setText("")
self.btn_cinquantanove.setObjectName("btn_cinquantanove")
self.btn_cinquantanove.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sessanta = QtWidgets.QPushButton(self.centralwidget)
self.btn_sessanta.setGeometry(QtCore.QRect(220, 430, 61, 51))
self.btn_sessanta.setText("")
self.btn_sessanta.setObjectName("btn_sessanta")
self.btn_sessanta.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sessantuno = QtWidgets.QPushButton(self.centralwidget)
self.btn_sessantuno.setGeometry(QtCore.QRect(290, 430, 61, 51))
self.btn_sessantuno.setText("")
self.btn_sessantuno.setObjectName("btn_sessantuno")
self.btn_sessantuno.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sessantadue = QtWidgets.QPushButton(self.centralwidget)
self.btn_sessantadue.setGeometry(QtCore.QRect(360, 430, 61, 51))
self.btn_sessantadue.setText("")
self.btn_sessantadue.setObjectName("btn_sessantadue")
self.btn_sessantadue.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sessantatre = QtWidgets.QPushButton(self.centralwidget)
self.btn_sessantatre.setGeometry(QtCore.QRect(430, 430, 61, 51))
self.btn_sessantatre.setText("")
self.btn_sessantatre.setObjectName("btn_sessantatre")
self.btn_sessantatre.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_sessantaquattro = QtWidgets.QPushButton(self.centralwidget)
self.btn_sessantaquattro.setGeometry(QtCore.QRect(500, 430, 61, 51))
self.btn_sessantaquattro.setText("")
self.btn_sessantaquattro.setObjectName("btn_sessantaquattro")
self.btn_sessantaquattro.setStyleSheet('background-color:#C0C0C0;color:#000000;')
self.btn_generate_code = QtWidgets.QPushButton(self.centralwidget)
self.btn_generate_code.setGeometry(QtCore.QRect(20, 510, 151, 81))
font = QtGui.QFont()
font.setPointSize(10)
self.btn_generate_code.setFont(font)
self.btn_generate_code.setObjectName("btn_generate_code")
self.txt_array_result = QtWidgets.QTextEdit(self.centralwidget)
self.txt_array_result.setGeometry(QtCore.QRect(200, 510, 361, 87))
self.txt_array_result.setObjectName("txt_array_result")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 575, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_generate_code.setText(_translate("MainWindow", "Generate Code"))
<file_sep>from PyQt5 import QtWidgets
from gui import Ui_MainWindow
import sys
from functools import partial
RIGA_UNO = 1
RIGA_DUE = 2
RIGA_TRE = 3
RIGA_QUATTRO = 4
RIGA_CINQUE = 5
RIGA_SEI = 6
RIGA_SETTE = 7
RIGA_OTTO = 8
class mywindow(QtWidgets.QMainWindow):
def __init__(self):
super(mywindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.row_one = 0
self.row_two = 0
self.row_three = 0
self.row_four = 0
self.row_five = 0
self.row_six = 0
self.row_seven = 0
self.row_eight = 0
self.ui.btn_uno.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 7))
self.ui.btn_due.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 6))
self.ui.btn_tre.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 5))
self.ui.btn_quattro.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 4))
self.ui.btn_cinque.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 3))
self.ui.btn_sei.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 2))
self.ui.btn_sette.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 1))
self.ui.btn_otto.clicked.connect(partial(self.btn_set_led, self.row_one, RIGA_UNO, 0))
self.ui.btn_nove.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 7))
self.ui.btn_dieci.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 6))
self.ui.btn_undici.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 5))
self.ui.btn_dodici.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 4))
self.ui.btn_tredici.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 3))
self.ui.btn_quattordici.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 2))
self.ui.btn_quindici.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 1))
self.ui.btn_sedici.clicked.connect(partial(self.btn_set_led, self.row_two, RIGA_DUE, 0))
self.ui.btn_diciassette.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 7))
self.ui.btn_diciotto.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 6))
self.ui.btn_diciannove.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 5))
self.ui.btn_venti.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 4))
self.ui.btn_ventuno.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 3))
self.ui.btn_ventidue.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 2))
self.ui.btn_ventitre.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 1))
self.ui.btn_ventiquattro.clicked.connect(partial(self.btn_set_led, self.row_three, RIGA_TRE, 0))
self.ui.btn_venticinque.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 7))
self.ui.btn_ventisei.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 6))
self.ui.btn_ventisette.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 5))
self.ui.btn_ventotto.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 4))
self.ui.btn_ventinove.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 3))
self.ui.btn_trenta.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 2))
self.ui.btn_trentuno.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 1))
self.ui.btn_trentadue.clicked.connect(partial(self.btn_set_led, self.row_four, RIGA_QUATTRO, 0))
self.ui.btn_trentatre.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 7))
self.ui.btn_trentaquattro.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 6))
self.ui.btn_trentacinque.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 5))
self.ui.btn_trentasei.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 4))
self.ui.btn_trentasette.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 3))
self.ui.btn_trentotto.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 2))
self.ui.btn_trentanove.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 1))
self.ui.btn_quaranta.clicked.connect(partial(self.btn_set_led, self.row_five, RIGA_CINQUE, 0))
self.ui.btn_quarantuno.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 7))
self.ui.btn_quarantadue.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 6))
self.ui.btn_quarantatre.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 5))
self.ui.btn_quarantaquattro.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 4))
self.ui.btn_quarantacinque.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 3))
self.ui.btn_quarantasei.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 2))
self.ui.btn_quarantasette.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 1))
self.ui.btn_quarantotto.clicked.connect(partial(self.btn_set_led, self.row_six, RIGA_SEI, 0))
self.ui.btn_quarantanove.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 7))
self.ui.btn_cinquanta.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 6))
self.ui.btn_cinquantuno.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 5))
self.ui.btn_cinquantadue.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 4))
self.ui.btn_cinquantatre.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 3))
self.ui.btn_cinquantaquattro.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 2))
self.ui.btn_cinquantacinque.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 1))
self.ui.btn_cinquantasei.clicked.connect(partial(self.btn_set_led, self.row_seven, RIGA_SETTE, 0))
self.ui.btn_cinquantasette.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 7))
self.ui.btn_cinquantotto.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 6))
self.ui.btn_cinquantanove.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 5))
self.ui.btn_sessanta.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 4))
self.ui.btn_sessantuno.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 3))
self.ui.btn_sessantadue.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 2))
self.ui.btn_sessantatre.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 1))
self.ui.btn_sessantaquattro.clicked.connect(partial(self.btn_set_led, self.row_eight, RIGA_OTTO, 0))
self.ui.btn_generate_code.clicked.connect(self.generate_code)
self.ui.txt_array_result.setReadOnly(True)
def btn_set_led(self, _, row, amount_shift):
if(row == RIGA_UNO):
shifted_value = 1 << amount_shift
self.row_one |= shifted_value
self.color_button(row, amount_shift)
elif(row == RIGA_DUE):
shifted_value = 1 << amount_shift
self.row_two |= shifted_value
self.color_button(row, amount_shift)
elif (row == RIGA_TRE):
shifted_value = 1 << amount_shift
self.row_three |= shifted_value
self.color_button(row, amount_shift)
elif (row == RIGA_QUATTRO):
shifted_value = 1 << amount_shift
self.row_four |= shifted_value
self.color_button(row, amount_shift)
elif (row == RIGA_CINQUE):
shifted_value = 1 << amount_shift
self.row_five |= shifted_value
self.color_button(row, amount_shift)
elif (row == RIGA_SEI):
shifted_value = 1 << amount_shift
self.row_six |= shifted_value
self.color_button(row, amount_shift)
elif (row == RIGA_SETTE):
shifted_value = 1 << amount_shift
self.row_seven |= shifted_value
self.color_button(row, amount_shift)
elif (row == RIGA_OTTO):
shifted_value = 1 << amount_shift
self.row_eight |= shifted_value
self.color_button(row, amount_shift)
def btn_clear(self):
print(self.row_one)
self.row_one = ''
print(self.row_one)
def generate_code(self):
print('0x{:02x}'.format(self.row_one))
print('0x{:02x}'.format(self.row_two))
print('0x{:02x}'.format(self.row_three))
print('0x{:02x}'.format(self.row_four))
print('0x{:02x}'.format(self.row_five))
print('0x{:02x}'.format(self.row_six))
print('0x{:02x}'.format(self.row_seven))
print('0x{:02x}'.format(self.row_eight))
# Write reulsting array inside textbox
self.ui.txt_array_result.insertPlainText('{' + '0x{:02x}'.format(self.row_one) + ',' +
'0x{:02x}'.format(self.row_two) + ',' + '0x{:02x}'.format(self.row_three) + ',' +
'0x{:02x}'.format(self.row_four) + ',' + '0x{:02x}'.format(self.row_five) + ',' +
'0x{:02x}'.format(self.row_six) + ',' + '0x{:02x}'.format(self.row_seven) + ',' +
'0x{:02x}'.format(self.row_eight) + '}')
def color_button(self, linea, posizione):
if(linea == RIGA_UNO):
if(posizione == 7):
self.ui.btn_uno.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_due.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_tre.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_quattro.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_cinque.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_sei.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_sette.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_otto.setStyleSheet('background-color:#FF0000;color:#000000;')
if(linea == RIGA_DUE):
if(posizione == 7):
self.ui.btn_nove.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_dieci.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_undici.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_dodici.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_tredici.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_quattordici.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_quindici.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_sedici.setStyleSheet('background-color:#FF0000;color:#000000;')
if(linea == RIGA_TRE):
if(posizione == 7):
self.ui.btn_diciassette.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_diciotto.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_diciannove.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_venti.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_ventuno.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_ventidue.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_ventitre.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_ventiquattro.setStyleSheet('background-color:#FF0000;color:#000000;')
if(linea == RIGA_QUATTRO):
if(posizione == 7):
self.ui.btn_venticinque.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_ventisei.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_ventisette.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_ventotto.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_ventinove.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_trenta.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_trentuno.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_trentadue.setStyleSheet('background-color:#FF0000;color:#000000;')
if(linea == RIGA_CINQUE):
if(posizione == 7):
self.ui.btn_trentatre.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_trentaquattro.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_trentacinque.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_trentasei.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_trentasette.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_trentotto.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_trentanove.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_quaranta.setStyleSheet('background-color:#FF0000;color:#000000;')
if(linea == RIGA_SEI):
if(posizione == 7):
self.ui.btn_quarantuno.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_quarantadue.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_quarantatre.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_quarantaquattro.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_quarantacinque.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_quarantasei.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_quarantasette.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_quarantotto.setStyleSheet('background-color:#FF0000;color:#000000;')
if(linea == RIGA_SETTE):
if(posizione == 7):
self.ui.btn_quarantanove.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_cinquanta.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_cinquantuno.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_cinquantadue.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_cinquantatre.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_cinquantaquattro.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_cinquantacinque.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_cinquantasei.setStyleSheet('background-color:#FF0000;color:#000000;')
if(linea == RIGA_OTTO):
if(posizione == 7):
self.ui.btn_cinquantasette.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 6):
self.ui.btn_cinquantotto.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 5):
self.ui.btn_cinquantanove.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 4):
self.ui.btn_sessanta.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 3):
self.ui.btn_sessantuno.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 2):
self.ui.btn_sessantadue.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 1):
self.ui.btn_sessantatre.setStyleSheet('background-color:#FF0000;color:#000000;')
elif(posizione == 0):
self.ui.btn_sessantaquattro.setStyleSheet('background-color:#FF0000;color:#000000;')
# Questa riga di codice mi permette di convertire un numero binario sotto in esadecimale (come stringa)
# hex_string = '0x{:02x}'.format(int(bin(10), 2))
#FF0000 per il rosso
app = QtWidgets.QApplication([])
application = mywindow()
application.show()
sys.exit(app.exec()) | 3b7b57bd745f781d5231b1d5c6f3a38c5b0f8f66 | [
"Python"
] | 2 | Python | ric-geek/Symbol-Maker-MAX7219 | 8d25e4e2f0aad5d5f8715958c2fc46d3b342003a | e0593ca2558a0a99ff15629a62cadc25cb27e47b |
refs/heads/master | <file_sep>import Customizator from './modules/customizator';
import parcer from './modules/parcer';
window.addEventListener('DOMContentLoaded', () => {
const panel = new Customizator();
panel.render();
parcer();
});
<file_sep>export default class Customizator {
constructor() {
this.btnBlock = document.createElement('div');
this.colorPicker = document.createElement('input');
this.clear = document.createElement('div');
this.scale = +localStorage.getItem('scale') || 1;
this.color = localStorage.getItem('color') || '#ffffff';
}
setScale(element) {
element.childNodes.forEach(node => {
if (node.nodeName === '#text' && node.length > 13) {
let fontSize = window.getComputedStyle(node.parentNode, null).fontSize;
if (this.scale === 1.5 && !node.parentNode.style.fontSize) {
node.parentNode.style.fontSize = parseInt(fontSize) * this.scale + 'px';
} else if (this.scale === 1) {
node.parentNode.style.fontSize = '';
}
} else {
this.setScale(node);
}
});
}
scaleChange(event) {
if (event.target.classList.contains('scale_btn')) {
this.scale = parseFloat(event.target.value);
localStorage.setItem('scale', this.scale);
}
this.setScale(document.body);
}
setColor() {
document.body.style.backgroundColor = this.color;
}
colorChange(event) {
document.body.style.backgroundColor = event.target.value;
localStorage.setItem('color', event.target.value);
}
createPanel() {
let scaleInputS = document.createElement('input'),
scaleInputM = document.createElement('input'),
panel = document.createElement('div');
scaleInputS.classList.add('scale_btn');
scaleInputM.classList.add('scale_btn');
this.btnBlock.classList.add('scale');
panel.classList.add('panel');
this.colorPicker.classList.add('color');
this.clear.classList.add('clear');
scaleInputS.setAttribute('type', 'button');
scaleInputM.setAttribute('type', 'button');
scaleInputS.setAttribute('value', '1x');
scaleInputM.setAttribute('value', '1.5x');
this.colorPicker.setAttribute('type', 'color');
this.colorPicker.setAttribute('value', this.color);
this.clear.innerHTML = '×';
this.btnBlock.append(scaleInputS, scaleInputM);
panel.append(this.btnBlock, this.colorPicker, this.clear);
document.body.append(panel);
}
clearСustomization() {
this.scale = 1;
this.setScale(document.body);
this.color = '#ffffff';
this.setColor();
this.colorPicker.setAttribute('value', this.color);
localStorage.clear();
}
render() {
this.createPanel();
this.setScale(document.body);
this.setColor();
this.btnBlock.addEventListener('click', event => this.scaleChange(event));
this.colorPicker.addEventListener('input', event => this.colorChange(event));
this.clear.addEventListener('click', () => this.clearСustomization());
}
}
| 1aa08c06728e3e960f3d24417adc0d1b88b423eb | [
"JavaScript"
] | 2 | JavaScript | bamfl/parcer | ee2b38928ac6a79301f1189d905d40e86f79bdb9 | b9816dc91c8042ef4714011676467303604f7655 |
refs/heads/master | <repo_name>matthewspencer/matthewspencer.me<file_sep>/assets/js/modules/util.js
define([], function () {
/**
* Does the current browser support touch?
*
* Looking for browsers without hover.
*
* @return boolean
*/
function isTouch() {
return 'ontouchstart' in window || navigator.msMaxTouchPoints > 0;
}
return {
isTouch: isTouch
}
})<file_sep>/assets/js/modules/performance.js
require([], function () {
/**
* Initialize performance module.
*/
(function init() {
var timing = performanceTiming()
if (! timing) {
return
}
var comment = formatComment(timing)
writeCommentToHead(comment)
})()
/**
* Get performance timing object.
*
* @return false | PerformanceTiming object Timing object if exists, false if not.
*/
function performanceTiming() {
if (! 'performance' in window) {
return false
}
if (! 'timing' in window.performance) {
return false
}
return window.performance.timing
}
/**
* Format timing object into HTML comment.
*
* @param PerformanceTiming object timing Performance timing object.
* @return string comment HTML comment.
*/
function formatComment(timing) {
var comment = ''
for (var key in timing) {
var value = timing[key]
if (0 === value) {
continue
}
comment += '\n' + key + ': ' + value
}
comment += '\n'
return comment
}
/**
* Write comment to head.
*
* @param string comment Timing comment.
*/
function writeCommentToHead(comment) {
document.head.appendChild(document.createComment(comment));
}
})<file_sep>/assets/js/modules/router.js
define(['jquery', 'pjax'], function ($) {
var initialized = false,
bodyClassCache = {};
(function init() {
if (initialized) {
return
}
updateBodyClassCache(document.body.className)
$(document)
.on('click', 'a:not([data-exclude])', function (event) {
$.pjax.click(event, {
container: 'main',
fragment: 'main'
})
})
.on('pjax:success', function(event, data) {
var bodyClass = data.match(/body class=\"(.*?)\"/)[1]
updateBodyClassCache(bodyClass)
})
.on('pjax:end', function (event) {
document.body.className = bodyClassCache[document.location.pathname]
})
initialized = true;
})()
/**
* Keep track of the body classes for by location.
*
* @param {String} className
*/
function updateBodyClassCache(className) {
bodyClassCache[document.location.pathname] = className
}
})<file_sep>/bin/bower/post-install
#!/bin/bash
pushd `dirname $0` > /dev/null
dir=`pwd`
popd > /dev/null
bower="$dir/../../bower_components"
vendor="$dir/../../assets/js/vendor"
if [ ! -d "$vendor" ]; then
mkdir "$vendor"
fi
cp "$bower/jquery/dist/jquery.min.js" "$vendor"
cp "$bower/jquery/dist/jquery.min.map" "$vendor"
cp "$bower/requirejs/require.js" "$vendor"
cp "$bower/jquery-pjax/jquery.pjax.js" "$vendor"<file_sep>/gulpfile.js
var gulp = require('gulp');
var watch = require('gulp-watch');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var paths = {
styles: {
src: 'assets/sass/site.scss',
watch: [
'assets/sass/site.scss',
'assets/sass/**/*.scss'
]
}
};
gulp.task('sass', function () {
gulp.src(paths.styles.src)
.pipe(sass({
includePaths: [
'./bower_components/bootstrap-sass-official/assets/stylesheets/'
]
}))
.pipe(autoprefixer({
browsers: ['> 5%'],
cascade: false
}))
.pipe(gulp.dest('assets'));
});
gulp.task('watch', function () {
gulp.watch(paths.styles.watch, ['sass']);
});
gulp.task('default', ['sass', 'watch']); | bf76f08fbf86ea46994cfe607e10dac961234fd5 | [
"JavaScript",
"Shell"
] | 5 | JavaScript | matthewspencer/matthewspencer.me | e8c2bca50dbba086207ec7db16f3bcdb730b07a3 | b37f20d0730b6308677f71327ff12a1725ed9fd2 |
refs/heads/master | <repo_name>lavish22/apachepoi<file_sep>/ReadWriteApachePoi.java
package com.src.apachePackage;
import java.io.*;
import java.util.*;
import java.sql.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadWriteApachePoi {
public static void main(String[] args)
{
try {
FileInputStream file = new FileInputStream(new File("Geeks.xlsx"));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows one by one
List<Integer> passlist = new ArrayList<Integer>();
List<Integer> faillist = new ArrayList<Integer>();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
int temp=0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case NUMERIC:
temp=(int)cell.getNumericCellValue();
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
if( cell.getStringCellValue().equals("pass") )
passlist.add(temp);
else if( cell.getStringCellValue().equals("fail") )
faillist.add(temp);
break;
}
}
System.out.println("");
}
file.close();
System.out.print(passlist);
System.out.print(faillist);
XSSFWorkbook workbookw = new XSSFWorkbook();
// Create a blank sheet
XSSFSheet sheetw = workbookw.createSheet("sorted details");
int rownum=0;
for( Integer i : passlist ) {
int cellnum=0;
Row row = sheetw.createRow(rownum++);
Cell cell1 = row.createCell(cellnum++);
cell1.setCellValue(i);
Cell cell2 = row.createCell(cellnum++);
cell2.setCellValue((String)"pass");
}
for( Integer i : faillist ) {
int cellnum=0;
Row row = sheetw.createRow(rownum++);
row.createCell(cellnum++).setCellValue(i);
row.createCell(cellnum++).setCellValue((String)"fail");;
}
try {
// this Writes the workbook gfgcontribute
FileOutputStream out = new FileOutputStream(new File("Test_results.xlsx"));
workbookw.write(out);
out.close();
System.out.println("Test_results.xlsx written successfully on disk.");
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
} | 2999d4d0d08ad52cbbb98f03b63bcd444da8fe3b | [
"Java"
] | 1 | Java | lavish22/apachepoi | 7b4e078dbae6d3617ec2d28244181368d4501cc7 | edbe9a5da8de716220afe93874fbaa8f00f07b9b |
refs/heads/master | <repo_name>DanielCuSanchez/algoritmos-ordenamiento<file_sep>/selectionSort.py
import sys
array = [50, 23, 15, 20, 10]
print(len(array))
# Buscar el menor numero en mi array
# Crear dos subarrays para llevar el control del algoritmo
# Imprimir el resultado del ordenamiento
def selectionSort(array):
# Recorre todo el array
for i in range(len(array)):
print(array)
# Encontrar el valor minimo dentro del array desordenando
idxDes = i
for j in range(i+1, len(array)):
if array[idxDes] > array[j]:
idxDes = j
# Ya que encontramos el minimo lo vamos a cambiar por el primer valor
# de nuestro array desordenado
array[i], array[idxDes] = array[idxDes], array[i]
selectionSort(array)
print(array)
for i in range(len(array)):
print("%d"%array[i])<file_sep>/bubbleSort.py
# 1 - Comenzar a hacer elementos adyacentes
# 2 - Repetir hasta tener una pasada completa sin ningun swap
def bubbleSort(array):
n = len(array)
for i in range(n):
# print(array)
for j in range(0, n-i-1):
print(n-i-1)
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
array = [1, 33, 2, 4322, 21, 1331, 90]
bubbleSort(array)
# print(array)
# for i in range(len(array)):
# print("%d" % array[i])
| 0dadfe9d1d91e26d826d811d45f177edb923fcb9 | [
"Python"
] | 2 | Python | DanielCuSanchez/algoritmos-ordenamiento | ed495d4e99acdbd3b6641720ebfeb367894465ba | db4cd10ad726399583a1d87b55f3a03c1e37cd9d |
refs/heads/master | <repo_name>mohanaad-abalkhail/ReportCard<file_sep>/app/src/main/java/com/android/example/reportcard/ReportCard.java
package com.android.example.reportcard;
/**
* Created by MOHANAAD on 3/11/17.
*/
public class ReportCard {
private String mStudentName;
private String mCourseName;
private char mGrade;
public ReportCard(String studentName, String courseName, char grade) {
mStudentName = studentName;
mCourseName = courseName;
mGrade = grade;
}
public String getStudentName() {
return mStudentName;
}
public String getCourseName() {
return mCourseName;
}
public char getGrade() {
return mGrade;
}
public char setGrade(char newGrade) {
return mGrade = newGrade;
}
@Override
public String toString() {
return "ReportCard{" +
"StudentName is :'" + mStudentName + '\'' +
", CourseName is :'" + mCourseName + '\'' +
", Grade is :" + mGrade +
'}';
}
}
<file_sep>/README.md
# ReportCard
this a basic examole of what report card class should look like
one of Android basic Nanodgree apps from udacity
| 85dcb4c902e04d8c2166c528dd8d1b2192b52e97 | [
"Markdown",
"Java"
] | 2 | Java | mohanaad-abalkhail/ReportCard | 98d891a22e05adf636a07720e0fdce692461c1ed | fa235b8d083244a32a5ff091ac1f0f77513ec0c5 |
refs/heads/main | <file_sep>package home.com.Lesson9;
public class Main {
public static void main(String[] args) {
Collection<String> c = new Collection<>();
Collection<String> d = new Collection<>();
c.add("John");
c.add("NHN");
c.add("BBB");
System.out.println(c.size());
System.out.println(c.toString());
d.add("John");
d.add("NHN");
d.add("bbb");
System.out.println(d.size());
//System.out.println(c.delete(1));
// System.out.println(c.get(0));
//System.out.println(c.contains("John"));
//System.out.println(c.contains("NHN"));
//System.out.println(c.contains("BBB"));
//System.out.println(c.contains("BBBB"));
//System.out.println(c.contains("MHH"));
System.out.println(c.compare(d));
/* System.out.println(c.first.item);
System.out.println(c.last.item);
System.out.println(c.last.next.next.next.prev.next.item);
c.clear();
System.out.println(c.first.item);
System.out.println(c.last.item);
System.out.println(c.last.next.next.next.prev.next.item);
System.out.println(c.toString());*/
}
}
<file_sep>package HibernateHW;
import org.hibernate.Query;
import org.hibernate.Session;
import java.util.List;
import static HibernateHW.HibernateUtil.shutdown;
public class Creation {
public void recordsAdd( String name,int group, int year)
{
try {
System.out.println("Добавление записи в таблицу БД");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Student s = new Student();
s.setGroup(group);
s.setName_surname(name);
s.setYearOfEntering(year);
session.save(s);
session.getTransaction().commit();
System.out.println(s.toString());
shutdown();
System.out.println("Succsess!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void recordsFindName( String name_surname)
{
try {
System.out.println("Поиск студента");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
// String hql = "FROM Student where name_surname = :paramName";
String hql1 = "FROM Student where name_surname = "+ "'" + name_surname+ "'";
Query query = session.createQuery(hql1);
// query.setParameter("paramName", name_surname);
List<Student> studentList = query.list();
studentList.forEach(System.out::println);
shutdown();
System.out.println("Succsess!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void recordsFindId( int id)
{
try {
System.out.println("Поиск студента");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "FROM Student where studId = " + id;
Query query = session.createQuery(hql);
List<Student> studentList = query.list();
studentList.forEach(System.out::println);
shutdown();
System.out.println("Succsess!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
<file_sep>package home.com.Lesson3;
public class Chess {
public static void main(String[] args) {
char[][] chess = new char[8][8];
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess[0].length; j++) {
if ((i + j) % 2 == 0) { // четные - белые
chess[i][j] = 'W';
} else { // нечетные - белые
chess[i][j] = 'B';
}
System.out.print(chess[i][j]+ " ");
}
System.out.println();
}
}
}
<file_sep>package home.com.Lesson2;
import java.util.Scanner;
public class InvestmentMoneyCalculation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls press your previous value");
int Pv = input.nextInt();//первоначальный вклад
System.out.println("Pls press the percent");
double p = input.nextDouble(); // процент
System.out.println("Pls press the period of investment ");
byte n = input.nextByte(); // количетсво лет на инвестирование
System.out.println("Your income year by year:");
for (int i = 1; i <= n; i++) {
double Fv = Pv * (1 + (p / 100) * i); //формула расчета простых процентов
System.out.println(i + " year you will get " + Fv + " UAH");
}
double finalP = p * n; // проенті за все n лет
System.out.println();
System.out.println("Total percent for all years : " + finalP);
}
}
<file_sep>package home.com.Lesson5;
public class Cat extends Pets {
@Override
public String voice() {
return super.voice()+ ". Meow! ";
}
public Cat(String id, double age, double weight, String color, String name, boolean isVaccinated) {
super(id, age, weight, color, name, isVaccinated);
}
@Override
public String love() {
return super.love()+ "But myself i love more ♥";
}
}
<file_sep>package HW16;
import static HW16.Count.getCount;
import static HW16.Count.setCount;
public class ThreadGet extends Thread {
private int sum;
ThreadGet(int sum, String name) {
super(name);
this.sum = sum;
}
@Override
public void run() {
while (getCount() != 0 && sum <= getCount()){
setCount(getCount() - sum);
System.out.println(Thread.currentThread().getName() + "--" + "You get " + sum + " usd on your balance ");
System.out.println("current count: "+getCount());
}
System.out.println("you have no money: " +getCount());
}
}
<file_sep>package home.com.Lesson3;
import java.util.Arrays;
import java.util.Scanner;
public class FindTheMinElement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Ple enter the size of array");
// задаем размер массива
int n = scanner.nextInt();
int[] array = new int[n];
//задааем мин. элемент = первому элементу массива
int min = array[0];
// заполняем и выводим массив
for (int i = 0; i < array.length - 1; i++) {
array[i] = (int) (Math.round(Math.random() * 20)) - 10; // делаем диапазон рандомных чисел от -10 до 10
if (array[i] < min) { // сравниваем минимальные значения
min = array[i];
}
}
System.out.println("The array is: " + Arrays.toString(array));
// выводим мин. значение (-я)
for (int i = 0; i < array.length; i++) {
if (min == array[i]) {
System.out.println("The minimum is : " + min + " index[" + i + "] ");
}
}
}
}
<file_sep>package HW13;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your number");
String b = scanner.nextLine();
Figures a = new Figures();
System.out.println("result");
a.fig(b);
a.print();
}
}
<file_sep>package CacheHW;
import static CacheHW.CacheHelper.loggerInfo;
import static CacheHW.CacheHelper.loggerWarn;
public class Main {
public static void main(String[] args) throws InterruptedException {
CacheHelper ch = new CacheHelper();
System.out.println(ch.putCache("names", "1", "Petrov"));
// System.out.println(ch.toString());
loggerInfo.info("Print of cache"+ ch.toString());
ch.putCache("names","2", "Ivanov");
loggerInfo.info("Print of cache"+ch.toString());
// System.out.println(ch.toString());
ch.putCache("lol","3", "Andrew");
loggerInfo.info("Print of cache"+ch.toString());
// System.out.println(ch.toString());
System.out.println(ch.getCache("names", "2"));
loggerInfo.info("Print of cache"+ch.toString());
ch.clearCache("lol");
// System.out.println(ch.toString());
}
}
<file_sep>package classroom.constructor.test;
public class Director {
public String name;
public String surName;
public int age;
public Director( String name, String surName, int age){
this.name= name;
this.surName= surName;
this.age= age;
}
}
<file_sep>setName = Bitte setzen Sie Ihren Namen
pName = Der Spieler
pEnter = hat das Spiel betreten
setNummber = Wahlen Sie die Anzahl der Spiele
pChoice = Der Spieler wahlt die Anzahl der Spiele:
start = Spiel ist gestartet!
choice = Wahlen Sie Ihren Artikel:
ROCK = 1.FELSEN
SCISSORS= 2.SCHERE
PAPER=3.PAPIER
STOP = 4.STOP
winnerP = Spieler hat gewonnen!
winnerR = Der Roboter hat gewonnen!
nowin = Keine Gewinner<file_sep>import GameCreator.Hero;
import GameCreator.HeroCreate;
import java.util.Scanner;
public class game {
public static void main(String[] args) {
System.out.println("_________START GAME_________");
System.out.println("Select rasa");
System.out.println("1. WARRIOR");
System.out.println("2. WIZARD");
System.out.println("3. ARCHER");
Scanner sc = new Scanner(System.in);
//select name
System.out.println("Name: ");;
String name = sc.nextLine();
//select rasa
Integer rasa = sc.nextInt();
System.out.println(rasa);
System.out.println("Name: " + name);
// Hero hero = new HeroCreate.createHero();
}
}
<file_sep>package home.com.Lesson9;
//создаем класс для ссылок
class Node<E> {
public E item;
public Node<E> next;
public Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
public class Collection<E> implements CustomCollection <E> {
private int count =0;
Node<E> first;
Node<E> last;
//дефолтный конструктор
Collection (){
first = new Node<E>(first,null,first);
last= first;
}
//методы:
@Override
public boolean add(E str) {
Node<E> nodeNew = new Node<E> (last,str,first);
last.next = nodeNew;
first.prev = nodeNew;
last = nodeNew;
count++;
return true;
}
@Override
public boolean addAll(E[] strArr) {
for (int i = 0; i <strArr.length ; i++) {
add(strArr[i]);
}
return true;
}
@Override
public boolean addAll(Collection<E> strColl) {
for (int i = 0; i <strColl.size(); i++) {
add(strColl.get(i));
}
return true;
}
@Override
public boolean delete(int index) {
Node current = first;
Node previous = first;
int i =0;
while (i!= index){
if (current.next== null){
return false;
} else {
previous = current;
current = current.next;
i++;
}
}
if (current== first)
first = first.next;
else
previous.next= current.next;
count--;
return true;
}
@Override
public boolean delete(E str) {
Node current = first;
Node previous = first;
while (!current.item.equals(str)){
if (current.next== null){
return false;
} else {
previous = current;
current = current.next;
}
}
if (current== first)
first = first.next;
else
previous.next= current.next;
count--;
return true;
}
@Override
public E get(int index) {
Node <E> current = first.next;
for (int i = 0; i <count ; i++) {
if (i == index){
return current.item;
}
current = current.next;
}
return null;
}
@Override
public boolean contains(E str) {
Node <E> current = first.next;
for (int i = 0; i <count ; i++) {
if (str.equals(current.item)) {
return true;
}
current = current.next;
}
return false;
}
@Override
public boolean clear() {
//удаляем ссылки
first.next.prev = null;
last.next = null;
first.next = first;
first.prev = first;
last= first;
count =0;
return true;
}
@Override
public int size() {
return count;
}
@Override
public boolean trim() {
return true;
}
@Override
public boolean compare(Collection<E> coll) {
Node <E> current = first.next;
if (this==coll){return true;}
if (count== (coll.size())){
for (int i = 0; i < count; i++) {
if (!coll.get(i).equals(current.item)){
return false;}
current = current.next;
}
return true;
}
return false;
}
public String toString() {
Node <E> current = first.next;
String res ="";
for (int i = 0; i < count; i++) {
res += current.item + " ";
current = current.next;
}
return res;
}
}
<file_sep>package home.com.Lesson7;
import java.util.Arrays;
public class Methods {
private String[] array;
Methods() {
array = new String[10];
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getArray() {
return array;
}
public void setArray(String[] array) {
this.array = array;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
private int count = 0;
// для распечатки массива
public String toString() {
String res = "";
for (int i = 0; i < array.length; i++) {
res += array[i] + " ";
}
return res;
}
// метод добавления по индексу
public String[] addIndex(int index, String name) {
this.name = name;
if (index < 0) {
return null;
}
if (count == array.length) {
String[] arrayNew = Arrays.copyOfRange(array, 0, array.length + 1);
for (int i = array.length - 1; i > index; i--) {
arrayNew[i + 1] = arrayNew[i];
}
array = arrayNew;
}
array[index] = name;
count++;
return array;
}
// метод добавления по значению
public String[] addName(String name) {
this.name = name;
if (count == array.length) {
String[] arrayNew = Arrays.copyOfRange(array, 0, array.length + 1);
for (int i = array.length - 1; i > count; i--) {
arrayNew[i + 1] = arrayNew[i];
}
array = arrayNew;
}
array[count] = name;
count++;
return array;
}
// метод удаления по индексу
public String[] deleteIndex(int index) {
if (index < 0 || index > array.length) {
return null;
}
String[] arrayNew = Arrays.copyOfRange(array, 0, array.length - 1);//добавляем новый массив с длинной -1
int j = 0;
for (int i = 0; i < array.length; i++) {
if (i == index) {
i++;
}
arrayNew[j++] = array[i];
}
array = arrayNew;
return array;
}
// метод удаления по значению
public boolean deleteName(String name) {
this.name = name;
String[] arrayNew = Arrays.copyOfRange(array, 0, array.length-1 );//добавляем новый массив с длинной -1
int j = 0;
boolean delete = false;
for (int i = 0; i < array.length-1; i++) {
if (array[i].equals(name)) {
i++;
delete = true;
}
arrayNew[j++] = array[i];
}
array = arrayNew;
count--;
return delete;
}
//метод получения значения по индексу
public String getIndex(int index) {
String name = null;
for (int i = 0; i < array.length; i++) {
if (index < 0 || index >= array.length) {
System.out.print("Wrong,");
break;
} else if (index == i) {
name = array[i];
}
}
return name;
}
}
<file_sep>package GameCreator;
public enum Rasa {
WARRIOR,
WIZARD,
ARCHER
}
<file_sep>package GameCreator;
public class Monster extends Person{
}
<file_sep>package classroom.Lesson6;
public interface PrintInfo {
String print(String message);
}
<file_sep>package home.com.Lesson5;
public class Fish extends Pets {
@Override
public String voice() {
return "......";
}
@Override
public String move() {
return "I like to swim, bool bool ";
}
public Fish(String id, double age, double weight, String color, String name, boolean isVaccinated) {
super(id, age, weight, color, name, isVaccinated);
}
}
<file_sep>package HW12;
import HW12.Average;
import HW12.FilterList;
import HW12.ListPairs;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class Testing {
Average average;
Collection<Integer> coll;
FilterList filter;
List<String> list;
ListPairs pair;
List<String> coll2;
@Before
public void init (){
average = new Average();
coll= Arrays.asList(8,70,5,65);
filter = new FilterList();
list = new ArrayList<>();
list.add("spring");
list.add("AUTUMN");
list.add("summer");
list.add("WINTER");
list.add("ELEVEN");
list.add("nine");
list.add("NOVEMBER");
pair = new ListPairs();
coll2 = new ArrayList<>();
coll2.add("hello");
coll2.add("world");
coll2.add("java");
}
//тест среднеарифмет.число
@Test
public void averageTest(){
long sum = coll.stream().mapToLong((s) -> s).sum();
double res = (double)sum/coll.size();
Assert.assertEquals(java.util.Optional.of(res),java.util.Optional.of(average.calc(coll)));
}
//тесты фильтров
@Test
public void filterTest1(){
List<String> list2 = filter.filter(list);
for (int i = 0; i <list.size() ; i++) {
if (list.get(i).equals(list.get(i).toUpperCase()) || list.get(i).length() != 4) {
list.remove(i);
i--;
}
}
Assert.assertEquals(list.size(),list2.size());
}
@Test
public void filterTest2(){
List<String> list2 = filter.filter(list);
for (int i = 0; i <list2.size() ; i++) {
Assert.assertFalse(list2.contains(list2.get(i)==list2.get(i).toUpperCase()));
Assert.assertFalse(list2.contains(list.get(i).length() != 4));
}
}
//тест парной коллекции
@Test
public void pairTest() {
List<Pair> pairedColl = new ArrayList<>();
for (String s : coll2) {
pairedColl.add(new Pair(s, s.toUpperCase()));
}
Assert.assertEquals(pairedColl, pair.pair(coll2));
}
}
<file_sep>package home.com.Lesson6;
public class Lion extends Predators implements Cloneable {
public Lion(String id, double age, double weight, String color, boolean isPredator) {
super(id, age, weight, color, isPredator);
}
@Override
public void hunt() {
super.hunt();
System.out.println("I am a king!");
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
<file_sep>setName = Pls set your name
pName = The player
pEnter= entered the game
setNummber = Select the number of games
pChoice = The player chose amount of games :
start = Game is start!!
choice = Choose your item:
ROCK = 1.ROCK
SCISSORS= 2.SCISSORS
PAPER=3.PAPER
STOP = 4.STOP
winnerP = Player won!
winnerR = Robot won!
nowin = No winners<file_sep>package home.com.Lesson6;
public class Fish extends Pets implements Cloneable{
public Fish(String id, double age, double weight, String color, String name, boolean isVaccinated) {
super(id, age, weight, color, name, isVaccinated);
}
@Override
public void voice() {
System.out.println("......");
}
@Override
public void move() {
System.out.println("I like to swim, bool bool ");
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
<file_sep>package home.com.Lesson5;
import java.io.Serializable;
public class Hamster extends Pets implements Serializable {
public Hamster(String id, double age, double weight, String color, String name, boolean isVaccinated) {
super(id, age, weight, color, name, isVaccinated);
}
@Override
public String move() {
return "I like to move in my circle";
}
}
<file_sep>package home.com.Lesson3;
public class PowerN {
public static void main(String[] args) {
int x = 5;
int n = 2;
double pow = Math.pow(x, n);
System.out.println("The number " + x + " in power " + n + " is: " + pow);
}
}
<file_sep>package HibernateHW;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import javax.persistence.*;
@Entity
@Table(name = "student")
@Setter
@Getter
@ToString
@Accessors(chain = true)
public class Student {
@Id
@GeneratedValue
@Column(name = "studId", unique = true)
private int studId;
@Column(name = "name_surname")
private String name_surname;
@Column(name = "`group`")
private int group;
public String getName_surname() {
return name_surname;
}
public void setName_surname(String name_surname) {
this.name_surname = name_surname;
}
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
public Integer getYearOfEntering() {
return yearOfEntering;
}
public void setYearOfEntering(Integer yearOfEntering) {
this.yearOfEntering = yearOfEntering;
}
@Column(name="yearOfEntering")
private Integer yearOfEntering;
@Override
public String toString() {
return "Student{" +
"studId=" + studId +
", name_surname='" + name_surname + '\'' +
", group='" + group + '\'' +
", yearOfEntering=" + yearOfEntering +
'}';
}
}
<file_sep>package classroom.Cafe;
import java.math.BigDecimal;
public class Staff {
private int id;
private String firstName;
private String lastName;
private String passportNumber;
private String phone;
private Address address ;
private BigDecimal salary;
private byte age;
private byte size;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public byte getAge() {
return age;
}
public void setAge(byte age) {
this.age = age;
}
public byte getSize() {
return size;
}
public void setSize(byte size) {
this.size = size;
}
}
<file_sep>package GameCreator;
public class UnsupportedHeroException extends RuntimeException{
public UnsupportedHeroException(String message) {
super(message);
}
}
<file_sep>package home.com.Lesson6;
public class Giraffe extends Wild implements Cloneable {
public Giraffe(String id, double age, double weight, String color, boolean isPredator) {
super(id, age, weight, color, isPredator);
}
@Override
public void move() {
super.move();
System.out.println("And seeing at the sun. ");
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
<file_sep>package HW11;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestArray {
Array array ;
@Before
public void init (){
array = new Array();
array.add(5);
array.add(4);
array.add(3);
}
@Test
public void addTest(){
Assert.assertTrue(array.add(5));
Assert.assertEquals(4,array.size());
Assert.assertTrue(array.contain(5));
}
@Test
public void addIndexTest(){
Assert.assertTrue(array.add(1,4));
Assert.assertEquals(4,array.size());
Assert.assertTrue(array.contain(4));
Assert.assertEquals(array.get(1),4);
}
@Test
public void deleteTest(){
Assert.assertTrue(array.delete(5));
Assert.assertEquals(2,array.size());
Assert.assertFalse(array.contain(5));
}
@Test
public void getTest(){
Assert.assertEquals(5,array.get(0));
}
@Test
public void containTest(){
Assert.assertTrue(array.contain(4));
Assert.assertFalse(array.contain(50));
}
@Test
public void sizeTest(){
Assert.assertEquals(3,array.size());
}
@Test
public void equalsTest(){
Array arr2= new Array();
arr2.add(5);
arr2.add(4);
arr2.add(3);
Assert.assertTrue(array.equals(arr2));
arr2.add(10);
Assert.assertFalse(array.equals(arr2));
}
@Test
public void clear(){
Assert.assertTrue(array.clear());
Assert.assertEquals(0,array.size());
}
}
<file_sep>package HibernateHW;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Creation d = new Creation();
//d.recordsFindName("<NAME>");
System.out.println("Hello! I'm smart system!What you would like to do?");
System.out.println("1-create\n"+"2-find by name\n"+"3-find by id\n");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Pls enter the student's name&surname");
String a = scanner.next();
System.out.println("Pls enter the group");
int b = scanner.nextInt();
System.out.println("Pls enter year");
int c = scanner.nextInt();
d.recordsAdd(a,b,c);
break;
case 2:
System.out.println("Pls enter the student's name&surname");
String e = scanner.next();
e += " " + scanner.next();
d.recordsFindName(e);
break;
case 3:
System.out.println("Pls enter the student's id");
int f = scanner.nextInt();
d.recordsFindId(f);
break;
default:
System.out.println("Incorrect");
break;
}
}
}
<file_sep>setName = Пожалуйста, укажите свое имя
pName = Игрок
pEnter = вошел в игру
setNummber = Выберите количество игр
pChoice = Игрок выбрал количество игр :
start = Игра началась!
choice = Выберите ход :
ROCK = 1.КАМЕНЬ
SCISSORS= 2.НОЖНИЦЫ
PAPER=3.БУМАГА
STOP = 4.СТОП
winnerP = Игрок выиграл!
winnerR = Робот выиграл!
nowin = Нет победителей
<file_sep># Hometasks
homeworks for Java Elementary
<file_sep>package home.com.Lesson5;
//создаем главный класс
public class Animals implements Cloneable {
private String id;
// создаем конструктор
public Animals(String id, double age, double weight, String color) {
this.id = id;
this.age = age;
this.weight = weight;
this.color = color;
}
private double age;
private double weight;
private String color;
// геттеры / сеттеры
public String getId() { return id; }
public void setId(String id) {
this.id = id;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
//методы, для всех животных
public String voice() {
return "Hello, ";
}
public String move() {
return "I like to move";
}
public void printInfo() {
System.out.println("ID: " + getId());
System.out.println("Age: " + getAge() + " year(s)");
System.out.println("Color: " + getColor());
System.out.println("Weight: " + getWeight() + " kg(s)");
}
}
<file_sep>package classroom.Cafe;
public class Auto {
private String model;
private String lifting;
private String year;
private String type;
private String number;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getLifting() {
return lifting;
}
public void setLifting(String lifting) {
this.lifting = lifting;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
<file_sep>package classroom.Cafe;
import java.math.BigDecimal;
public class Barmen extends Staff{
private BigDecimal tips;
private boolean healthBook;
private String systemCode;
public BigDecimal getTips() {
return tips;
}
public void setTips(BigDecimal tips) {
this.tips = tips;
}
public boolean isHealthBook() {
return healthBook;
}
public void setHealthBook(boolean healthBook) {
this.healthBook = healthBook;
}
public String getSystemCode() {
return systemCode;
}
public void setSystemCode(String systemCode) {
this.systemCode = systemCode;
}
}
<file_sep>package home.com.Lesson3;
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Pls enter the number");
int n = scanner.nextInt();
if (n>0) { //условие неотрицательности
int res;
System.out.println("The multiplication table of number " + n + " is:");
for (int i = 1; i <= 10; i++) {
res = i * n;
System.out.println(i + "*" + n + " = " + res);
}
} else {
System.out.println("Wrong number, try again");
}
}
}
<file_sep>package classroom.Other;
public class Hier {
String name;
String phone;
String age;
}
<file_sep>package home.com.Lesson5;
public class Giraffe extends Wild {
public Giraffe(String id, double age, double weight, String color, boolean isPredator) {
super(id, age, weight, color, isPredator);
}
@Override
public String move() {
return super.move() +"And seeing at the sun. ";
}
}
<file_sep>package home.com.Lesson9;
public interface CustomCollection <E> {
boolean add(E str);
boolean addAll(E [] strArr);
boolean addAll(Collection<E> strColl);
boolean delete (int index);
boolean delete (E str);
E get(int index);
boolean contains(E str);
boolean clear();
int size();
boolean trim();
boolean compare(Collection<E> coll);
}
<file_sep>package GameCreator;
public enum Items {
SHIELD(50,0),
SWORD(25,100);
public int def;
public int ataka;
Items(int def, int ataka) {
this.def = def;
this.ataka = ataka;
}
}
<file_sep>package home.com.Lesson6;
public class Crocodile extends Predators implements Cloneable {
public Crocodile(String id, double age, double weight, String color, boolean isPredator) {
super(id, age, weight, color, isPredator);
}
@Override
public void move() {
super.move();
System.out.println("Very slowly!");
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
<file_sep>package home.com.Lesson6;
public interface PetInterface {
void Vaccinated();
void love();
}
<file_sep>package classroom.Other;
public class Lesson5 {
public static void main(String[] args) {
Box b1 = new Box(5,6,7);
Box b2 = new Box(3,4,5);
System.out.println(b1.toString());
b1.toString();
b2.toString();
}
}
<file_sep>package home.com.Lesson6;
public class GuideDog extends Pets implements GuideDogInterface, Cloneable {
// перемнные только для тренированных животных:
private boolean isTrained;
public GuideDog(String id, double age, double weight, String color, String name, boolean isVaccinated, boolean isTrained) {
super(id, age, weight, color, name, isVaccinated);
this.isTrained = isTrained;
}
// геттеры/сеттеры
public boolean isTrained() { return isTrained;
}
public void setTrained(boolean trained) {
isTrained = trained;
}
// стандартные методы для всех животных + особенности
@Override
public void voice() {
super.voice() ;
System.out.println("I can take you home");
}
@Override
public void love() {
super.love();
System.out.println("And i really care about him.");
}
@Override
public void goHome() {
System.out.println("Let's go home!");
}
// метод только для тренированных животных
@Override
public void Trained() {
System.out.println("IsTrained: "+ isTrained());
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
<file_sep>package home.com.Lesson6;
public class Pets extends Animals implements AnimalsInterface,PetInterface{
// перемнные только для домащних животных:
private String name;
private boolean isVaccinated;
public Pets(String id, double age, double weight, String color, String name, boolean isVaccinated) {
super(id, age, weight, color);
this.name = name;
this.isVaccinated = isVaccinated;
}
// геттеры/сеттеры
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isVaccinated() {
return isVaccinated;
}
public void setVaccinated(boolean vaccinated) {
isVaccinated = vaccinated;
}
//// стандартные методы для всех животных + особенности
@Override
public void voice() {
System.out.println("Hello, my name is " + name);
}
@Override
public void move() {
System.out.println("I like to move around the house");
}
@Override
public void printInfo() {
System.out.println("ID: " + getId());
System.out.println("Age: " + getAge() + " year(s)");
System.out.println("Color: " + getColor());
System.out.println("Weight: " + getWeight() + " kg(s)");
System.out.println("Name: " + getName());
}
@Override
public void Vaccinated() {
System.out.println("IsVaccinated: " + isVaccinated());
}
@Override
public void love() {
System.out.println("I love my owner!");
}
}
<file_sep>package home.com.Lesson8;
public class Main {
public static void main(String[] args) {
// взаимодейтсвуем с коллекцией
Collections coll = new Collections();
coll.add(5);
coll.add(6);
coll.add(7);
coll.add(8);
coll.add(9);
coll.add(10);
coll.add(8);
coll.add(8);
coll.add(8);
coll.add(8);
coll.add(8);
coll.add(8);
System.out.println(coll.toString());
Collections coll2 = coll;
Collections str = new Collections();
str.add(5);
str.add(6);
str.add(7);
str.add(8);
str.add(9);
str.add(10);
System.out.println(str.toString());
System.out.println(coll.equals(str));
System.out.println(coll.equals(coll2));
System.out.println("contain?");
System.out.println(coll.contain(8));
System.out.println(coll.contain(null));
System.out.println(coll.size());
System.out.println(coll.toString());
System.out.println("clear up!");
coll.clear();
System.out.println(coll.toString());
System.out.println(coll.size());
str.add(3,90);
System.out.println(str.toString());
System.out.println(str.get(2));
System.out.println(str.get(20));
System.out.println(coll.equals(str));
}
}
<file_sep>package CacheHW;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CacheTests {
CacheHelper cacheHelper;
String cacheName = "TestCache1";
String key ="1.";
Object o = "Ivanov";
@Before
public void init () throws InterruptedException {
cacheHelper = new CacheHelper();
//for test# 2
cacheHelper.putCache(cacheName,key,o);
//for test #4
cacheHelper.putCache("TestDelete","000",true);
}
//test #1
@Test
public void putCacheTest() throws InterruptedException {
Assert.assertTrue(cacheHelper.putCache(cacheName,key,o));
Assert.assertEquals(o, cacheHelper.getCache(cacheName,key));
}
//test #2
@Test
public void getCacheTest() throws InterruptedException {
Assert.assertEquals(cacheHelper.getCache(cacheName,key),o);
}
//test #3
@Test
public void clearAllCacheTest() throws InterruptedException {
cacheHelper.clearCache();
Assert.assertEquals(cacheHelper.getSize(),0);
}
//test #4
@Test
public void clearCacheTest() throws InterruptedException {
cacheHelper.clearCache("TestDelete");
Assert.assertEquals(cacheHelper.getSize(),1);
Assert.assertFalse(cacheHelper.getSize()==0);
}
}
<file_sep>package HW16;
public class Main {
public static void main(String[] args) {
ThreadGet g = new ThreadGet(200,"Get th");
ThreadPut p = new ThreadPut(500,"Put th");
g.start();
p.start();
}
}
<file_sep>package home.com.Lesson10;
public class MathExample {
public static void main(String[] args) {
Sqrt sq = new Sqrt(1,12,36);
System.out.println(sq.count());
}
}
class Sqrt{
private int a;
private int b;
private int c;
private double x1;
private double x2;
private String res;
Sqrt(int a,int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
public String count(){
double d = Math.pow(b,2) - 4*(a*c);
if (d<0){
res = "No x " + null;
return res;
} if (d>0){
x1 = (-b+Math.sqrt(d))/(2*a);
x2 = (-b-Math.sqrt(d))/(2*a);
res = "x1 =" + x1 + " "+"x2 =" + x2;
} else {
x1 = (-b+Math.sqrt(d))/(2*a);
res = "x1 =" + x1;
}
return res;
}
}
<file_sep>package classroom.Lesson6;
@FunctionalInterface
public interface FuncInt {
void print ();
}
<file_sep>package home.com.Lesson6;
public interface GuideDogInterface {
void goHome();
void Trained();
}
<file_sep>package home.com.Lesson5;
public class Lion extends Predators {
public Lion(String id, double age, double weight, String color, boolean isPredator) {
super(id, age, weight, color, isPredator);
}
@Override
public String hunt() {
return super.hunt() + "I am a king!";
}
}
<file_sep>package GameCreator;
public class HeroCreate {
public Hero createHero (int rasa, String name){
Hero hero = new Hero();
hero.setName(name);
if (rasa == 1){
hero.setRasa(Rasa.WARRIOR);
hero.setlHand(Items.SWORD);
hero.setrHand(Items.SHIELD);
return hero;
} else if(rasa == 2){
hero.setRasa(Rasa.WIZARD);
hero.setlHand(Items.SWORD);
hero.setrHand(Items.SHIELD);
return hero;
}else if(rasa == 3) {
hero.setRasa(Rasa.ARCHER);
hero.setlHand(Items.SWORD);
hero.setrHand(Items.SHIELD);
return hero;
}
else {throw new UnsupportedHeroException("Cant create"); }
//return null;
}
public Monster createMonster(){
Monster monster = new Monster();
monster.setName("Big monster");
monster.setHealth(1500);
monster.setStrength(10);
return monster;
}
}
<file_sep>package classroom.Lesson6;
public class Test implements Cloneable {
int i =0;
@Override
public Object clone() throws CloneNotSupportedException {
System.out.println(15);
return super.clone();
}
}
| 3206d132c6128d71937423756a84c404052ea4da | [
"Markdown",
"Java",
"INI"
] | 54 | Java | anastasia1enya/Hometasks | c8386d7c92d39957b946c4ffc4e61cb0d8b72432 | 37b898ab7fc89f8bb22a7dedd97c8424b9b6bcd2 |
refs/heads/master | <repo_name>denniskuczynski/mongodb_changestream_chat<file_sep>/src/main/webapp/client.js
(function() {
var connection;
function createConnection() {
connection = new WebSocket('ws://' + location.host + '/ws');
connection.onopen = function () {
console.log('onopen', arguments);
bindFormListener();
};
connection.onerror = function () {
console.log('onerror', arguments);
};
connection.onclose = function () {
console.log('onclose', arguments);
unbindFormListener();
clearMessages();
setTimeout(createConnection, 5000);
};
connection.onmessage = function (message) {
console.log('onmessage', arguments);
var msg = JSON.parse(message.data);
if (msg.type === 'history') {
msg.data.forEach(appendMessage);
} else {
appendMessage(msg.data);
}
};
}
function bindFormListener() {
var form = document.getElementById('input_form');
form.submit.disabled = false;
form.addEventListener('submit', onSubmitHandler);
}
function unbindFormListener() {
var form = document.getElementById('input_form');
form.submit.disabled = true;
form.removeEventListener('submit', onSubmitHandler);
}
function onSubmitHandler(e) {
e.preventDefault();
var form = e.target;
connection.send(form.message.value);
form['message'].value = '';
form['message'].focus();
}
function appendMessage(data) {
var messages = document.getElementById('messages');
var li = document.createElement('li');
li.appendChild(
document.createTextNode(data.address+' @ '+new Date(data.time)+': '+data.text)
);
if (messages.children && messages.children.length) {
messages.insertBefore(li, messages.children[0]);
} else {
messages.appendChild(li);
}
}
function clearMessages() {
document.getElementById('messages').innerHTML = null;
}
document.addEventListener('DOMContentLoaded', function(event) {
createConnection();
});
})();<file_sep>/README.md
# MongoDB Changestream Chat
Example code using Websockets and MongoDB Changestreams to implement a persisted chatroom with multiple servers.
## To Build
```
cd mongodb_changestream_chat
mvn install
mvn package
```
## To Demo
Start a local 3 node MongoDB replica set on port 3000, 3001, and 3002.
In two terminal windows startup two instances of the Java server
```
export PORT=9000; java -cp target/classes:target/dependency/* com.example.server.Main
export PORT=9001; java -cp target/classes:target/dependency/* com.example.server.Main
```
In two browser windows browse to:
http://localhost:9000 and http://localhost:9001
<file_sep>/src/main/java/com/example/ws/ExampleWebSocketServlet.java
package com.example.ws;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class ExampleWebSocketServlet extends WebSocketServlet {
@Override
public void configure(final WebSocketServletFactory factory)
{
factory.getPolicy().setIdleTimeout(60000);
factory.register(ExampleSocket.class);
}
} | b812341eb720cc307ad28d80ac8ae6569a9dc79a | [
"JavaScript",
"Java",
"Markdown"
] | 3 | JavaScript | denniskuczynski/mongodb_changestream_chat | b12bb1fc018f26958013cae386526c0bbfa20b44 | 3cc1325321e3742c1c8e4cb3e081b1cfe8a47f40 |
refs/heads/master | <file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System;
using DeltaForth.DataStructures;
using DeltaForth.Descriptors;
using DeltaForth.Parser;
using DeltaForth.SyntacticAnalyzer;
namespace DeltaForth
{
/// <summary>
/// Delta Forth - The .NET Forth Compiler
/// (C) <NAME>, PhD (<EMAIL>)
///
/// Class ForthCompiler
///
/// Date of creation: September 5, 2001
/// Date of last update: October 26, 2011
///
/// Description:
/// The ForthCompiler class requires a Forth source file as a parameter and an output file
/// to generate code to.
/// </summary>
public class ForthCompiler
{
#region Event Delegate
public delegate void CompilerEventHandler(object sender, object e);
#endregion
#region Compiler events
/// <summary>
/// Raised when parsing of the source file starts
/// </summary>
public event CompilerEventHandler OnParsingStart;
/// <summary>
/// Raised when parsing of the source file ends
/// </summary>
public event CompilerEventHandler OnParsingEnd;
/// <summary>
/// Raised when syntactic analysis starts
/// </summary>
public event CompilerEventHandler OnSyntacticAnalysisStart;
/// <summary>
/// Raised when syntactic analysis ends
/// </summary>
public event CompilerEventHandler OnSyntacticAnalysisEnd;
/// <summary>
/// Raised when code generation starts
/// </summary>
public event CompilerEventHandler OnCodeGenerationStart;
/// <summary>
/// Raised when code generation ends
/// </summary>
public event CompilerEventHandler OnCodeGenerationEnd;
/// <summary>
/// Raised when compilation starts
/// </summary>
public event CompilerEventHandler OnCompilationStart;
/// <summary>
/// Raised when compilation ends
/// </summary>
public event CompilerEventHandler OnCompilationEnd;
#endregion
#region Event Launchers
public void SignalCompilationStart()
{
if (OnCompilationStart != null)
{
OnCompilationStart(this, null);
}
}
public void SignalCompilationEnd()
{
if (OnCompilationEnd != null)
{
OnCompilationEnd(this, null);
}
}
public void SignalParsingStart(string FileName)
{
if (OnParsingStart != null)
{
OnParsingStart(this, FileName);
}
}
public void SignalParsingEnd()
{
if (OnParsingEnd != null)
{
OnParsingEnd(this, null);
}
}
public void SignalSyntacticAnalysisStart()
{
if (OnSyntacticAnalysisStart != null)
{
OnSyntacticAnalysisStart(this, null);
}
}
public void SignalSyntacticAnalysisEnd()
{
if (OnSyntacticAnalysisEnd != null)
{
OnSyntacticAnalysisEnd(this, null);
}
}
public void SignalCodeGenerationStart()
{
if (OnCodeGenerationStart != null)
{
OnCodeGenerationStart(this, null);
}
}
public void SignalCodeGenerationEnd()
{
if (OnCodeGenerationEnd != null)
{
OnCodeGenerationEnd(this, null);
}
}
#endregion
#region Local variables
private CompilerMetadata _MetaData;
#endregion
#region Public accessors
public CompilerMetadata MetaData { get { return _MetaData; } }
#endregion
public ForthCompiler()
{
}
public void CompileFile(string SourceFileName, string TargetFileName, string TargetDirectory, string SignatureFile, bool GenerateExecutable, bool GenerateStackFrames, int ForthStackSize, int ReturnStackSize)
{
// Compilation start
SignalCompilationStart();
try
{
// Parsing
SignalParsingStart(SourceFileName);
ForthParser parser = new ForthParser(SourceFileName);
var SourceAtoms = parser.GetForthAtoms();
SignalParsingEnd();
// Syntactic analysis
SignalSyntacticAnalysisStart();
ForthSyntacticAnalyzer analyzer = new ForthSyntacticAnalyzer(SourceAtoms);
_MetaData = analyzer.GetMetaData();
SignalSyntacticAnalysisEnd();
// Code generation
SignalCodeGenerationStart();
ForthCodeGenerator generator = new ForthCodeGenerator(MetaData, TargetFileName, TargetDirectory, SignatureFile, GenerateExecutable, GenerateStackFrames, ForthStackSize, ReturnStackSize);
generator.DoGenerateCode();
SignalCodeGenerationEnd();
// Compilation end
SignalCompilationEnd();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System;
using System.IO;
using System.Text.RegularExpressions;
using DeltaForth.DataStructures;
using System.Collections.Generic;
using System.Linq;
namespace DeltaForth.Parser
{
/// <summary>
/// The ForthParser class takes a input file that contains Forth code and extracts the atoms. An atom is the smallest semantic unit that has a meaning of its own.
/// </summary>
/// <remarks>
/// Date of creation: September 5, 2001
/// Date of last update: October 25, 2011
/// </remarks>
internal class ForthParser
{
#region Local variables
/// <summary>
/// Comment mode (TRUE if atoms should be ignored)
/// </summary>
private bool CommentMode = false;
/// <summary>
/// List of files already processed (so we don't process the same file multiple times in case of circular references)
/// </summary>
private HashSet<string> ProcessedFiles;
/// <summary>
/// Name of the file to parse(it may include LOAD directives case in which other files will be processed as well)
/// </summary>
private string SourceFileName;
#endregion
/// <summary>
/// Public constructor
/// </summary>
/// <param name="SourceFileName">Source file with Forth code.</param>
public ForthParser(string SourceFileName)
{
ProcessedFiles = new HashSet<string>();
this.SourceFileName = SourceFileName;
}
/// <summary>
/// Get the list of Forth atoms from the input source file
/// </summary>
/// <returns>List of Forth atoms</returns>
public List<ForthAtom> GetForthAtoms()
{
// Prcess the source file
var SourceAtoms = ProcessSourceFile(SourceFileName);
// Process (any) LOAD directives
var ProcessedSourceAtoms = ProcessLoadDirectives(SourceAtoms);
return ProcessedSourceAtoms;
}
/// <summary>
/// Parse a file containing Forth source code.
/// </summary>
/// <param name="SourceFileName">File name of the source code.</param>
/// <returns>An list of ForthAtom objects found in the file.</returns>
private List<ForthAtom> ProcessSourceFile(string SourceFileName)
{
// Check whether we already visited this file
if (ProcessedFiles.Contains(SourceFileName))
{
throw new Exception(string.Format("Circular dependency in LOAD directives for file {0}.", SourceFileName));
}
var AtomList = new List<ForthAtom>();
try
{
int LineNumber = 1;
StreamReader source = new StreamReader(SourceFileName);
string line = source.ReadLine();
while (line != null)
{
var ParsedAtoms = ProcessSourceLine(line, SourceFileName, LineNumber++);
AtomList.AddRange(ParsedAtoms);
line = source.ReadLine();
}
source.Close();
}
catch (Exception)
{
throw new Exception(string.Format("Invalid file specified by the LOAD directive: {0}", SourceFileName));
}
// Add the file to the processed file list
ProcessedFiles.Add(SourceFileName);
return AtomList;
}
/// <summary>
/// Parse the source line containing Forth code.
/// </summary>
/// <param name="ForthSourceCode">A line containing some Forth code</param>
/// <param name="SourceFileName">File name of the source code (for reporting in case of error).</param>
/// <param name="LineNumber">Line number in the file name with the source code (for reporting in case of error).</param>
/// <returns>An enumeration of ForthAtom objects found in the line.</returns>
private IEnumerable<ForthAtom> ProcessSourceLine(string ForthSourceCode, string SourceFileName, int LineNumber)
{
string atom = string.Empty;
// The regular expression matches display strings (." "), dump strings (" ") and individual atoms
Regex reg = new Regex("\\.\"[^\"]*\"|\"[^\"]*\"|\\S+");
Match match = reg.Match(ForthSourceCode);
while (match.Success)
{
atom = match.ToString(); // Get the current atom
// Deal with the single line comment (if found, drop the line)
if (atom.StartsWith(@"\"))
{
yield break;
}
// Avoid entering comment mode
// if the atom is in the form '(comment)'
if(atom.StartsWith("(") && atom.EndsWith(")"))
{
match = match.NextMatch(); // Advance to the next atom
continue;
}
if(atom.StartsWith("(")) // Begin multi-line comment
{
CommentMode = true;
match = match.NextMatch(); // Advance to the next atom
continue;
}
if(atom.EndsWith(")")) // End multi-line comment
{
CommentMode = false;
match = match.NextMatch(); // Advance to the next atom
continue;
}
if (!CommentMode)
{
yield return new ForthAtom { Name = atom, FileName = SourceFileName, LineNumber = LineNumber };
}
match = match.NextMatch();
}
}
/// <summary>
/// Parses the atom list and recursively processes the LOAD directives
/// </summary>
/// <param name="ForthAtoms">List of Forth atoms that may possibily include LOAD directives</param>
/// <returns>List of Forth atoms with expanded definitions of LOAD directives</returns>
private List<ForthAtom> ProcessLoadDirectives(List<ForthAtom> ForthAtoms)
{
var ProcessedForthAtoms = new List<ForthAtom>();
for (int i = 0; i < ForthAtoms.Count(); i++)
{
var CurrentAtom = ForthAtoms.ElementAt(i);
// Check whether the current atom is a LOAD directive
if (CurrentAtom.Name.ToUpper() != "LOAD")
{
ProcessedForthAtoms.Add(ForthAtoms.ElementAt(i));
continue;
}
string FileToLoad = string.Empty;
try
{
FileToLoad = ForthAtoms.ElementAt(i + 1).Name;
}
catch (Exception)
{
throw new Exception("No file name specified after the LOAD directive. (" + CurrentAtom.FileName + ", line " + CurrentAtom.LineNumber + ")"); // Signal error if no file name is supplied
}
var NewAtoms = ProcessSourceFile(FileToLoad);
ProcessedForthAtoms.AddRange(NewAtoms);
}
return ProcessedForthAtoms;
}
}
}
<file_sep>using System;
namespace Library1
{
public static class Class1
{
static Class1()
{
Console.WriteLine("This is the constructor of the static class Class1.");
}
public static void DisplayLogo()
{
Console.WriteLine("Logo typed in a C# program.");
}
}
}
<file_sep># Delta Forth - World's first Forth compiler for .NET
## Welcome to the world of Forth
Forth is a procedural, stack-oriented, reflective programming language and programming environment. It was initially developed by <NAME> at the US National Radio Astronomy Observatory in the early 1970s, formalized as a programming language in 1977, and standardized by ANSI in 1994. The original implementations featured both interactive execution of commands (making it suitable as a shell for systems that lack a more formal operating system), as well as the ability to compile sequences of commands for later execution.
Forth is so named because Moore considered it appropriate for fourth-generation computers (i.e. microcomputers), and the system on which he developed it was limited to five-letter filenames. Although the name is not an acronym, it is sometimes spelled in all capital letters, following the customary usage during its earlier years.
Forth offers a standalone programming environment consisting of a stack-oriented, interactive, incremental interpreter and compiler. Programming is done by extending the language with words (the term used for Forth subroutines), which become part of the language once defined.
Forth has been popular for developing embedded systems and instrument controls because it is easy to add small machine code definitions to the language and use those in an interactive high-level programming environment.
The logical structure of Forth resembles a virtual machine. It has been implemented efficiently on modern RISC processors, and processors that use Forth as machine language have been produced. The modular extensible nature of Forth permits many high-level applications such as CAD systems to be written in Forth.
Forth is used in the Open Firmware boot ROMs used by Apple, IBM, and Sun Microsystems. It is also used by the FreeBSD operating system as the first stage boot controller.
## The Delta Forth .NET Project
Delta Forth is a non-standard Forth dialect. It has several limitations over traditional standards but it is an excellent starting point for beginners and enthusiasts. The traditional compreter (compiler – interpreter) approach of other implementations does not fit in the .NET environment as we deal with compiled programs. Several of the words in the original Forth specification have lost their meaning (see STATE, COMPILE, IMMEDIATE, etc.) but I think the compiled approach of this flavor is still appealing and useful. The true power of Forth is in its ability to stay close to the machine assembly language while it has some incredibly powerful control structures.
Delta Forth generates true .NET code in the form of console executables (.EXE) and libraries (.DLL). The code can be executed on any .NET platform, such as Microsoft .NET on Windows or Mono on Linux. Beginning with version Delta Forth 1.2 the code generated by the compiler can be strongly-signed using a regular signature file generated by the sn.exe tool.
Forth literature states that a complete traditional Forth environment can be coded by a single person in a three-month time. I managed to release the beta 1 version of Delta in half that time. Despite the short time it took to be developed, this tool has a long history, being a continuation of the Delta Forth for Java project that I started back in 1997. At that time, it was the first Forth compiler for Java and was a real surprise when I presented it as my graduation project two years later.
## Testimonials
- **<NAME>, .NET Developer Group, Microsoft Corp.**
Well done on your Forth compiler for .NET. It must be over fifteen years since I last touched Forth, but it’s a great example of how the .NET Framework supports stack-based languages well.
- **<NAME>, Microsoft Corp.**
I work with all of our .NET language partners, and noticed your recent announcement of your Forth compiler […]
- **<NAME>, www.codeproject.com**
Excellent work Valer - I’m most impressed!
- **<NAME>, author of HTML Assistant Pro**
I taught Forth during most of the eighties. It’s a wonderful language and many of my students loved it. I’m glad to see another modern incarnation. Congratulations!
- **<NAME>**
What a delight to trip across your Delta Forth .NET. I was wondering who’d have the first FORTH .NET offering. I need wonder no more. […] Keep up the good work.
- **<NAME>**
I started out with your Delta Forth. NET […] and found it very interesting using Forth for writing .NET applications.
- **<NAME>**
I teach Forth and C# in Providence in Taiwan and how wonderful I could tell students Forth has a .Net version that could be used with C#. Thanks a lot!
- **<NAME>**
Thanks for keeping FORTH alive on .NET<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
namespace DeltaForth.DataStructures
{
/// <summary>
/// Definition of a local variable as used by the Forth syntactic analyzer
/// </summary>
public class ForthLocalVariable
{
/// <summary>
/// Variable name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Word where the variable has been defined
/// </summary>
public string WordName { get; set; }
/// <summary>
/// Address of the variable (computed by the code generator)
/// </summary>
public int Address { get; set; }
}
}<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
namespace DeltaForth.DataStructures
{
/// <summary>
/// Definition of an atom as used by the Forth parser
/// </summary>
public class ForthAtom
{
/// <summary>
/// Atom name
/// </summary>
public string Name { get; set; }
/// <summary>
/// File where the atom occured
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Line number at which the atom occured
/// </summary>
public int LineNumber { get; set; }
}
}<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
namespace DeltaForth.SyntacticAnalyzer
{
/// <summary>
/// Types of exceptions that may be thrown by the syntactic analyzer
/// </summary>
public enum SyntacticExceptionType
{
_EDeclareOutsideWords, // The identifier should be defined outside words
_EDeclareInsideWords, // The identifier should be defined inside words
_EReservedWord, // The specified identifier is a reserved word
_EInvalidIdentifier, // The specified identifier is invalid
_EUnableToDefineConst, // Unable to define constant since the stack is empty
_EUnableToAllocVar, // Unable to alloc variable space since the stack is empty
_EUnexpectedEndOfFile, // An unexpected end of file has occured
_EWrongAllotConstType, // A constant of type other than 'int' was specified for ALLOT
_ENestedWordsNotAllowed,// A word definition occured within another word definition
_EMalformedBWRStruct, // Malformed BEGIN-WHILE-REPEAT struct encountered
_EMalformedBAStruct, // Malformed BEGIN-AGAIN struct encountered
_EMalformedBUStruct, // Malformed BEGIN-UNTIL struct encountered
_EMalformedIETStruct, // Malformed IF-ELSE-THEN struct encountered
_EMalformedDLStruct, // Malformed DO-LOOP/+LOOP struct encountered
_EMalformedCOEStruct, // Malformed CASE-OF-ENDCASE struct encountered
_EUnfinishedControlStruct, // Control structures must be terminated before ';'
_EMalformedConversion, // Malformed conversion
_EUnfinishedConversion, // Conversions must be finished before ';'
_EMainNotDefined, // Word MAIN not defined
_EDuplicateConst, // Duplicate constant defined
_EDuplicateVar, // Duplicate variable defined
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System.Collections.Generic;
namespace DeltaForth.DataStructures
{
/// <summary>
/// Definition of a word as used by the Forth syntactic analyzer
/// </summary>
public class ForthWord
{
/// <summary>
/// Forth word name
/// </summary>
public string Name { get; set; }
/// <summary>
/// List of atoms that define the word
/// </summary>
public List<string> Definition { get; set; }
public ForthWord()
{
Definition = new List<string>();
}
}
}<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System.Collections.Generic;
namespace DeltaForth.DataStructures
{
/// <summary>
/// Metadata generated by the Forth syntactic analyzer and consumed by the code generator
/// </summary>
public class CompilerMetadata
{
/// <summary>
/// Global constants
/// </summary>
public List<ForthConstant> GlobalConstants { get; set; }
/// <summary>
/// Global variables
/// </summary>
public List<ForthVariable> GlobalVariables { get; set; }
/// <summary>
/// Local variables
/// </summary>
public List<ForthLocalVariable> LocalVariables { get; set; }
/// <summary>
/// Words
/// </summary>
public List<ForthWord> Words { get; set; }
/// <summary>
/// External words
/// </summary>
public List<ExternalWord> ExternalWords { get; set; }
/// <summary>
/// Library name (as declared by the LIBRARY keyword)
/// </summary>
public string LibraryName { get; set; }
}
}<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System.Reflection.Emit;
namespace DeltaForth.Descriptors
{
/// <summary>
/// Definition of a structure used to code BEGIN-AGAIN, BEGIN-UNTIL, BEGIN-WHILE-REPEAT
/// </summary>
public class BEGINDescriptor
{
/// <summary>
/// Label for BEGIN
/// </summary>
public Label lbBegin { get; set; }
/// <summary>
/// Label for END
/// </summary>
public Label lbEnd { get; set; }
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System.Reflection.Emit;
namespace DeltaForth.Descriptors
{
/// <summary>
/// Definition of a structure used to code DO-LOOP/+LOOP structure
/// </summary>
public class DODescriptor
{
/// <summary>
/// Label for DO
/// </summary>
public Label lbDo { get; set; }
/// <summary>
/// Label for LOOP
/// </summary>
public Label lbLoop { get; set; }
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System;
using System.Collections;
using System.Text.RegularExpressions;
using DeltaForth.DataStructures;
using System.Collections.Generic;
namespace DeltaForth.SyntacticAnalyzer
{
/// <summary>
/// Delta Forth - The .NET Forth Compiler
/// (C) <NAME>, PhD (<EMAIL>)
///
/// Class ForthSyntacticAnalyzer
///
/// Date of creation: September 5, 2001
/// Date of last update: November 2, 2011
///
/// Description:
/// </summary>
internal class ForthSyntacticAnalyzer
{
private List<ForthVariable> GlobalVariables; // List of source global variables
private List<ForthLocalVariable> LocalVariables; // List of source local variables
private List<ForthConstant> GlobalConstants; // List of source global constants
private List<ForthWord> Words; // List of words defined in the source file
private List<ExternalWord> ExternalWords; // List of external words defined in the source file
private string LibraryName; // Name of the library to be generated, null if an executable program should be generated
private List<ForthAtom> SourceAtoms; // List of source atoms (obtained from a ForthParser)
private Stack SourceStack; // Stack used when defining variables and constants
private bool InWordDefinition; // TRUE if parsing inside a word
private bool MainDefined; // TRUE if the word MAIN has been defined
private string[] ReservedWords = new string[] {"@", "?", "!", "+!", "DUP", "-DUP", "DROP",
"SWAP", "OVER", "ROT", ".", "+", "-", "*",
"/", ">R", "R>", "I", "I'", "J", "MOD", "/MOD", "*/",
"*/MOD", "MINUS", "ABS", "MIN", "MAX", "1+",
"2+", "0=", "0<", "=", "<", ">", "<>", "AND",
"OR", "XOR", "EMIT", "CR", "SPACE", "SPACES",
"TYPE", "FILL", "ERASE", "BLANKS", "CMOVE", "KEY",
"EXPECT", "PAD", "S0", "R0",
"SP@", "SP!", "RP@", "RP!", "TIB", "QUERY",
"STR2INT", "IF", "ELSE", "THEN", "DO", "LOOP",
"+LOOP", "LEAVE", "BEGIN", "INT2STR",
"AGAIN", "UNTIL", "WHILE", "REPEAT", "CASE", "OF", "ENDOF",
"ENDCASE", "COUNT", "EXIT", "EXTERN", "CONSTANT",
"VARIABLE", "ALLOT", "LIBRARY", "LOAD"};
// ForthSyntacticAnalyzer constructor
public ForthSyntacticAnalyzer(List<ForthAtom> p_SourceAtoms)
{
// Initialize variables
GlobalVariables = new List<ForthVariable>();
LocalVariables = new List<ForthLocalVariable>();
GlobalConstants = new List<ForthConstant>();
Words = new List<ForthWord>();
ExternalWords = new List<ExternalWord>();
SourceStack = new Stack();
LibraryName = null;
SourceAtoms = p_SourceAtoms;
InWordDefinition = false;
MainDefined = false;
}
/// <summary>
/// Get the meta information generated by the syntactic analyzer
/// </summary>
/// <returns>Compiler metadata.</returns>
public CompilerMetadata GetMetaData()
{
// Analyze source atoms
try
{
DoAnalysis();
}
catch (InvalidOperationException)
{
RaiseException(SyntacticExceptionType._EUnexpectedEndOfFile, ((ForthAtom)SourceAtoms[0]));
}
return new CompilerMetadata
{
GlobalConstants = GlobalConstants,
GlobalVariables = GlobalVariables,
LocalVariables = LocalVariables,
Words = Words,
ExternalWords = ExternalWords,
LibraryName = LibraryName
};
}
// IsReserved - Checkes whether a specified word is reserved
// Input: WordName - the name of the atom
// Output: Returns true if the specified word is reserved
private bool IsReserved(string WordName)
{
bool reserved = false;
WordName = WordName.ToLower();
for(int i = 0; i < ReservedWords.Length; i++)
{
if(ReservedWords[i].ToLower() == WordName)
{
reserved = true;
break;
}
}
return reserved;
}
// IsConstOrVar - Checkes whether a specified word is a constant or a variable
// Input: Atom - the name of the atom
// Output: Returns true if the specified word is a constant or a variable
private bool IsConstOrVar(string Atom)
{
bool bConstOrVar = false;
// Search constant name space
for(int i = 0; i < GlobalConstants.Count; i++)
{
ForthConstant fc = (ForthConstant)GlobalConstants[i];
if(fc.Name.ToUpper() == Atom.ToUpper()) bConstOrVar = true;
}
// Search variable name space
for(int i = 0; i < GlobalVariables.Count; i++)
{
ForthVariable fv = (ForthVariable)GlobalVariables[i];
if(fv.Name.ToUpper() == Atom.ToUpper()) bConstOrVar = true;
}
return bConstOrVar;
}
// IsIdentifier - Checkes whether a specified atom is a properly named identifier
// Input: Identifier - the name of the atom
// Output: Returns true if the atom is an identifier
private bool IsIdentifier(string atom)
{
if(atom.Length > 31) return false; // The atom should not be longer than 31 characters
if((atom[0] >= '0') && (atom[0] <= '9')) return false; // The first character cannot be a figure
if(IsReserved(atom)) return false; // The atom should not be a reserved name
return true;
}
// IsNumber - Checkes whether a specified atom is a number
// Input: Identifier - the name of the atom
// Output: Returns true if the specified word is a number
private bool IsNumber(string atom)
{
try
{
Convert.ToInt32(atom);
}
catch(Exception)
{
return false;
}
return true;
}
// IsString - Checkes whether a specified atom is a string (should include the quotation marks)
// Input: Identifier - the name of the atom
// Output: Returns true if the specified word is a string
private bool IsString(string atom)
{
Regex reg = new Regex("\".*\""); // Matches any string between quotation marks
Match match = reg.Match(atom);
return match.Success;
}
// DoAnalysis - Builds up the word, constant and variable lists
// Input: None
// Output: None (Globally changes GlobalVariables, GlobalConstants, LocalVariables, Words)
private void DoAnalysis()
{
ForthAtom Atom, NextAtom;
ForthWord WordDef = null; // Holds the definition of a word
string temp;
int noIFs = 0; // Number of IF statements
int noDOs = 0; // Number of DO statements
int noBEGINs = 0; // Number of BEGIN statements
int noWHILEs = 0; // Number of WHILE statements
int noCASEs = 0; // Number of CASE statements
int noOFs = 0; // Number of OF statements
// Define enumerator for the source atoms list
IEnumerator saEnum = SourceAtoms.GetEnumerator();
while(saEnum.MoveNext())
{
Atom = (ForthAtom)saEnum.Current;
// If the atom does not start with " or ." make the atom upper case
if(!Atom.Name.StartsWith(".\"") && !Atom.Name.StartsWith("\""))
Atom.Name = Atom.Name.ToUpper();
// Process atoms
switch(Atom.Name)
{
case "EXTERN": // Store information after EXTERN for calling methods at runtime
if (InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareOutsideWords, Atom);
saEnum.MoveNext(); // Advance to next atom
NextAtom = ((ForthAtom)saEnum.Current);
string ForthWord = NextAtom.Name; // Forth word name
if (IsReserved(ForthWord)) RaiseException(SyntacticExceptionType._EReservedWord, NextAtom);
if (!IsIdentifier(ForthWord)) RaiseException(SyntacticExceptionType._EInvalidIdentifier, NextAtom);
saEnum.MoveNext(); // Advance to next atom
NextAtom = ((ForthAtom)saEnum.Current);
string FileName = NextAtom.Name; // Library name
saEnum.MoveNext(); // Advance to next atom
NextAtom = ((ForthAtom)saEnum.Current);
string Callee = NextAtom.Name;
int DotPos = Callee.LastIndexOf('.');
string ClassName = Callee.Substring(0, DotPos);
string MethodName = Callee.Substring(DotPos + 1);
ExternalWords.Add(new ExternalWord { Name = ForthWord, Library = FileName, Class = ClassName, Method = MethodName });
break;
case "LIBRARY": // Store next atom as the name of the library
if (InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareOutsideWords, Atom);
saEnum.MoveNext(); // Advance to next atom
NextAtom = ((ForthAtom)saEnum.Current);
string libname = NextAtom.Name;
if(IsReserved(libname)) RaiseException(SyntacticExceptionType._EReservedWord, NextAtom);
if(!IsIdentifier(libname)) RaiseException(SyntacticExceptionType._EInvalidIdentifier, NextAtom);
LibraryName = libname;
break;
case "CONSTANT": // Associate the value on the global stack to the next atom
if(InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareOutsideWords, Atom);
saEnum.MoveNext(); // Advance to next atom
NextAtom = ((ForthAtom)saEnum.Current);
if(IsReserved(NextAtom.Name)) RaiseException(SyntacticExceptionType._EReservedWord, NextAtom);
if(!IsIdentifier(NextAtom.Name)) RaiseException(SyntacticExceptionType._EInvalidIdentifier, NextAtom);
if(IsConstOrVar(NextAtom.Name)) RaiseException(SyntacticExceptionType._EDuplicateConst, NextAtom);
if(SourceStack.Count == 0) RaiseException(SyntacticExceptionType._EUnableToDefineConst, NextAtom);
GlobalConstants.Add(new ForthConstant{Name = NextAtom.Name, Value = SourceStack.Pop()}); // Add constant definiton to the list
break;
case "VARIABLE": // The next atom is the variable name with the initial size of 1
saEnum.MoveNext(); // Advance to next atom
NextAtom = ((ForthAtom)saEnum.Current);
if(IsReserved(NextAtom.Name)) RaiseException(SyntacticExceptionType._EReservedWord, NextAtom);
if(!IsIdentifier(NextAtom.Name)) RaiseException(SyntacticExceptionType._EInvalidIdentifier, NextAtom);
if(IsConstOrVar(NextAtom.Name)) RaiseException(SyntacticExceptionType._EDuplicateVar, NextAtom);
if(!InWordDefinition)
{
GlobalVariables.Add(new ForthVariable { Name = NextAtom.Name, Size = 1 });
}
else
{
LocalVariables.Add(new ForthLocalVariable { Name = NextAtom.Name, WordName = WordDef.Name });
}
break;
case "ALLOT": // The last number on the stack is the additional size for the last defined variable
if(InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareOutsideWords, Atom);
if(SourceStack.Count == 0) RaiseException(SyntacticExceptionType._EUnableToAllocVar, Atom);
if(SourceStack.Peek().GetType() != typeof(int)) RaiseException(SyntacticExceptionType._EWrongAllotConstType, Atom);
int AllotSize = (int)SourceStack.Pop(); // Get the ALLOT size
// Change the size of the last defined variable
int LastVarPos = GlobalVariables.Count - 1; // Get the position of the last variable we defined
ForthVariable fv = (ForthVariable)(GlobalVariables[LastVarPos]);
fv.Size += AllotSize;
GlobalVariables[LastVarPos] = fv; // Update changes in list
break;
case ":": // Begin word definition
if(InWordDefinition) RaiseException(SyntacticExceptionType._ENestedWordsNotAllowed, Atom);
saEnum.MoveNext(); // Advance to next atom
NextAtom = ((ForthAtom)saEnum.Current);
NextAtom.Name = NextAtom.Name.ToUpper();
if(IsReserved(NextAtom.Name)) RaiseException(SyntacticExceptionType._EReservedWord, NextAtom);
if(!IsIdentifier(NextAtom.Name)) RaiseException(SyntacticExceptionType._EInvalidIdentifier, NextAtom);
InWordDefinition = true; // Signal beginning of word definition
WordDef = new ForthWord{Name = NextAtom.Name}; // Alloc here the structure, we fill it later
if(NextAtom.Name == "MAIN") MainDefined = true;
break;
case ";": // End word definition
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
// All control structures should be terminated by now
if((noIFs > 0) || (noDOs > 0) || (noBEGINs > 0) || (noWHILEs > 0) || (noCASEs > 0))
RaiseException(SyntacticExceptionType._EUnfinishedControlStruct, Atom);
Words.Add(WordDef); // Add word to the list
InWordDefinition = false; // Signal end of word definition
break;
case "IF": // IF statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
noIFs++;
goto default;
case "ELSE": // ELSE statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noIFs == 0) RaiseException(SyntacticExceptionType._EMalformedIETStruct, Atom);
goto default;
case "THEN": // THEN statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noIFs == 0) RaiseException(SyntacticExceptionType._EMalformedIETStruct, Atom);
noIFs--;
goto default;
case "DO": // DO statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
noDOs++;
goto default;
case "LOOP": // LOOP statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noDOs == 0) RaiseException(SyntacticExceptionType._EMalformedDLStruct, Atom);
noDOs--;
goto default;
case "+LOOP": // +LOOP statement
goto case "LOOP";
case "LEAVE": // LEAVE statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noDOs == 0) RaiseException(SyntacticExceptionType._EMalformedDLStruct, Atom);
goto default;
case "BEGIN": // BEGIN statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
noBEGINs++;
goto default;
case "WHILE": // WHILE statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noBEGINs == 0) RaiseException(SyntacticExceptionType._EMalformedBWRStruct, Atom);
noWHILEs++;
goto default;
case "REPEAT": // REPEAT statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if((noBEGINs == 0) || (noWHILEs == 0)) RaiseException(SyntacticExceptionType._EMalformedBWRStruct, Atom);
noBEGINs--;
noWHILEs--;
goto default;
case "AGAIN": // AGAIN statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noBEGINs == 0) RaiseException(SyntacticExceptionType._EMalformedBAStruct, Atom);
noBEGINs--;
goto default;
case "UNTIL": // UNTIL statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noBEGINs == 0) RaiseException(SyntacticExceptionType._EMalformedBUStruct, Atom);
noBEGINs--;
goto default;
case "CASE": // CASE statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
noCASEs++;
goto default;
case "OF": // OF statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noCASEs == 0) RaiseException(SyntacticExceptionType._EMalformedCOEStruct, Atom);
noOFs++;
goto default;
case "ENDOF": // ENDOF statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noOFs == 0) RaiseException(SyntacticExceptionType._EMalformedCOEStruct, Atom);
noOFs--;
goto default;
case "ENDCASE": // ENDCASE statement
if(!InWordDefinition) RaiseException(SyntacticExceptionType._EDeclareInsideWords, Atom);
if(noOFs > 0) RaiseException(SyntacticExceptionType._EMalformedCOEStruct, Atom);
noCASEs--;
goto default;
default:
temp = Atom.Name; // Get the atom name
if(InWordDefinition)
{
WordDef.Definition.Add(temp); // Add atom to word definition
}
else
{
// The atom should now be a constant previously defined, a number or a string
int ConstValue; // Here we hold the value of the constant, in case we find it
if(GetConstIntValue(temp, out ConstValue)) SourceStack.Push(ConstValue);
else if(IsNumber(temp)) SourceStack.Push(Convert.ToInt32(temp));
else if(IsString(temp)) SourceStack.Push(temp.Trim(new char[] {'"'}));
else RaiseException(SyntacticExceptionType._EInvalidIdentifier, Atom);
}
break;
}
}
// Check whether word MAIN is defined
if(MainDefined == false) RaiseException(SyntacticExceptionType._EMainNotDefined);
}
// GetConstIntValue - Retrieves the value of an integer constant (if found)
// Input: ConstName - the name of the constant
// Output: ConstValue - The integer value of the constant
private bool GetConstIntValue(string ConstName, out int ConstValue)
{
bool ConstFound = false;
ConstValue = 0;
IEnumerator ConstEnum = GlobalConstants.GetEnumerator();
while(ConstEnum.MoveNext())
{
ForthConstant fc = (ForthConstant)ConstEnum.Current;
if((fc.Name.ToLower() == ConstName.ToLower()) && (fc.Value.GetType() == typeof(int)))
{
ConstValue = (int)fc.Value;
ConstFound = true;
}
}
return ConstFound;
}
// RaiseException - Throws a specified exception
// Input: SyntacticExceptionType - the code of the exception to be thrown
// ForthAtom - the atom (with file name and line number) that caused the error
// Output: None
// Overloads: 1
private void RaiseException(SyntacticExceptionType exc)
{
ForthAtom atom = new ForthAtom { Name = string.Empty, FileName = string.Empty, LineNumber = 0 }; // Create an "empty" atom
RaiseException(exc, atom);
}
private void RaiseException(SyntacticExceptionType exc, ForthAtom atom)
{
switch(exc)
{
case SyntacticExceptionType._EDeclareOutsideWords:
throw new Exception(atom.Name + " should be declared outside words. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EDeclareInsideWords:
throw new Exception(atom.Name + " should be declared inside words. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EReservedWord:
throw new Exception(atom.Name + " is a reserved identifier. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EInvalidIdentifier:
throw new Exception(atom.Name + " is an invalid identifier. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EUnableToDefineConst:
throw new Exception("Unable to define constant " + atom.Name + ". Number or string required before CONSTANT. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EUnableToAllocVar:
throw new Exception("Unable to alloc variable space " + atom.Name + ". Number needed before ALLOT. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EUnexpectedEndOfFile:
throw new Exception("Unexpected end of file " + atom.FileName + ".");
case SyntacticExceptionType._EWrongAllotConstType:
throw new Exception("Wrong constant type specified for ALLOT. Use an integer. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._ENestedWordsNotAllowed:
throw new Exception("Nested words are not allowed. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EMalformedBWRStruct:
throw new Exception("Malformed BEGIN-WHILE-REPEAT control structure. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EMalformedBAStruct:
throw new Exception("Malformed BEGIN-AGAIN control structure. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EMalformedBUStruct:
throw new Exception("Malformed BEGIN-UNTIL control structure. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EMalformedIETStruct:
throw new Exception("Malformed IF-ELSE-THEN control structure. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EMalformedCOEStruct:
throw new Exception("Malformed CASE-OF-ENDCASE control structure. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EUnfinishedControlStruct:
throw new Exception("Control structures must be terminated before ';'. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EMainNotDefined:
throw new Exception("Program starting point is missing. Please define the word MAIN.");
case SyntacticExceptionType._EDuplicateConst:
throw new Exception("Constant redefines an already defined constant or variable. (" + atom.FileName + ":" + atom.LineNumber + ")");
case SyntacticExceptionType._EDuplicateVar:
throw new Exception("Variable redefines an already defined constant or variable. (" + atom.FileName + ":" + atom.LineNumber + ")");
}
}
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System;
using System.IO;
namespace DeltaForth
{
public class ForthConsole
{
#region Compiler command-line option values
static bool DisplayLogo, QuietMode, ShowTimings, GenerateExecutable, CheckStack, DisplayMap;
static int ForthStackSize = 524288, ReturnStackSize = 1024;
static string SourceFile; // Input filename
static string OutputFile; // Output filename
static string OutputDirectory; // Output directory
static string SignatureFile; // Signature file (snk)
#endregion
#region Local variables
static DateTime CompilationTimeStart, CompilationTimeEnd;
static DateTime PartialTimeStart, PartialTimeEnd;
#endregion
#region Display Methods
/// <summary>
/// Display text on the console with the specified color
/// </summary>
/// <param name="Text">Text to display to console</param>
/// <param name="Color">Color of the text</param>
static void DisplayLineToConsole(string Text, ConsoleColor Color)
{
if (!QuietMode)
{
var OldConsoleColor = Console.ForegroundColor;
Console.ForegroundColor = Color;
Console.WriteLine(Text);
Console.ForegroundColor = OldConsoleColor;
}
}
/// <summary>
/// Display text on the console with the default color
/// </summary>
/// <param name="Text">Text to display to console</param>
static void DisplayLineToConsole(string Text)
{
DisplayLineToConsole(Text, ConsoleColor.Gray);
}
/// <summary>
/// Display text on the console with the specified color
/// </summary>
/// <param name="Text">Text to display to console</param>
/// <param name="Color">Color of the text</param>
static void DisplayToConsole(string Text, ConsoleColor Color)
{
if (!QuietMode)
{
var OldConsoleColor = Console.ForegroundColor;
Console.ForegroundColor = Color;
Console.Write(Text);
Console.ForegroundColor = OldConsoleColor;
}
}
/// <summary>
/// Display text on the console with the default color
/// </summary>
/// <param name="Text">Text to display to console</param>
static void DisplayToConsole(string Text)
{
DisplayToConsole(Text, ConsoleColor.Gray);
}
static void DisplayLogoToConsole()
{
DisplayLineToConsole("Delta Forth .NET Compiler, Version 1.4", ConsoleColor.Yellow);
DisplayLineToConsole("World's first Forth compiler for the .NET platform", ConsoleColor.White);
DisplayLineToConsole("Copyright (C)1997-2019 <NAME>, PhD <<EMAIL>>. All Rights Reserved.");
DisplayLineToConsole("Web: http://www.bocan.ro/deltaforthnet\n\r");
}
static void DisplayUsageToConsole()
{
DisplayLogoToConsole();
DisplayLineToConsole("Usage: DeltaForth.exe <source file> [options]", ConsoleColor.Yellow);
DisplayLineToConsole("\n\rOptions:");
DisplayLineToConsole("/NOLOGO\t\t\tDon't type the logo");
DisplayLineToConsole("/QUIET\t\t\tDon't report compiling progress");
DisplayLineToConsole("/CLOCK\t\t\tMeasure and report compilation times");
DisplayLineToConsole("/EXE\t\t\tCompile to EXE (default)");
DisplayLineToConsole("/DLL\t\t\tCompile to DLL");
DisplayLineToConsole("/NOCHECK\t\tDisable stack bounds checking");
DisplayLineToConsole("/FS:<size>\t\tSpecify Forth stack size (default is 524288 cells)");
DisplayLineToConsole("/RS:<size>\t\tSpecify return stack size (default is 1024 cells)");
DisplayLineToConsole("/MAP\t\t\tGenerate detailed map information");
DisplayLineToConsole("/OUTPUT=<targetfile>\tCompile to file with specified name\n\r\t\t\t(user must provide extension, if any)");
DisplayLineToConsole("/KEY=<keyfile>\t\tCompile with strong signature\n\r\t\t\t(<keyfile> contains private key)");
DisplayLineToConsole("\n\rDefault source file extension is .4th", ConsoleColor.Green);
}
#endregion
static void DisplayMapInformation(ForthCompiler compiler)
{
DisplayLineToConsole(string.Empty);
DisplayLineToConsole("Summary of compilation objects", ConsoleColor.White);
// Display global constants
DisplayLineToConsole(string.Empty);
DisplayLineToConsole("Global constants:", ConsoleColor.Blue);
foreach (var fc in compiler.MetaData.GlobalConstants)
{
if (fc.Value.GetType() != typeof(string))
{
DisplayLineToConsole(string.Format("{0} = {1}", fc.Name, fc.Value));
}
else
{
DisplayLineToConsole(string.Format("{0} = \"{1}\"", fc.Name, fc.Value));
}
}
// Display global variables
DisplayLineToConsole(string.Empty);
DisplayLineToConsole("Global variables:", ConsoleColor.Blue);
foreach (var fv in compiler.MetaData.GlobalVariables)
{
DisplayLineToConsole(string.Format("{0} = (Addr:{1}, Size:{2})", fv.Name, fv.Address, fv.Size));
}
// Display local variables
DisplayLineToConsole(string.Empty);
DisplayLineToConsole("Local variables:", ConsoleColor.Blue);
foreach (var flv in compiler.MetaData.LocalVariables)
{
DisplayLineToConsole(string.Format("{0} = (Addr:{1}, Word:{2})", flv.Name, flv.Address, flv.WordName));
}
// Display words
DisplayLineToConsole(string.Empty);
DisplayLineToConsole("Words:", ConsoleColor.Blue);
foreach (var ew in compiler.MetaData.Words)
{
DisplayLineToConsole(string.Format("-> {0}", ew.Name));
}
// Display external words
DisplayLineToConsole(string.Empty);
DisplayLineToConsole("External words:", ConsoleColor.Blue);
foreach (var ew in compiler.MetaData.ExternalWords)
{
DisplayLineToConsole(string.Format("{0} = (Library:{1}, Class:{2}, Method:{3})", ew.Name, ew.Library, ew.Class, ew.Method));
}
}
static void Main(string[] args)
{
// Initialize default parameter values
DisplayLogo = GenerateExecutable = CheckStack = true;
QuietMode = ShowTimings = DisplayMap = false;
OutputFile = OutputDirectory = SignatureFile = string.Empty;
// Display usage screen if no parameters are given
if(args.Length < 1)
{
DisplayUsageToConsole();
return;
}
SourceFile = args[0];
// Cycle through command line parameters
for (int i = 1; i < args.Length; i++)
{
switch (args[i].ToUpper())
{
case "/NOLOGO":
DisplayLogo = false;
break;
case "/QUIET":
QuietMode = true;
break;
case "/CLOCK":
ShowTimings = true;
break;
case "/EXE":
GenerateExecutable = true;
break;
case "/DLL":
GenerateExecutable = false;
break;
case "/NOCHECK":
CheckStack = false;
break;
case "/MAP":
DisplayMap = true;
break;
default:
if (args[i].ToUpper().StartsWith("/OUTPUT="))
{
OutputFile = args[i].Substring(8);
}
else
if (args[i].ToUpper().StartsWith("/FS:"))
{
try
{
ForthStackSize = Convert.ToInt32(args[i].Substring(4));
}
catch (FormatException)
{
DisplayUsageToConsole();
return;
}
}
else
if (args[i].ToUpper().StartsWith("/RS:"))
{
try
{
ReturnStackSize = Convert.ToInt32(args[i].Substring(4));
}
catch (FormatException)
{
DisplayUsageToConsole();
return;
}
}
else
if (args[i].ToUpper().StartsWith("/KEY="))
{
SignatureFile = args[i].Substring(5);
}
else
{
DisplayUsageToConsole();
return;
}
break;
}
}
// Process parameters
if (DisplayLogo) DisplayLogoToConsole();
#region Input File Processing
// If the extension for the input file is missing, add it
if (!Path.HasExtension(SourceFile))
{
SourceFile = Path.ChangeExtension(SourceFile, ".4th");
}
#endregion
#region Input File Existence Check
// Check whether the input file really exists
if (!File.Exists(SourceFile))
{
DisplayLineToConsole(string.Format("\n\rERROR: The file '{0}' could not be found.", SourceFile), ConsoleColor.Red);
return;
}
#endregion
#region Output File Processing
// If there is no output file specified, generate a name for it based on the input file
if (OutputFile == string.Empty)
{
OutputFile = Path.GetFileName(SourceFile);
OutputFile = Path.ChangeExtension(OutputFile, GenerateExecutable ? ".exe" : ".dll");
OutputDirectory = Path.GetDirectoryName(SourceFile);
if (OutputDirectory == string.Empty)
{
OutputDirectory = ".";
}
}
else
{
OutputDirectory = Path.GetDirectoryName(OutputFile);
if (OutputDirectory == string.Empty)
OutputDirectory = null;
OutputFile = Path.GetFileName(OutputFile);
}
#endregion
ForthCompiler compiler = new ForthCompiler();
compiler.OnCodeGenerationStart += new ForthCompiler.CompilerEventHandler(compiler_OnCodeGenerationStart);
compiler.OnCodeGenerationEnd += new ForthCompiler.CompilerEventHandler(compiler_OnCodeGenerationEnd);
compiler.OnCompilationStart += new ForthCompiler.CompilerEventHandler(compiler_OnCompilationStart);
compiler.OnCompilationEnd += new ForthCompiler.CompilerEventHandler(compiler_OnCompilationEnd);
compiler.OnParsingEnd += new ForthCompiler.CompilerEventHandler(compiler_OnParsingEnd);
compiler.OnParsingStart += new ForthCompiler.CompilerEventHandler(compiler_OnParsingStart);
compiler.OnSyntacticAnalysisEnd += new ForthCompiler.CompilerEventHandler(compiler_OnSyntacticAnalysisEnd);
compiler.OnSyntacticAnalysisStart += new ForthCompiler.CompilerEventHandler(compiler_OnSyntacticAnalysisStart);
try
{
compiler.CompileFile(SourceFile, OutputFile, OutputDirectory, SignatureFile, GenerateExecutable, CheckStack, ForthStackSize, ReturnStackSize);
}
catch(Exception e)
{
DisplayLineToConsole("\t\tFAILED", ConsoleColor.Red);
DisplayLineToConsole(string.Format("\n\rCompilation error: {0}", e.Message), ConsoleColor.White);
return;
}
if(DisplayMap)
DisplayMapInformation(compiler);
}
#region Event Handlers
static void compiler_OnSyntacticAnalysisStart(object sender, object e)
{
PartialTimeStart = DateTime.Now;
DisplayToConsole("Starting syntactic analysis...");
}
static void compiler_OnSyntacticAnalysisEnd(object sender, object e)
{
PartialTimeEnd = DateTime.Now;
PartialTimeEnd = DateTime.Now;
if (ShowTimings)
{
DisplayToConsole("\t\tOK", ConsoleColor.Green);
DisplayLineToConsole("\t(" + Math.Round((PartialTimeEnd - PartialTimeStart).TotalMilliseconds) + " ms)");
}
else
{
DisplayLineToConsole("\t\tOK", ConsoleColor.Green);
}
}
static void compiler_OnParsingStart(object sender, object e)
{
PartialTimeStart = DateTime.Now;
DisplayToConsole("Parsing source file...");
}
static void compiler_OnParsingEnd(object sender, object e)
{
PartialTimeEnd = DateTime.Now;
if (ShowTimings)
{
DisplayToConsole("\t\t\tOK", ConsoleColor.Green);
DisplayLineToConsole("\t(" + Math.Round((PartialTimeEnd - PartialTimeStart).TotalMilliseconds) + " ms)");
}
else
{
DisplayLineToConsole("\t\t\tOK", ConsoleColor.Green);
}
}
static void compiler_OnCompilationStart(object sender, object e)
{
DisplayLineToConsole("Starting compilation...", ConsoleColor.White);
DisplayLineToConsole(string.Empty);
CompilationTimeStart = DateTime.Now;
}
static void compiler_OnCompilationEnd(object sender, object e)
{
CompilationTimeEnd = DateTime.Now;
if (ShowTimings)
{
DisplayLineToConsole(string.Empty);
DisplayToConsole("Compilation ended.", ConsoleColor.White);
DisplayLineToConsole("\t\t\t\t(" + Math.Round((CompilationTimeEnd - CompilationTimeStart).TotalMilliseconds) + " ms)");
}
else
{
DisplayLineToConsole(string.Empty);
DisplayLineToConsole("Compilation ended successfully.", ConsoleColor.White);
}
}
static void compiler_OnCodeGenerationEnd(object sender, object e)
{
PartialTimeEnd = DateTime.Now;
if (ShowTimings)
{
DisplayToConsole("\t\tOK", ConsoleColor.Green);
DisplayLineToConsole("\t(" + Math.Round((PartialTimeEnd - PartialTimeStart).TotalMilliseconds) + " ms)");
}
else
{
DisplayLineToConsole("\t\tOK", ConsoleColor.Green);
}
}
static void compiler_OnCodeGenerationStart(object sender, object e)
{
PartialTimeStart = DateTime.Now;
DisplayToConsole("Generating executable code...");
}
#endregion
}
}
<file_sep>using System;
namespace Library1
{
public class Class2
{
public Class2()
{
Console.WriteLine("This is the constructor of the Class2 class.");
}
public void DisplayRandom()
{
Random RandNumber = new Random();
Console.WriteLine("Random number: {0}", RandNumber.Next(1000));
RandNumber = null;
}
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System.Reflection.Emit;
namespace DeltaForth.Descriptors
{
/// <summary>
/// Definition of an IF structure used to code IF-ELSE-THEN
/// </summary>
public class IFDescriptor
{
/// <summary>
/// Label for the ELSE branch
/// </summary>
public Label lbElse {get; set;}
/// <summary>
/// // TRUE if lbElse has already been used
/// </summary>
public bool bElse { get; set; }
/// <summary>
/// // Label for the end of the control struct
/// </summary>
public Label lbEnd { get; set; }
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.IO;
using DeltaForth.DataStructures;
using System.Collections.Generic;
namespace DeltaForth.Descriptors
{
/// <summary>
/// Delta Forth - The .NET Forth Compiler
/// (C) <NAME>, PhD (<EMAIL>)
///
/// Class ForthCodeGenerator
///
/// Date of creation: September 12, 2001
/// Date of last update: November 1, 2011
///
/// Description:
/// </summary>
///
internal class ForthCodeGenerator
{
#region Local variables
private AppDomain appDomain; // Domain where we define the assemblies
private AssemblyName assemblyName; // AssemblyName
private AssemblyBuilder assembly; // Assembly
private ModuleBuilder module; // Module builder
private TypeBuilder ForthEngineClass; // DeltaForthEngine type
private List<MethodBuilder> Methods; // Metods defined in the class
private CompilerMetadata MetaData; // Compiler metadata (generated by the syntactic analyzer)
private MethodInfo StartupCode; // Describes the pre-MAIN startup code
private string TargetFileName; // Name of the target file (no path information)
private string TargetDirectory; // Name of the target directory
private bool bExe; // TRUE if generating code for EXE, FALSE for DLL
private bool bCheckStack; // TRUE if generating exception catching code for each method
private bool bExtCallerDefined; // TRUE if the runtime contains the ExternalCaller function
// The function is generated in the runtime area at the first external call
private MethodBuilder extCaller; // ExternalCaller method builder
#endregion
#region Stacks
private int ForthStackOrigin; // The Forth stack origin
private FieldBuilder ForthStack; // The Forth stack
private FieldBuilder ForthStackIndex; // The Forth stack index
private int ReturnStackOrigin; // The return stack origin
private FieldBuilder ReturnStack; // The return stack
private FieldBuilder ReturnStackIndex; // The return stack index
private int ForthStackSize; // The Forth stack size
private int ReturnStackSize; // The Return stack size
private int Tib; // TIB area offset
private int Pad; // PAD area offset
private int LocalVarArea; // A maximum of 1024 local variables can be defined
#endregion
#region Temporary variables
private FieldBuilder Dummy1; // Dummy variable, used for temporary storage
private FieldBuilder Dummy2; // Dummy variable, used for temporary storage
private FieldBuilder Dummy3; // Dummy variable, used for temporary storage
private FieldBuilder strDummy; // Dummy variable, used for temporary storage
private FieldBuilder DoLoopDummy; // Dummy variable, used for Do-LOOP/+LOOP structure
#endregion
#region Write methods (used when generating code that displays text)
private MethodInfo WriteStringMethod; // Describes the Write(string) method
private MethodInfo WriteLineStringMethod; // Describes the WriteLine(string) method
private MethodInfo WriteIntMethod; // Describes the Write(int) method
private MethodInfo WriteCharMethod; // Describes the Write(char) method
#endregion
#region Control structures stacks
private Stack<IFDescriptor> IFStack; // Stack for the IF-ELSE-THEN control structure
private Stack<BEGINDescriptor> BEGINStack; // Stack for the BEGIN-UNTIL control structure
private Stack<Label> CASEStack; // Stack for the CASE-ENDCASE control structure
private Stack<DODescriptor> DOStack; // Stack for the DO-LOOP/+LOOP control structure
#endregion
public ForthCodeGenerator(CompilerMetadata MetaData, string TargetFileName, string TargetDirectory, string SignatureFileName, bool GenerateExecutable, bool GenerateStackFrames, int ForthStackSize, int ReturnStackSize)
{
// Initialize variables
this.TargetFileName = TargetFileName;
this.TargetDirectory = TargetDirectory;
this.MetaData = MetaData;
bExe = GenerateExecutable;
bCheckStack = GenerateStackFrames;
bExtCallerDefined = false;
// Set stack sizes
this.ForthStackSize = ForthStackSize;
this.ReturnStackSize = ReturnStackSize;
// Set system variables
Tib = ForthStackSize - 64 - 80;
Pad = ForthStackSize - 64;
LocalVarArea = ForthStackSize - 64 - 80 - 1024;
// Initialize stack origins
ForthStackOrigin = 0;
ReturnStackOrigin = 0;
// Initialize Write methods
WriteStringMethod = typeof(Console).GetMethod("Write", new Type[] { typeof(String) });
WriteLineStringMethod = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) });
WriteIntMethod = typeof(Console).GetMethod("Write", new Type[] { typeof(int) });
WriteCharMethod = typeof(Console).GetMethod("Write", new Type[] { typeof(char) });
// Initialize stacks
IFStack = new Stack<IFDescriptor>();
BEGINStack = new Stack<BEGINDescriptor>();
CASEStack = new Stack<Label>();
DOStack = new Stack<DODescriptor>();
// Initialize address of global variables
for(int i = 0; i < MetaData.GlobalVariables.Count; i++)
{
ForthVariable fv = MetaData.GlobalVariables[i];
fv.Address = ForthStackOrigin;
ForthStackOrigin += fv.Size; // Advance the stack origin to accomodate the variable size
MetaData.GlobalVariables[i] = fv;
}
Methods = new List<MethodBuilder>();
// ...
appDomain = Thread.GetDomain(); // Initialize domain
assemblyName = new AssemblyName(); // Create an assembly name
assemblyName.Name = "DeltaForthEngine";
// Sign assembly (if the p_SignatureFileName parameter is not empty)
if(SignatureFileName != string.Empty)
{
try
{
FileStream fs = new FileStream(SignatureFileName, FileMode.Open);
StrongNameKeyPair kp = new StrongNameKeyPair(fs);
// The line below will throw an exception if the file does not
// contain a valid key
string PublicKey = kp.PublicKey.ToString();
fs.Close();
assemblyName.KeyPair = kp;
}
catch(FileNotFoundException)
{
throw new Exception("Signature file " + SignatureFileName + " is missing.");
}
catch(Exception)
{
throw new Exception("Signature file " + SignatureFileName + " is invalid.");
}
}
// Create the assembly
assembly = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save, TargetDirectory);
// Create a module within the assembly
module = assembly.DefineDynamicModule("DeltaForthModule", TargetFileName);
// Define a public class
var LibraryName = "DeltaForthEngine"; // Default class name
if (!string.IsNullOrEmpty(MetaData.LibraryName)) LibraryName = MetaData.LibraryName;
ForthEngineClass = module.DefineType(LibraryName, TypeAttributes.Public | TypeAttributes.BeforeFieldInit);
// Create the class constructor
Type[] constructorArgs = {};
ConstructorBuilder constructor = ForthEngineClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs);
// Create the method "InitForthEngine" to initialize the Forth environment
StartupCode = CreateStartupCode();
// Generate IL code for the constructor
ILGenerator constructorIL = constructor.GetILGenerator();
constructorIL.Emit(OpCodes.Ldarg_0);
ConstructorInfo superConstructor = typeof(Object).GetConstructor(new Type[0]);
constructorIL.Emit(OpCodes.Call, superConstructor);
constructorIL.Emit(OpCodes.Ret);
}
// CreateStartupCode - Creates a function that initializes the Forth stack, the return stack, system variables, etc.
// Input: None
// Output: A MethodBuilder structure describing the pre-MAIN start-up code
private MethodBuilder CreateStartupCode()
{
// Initialize the Forth stack
ForthStack = ForthEngineClass.DefineField("ForthStack", typeof(int[]), FieldAttributes.Public|FieldAttributes.Static);
ForthStackIndex = ForthEngineClass.DefineField("ForthStackIndex", typeof(int), FieldAttributes.Public|FieldAttributes.Static);
// Initialize the return stack
ReturnStack = ForthEngineClass.DefineField("ReturnStack", typeof(int[]), FieldAttributes.Private|FieldAttributes.Static);
ReturnStackIndex = ForthEngineClass.DefineField("ReturnStackIndex", typeof(int), FieldAttributes.Private|FieldAttributes.Static);
// Initialize dummy fields
Dummy1 = ForthEngineClass.DefineField("dummy1", typeof(int), FieldAttributes.Private|FieldAttributes.Static);
Dummy2 = ForthEngineClass.DefineField("dummy2", typeof(int), FieldAttributes.Private|FieldAttributes.Static);
Dummy3 = ForthEngineClass.DefineField("dummy3", typeof(int), FieldAttributes.Private|FieldAttributes.Static);
strDummy = ForthEngineClass.DefineField("strdummy", typeof(string), FieldAttributes.Private|FieldAttributes.Static);
DoLoopDummy = ForthEngineClass.DefineField("dummy4", typeof(int), FieldAttributes.Private|FieldAttributes.Static);
// Create the InitEngine method
MethodBuilder InitMethod = ForthEngineClass.DefineMethod("InitEngine", MethodAttributes.Private | MethodAttributes.Static, typeof(void), null);
ILGenerator ilgen = InitMethod.GetILGenerator();
// Initialize ForthStack array
ilgen.Emit(OpCodes.Ldc_I4, ForthStackSize);
ilgen.Emit(OpCodes.Newarr, typeof(int)); // Was "int[]". Thanks to <NAME> from Microsoft.
ilgen.Emit(OpCodes.Stsfld, ForthStack);
// Initialize ReturnStack array
ilgen.Emit(OpCodes.Ldc_I4, ReturnStackSize);
ilgen.Emit(OpCodes.Newarr, typeof(int)); // Was "int[]". Thanks to <NAME> from Microsoft.
ilgen.Emit(OpCodes.Stsfld, ReturnStack);
// Initialize ForthStackIndex to origin
ilgen.Emit(OpCodes.Ldc_I4, ForthStackOrigin);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
// Normal return from function
ilgen.Emit(OpCodes.Ret);
return InitMethod;
}
// SetEntryPoint - Sets the starting point of the program
// Input: The name of the method that starts the program
// Output: None
private void SetEntryPoint(string MethodName)
{
// Setup program entry point (MAIN code)
MethodInfo entrypoint = GetMethod(MethodName).GetBaseDefinition();
if(entrypoint == null) // No MAIN function defined
{
entrypoint = StartupCode; // Execution begins with the startup code
}
assembly.SetEntryPoint(entrypoint, PEFileKinds.ConsoleApplication);
// NOTE:
// DF versions prior to 1.0 beta 2b used the line below to set up the entry point
// of the DLL. With the advent of the .NET Framework RC, this technique didn't work
// any more, since a DLL initialization exception occurs at runtime.
//assembly.SetEntryPoint(entrypoint, PEFileKinds.Dll);
}
// AddMethod - Builds a method and adds it to the DeltaForthEngine class
// Input: MethodName - the name of the method
// Output: A MethodBuilder structure
private MethodBuilder AddMethod(string MethodName)
{
MethodBuilder ForthMethod = ForthEngineClass.DefineMethod(MethodName, MethodAttributes.Public | MethodAttributes.Static, typeof(void), null);
Methods.Add(ForthMethod); // Add method builder to our list
return ForthMethod;
}
// GetMethod - Gets the information for a specified method
// Input: MethodName - the name of the method
// Output: A MethodBuilder structure
private MethodBuilder GetMethod(string MethodName)
{
return Methods.Find(m => m.Name.ToUpper() == MethodName.ToUpper());
}
// DoGenerateCode - Generates code out of available words
// Input: None
// Output: None
public void DoGenerateCode()
{
// Add all words to the module
foreach (var word in MetaData.Words)
{
AddMethod(word.Name);
}
// Generate the code for each method (Forth word)
foreach (var word in MetaData.Words)
{
MethodBuilder mb = GetMethod(word.Name);
GenerateMethodCode(mb);
}
// Save the assembly
SetEntryPoint("MAIN");
SaveAssembly();
}
// SaveAssembly - Saves the generated code to target file
// Input: None
// Output: None
private void SaveAssembly()
{
try
{
ForthEngineClass.CreateType();
assembly.Save(TargetFileName);
}
catch(Exception ex)
{
string Target = Path.Combine(TargetDirectory, TargetFileName);
throw new Exception("Could not write the output file to '" + Target + "'. Reason: " + ex.Message);
}
}
// GenerateMethodCode - Generate the code of the specified method
// Input: None
// Output: None
private void GenerateMethodCode(MethodBuilder mb)
{
string MethodName = mb.Name;
ILGenerator MethodILGen = mb.GetILGenerator();
// Initialize address of local variables for the current method
for (int i = 0; i < MetaData.LocalVariables.Count; i++)
{
ForthLocalVariable fv = MetaData.LocalVariables[i];
if(fv.WordName == MethodName)
{
fv.Address = LocalVarArea + i;
MetaData.LocalVariables[i] = fv;
}
}
// If we are generating code for the MAIN function, we should call the startup code first
if(MethodName == "MAIN")
{
MethodILGen.Emit(OpCodes.Call, StartupCode);
}
// Each method should catch exceptions thrown by stack operations
if(bCheckStack) MethodILGen.BeginExceptionBlock();
// We have the method name, now look for the contents of the word
List<string> WordContents = MetaData.Words.Find(w => w.Name.ToUpper() == MethodName.ToUpper()).Definition;
// The contents of the 'MethodName' word is now in the 'WordContents' list
foreach(string at in WordContents)
{
// Get the current atom
string atom = at;
// Display statement ( ."<text>" )
if(atom.StartsWith(".\""))
{
atom = atom.Remove(0, 2); // Remove ."
atom = atom.TrimEnd(new char[] {'\"'}); // Remove trailing "
MethodILGen.Emit(OpCodes.Ldstr, atom); // ldstr "text"
MethodILGen.Emit(OpCodes.Call, WriteStringMethod); // call WriteLine(string)
continue;
}
// Dump statement ( "<text>")
if(atom.StartsWith("\""))
{
atom = atom.Trim(new char[] {'\"'}); // Remove " from the beginning and the end of the string
_Dump(MethodILGen, atom); // Dump the string at the address specified on the stack
continue;
}
switch(atom)
{
case "+": // "+" - adds two numbers on the stack
MathOp(MethodILGen, '+');
break;
case "-": // "-" - adds two numbers on the stack
MathOp(MethodILGen, '-');
break;
case "*": // "*" - adds two numbers on the stack
MathOp(MethodILGen, '*');
break;
case "/": // "/" - adds two numbers on the stack
MathOp(MethodILGen, '/');
break;
case "MOD": // "MOD" - division remainder
MathOp(MethodILGen, '%');
break;
case "/MOD": // "Slash MOD" - division remainder and result
_SlashMod(MethodILGen);
break;
case "*/": // "Star Slash" - scaling operator
_StarSlash(MethodILGen);
break;
case "*/MOD": // "Star Slash Mod" - scaling operator
_StarSlashMod(MethodILGen);
break;
case "MINUS": // "Minus" - minus
_Minus(MethodILGen);
break;
case "ABS": // "Absolute" - absolute value
_Abs(MethodILGen);
break;
case "MIN": // "MIN" - minimum of two values
_MinMax(MethodILGen, true);
break;
case "MAX": // "MAX" - maximum of two values
_MinMax(MethodILGen, false);
break;
case "1+": // "One Plus" - adds 1 to the value on top of stack
_OnePlus(MethodILGen);
break;
case "2+": // "Two Plus" - adds 2 to the value on top of stack
_TwoPlus(MethodILGen);
break;
case "0=": // "Zero Equal" - test for equality with 0
_ZeroEqual(MethodILGen);
break;
case "0<": // "Zero Less" - test for 0 or less
_ZeroLess(MethodILGen);
break;
case "=": // "Equal" - test for equal
_Equal(MethodILGen);
break;
case "<": // "Less" - test for less
_Less(MethodILGen);
break;
case ">": // "Greater" - test for greater
_Greater(MethodILGen);
break;
case "<>": // "Not equal" - test for not-equal
_NotEqual(MethodILGen);
break;
case "~AND": // Bitwise AND
_BitwiseOp(MethodILGen, '&');
break;
case "~OR": // Bitwise OR
_BitwiseOp(MethodILGen, '|');
break;
case "~XOR": // Bitwise XOR
_BitwiseOp(MethodILGen, '^');
break;
case "~NOT": // Bitwise NOT
_BitwiseNOT(MethodILGen);
break;
case "AND": // Logical AND
_LogicalAND(MethodILGen);
break;
case "OR": // Logical OR
_LogicalOR(MethodILGen);
break;
case "NOT": // Logical NOT
_LogicalNOT(MethodILGen);
break;
case "DUP": // Duplicates the value on top of stack
_Dup(MethodILGen);
break;
case "-DUP": // Duplicates the value on top of stack unless it is 0
_DashDup(MethodILGen);
break;
case "DROP": // Removes the value on top of stack
_Drop(MethodILGen);
break;
case "SWAP": // Swaps the topmost two values on the stack
_Swap(MethodILGen);
break;
case "OVER": // Duplicates the second value on the stack
_Over(MethodILGen);
break;
case "ROT": // Rotates top three elements on the stack
_Rot(MethodILGen);
break;
case "SP@": // Stack pointer fetch
_SPfetch(MethodILGen);
break;
case "RP@": // Return stack pointer fetch
_RPfetch(MethodILGen);
break;
case "SP!": // Flush Forth stack
_SPstore(MethodILGen);
break;
case "RP!": // Flush return stack
_RPstore(MethodILGen);
break;
case "@": // Fetch
_Fetch(MethodILGen);
break;
case "?": // Question-mark
_QuestionMark(MethodILGen);
break;
case "!": // Store
_Store(MethodILGen);
break;
case "+!": // Plus store
_PlusStore(MethodILGen);
break;
case "EMIT": // Emit
_Emit(MethodILGen);
break;
case ".":
// October 18, 2003
// Added stack bounds verification for the . word
if(bCheckStack)
{
Label lb1 = MethodILGen.DefineLabel();
MethodILGen.Emit(OpCodes.Ldsfld, ForthStackIndex);
MethodILGen.Emit(OpCodes.Ldc_I4, ForthStackOrigin);
MethodILGen.Emit(OpCodes.Bgt_S, lb1);
// Throw exception (stack underflow)
MethodILGen.ThrowException(typeof(System.IndexOutOfRangeException));
MethodILGen.MarkLabel(lb1);
}
MethodILGen.Emit(OpCodes.Ldsfld, ForthStack);
MethodILGen.Emit(OpCodes.Ldsfld, ForthStackIndex);
MethodILGen.Emit(OpCodes.Ldc_I4_1);
MethodILGen.Emit(OpCodes.Sub);
MethodILGen.Emit(OpCodes.Dup);
MethodILGen.Emit(OpCodes.Stsfld, ForthStackIndex);
MethodILGen.Emit(OpCodes.Ldelem_I4);
MethodILGen.Emit(OpCodes.Call, WriteIntMethod); // call WriteLine(int)
break;
case "CR": // CR - moves the cursor to the beginning of the next line
MethodILGen.Emit(OpCodes.Ldstr, ""); // ldstr ""
MethodILGen.Emit(OpCodes.Call, WriteLineStringMethod); // call WriteLine(string)
break;
case "SPACE": // SPACE - displays an empty space on the screen
MethodILGen.Emit(OpCodes.Ldstr, " "); // ldstr " "
MethodILGen.Emit(OpCodes.Call, WriteStringMethod); // call WriteLine(string)
break;
case "SPACES": // SPACES - displays a number of space on the screen
_Spaces(MethodILGen);
break;
case "TYPE": // TYPE - Types a text on the screen
_Type(MethodILGen);
break;
case "PAD": // PAD - 64-cell area
_Pad(MethodILGen);
break;
case "TIB": // TIB - 80-cell area
_Tib(MethodILGen);
break;
case "S0": // Forth stack origin
_StackOrigin(MethodILGen, true);
break;
case "R0": // Return stack origin
_StackOrigin(MethodILGen, false);
break;
case "KEY": // KEY - Places the key code on the stack
_Key(MethodILGen);
break;
case "EXPECT":
_Expect(MethodILGen);
break;
case "QUERY":
_Query(MethodILGen);
break;
case ">R":
_ToR(MethodILGen);
break;
case "R>":
_RFrom(MethodILGen);
break;
case "I":
_I(MethodILGen);
break;
case "I'":
_Isecond(MethodILGen);
break;
case "J":
_J(MethodILGen);
break;
case "FILL":
_Fill(MethodILGen);
break;
case "ERASE":
_Erase(MethodILGen, 0);
break;
case "BLANKS":
_Erase(MethodILGen, 32);
break;
case "STR2INT":
_Str2Int(MethodILGen);
break;
case "COUNT":
_Count(MethodILGen);
break;
case "CMOVE":
_CMove(MethodILGen);
break;
case "INT2STR":
_Int2Str(MethodILGen);
break;
case "EXIT":
_Exit(MethodILGen);
break;
case "IF":
_If(MethodILGen);
break;
case "ELSE":
_Else(MethodILGen);
break;
case "THEN":
_Then(MethodILGen);
break;
case "BEGIN":
_Begin(MethodILGen);
break;
case "UNTIL":
_Until(MethodILGen);
break;
case "AGAIN":
_Again(MethodILGen);
break;
case "WHILE":
_While(MethodILGen);
break;
case "REPEAT":
_Repeat(MethodILGen);
break;
case "CASE":
_Case(MethodILGen);
break;
case "OF":
_Of(MethodILGen);
break;
case "ENDOF":
_EndOf(MethodILGen);
break;
case "ENDCASE":
_EndCase(MethodILGen);
break;
case "DO":
_Do(MethodILGen);
break;
case "LEAVE":
_Leave(MethodILGen);
break;
case "LOOP":
_Loop(MethodILGen);
break;
case "+LOOP":
_PlusLoop(MethodILGen);
break;
default:
try
{
// Try to push the atom onto the stack (hoping that it is a number)
_PushStack(MethodILGen, Convert.ToInt32(atom, 10));
break;
}
catch(Exception)
{
// It's not a number, swallow the error and continue checking
}
// Check whether the atom is a constant
var GlobalConstant = MetaData.GlobalConstants.Find(c => c.Name.ToUpper() == atom);
if (GlobalConstant != null)
{
if (GlobalConstant.Value.GetType() == typeof(int))
{
// The constant is of integer type
_PushStack(MethodILGen, (int)GlobalConstant.Value);
}
else
{
// The constant is of string type
_Dump(MethodILGen, (string)GlobalConstant.Value);
}
break;
}
// Check whether the atom is a local variable
var LocalVar = MetaData.LocalVariables.Find(v => v.Name.ToUpper() == atom && v.WordName.ToUpper() == MethodName);
if (LocalVar != null)
{
string varaddr = LocalVar.Address.ToString();
_PushStack(MethodILGen, Convert.ToInt32(varaddr, 10));
break;
}
// Check whether the atom is a variable
var GlobalVar = MetaData.GlobalVariables.Find(v => v.Name.ToUpper() == atom);
if (GlobalVar != null)
{
string varaddr = GlobalVar.Address.ToString();
_PushStack(MethodILGen, Convert.ToInt32(varaddr, 10));
break;
}
// Check whether the atom is an external word
var ExternalWord = MetaData.ExternalWords.Find(v => v.Name.ToUpper() == atom);
if (ExternalWord != null)
{
CallExternalMethod(MethodILGen, ExternalWord.Library, ExternalWord.Class, ExternalWord.Method);
break;
}
// Finally, if it's not a known word, then raise and error
MethodBuilder lmb = GetMethod(atom);
if(lmb != null)
{
// It must be a word we're dealing with
MethodILGen.Emit(OpCodes.Call, GetMethod(atom)); // Call function
}
else
{
throw new Exception(atom + " in word " + MethodName + " is not known.");
}
break;
}
}
// Catch the index out of bounds exception
if(bCheckStack)
{
MethodILGen.BeginCatchBlock(typeof(IndexOutOfRangeException));
MethodILGen.Emit(OpCodes.Pop);
// If exception occured in MAIN, simply display an error message and return
if(MethodName == "MAIN")
{
MethodILGen.EmitWriteLine("RUNTIME ERROR: Stack underflow or overflow.");
}
else
{
// If the exception occured in some method, rethrow the exception to MAIN
MethodILGen.ThrowException(typeof(IndexOutOfRangeException));
}
// Catch the file not found exception (thrown by ExternalCaller)
MethodILGen.BeginCatchBlock(typeof(System.IO.FileNotFoundException));
MethodILGen.Emit(OpCodes.Pop);
MethodILGen.EmitWriteLine("RUNTIME ERROR: Library file not found.");
MethodILGen.EndExceptionBlock();
}
// Every function ends with the RET statement
MethodILGen.Emit(OpCodes.Ret);
}
// MathOp - Generates code for operations +, -, *, /
// ForthStack[ForthStackIndex - 2] = ForthStack[ForthStackIndex - 2] "MathOp" ForthStack[ForthStackIndex - 1];
// ForthStackIndex--;
// Input: ILGenerator for the method, operation to perform
// Output: None
private void MathOp(ILGenerator ilgen, char Op)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
// -------------------------
switch(Op)
{
case '+':
ilgen.Emit(OpCodes.Add);
break;
case '-':
ilgen.Emit(OpCodes.Sub);
break;
case '*':
ilgen.Emit(OpCodes.Mul);
break;
case '/':
ilgen.Emit(OpCodes.Div);
break;
case '%':
ilgen.Emit(OpCodes.Rem);
break;
}
// -------------------------
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _PushStack - Push a value on the stack
// ForthStack[ForthStackIndex++] = "value";
// Input: ILGenerator for the method, value to push
// Output: None
private void _PushStack(ILGenerator ilgen, int value)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4, value);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _SlashMod - Division remainder and result
// Dummy1 = ForthStack[ForthStackIndex - 1];
// Dummy2 = ForthStack[ForthStackIndex - 2];
// ForthStack[ForthStackIndex - 2] = Dummy2 % Dummy1;
// ForthStack[ForthStackIndex - 1] = Dummy2 / Dummy1;
// Input: ILGenerator for the method
// Output: None
private void _SlashMod(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Rem);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Div);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _StarSlash - Scaling operator
// Dummy1 = ForthStack[ForthStackIndex - 1];
// Dummy2 = ForthStack[ForthStackIndex - 2];
// Dummy3 = ForthStack[ForthStackIndex - 3];
// ForthStackIndex-=2;
// ForthStack[ForthStackIndex - 1] = Dummy3 * Dummy2 / Dummy1;
// Input: ILGenerator for the method
// Output: None
private void _StarSlash(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_3);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Mul);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Div);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _StarSlashMod - Scaling operator
// Dummy1 = ForthStack[ForthStackIndex - 1];
// Dummy2 = ForthStack[ForthStackIndex - 2];
// Dummy3 = ForthStack[ForthStackIndex - 3];
// ForthStackIndex--;
// ForthStack[ForthStackIndex - 2] = (Dummy3 * Dummy2) % Dummy1;
// ForthStack[ForthStackIndex - 1] = Dummy3 * Dummy2 / Dummy1;
// Input: ILGenerator for the method
// Output: None
private void _StarSlashMod(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_3);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Mul);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Rem);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Mul);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Div);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Minus - Changes the sign of the number on top of stack
// ForthStack[ForthStackIndex - 1] = - ForthStack[ForthStackIndex - 1];
// Input: ILGenerator for the method
// Output: None
private void _Minus(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Neg);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Abs - Absolute value of number
//
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 1] = Math.Abs(ForthStack[ForthStackIndex - 1]);
// Output: None
private void _Abs(ILGenerator ilgen)
{
MethodInfo Abs = typeof(Math).GetMethod("Abs", new Type[] { typeof(int) });
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Call, Abs);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _MinMax - Minimum and maximum value
//
// Input: ILGenerator for the method
// Minimum - true if minimum is to calculated, false for maximum
// ForthStack[ForthStackIndex - 1] = Math.Min(ForthStack[ForthStackIndex - 1]);
// ForthStackIndex--;
// Output: None
private void _MinMax(ILGenerator ilgen, bool Minimum)
{
MethodInfo Min = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) });
MethodInfo Max = typeof(Math).GetMethod("Max", new Type[] { typeof(int), typeof(int) });
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
if(Minimum)
ilgen.Emit(OpCodes.Call, Min);
else
ilgen.Emit(OpCodes.Call, Max);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _OnePlus - Adds 1 to the value on top of stack
//
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 1] = ForthStack[ForthStackIndex - 1] + 1;
// Output: None
private void _OnePlus(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _TwoPlus - Adds 2 to the value on top of stack
//
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 1] = ForthStack[ForthStackIndex - 1] + 2;
// Output: None
private void _TwoPlus(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _ZeroEqual - Test for "zero-equal"
//
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 1] = (ForthStack[ForthStackIndex - 1] == 0) ? 1 : 0;
// Output: None
private void _ZeroEqual(ILGenerator ilgen)
{
Label lbZero = ilgen.DefineLabel();
Label lbOne = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brfalse_S, lbOne);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lbZero);
ilgen.MarkLabel(lbOne);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lbZero);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _ZeroLess - Test for "zero or less"
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 1] = (ForthStack[ForthStackIndex - 1] <= 0) ? 1 : 0;
// Output: None
private void _ZeroLess(ILGenerator ilgen)
{
Label lbZero = ilgen.DefineLabel();
Label lbOne = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Ble_S, lbOne);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lbZero);
ilgen.MarkLabel(lbOne);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lbZero);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Equal - Test for "equal"
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 2] = (ForthStack[ForthStackIndex - 1] == ForthStack[ForthStackIndex - 2]) ? 1 : 0;
// ForthStackIndex--;
// Output: None
private void _Equal(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Beq_S, lb1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lb2);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _Less - Test for "less"
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 2] = (ForthStack[ForthStackIndex - 2] < ForthStack[ForthStackIndex - 1]) ? 1 : 0;
// ForthStackIndex--;
// Output: None
private void _Less(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Blt_S, lb1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lb2);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _Greater - Test for "greater"
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 2] = (ForthStack[ForthStackIndex - 2] > ForthStack[ForthStackIndex - 1]) ? 1 : 0;
// ForthStackIndex--;
// Output: None
private void _Greater(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Bgt_S, lb1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lb2);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _NotEqual - Test for "not equal"
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 2] = (ForthStack[ForthStackIndex - 2] <> ForthStack[ForthStackIndex - 1]) ? 1 : 0;
// ForthStackIndex--;
// Output: None
private void _NotEqual(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Bne_Un_S, lb1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lb2);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _BitwiseOp - Bitwise operations (AND, OR, XOR)
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 2] = ForthStack[ForthStackIndex - 2] "op" ForthStack[ForthStackIndex - 1];
// ForthStackIndex--;
// Output: None
private void _BitwiseOp(ILGenerator ilgen, char Op)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
switch(Op)
{
case '&':
ilgen.Emit(OpCodes.And);
break;
case '|':
ilgen.Emit(OpCodes.Or);
break;
case '^':
ilgen.Emit(OpCodes.Xor);
break;
}
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _BitwiseNOT - Bitwise NOT
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 1] = ~ForthStack[ForthStackIndex - 1];
// Output: None
private void _BitwiseNOT(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Not);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _LogicalAND - Logical AND
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 2] = ((ForthStack[ForthStackIndex - 2] > 0) && (ForthStack[ForthStackIndex - 1] > 0) ? 1 : 0);
// ForthStackIndex--;
// Output: None
private void _LogicalAND(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
Label lb3 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Ble_S, lb1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb2);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lb3);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lb3);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _LogicalOR - Logical OR
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 2] = ((ForthStack[ForthStackIndex - 2] > 0) || (ForthStack[ForthStackIndex - 1] > 0) ? 1 : 0);
// ForthStackIndex--;
// Output: None
private void _LogicalOR(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
Label lb3 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Br_S, lb2);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _LogicalNOT - Logical NOT
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex - 1] = (ForthStack[ForthStackIndex - 1] != 0) ? 0 : 1;
// Output: None
private void _LogicalNOT(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brtrue_S, lb1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Br_S, lb2);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Dup - Duplicates the element on top of stack
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex] = ForthStack[ForthStackIndex - 1];
// ForthStackIndex++;
// Output: None
private void _Dup(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _DashDup - Duplicates the element on top of stack unless it is 0
// Input: ILGenerator for the method
// if(ForthStack[ForthStackIndex - 1] != 0) ForthStack[ForthStackIndex] = ForthStack[ForthStackIndex - 1];
// ForthStackIndex++;
// Output: None
private void _DashDup(ILGenerator ilgen)
{
Label lb = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brfalse_S, lb);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.MarkLabel(lb);
ilgen.Emit(OpCodes.Nop);
}
// _Drop - Removes the element on top of stack
// Input: ILGenerator for the method
// ForthStackIndex--;
// Output: None
private void _Drop(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _Swap - Swaps the two elements on the top of stack
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 1];
// ForthStack[ForthStackIndex - 1] = ForthStack[ForthStackIndex - 2];
// ForthStack[ForthStackIndex - 2] = Dummy1;
// Output: None
private void _Swap(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Over - Duplicates the second value on the stack
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex] = ForthStack[ForthStackIndex - 2];
// ForthStackIndex++;
// Output: None
private void _Over(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _Rot
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 3];
// ForthStack[ForthStackIndex - 3] = ForthStack[ForthStackIndex - 2];
// ForthStack[ForthStackIndex - 2] = ForthStack[ForthStackIndex - 1];
// ForthStack[ForthStackIndex - 1] = Dummy1;
// Output: None
private void _Rot(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_3);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_3);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _SPfetch - Current Forth stack index
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex] = ForthStackIndex;
// ForthStackIndex++;
// Output: None
private void _SPfetch(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _RPfetch - Current return stack index
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex] = ReturnStackIndex;
// ForthStackIndex++;
// Output: None
private void _RPfetch(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _SPstore - Flush Forth stack
// Input: ILGenerator for the method
// ForthStackIndex = ForthStackOrigin;
// Output: None
private void _SPstore(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldc_I4, ForthStackOrigin);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _RPstore - Flush return stack
// Input: ILGenerator for the method
// ForthStackIndex = ReturnStackOrigin;
// Output: None
private void _RPstore(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldc_I4, ReturnStackOrigin);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _Fetch - Fetch the value from a given address
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 1];
// ForthStack[ForthStackIndex - 1] = ForthStack[Dummy1];
// Output: None
private void _Fetch(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _QuestionMark - Display the value from a given address
// Input: ILGenerator for the method
// Console.Write(ForthStack[ForthStack[--ForthStackIndex]]);
// Output: None
private void _QuestionMark(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Call, WriteIntMethod);
}
// _Store - Stores a value at a given address
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 2];
// Dummy2 = ForthStack[ForthStackIndex - 1];
// ForthStack[Dummy2] = Dummy1;
// ForthStackIndex -= 2;
// Output: None
private void _Store(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _PlusStore - Adds a value at a given address
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 2];
// Dummy2 = ForthStack[ForthStackIndex - 1];
// ForthStack[Dummy2] += Dummy1;
// ForthStackIndex -= 2;
// Output: None
private void _PlusStore(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _Emit - Prints a char with the specified code
// Input: ILGenerator for the method
// Console.Write((char)ForthStack[--ForthStackIndex]);
// Output: None
private void _Emit(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Conv_U2);
ilgen.Emit(OpCodes.Call, WriteCharMethod);
}
// _Spaces - Prints a series of spaces
// Input: ILGenerator for the method
// for(Dummy1 = 0; Dummy1 < ForthStack[--ForthStackIndex]; Dummy1++) Console.Write(' ');
// Output: None
private void _Spaces(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldc_I4_S, 32);
ilgen.Emit(OpCodes.Call, WriteCharMethod);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Blt_S, lb2);
}
// _Type - Types a text
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 2];
// Dummy2 = ForthStack[ForthStackIndex - 1];
// for(Dummy3 = Dummy1; Dummy3 < Dummy1 + Dummy2; Dummy3++) Console.Write((char)ForthStack[Dummy3]);
// ForthStackIndex -= 2;
// Output: None
private void _Type(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Conv_U2);
ilgen.Emit(OpCodes.Call, WriteCharMethod);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Blt_S, lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
}
// _Pad - Pointer to a 64-cell area
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = Pad;
// Output: None
private void _Pad(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4, Pad); // PAD is at the end of the Forth stack
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Tib - Pointer to a 80-cell area
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = Tib;
// Output: None
private void _Tib(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4, Tib); // TIB is before the PAD area
ilgen.Emit(OpCodes.Stelem_I4);
}
// _StackOrigin - Forth stack and return stack origin
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = "ForthStackOrigin | ReturnStackOrigin";
// Output: None
private void _StackOrigin(ILGenerator ilgen, bool bForthStack)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
if(bForthStack)
ilgen.Emit(OpCodes.Ldc_I4, ForthStackOrigin);
else
ilgen.Emit(OpCodes.Ldc_I4, ReturnStackOrigin);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Key - Places on the stack the code of the key pressed
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = Console.Read();
// Output: None
private void _Key(ILGenerator ilgen)
{
MethodInfo ReadCharMethod = typeof(Console).GetMethod("Read");
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Call, ReadCharMethod);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Expect - Awaits characters and places them on the stack
// Input: ILGenerator for the method
// Dummy1 = ForthStack[--ForthStackIndex]; // Max number of characters
// Dummy2 = ForthStack[--ForthStackIndex]; // Address
// while(Dummy1 > 0)
// {
// Dummy3 = Console.Read();
// if(Dummy3 == 13)
// {
// ForthStack[Dummy2++] = 0;
// break;
// }
// ForthStack[Dummy2++] = Dummy3;
// Dummy1--;
// }
// Output: None
private void _Expect(ILGenerator ilgen)
{
MethodInfo ReadCharMethod = typeof(Console).GetMethod("Read");
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
Label lb3 = ilgen.DefineLabel();
Label lb4 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb4);
ilgen.Emit(OpCodes.Call, ReadCharMethod);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldc_I4, 13);
ilgen.Emit(OpCodes.Bne_Un_S, lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Br_S, lb3);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb4);
ilgen.MarkLabel(lb3);
}
// _Query - Awaits 80 characters at the TIB area
// Input: ILGenerator for the method
// Dummy1 = 80; // Max number of characters
// Dummy2 = Tib; // Address
// while(Dummy1 > 0)
// {
// Dummy3 = Console.Read();
// if(Dummy3 == 10)
// {
// ForthStack[Dummy2++] = 0;
// break;
// }
// ForthStack[Dummy2++] = Dummy3;
// Dummy1--;
// }
// Output: None
private void _Query(ILGenerator ilgen)
{
MethodInfo ReadCharMethod = typeof(Console).GetMethod("Read");
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
Label lb3 = ilgen.DefineLabel();
Label lb4 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldc_I4_S, 80);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4, Tib);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb4);
ilgen.Emit(OpCodes.Call, ReadCharMethod);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Ldc_I4, 10);
ilgen.Emit(OpCodes.Bne_Un_S, lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Br_S, lb3);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb4);
ilgen.MarkLabel(lb3);
}
// _ToR - Transfers the element to the top of the return stack
// Input: ILGenerator for the method
// ReturnStack[ReturnStackIndex++] = ForthStack[--ForthStackIndex];
// Output: None
private void _ToR(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _RFrom - Transfers the element from the return stack to the forth stack
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = ReturnStack[--ReturnStackIndex];
// Output: None
private void _RFrom(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _I - Copies the top element from the return stack to the Forth stack
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = ReturnStack[ReturnStackIndex - 1];
// Output: None
private void _I(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Isecond - Copies the second top element from the return stack to the Forth stack
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = ReturnStack[ReturnStackIndex - 2];
// Output: None
private void _Isecond(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _J - Copies the third top element from the return stack to the Forth stack
// Input: ILGenerator for the method
// ForthStack[ForthStackIndex++] = ReturnStack[ReturnStackIndex - 3];
// Output: None
private void _J(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_3);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Fill - Fills an area
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 1]; // c
// Dummy2 = ForthStack[ForthStackIndex - 2]; // n
// Dummy3 = ForthStack[ForthStackIndex - 3]; // addr
// ForthStackIndex -= 3;
// while(Dummy2-- > 0)
// {
// ForthStack[Dummy3++] = Dummy1;
// }
// Output: None
private void _Fill(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_3);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_3);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb2);
}
// _Erase - Fills an area
// Input: ILGenerator for the method
// Dummy1 = ForthStack[ForthStackIndex - 1]; // n
// Dummy2 = ForthStack[ForthStackIndex - 2]; // addr
// ForthStackIndex -= 2;
// while(Dummy1-- > 0)
// {
// ForthStack[Dummy2++] = "Value"; // 0 or 32
// }
// Output: None
private void _Erase(ILGenerator ilgen, int FillValue)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4, FillValue);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb2);
}
// _Str2Int - Converts a string from TIB to a number on the stack
// Input: ILGenerator for the method
// Dummy1 = Tib;
// strDummy = "";
// while(ForthStack[Dummy1] != 0)
// {
// strDummy += (char)ForthStack[Dummy1];
// Dummy1++;
// }
// ForthStack[ForthStackIndex++] = Convert.ToInt32(strDummy);
// Output: None
private void _Str2Int(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
Label exc = ilgen.DefineLabel();
ilgen.BeginExceptionBlock();
ilgen.Emit(OpCodes.Ldc_I4, Tib);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldstr, "");
ilgen.Emit(OpCodes.Stsfld, strDummy);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, strDummy);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Conv_U2);
ilgen.Emit(OpCodes.Box, typeof(char));
ilgen.Emit(OpCodes.Call, typeof(string).GetMethod("Concat", new Type[] { typeof(Object), typeof(Object) }));
ilgen.Emit(OpCodes.Stsfld, strDummy);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brtrue_S, lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldsfld, strDummy);
ilgen.Emit(OpCodes.Call, typeof(Convert).GetMethod("ToInt32", new Type[] { typeof(string) }));
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.BeginCatchBlock(typeof(FormatException));
ilgen.EmitWriteLine("RUNTIME ERROR: Could not interpret the TIB area.");
ilgen.Emit(OpCodes.Pop);
ilgen.Emit(OpCodes.Ret);
ilgen.EndExceptionBlock();
}
// _Count - Counts the number of non-zero consecutive characters
// Input: ILGenerator for the method
// Dummy1 = Tib;
// strDummy = "";
// while(ForthStack[Dummy1] != 0)
// {
// strDummy += (char)ForthStack[Dummy1];
// Dummy1++;
// }
// ForthStack[ForthStackIndex++] = Convert.ToInt32(strDummy);
// Output: None
private void _Count(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brtrue_S, lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Dump - Dumps a string on the stack
// Input: ILGenerator for the method, string to dump on the stack
// Dummy1 = ForthStack[--ForthStackIndex]; // Address
// Dummy2 = strDummy.Length;
// Dummy3 = 0;
// while(Dummy2-- > 0)
// {
// ForthStack[Dummy1++] = strDummy[Dummy3++];
// }
// ForthStack[Dummy1] = 0;
// Output: None
private void _Dump(ILGenerator ilgen, string text)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldstr, text);
ilgen.Emit(OpCodes.Stsfld, strDummy);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, strDummy);
ilgen.Emit(OpCodes.Callvirt, typeof(string).GetMethod("get_Length"));
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, strDummy);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Callvirt, typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) }));
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _CMove - Dumps a string on the stack
// Input: ILGenerator for the method
// Dummy1 = ForthStack[--ForthStackIndex]; // Count
// Dummy2 = ForthStack[--ForthStackIndex]; // Destination
// Dummy3 = ForthStack[--ForthStackIndex]; // Source
// while(Dummy1-- > 0) ForthStack[Dummy2++] = ForthStack[Dummy3++];
// Output: None
private void _CMove(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb2);
}
// _Int2Str - Converts an integer on the stack to a string
// Input: ILGenerator for the method
// strDummy = (ForthStack[--ForthStackIndex]).ToString(); // Value to convert
// Dummy1 = ForthStack[--ForthStackIndex]; // Address
// Dummy2 = strDummy.Length;
// Dummy3 = 0;
// while(Dummy2-- > 0)
// {
// ForthStack[Dummy1++] = strDummy[Dummy3++];
// }
// ForthStack[Dummy1] = 0;
// Output: None
private void _Int2Str(ILGenerator ilgen)
{
Label lb1 = ilgen.DefineLabel();
Label lb2 = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelema, typeof(System.Int32));
ilgen.Emit(OpCodes.Call, typeof(System.Int32).GetMethod("ToString", new Type[] {}));
ilgen.Emit(OpCodes.Stsfld, strDummy);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, strDummy);
ilgen.Emit(OpCodes.Callvirt, typeof(string).GetMethod("get_Length"));
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Br_S, lb1);
ilgen.MarkLabel(lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy1);
ilgen.Emit(OpCodes.Ldsfld, strDummy);
ilgen.Emit(OpCodes.Ldsfld, Dummy3);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stsfld, Dummy3);
ilgen.Emit(OpCodes.Callvirt, typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) }));
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.MarkLabel(lb1);
ilgen.Emit(OpCodes.Ldsfld, Dummy2);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, Dummy2);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Bgt_S, lb2);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, Dummy1);
ilgen.Emit(OpCodes.Ldc_I4_0);
ilgen.Emit(OpCodes.Stelem_I4);
}
// _Exit - Exits from the current word
// Input: ILGenerator for the method
// Output: None
private void _Exit(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Ret);
}
// _If - Processes the IF atom
// Input: ILGenerator for the method
// Output: None
private void _If(ILGenerator ilgen)
{
IFDescriptor sIF = new IFDescriptor { lbElse = ilgen.DefineLabel(), lbEnd = ilgen.DefineLabel(), bElse = false };
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brfalse, sIF.lbElse);
IFStack.Push(sIF);
}
// _Else - Processes the ELSE atom
// Input: ILGenerator for the method
// Output: None
private void _Else(ILGenerator ilgen)
{
IFDescriptor sIF = IFStack.Pop();
ilgen.Emit(OpCodes.Br, sIF.lbEnd); // Avoid executing the False branch
ilgen.MarkLabel(sIF.lbElse);
sIF.bElse = true;
IFStack.Push(sIF);
}
// _Then - Processes the THEN atom
// Input: ILGenerator for the method
// Output: None
private void _Then(ILGenerator ilgen)
{
IFDescriptor sIF = IFStack.Pop();
ilgen.MarkLabel(sIF.lbEnd);
if(sIF.bElse == false) ilgen.MarkLabel(sIF.lbElse);
}
// _Begin - Processes the BEGIN atom
// Input: ILGenerator for the method
// Output: None
private void _Begin(ILGenerator ilgen)
{
BEGINDescriptor sBEGIN = new BEGINDescriptor { lbBegin = ilgen.DefineLabel(), lbEnd = ilgen.DefineLabel() };
ilgen.MarkLabel(sBEGIN.lbBegin);
BEGINStack.Push(sBEGIN);
}
// _Until - Processes the UNTIL atom
// Input: ILGenerator for the method
// Output: None
private void _Until(ILGenerator ilgen)
{
BEGINDescriptor sBEGIN = BEGINStack.Pop();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brfalse, sBEGIN.lbBegin);
}
// _Again - Processes the AGAIN atom
// Input: ILGenerator for the method
// Output: None
private void _Again(ILGenerator ilgen)
{
BEGINDescriptor sBEGIN = BEGINStack.Pop();
ilgen.Emit(OpCodes.Br, sBEGIN.lbBegin);
}
// _While - Processes the WHILE atom
// Input: ILGenerator for the method
// Output: None
private void _While(ILGenerator ilgen)
{
BEGINDescriptor sBEGIN = BEGINStack.Peek();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Brfalse, sBEGIN.lbEnd);
}
// _Repeat - Processes the REPEAT atom
// Input: ILGenerator for the method
// Output: None
private void _Repeat(ILGenerator ilgen)
{
BEGINDescriptor sBEGIN = BEGINStack.Pop();
ilgen.Emit(OpCodes.Br, sBEGIN.lbBegin);
ilgen.MarkLabel(sBEGIN.lbEnd);
}
// _Case - Processes the CASE atom
// Input: ILGenerator for the method
// Output: None
private void _Case(ILGenerator ilgen)
{
Label lbEndCase = ilgen.DefineLabel();
CASEStack.Push(lbEndCase);
}
// _Of - Processes the OF atom
// Input: ILGenerator for the method
// Output: None
private void _Of(ILGenerator ilgen)
{
Label lbEndOf = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Bne_Un, lbEndOf);
CASEStack.Push(lbEndOf);
}
// _EndOf - Processes the OF atom
// Input: ILGenerator for the method
// Output: None
private void _EndOf(ILGenerator ilgen)
{
Label lbEndOf = CASEStack.Pop();
Label lbEndCase = CASEStack.Pop();
ilgen.Emit(OpCodes.Br, lbEndCase);
ilgen.MarkLabel(lbEndOf);
CASEStack.Push(lbEndCase);
}
// _EndCase - Processes the ENDCASE atom
// Input: ILGenerator for the method
// Output: None
private void _EndCase(ILGenerator ilgen)
{
Label lbEndCase = CASEStack.Pop();
ilgen.MarkLabel(lbEndCase);
_Drop(ilgen);
}
// _Do - Processes the DO atom
// Input: ILGenerator for the method
// Output: None
private void _Do(ILGenerator ilgen)
{
DODescriptor sDO = new DODescriptor { lbDo = ilgen.DefineLabel(), lbLoop = ilgen.DefineLabel() };
_Swap(ilgen);
_ToR(ilgen);
_ToR(ilgen);
ilgen.MarkLabel(sDO.lbDo);
DOStack.Push(sDO);
}
// _Leave - Processes the LEAVE atom
// Input: ILGenerator for the method
// Output: None
private void _Leave(ILGenerator ilgen)
{
DODescriptor sDO = DOStack.Peek();
// Clean up 2 elements from the return stack
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Br, sDO.lbLoop);
}
// _Loop - Processes the LOOP atom
// Input: ILGenerator for the method
// Output: None
private void _Loop(ILGenerator ilgen)
{
DODescriptor sDO = DOStack.Peek();
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, DoLoopDummy);
ilgen.Emit(OpCodes.Ldsfld, DoLoopDummy);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
// The two following lines of code have been added in order to correct the behavior of the DO-LOOP structure which did not exit early enough
// Ex. 5 0 DO I . LOOP; should print 01234 instead of 012345 as it was previously
// <NAME>, October 26, 2011
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
// End of change
ilgen.Emit(OpCodes.Bge_S, sDO.lbLoop);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, DoLoopDummy);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Br, sDO.lbDo);
ilgen.MarkLabel(sDO.lbLoop);
// Clean up 2 elements from the return stack
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ReturnStackIndex);
DOStack.Pop();
}
// _PlusLoop - Processes the +LOOP atom
// Input: ILGenerator for the method
// Output: None
private void _PlusLoop(ILGenerator ilgen)
{
DODescriptor sDO = DOStack.Peek();
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Stsfld, DoLoopDummy);
ilgen.Emit(OpCodes.Ldsfld, DoLoopDummy);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldelem_I4);
// <NAME>, October 26, 2011 (see explanation from the LOOP)
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
// End of change
ilgen.Emit(OpCodes.Bge_S, sDO.lbLoop);
ilgen.Emit(OpCodes.Ldsfld, ReturnStack);
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Ldsfld, DoLoopDummy);
ilgen.Emit(OpCodes.Ldsfld, ForthStack);
ilgen.Emit(OpCodes.Ldsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Stsfld, ForthStackIndex);
ilgen.Emit(OpCodes.Ldelem_I4);
ilgen.Emit(OpCodes.Add);
ilgen.Emit(OpCodes.Stelem_I4);
ilgen.Emit(OpCodes.Br, sDO.lbDo);
ilgen.MarkLabel(sDO.lbLoop);
// Clean up 2 elements from the return stack
ilgen.Emit(OpCodes.Ldsfld, ReturnStackIndex);
ilgen.Emit(OpCodes.Ldc_I4_2);
ilgen.Emit(OpCodes.Sub);
ilgen.Emit(OpCodes.Stsfld, ReturnStackIndex);
DOStack.Pop();
}
// CallExternalMethod - Calls a method from a class in an external file
// Input: ILGenerator for the method
// FileName - the name of the file containing the class
// ClassName - the name of the class
// MethodName - the name of the method to call
// Output: None
private void CallExternalMethod(ILGenerator ilgen, string FileName, string ClassName, string MethodName)
{
if(!bExtCallerDefined)
{
// The runtime does not contain the ExternalCaller function, we add it here
// Function ExternalCaller
Type[] parameters = { typeof(String) /* FileName */, typeof(String) /* ClassName */, typeof(String) /* MethodName */ };
extCaller = ForthEngineClass.DefineMethod("ExternalCaller", MethodAttributes.Private|MethodAttributes.Static, typeof(void), parameters);
// Field calAssembly
FieldBuilder calAssembly = ForthEngineClass.DefineField("CalleeAssembly", typeof(System.Reflection.Assembly), FieldAttributes.Private|FieldAttributes.Static);
// Field calType
FieldBuilder calType = ForthEngineClass.DefineField("CalleeType", typeof(System.Type), FieldAttributes.Private|FieldAttributes.Static);
// Field calMethodInfo
FieldBuilder calMethodInfo = ForthEngineClass.DefineField("CalleeMethodInfo", typeof(System.Reflection.MethodInfo), FieldAttributes.Private|FieldAttributes.Static);
// Field calInstance
FieldBuilder calInstance = ForthEngineClass.DefineField("CalleeInstance", typeof(System.Object), FieldAttributes.Private|FieldAttributes.Static);
ILGenerator extCallerILGen = extCaller.GetILGenerator();
// Define a few local labels
Label lb1 = extCallerILGen.DefineLabel();
Label lb2 = extCallerILGen.DefineLabel();
Label lb3 = extCallerILGen.DefineLabel();
Label lb4 = extCallerILGen.DefineLabel();
Label lb5 = extCallerILGen.DefineLabel();
extCallerILGen.BeginExceptionBlock();
extCallerILGen.Emit(OpCodes.Ldarg_0);
extCallerILGen.Emit(OpCodes.Call, typeof(System.Reflection.Assembly).GetMethod("LoadFrom", new Type[] { typeof(String) }));
extCallerILGen.Emit(OpCodes.Stsfld, calAssembly);
extCallerILGen.Emit(OpCodes.Ldsfld, calAssembly);
extCallerILGen.Emit(OpCodes.Ldarg_1);
extCallerILGen.Emit(OpCodes.Ldc_I4_0);
extCallerILGen.Emit(OpCodes.Ldc_I4_1);
extCallerILGen.Emit(OpCodes.Callvirt, typeof(System.Reflection.Assembly).GetMethod("GetType", new Type[] { typeof(String), typeof(bool), typeof(bool) }));
extCallerILGen.Emit(OpCodes.Stsfld, calType);
extCallerILGen.Emit(OpCodes.Ldsfld, calType);
extCallerILGen.Emit(OpCodes.Ldnull);
extCallerILGen.Emit(OpCodes.Call, typeof(System.Type).GetMethod("op_Equality", new Type[] { typeof(System.Type), typeof(System.Type) }));
extCallerILGen.Emit(OpCodes.Brfalse_S, lb1);
extCallerILGen.EmitWriteLine("\n\rRUNTIME ERROR: Could not load library.");
extCallerILGen.Emit(OpCodes.Br_S, lb2);
extCallerILGen.MarkLabel(lb1);
extCallerILGen.Emit(OpCodes.Ldsfld, calType);
extCallerILGen.Emit(OpCodes.Ldarg_2);
extCallerILGen.Emit(OpCodes.Callvirt, typeof(System.Type).GetMethod("GetMethod", new Type[] { typeof(String) }));
extCallerILGen.Emit(OpCodes.Stsfld, calMethodInfo);
extCallerILGen.Emit(OpCodes.Ldsfld, calMethodInfo);
extCallerILGen.Emit(OpCodes.Ldnull);
extCallerILGen.Emit(OpCodes.Call, typeof(System.Reflection.MethodInfo).GetMethod("op_Equality", new Type[] { typeof(System.Reflection.MethodInfo), typeof(System.Reflection.MethodInfo) }));
extCallerILGen.Emit(OpCodes.Brfalse_S, lb3);
extCallerILGen.EmitWriteLine("\n\rRUNTIME ERROR: Could not call external method.");
extCallerILGen.Emit(OpCodes.Br_S, lb2);
extCallerILGen.MarkLabel(lb3);
extCallerILGen.Emit(OpCodes.Ldsfld, calMethodInfo);
extCallerILGen.Emit(OpCodes.Callvirt, typeof(System.Reflection.MethodBase).GetMethod("get_IsStatic", new Type[] { }));
extCallerILGen.Emit(OpCodes.Brtrue_S, lb4);
extCallerILGen.Emit(OpCodes.Ldsfld, calType);
extCallerILGen.Emit(OpCodes.Call, typeof(System.Activator).GetMethod("CreateInstance", new Type[] { typeof(System.Type) }));
extCallerILGen.Emit(OpCodes.Stloc_0);
extCallerILGen.Emit(OpCodes.Ldsfld, calMethodInfo);
extCallerILGen.Emit(OpCodes.Ldloc_0);
extCallerILGen.Emit(OpCodes.Ldnull);
extCallerILGen.Emit(OpCodes.Callvirt, typeof(System.Reflection.MethodBase).GetMethod("Invoke", new Type[] { typeof(Object), typeof(Object[]) }));
extCallerILGen.Emit(OpCodes.Pop);
extCallerILGen.Emit(OpCodes.Br_S, lb2);
extCallerILGen.MarkLabel(lb4);
extCallerILGen.Emit(OpCodes.Ldsfld, calMethodInfo);
extCallerILGen.Emit(OpCodes.Ldnull);
extCallerILGen.Emit(OpCodes.Ldnull);
extCallerILGen.Emit(OpCodes.Callvirt, typeof(System.Reflection.MethodBase).GetMethod("Invoke", new Type[] { typeof(Object), typeof(Object[]) }));
extCallerILGen.Emit(OpCodes.Pop);
extCallerILGen.MarkLabel(lb2);
extCallerILGen.Emit(OpCodes.Leave_S, lb5);
extCallerILGen.Emit(OpCodes.Pop);
extCallerILGen.BeginCatchBlock(typeof(System.IO.FileNotFoundException));
extCallerILGen.ThrowException(typeof(System.IO.FileNotFoundException));
extCallerILGen.EndExceptionBlock();
extCallerILGen.MarkLabel(lb5);
extCallerILGen.Emit(OpCodes.Ret);
bExtCallerDefined = true;
}
// ExternalCaller method is already defined in runtime, we just call it
ilgen.Emit(OpCodes.Ldstr, FileName);
ilgen.Emit(OpCodes.Ldstr, ClassName);
ilgen.Emit(OpCodes.Ldstr, MethodName);
ilgen.Emit(OpCodes.Call, extCaller);
}
}
}
<file_sep>using System;
using System.Reflection;
using System.IO;
namespace Library2
{
class Class1
{
static Assembly calAssembly;
static Type calType;
// Forth stack & index
static int []ForthStack;
static int ForthStackIndex;
[STAThread]
static void Main(string[] args)
{
if (!InitDLL("ForthLibrary.dll", "ForthLib")) return;
Push(30);
Push(18);
CallForthWord("ADDITION");
Console.WriteLine("Addition...");
CallForthWord("DISPLAYTOPOFSTACK");
Push(30);
Push(18);
CallForthWord("SUBTRACTION");
Console.WriteLine("Subtraction...");
CallForthWord("DISPLAYTOPOFSTACK");
}
// GetField - gets the value of a field defined in the Forth library
static object GetField(string FieldName)
{
FieldInfo fi = calType.GetField(FieldName);
if(fi == null)
{
Console.WriteLine("Runtime Error: Could not find field {0}.", FieldName);
return null;
}
return fi.GetValue(null);
}
// InitDLL - Loads the Forth library and sets up the stack pointers
static private bool InitDLL(string FileName, string ClassName)
{
try
{
calAssembly = Assembly.LoadFrom(FileName);
}
catch (FileLoadException fle)
{
Console.WriteLine("Error: {0}", fle.Message);
return false;
}
try
{
calType = calAssembly.GetType(ClassName, true, true);
}
catch (Exception ex)
{
Console.WriteLine("Runtime Error: Could not load class {0} from library. Reason: {1}", ClassName, ex.Message);
return false;
}
CallForthWord("MAIN");
// Initialize stacks and indexes
ForthStack = (int[])GetField("ForthStack");
ForthStackIndex = (int)GetField("ForthStackIndex");
return true;
}
// ShutdownDLL - Unloads the library
static private void ShutdownDLL()
{
calAssembly = null;
}
// CallForthWord - Calls the specified Forth word
static private bool CallForthWord(string WordName)
{
MethodInfo calMethodInfo = calType.GetMethod(WordName);
if(calMethodInfo == null)
{
Console.WriteLine("Runtime Error: Could not find word {0}.", WordName);
return false;
}
calMethodInfo.Invoke(null, null);
return true;
}
// Push - pushes an integer value onto the Forth stack
static private void Push(int val)
{
ForthStack[ForthStackIndex++] = val;
FieldInfo fi = calType.GetField("ForthStackIndex");
fi.SetValue(null, ForthStackIndex);
}
// Pop - pops an integer value from the Forth stack
static private int Pop()
{
FieldInfo fi = calType.GetField("ForthStackIndex");
fi.SetValue(null, --ForthStackIndex);
return ForthStack[ForthStackIndex];
}
// Peek - peeks the value on top of stack
static private int Peek()
{
return ForthStack[ForthStackIndex - 1];
}
}
}
<file_sep>using System;
using System.Threading;
namespace ForthLibrary
{
public class ForthLibrary
{
private static ForthExtender fe;
static ForthLibrary()
{
Console.WriteLine("ForthLibrary constructor called...");
fe = new ForthExtender("ForthLibraryTest.exe");
}
public static void GenerateRandomNumber(string param)
{
Console.WriteLine("Received parameter: " + param);
Thread.Sleep(50);
Random RandNumber = new Random();
int number = RandNumber.Next(50000);
RandNumber = null;
fe.Push(number);
}
}
}
<file_sep>using System;
using System.Reflection;
namespace ForthLibrary
{
/// <summary>
/// Provides the basic stack operations and word calling for an associated Delta Forth .NET program.
/// </summary>
public class ForthExtender
{
/// <summary>
/// Delta Forth .NET Assembly
/// </summary>
private Assembly calAssembly;
/// <summary>
/// Delta Forth .NET Type
/// </summary>
private Type calType;
private int []ForthStack;
private int ForthStackIndex;
/// <summary>
/// Initializes the assembly and the stacks, including stack pointers
/// </summary>
/// <param name="FileName">File name containing the Delta Forth .NET program</param>
public ForthExtender(string FileName)
{
// Initialize assembly and type
calAssembly = Assembly.LoadFrom(FileName);
calType = calAssembly.GetType("DeltaForthEngine", true, true);
// Initialize Forth stack
ForthStack = (int[])GetField("ForthStack");
ForthStackIndex = (int)GetField("ForthStackIndex");
}
#region "Forth Stack Handling Methods"
/// <summary>
/// Pushes an integer value onto the Forth stack
/// </summary>
/// <param name="val">Value to push</param>
public void Push(int val)
{
ForthStack[ForthStackIndex++] = val;
FieldInfo fi = calType.GetField("ForthStackIndex");
fi.SetValue(null, ForthStackIndex);
}
/// <summary>
/// Pops an integer value from the Forth stack
/// </summary>
/// <returns>Value retrieved from the stack</returns>
public int Pop()
{
FieldInfo fi = calType.GetField("ForthStackIndex");
fi.SetValue(null, --ForthStackIndex);
return ForthStack[ForthStackIndex];
}
/// <summary>
/// Peeks the value on top of the Forth stack
/// </summary>
/// <returns>Value retrieved from the stack</returns>
public int Peek()
{
return ForthStack[ForthStackIndex - 1];
}
#endregion
/// <summary>
/// Returns the object associated with the specified field (Delta Forth .NET variable)
/// </summary>
/// <param name="FieldName">Field name</param>
/// <returns>Object associated with the field</returns>
private object GetField(string FieldName)
{
FieldInfo fi = calType.GetField(FieldName);
if(fi == null)
{
return null;
}
return fi.GetValue(null);
}
/// <summary>
/// Calls a specified Delta Forth .NET word
/// </summary>
/// <param name="WordName">Word name</param>
/// <returns>TRUE if the call is successful</returns>
private bool CallForthWord(string WordName)
{
MethodInfo calMethodInfo = calType.GetMethod(WordName.ToUpper());
if(calMethodInfo == null)
{
return false;
}
calMethodInfo.Invoke(null, null);
return true;
}
}
}
<file_sep>/*
* Delta Forth - World's first Forth compiler for .NET
* Copyright (C)1997-2019 <NAME>, PhD, Romania (<EMAIL>)
*
* This program and its source code is distributed in the hope that it will
* be useful. No warranty of any kind is provided.
* Please DO NOT distribute modified copies of the source code.
*
*/
namespace DeltaForth.DataStructures
{
/// <summary>
/// Definition of a global constant as used by the Forth syntactic analyzer
/// </summary>
public class ForthConstant
{
/// <summary>
/// Constant name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Constant value (can be either string or integer)
/// </summary>
public object Value { get; set; }
}
} | 2f190be6b586b65cc59c88bfe126edd299663632 | [
"Markdown",
"C#"
] | 20 | C# | vbocan/delta-forth | c5cc775814044b334464c58cf3375e2dadb39d4f | f24c695dc3c769285bec546cee8ca61f692ceadd |
refs/heads/master | <repo_name>Carlesgr88/Primer_Programa<file_sep>/Num_g_list.py
lista_numeros=[12,4,6,88,24,4,74]
numero_grande = lista_numeros[0]
for numero in lista_numeros:
if numero > numero_grande:
numero_grande=numero
print("El número más grande es {}".format(numero_grande))
<file_sep>/Test_1.1.py
#Simulador de lucha pokemon
enemigo=input("contra que enemigo quieres luchar? (Bulbasaur/Charmander/Squirtle): ").upper()
vida_pikachu=100
vida_enemigo= 0
if enemigo == "SQUIRTLE":
vida_enemigo= 90
nombre_enemigo="Squirtle"
elif enemigo== "CHARMANDER":
vida_enemigo= 80
nombre_enemigo="Charmander"
else:
vida_enemigo= 100
nombre_enemigo="Bulbasaur"
while vida_pikachu > 0 and vida_enemigo >0:
ataque_elegido=input("que ataque quieres usar? (Chispazo/Bola Voltio): ").upper()
if ataque_elegido=="CHISPAZO":
vida_enemigo -=10
elif ataque_elegido=="BOLA VOLTIO":
vida_enemigo -=12
else:
print("Tu pikachu no conoce ese ataque")
print("La vida del {} enemigo ahora es de {}" .format(nombre_enemigo,vida_enemigo))
if enemigo== "SQUIRTLE":
ataque_enemigo=8
elif enemigo== "CHARMANDER":
ataque_enemigo=7
else:
ataque_enemigo=10
vida_pikachu -= ataque_enemigo
print("{} te hace un ataque de {} de daño".format(nombre_enemigo,ataque_enemigo))
print("la vida de tu pikachu es de {}".format(vida_pikachu))
if vida_enemigo <=0:
ganador="Pikachu"
else:
ganador=nombre_enemigo
print("El combate ha terminado, el ganador es {}".format(ganador))<file_sep>/test_if_else.py
"Programam de prueba if/else"
numero_del_usuario=int(input("dime un numero: "))
if numero_del_usuario > 100:
print("enhorabuena tu numero es mayor que 100")
else:
print("Ps no es el 100 lokillo")<file_sep>/FizzBuzz.py
lista_numeros=[1,2,3,4,5,6,7,8,9,10,11,12,15,532,64,45,44,99]
for numero in range(len(lista_numeros)):
numeros=lista_numeros[numero]
if numeros % 3 == 0 or numeros % 5 == 0:
lista_numeros[numero]=""
if numeros % 3 == 0:
lista_numeros[numero] +="Fizz"
if numeros % 5 == 0:
lista_numeros[numero] +="Buzz"
print(lista_numeros)<file_sep>/replace.py
string_inicial=input("Introduce una string: ")
str_final=string_inicial.replace("a","VACA").replace("A","VACA")
print(str_final)<file_sep>/sep_int_str.py
lista_datos=["daf",2,5,"hea",55,"asd","ynv",9]
lista_str=[]
lista_int=[]
for items in lista_datos:
if type(items)== type(2):
lista_int.append(items)
else:
lista_str.append(items)
print("Los datos {} son un int".format(lista_int))
print("Los datos {} son una str".format(lista_str))
<file_sep>/len_string.py
lista_str=["asd","fdggg","oojj","iuuyt","qwetgv"]
for item in lista_str:
print(len(item))<file_sep>/Vocales enlist.py
lista_vocales=[]
lista_consonantes=[]
frase_usuario= input("Introduce una oración: ").lower()
vocales= ["a","e","i","o","u"]
for letra in frase_usuario:
if letra in vocales:
lista_vocales.append(letra)
else:
lista_consonantes.append(letra)
for letra in lista_vocales:
print("En tu oración está la vocal {}".format(letra))
<file_sep>/numeros_g.py
lista_numeros=[]
numero_del_usuario=""
while len(lista_numeros) < 10:
while not numero_del_usuario.isdigit():
numero_del_usuario= input("Introduce un numero: ")
lista_numeros.append(numero_del_usuario)
numero_del_usuario=""
print("Número añadido")
numero_grande = lista_numeros[0]
for numero in lista_numeros:
if numero > numero_grande:
numero_grande=numero
print("El número más grande es {}".format(numero_grande))
<file_sep>/Calculadora.py
#Calculadora de operaciónes básicas
operacion=input("¿Que operación quieres realizar?(Sumar/Restar/Multiplicar/Dividir): ").upper()
primer_numero=int(input("Dime el primer número: "))
segundo_numero=int(input("Dime el segundo número: "))
if operacion== "SUMAR":
resultado=primer_numero+segundo_numero
elif operacion=="RESTAR":
resultado=primer_numero-segundo_numero
elif operacion=="MULTIPLICAR":
resultado=primer_numero*segundo_numero
elif operacion=="DIVIDIR":
resultado=primer_numero/segundo_numero
else:
print("no has seleccionado ninguna de las opciones anteriores")
print("El resultado de la operación es {}".format(resultado))<file_sep>/cls_mult.py
lista_numeros=[]
numeros_usuario=int(input("Introduce un número (escribe <0> para terminar): "))
print("Número añadido correctamente ")
print(lista_numeros)
while numeros_usuario != 0:
lista_numeros.append(numeros_usuario)
numeros_usuario=int(input("Introduce un número (escribe <0> para terminar):"))
print("Número añadido correctamente ")
print(lista_numeros)
multiplos_dos=[]
multiplos_tres=[]
multiplos_cinco=[]
multiplos_siete=[]
for indice in range(len(lista_numeros)):
numeros=lista_numeros[indice]
if lista_numeros[indice] % 2 == 0:
multiplos_dos.append(numeros)
if lista_numeros[indice] % 3 == 0:
multiplos_tres.append(numeros)
if lista_numeros[indice] % 5 == 0:
multiplos_cinco.append(numeros)
if lista_numeros[indice] % 7 == 0:
multiplos_siete.append(numeros)
print("Los multiplos de dos son {}".format(multiplos_dos))
print("Los multiplos de tres son {}".format(multiplos_tres))
print("Los multiplos de cinco son {}".format(multiplos_cinco))
print("Los multiplos de siete son {}".format(multiplos_siete))
<file_sep>/contador de ,..py
frase_usuario=input("Introduce una frase: ")
espacio=" "
punto="."
coma=","
n_espacios=0
n_puntos=0
n_comas=0
for elemento in frase_usuario:
if elemento in espacio:
n_espacios += 1
elif elemento in punto:
n_puntos += 1
elif elemento in coma:
n_comas +=1
print("En tu frase hay {} espacios, {} puntos y {} comas".format(n_espacios,n_puntos,n_comas))<file_sep>/numero_p.py
lista_numeros=[]
numero_usuario=""
while len(lista_numeros) < 10:
while not numero_usuario.isdigit():
numero_usuario=input("Introduce un número: ")
lista_numeros.append(numero_usuario)
numero_usuario=""
print("Número añadido")
print("El número más pequeño es el {}".format(min(lista_numeros)))
<file_sep>/Média.py
lista_numeros =[]
numeros_usuario =input("Introduce un numero: ")
print("Número añadido correctamente")
while numeros_usuario != "fin":
lista_numeros.append(numeros_usuario)
numeros_usuario =input("Introduce un numero: (Escribe <fin> para terminar)")
print("Número añadido correctamente")
suma =0
for i in lista_numeros:
suma += i
print(suma)<file_sep>/acertijo.py
numero_adivinar = 8
numero_usuario = int(input("dime un numero del 1 al 10: "))
if numero_usuario == numero_adivinar:
print("has acertado")
else:
numero_usuario = int(input("No has acertado, dime otro numero: "))
if numero_usuario == numero_adivinar:
print("has acertado")
else:
numero_usuario = int(input("No has acertado, dime otro numero: "))
if numero_usuario == numero_adivinar:
print("has acertado")
else:
numero_usuario = int(input("No has acertado, dime otro numero: "))
if numero_usuario == numero_adivinar:
print("has acertado")
else:
numero_usuario = int(input("No has acertado, dime otro numero: "))
if numero_usuario == numero_adivinar:
print("has acertado")
else:
print("te has equivocado, el numero a adivinar era {}".format(numero_adivinar))
<file_sep>/List_For.py
mi_lista= []
lista= input("Que necesitas comprar?(escribe Fin para terminar)").upper()
while lista != "FIN":
mi_lista.append(lista)
lista= input("Que necesitas comprar?(escribe Fin para terminar)").upper()
for item in mi_lista:
print("tengo que comprar {}".format(item))
print("Esta es la lista de la compra")<file_sep>/largo_lista.py
lista_numeros=[]
largo_lista=0
numero_usuario = input("Introduce un número: ")
print("Número añadido correctamente")
while numero_usuario != "fin":
lista_numeros.append(numero_usuario)
numero_usuario = input("Introduce un número: ")
print("Número añadido correctamente")
for item in lista_numeros:
largo_lista +=1
print("La lista tiene una longitud de {} elementos".format(largo_lista))
<file_sep>/FizzBuzz 2.0.py
lista_numeros=[1,2,3,4,5,6,7,8,9,10,11,12,15,532,64,45,44,99]
for numero in range(len(lista_numeros)):
numeros=lista_numeros[numero]
if numeros % 3 == 0 and numeros % 5 == 0:
lista_numeros[numero] ="Bazinga"
else:
if numeros % 3 == 0:
lista_numeros[numero] ="Fizz"
if numeros % 5 == 0:
lista_numeros[numero] ="Buzz"
print(lista_numeros)<file_sep>/Tabla de multiplicar.py
numero=int(input("De que numero quieres la tabla de multiplicar? "))
for multiplo in range (1,11):
print ("{}*{}={}".format(numero,multiplo,numero*multiplo))<file_sep>/Juego de adivinar.py
#Juego para dos jugadores, el 1r jugador pone el número a adivinar, mientras el otro, lo tiene que adivinar.(num 1 al 10)
numero_adivinar=int(input("Dime el numero que quieres adivinar (1 al 10): "))
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print()
print("Empieza el juego:")
numero_usuario=int(input("Adivina el numero (1 al 10): "))
while numero_usuario != numero_adivinar:
if numero_usuario <= 10 and numero_usuario > 0:
numero_usuario=int(input("Adivina el numero: "))
else:
print("el numero tiene que ser entre el 1 y el 10, el {} no cuenta".format(numero_usuario))
numero_usuario = int(input("Adivina el numero: "))
print("Enhorabuena has acertado el numero era el {}".format(numero_adivinar))<file_sep>/Operadores binarios.py
helado_input=(input("¿Quieres un helado? (si/no) ")).upper()
if helado_input == "SI":
helado= True
elif helado_input=="NO":
helado= False
else:
print("si o no monger")
helado= False
dinero_input=(input("¿Tienes dinero para un helado? (si/no) ")).upper()
esta_tu_tia_input= input("¿esta tu tia? (si/no) ").upper()
helado= helado_input == "SI"
dinero=dinero_input == "SI" or esta_tu_tia_input == "SI"
if helado and dinero:
print("pues comete un helado")
else:
print("pues entonces nada")
<file_sep>/Format.py
valores_a_sustituir=[1,2,"hola","adios"]
string_cambiar=",Hola , numero {}, numero {}, {} y {}"
for valor in valores_a_sustituir:
string_cambiar = string_cambiar.replace("{}",str(valor), 1)
print(string_cambiar)<file_sep>/Ripitidir.py
frase_inicial=input("Dime algo: ")
frase_final= frase_inicial.replace("a", "i").replace("e", "i").replace("o", "i").replace("u", "i")
print(frase_final)<file_sep>/Transformador de grados Fahrenheit a Celsius.py
#Programa para pasar de Grados Fahrenheit a Celsius
fahrenheit=float(input("Grados Fahrenheit: "))
celsius= (fahrenheit-32)/1.8
print("{} grados Fahrenheit, son {} grados Celsius".format(fahrenheit,celsius))<file_sep>/tipos de datos.py
lista_datos=[1,2,3,"asd",False,[],True,23,2.1]
lista_tipos=[]
for datos in lista_datos:
lista_tipos.append(type(datos))
print(lista_tipos)<file_sep>/multiplicar_lista.py
lista_numeros=[3,5,8,2,4,9]
suma=1
for item in lista_numeros:
suma= item * suma
print(suma)<file_sep>/Contador vocales y consonantes.py
frase_usuario=input("Introduce una frase: ")
vocales=["a","e","i","o","u"]
n_vocales= 0
n_consonantes=0
for letra in frase_usuario:
if letra in vocales:
n_vocales += 1
else:
n_consonantes +=1
print("En tu frase hay {} vocales y {} consonantes".format(n_vocales,n_consonantes))
<file_sep>/contador de letras mayusculas.py
frase_usuario= input("Introduce una frase: ")
mayusculas=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","Ñ","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
n_mayusculas= 0
for letra in frase_usuario:
if letra in mayusculas:
n_mayusculas += 1
else:
n_mayusculas += 0
print("En tu oración hay {} mayúsculas".format(n_mayusculas)) | 9642888a1d080d264d1882e534ff8ba7580585fd | [
"Python"
] | 28 | Python | Carlesgr88/Primer_Programa | f19a65f84abbfe71ae6aa979a277efeb9bf57c20 | 82fa1f41f5c2652b31b49456e670cae79b03e22d |
refs/heads/master | <repo_name>dhruvrrp/Medic-Bot<file_sep>/README.md
Medic Bot
1. **Value Iteration (Markov Decision Process)** - To find the optimal policy at each point in the grid, maximizing based on the rewards.# Medic-Bot
<file_sep>/scripts/robot.py
#!/usr/bin/env python
#robot.py implementation goes here
import astar
import numpy as np
import cv2
from cv_bridge import CvBridge, CvBridgeError
from mdp import mdp
import rospy
from std_msgs.msg import Bool
from medic_bot.msg import AStarPath, PolicyList
from sensor_msgs.msg import Image
class Robot():
def __init__(self):
rospy.init_node('Robot', anonymous=True)
self.hog = cv2.HOGDescriptor()
self.hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )
self.avg_width = 0.45
self.path_pub = rospy.Publisher(
"results/path_list",
AStarPath,
queue_size = 10
)
self.policy_pub = rospy.Publisher(
"results/policy_list",
PolicyList,
queue_size = 10
)
self.sim_pub = rospy.Publisher(
"map_node/sim_complete",
Bool,
queue_size = 10
)
self.cam_sub = rospy.Subscriber(
"/camera/visible/image",
Image,
self.detect_people
)
path_list = astar.astar()
for pl in path_list:
asp = AStarPath()
asp.data = pl
rospy.sleep(1)
self.path_pub.publish(asp)
markov = mdp()
pl = PolicyList()
pl.data = markov.policy_list
rospy.sleep(1)
rospy.sleep(1)
rospy.sleep(1)
self.policy_pub.publish(pl)
#print markov.policy_list
#for m in markov.policy_list:
#pl = PolicyList()
#pl.data = m
#rospy.sleep(1)
#self.policy_pub.publish(pl)
rospy.sleep(1)
rospy.signal_shutdown("Done.")
def detect_people(self, img):
self.frame_width = img.width
cv_image = CvBridge().imgmsg_to_cv2(img, desired_encoding="bgr8")
print "what the fuk"
found, w = self.hog.detectMultiScale(cv_image, winStride=(8,8), padding=(32,32), scale=1.05)
found_filtered = []
for ri, r in enumerate(found):
for qi, q in enumerate(found):
if ri != qi and inside(r, q):
break
else:
found_filtered.append(r)
x, y, w, _ = found_filtered[0]
self.calculate_distance(x, w)
if self.cur_distance <= 1.0:
rospy.sleep(1)
rospy.signal_shutdown("Done.")
self.calculate_goal()
self.markov = mdp(self.goal)
self.pl = PolicyList()
self.pl.data = markov.policy_list
self.make_move()
def calculate_distance(self, x, w):
# Z'=D*f/d'
self.cur_distance = self.avg_width * self.cam_focus / w
#Find the middle point of person
mid_point = x + w/2.0
# Ratio of width of person in pixels to the image
x_ratio = mid_point/self.frame_width
# Angle at which person is from the left end of vision
agle = x_ratio/self.camera_fov
# True angle from the middle of vision
self.angle = (self.camera_fov/2) - agle
def calculate_goal(self):
new_x = self.cur_distance * math.sin(self.angle)
new_y = self.cur_distance * math.cos(self.angle)
self.goal = [new_x, new_y]
if __name__ == '__main__':
try:
Robot()
except rospy.ROSInterruptException:
pass
| 4cd0c67b5837fd48dab3a24eae97763a6b550e77 | [
"Markdown",
"Python"
] | 2 | Markdown | dhruvrrp/Medic-Bot | 6854c8d7a3c819b25c4ef16aa10eb3ab4208efd4 | c5f38f04dbf4a2d11e262e12f717b1829cdad58f |
refs/heads/master | <file_sep>$(document).ready( function(){
$(".resultados").hide();
$("#calc").submit(function(e){
e.preventDefault();
$("#btnconfirma").prop( "disabled", true);
$("#skill1").prop( "disabled", true);
$("#skill2").prop( "disabled", true);
$("#skill3").prop( "disabled", true);
$("#skill4").prop( "disabled", true);
$('#bonecoss').prop( "disabled", false);
var s1 = $("#skill1").val();
var s2 = $("#skill2").val();
var s3 = $("#skill3").val();
var s4 = $("#skill4").val();
var ss = $('#bonecoss').prop('checked');
if(ss){
var result = 0;
for(var i=1;i<s1;i++){
result += (s1-i);
}
for(var i=1;i<s2;i++){
result += (s2-i);
}
for(var i=1;i<s3;i++){
result = result + (s3-i);
}
for(var i=1;i<s4;i++){
result = result + (s4-i);
}
$(".result_green").html("x"+result+" livros");
$(".result_blue").html("x"+result*2+" livros (Combinar)");
} else {
var result = 0;
for(var i=1;i<s1;i++){
result = result + (s1-i);
}
for(var i=1;i<s2;i++){
result = result + (s2-i);
}
for(var i=1;i<s3;i++){
result = result + (s3-i);
}
for(var i=1;i<s4;i++){
result = result + (s4-i);
}
$(".result_blue").html("x"+result+" livros");
$(".result_green").html("Não utiliza");
}
$(".resultados").toggle(500);
});
$(".limpar").click(function(){
$("#btnconfirma").prop( "disabled", false);
$("#skill1").prop( "disabled", false);
$("#skill2").prop( "disabled", false);
$("#skill3").prop( "disabled", false);
$("#skill4").prop( "disabled", false);
$('#bonecoss').prop( "disabled", false);
$("#skill1").val(1);
$("#skill2").val(1);
$("#skill3").val(1);
$("#skill4").val(1);
$(".resultados").toggle(500);
});
});
<file_sep># kotzcalc.github.io
Calculadora de skills para o jogo Saint Seiya Awakening
| dbb3dcdede016b8a5b1c2e1ad4382a4d19685ff9 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | kotzcalc/kotzcalc.github.io | a3a1c9847c245c139e79114536ddfab8a770b44f | 13d379a59d906f75d430683f621978e7ff23f9ca |
refs/heads/master | <file_sep>package com.jcpdev.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/3th.dev")
public class ThirdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ThirdServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request 애트리뷰트 저장은 없지만 url 패턴을 xxx.dev 로 유지하기 위해 아래 코딩으로
//view 출력하고 request,response도 전달합니다.
RequestDispatcher rd = request.getRequestDispatcher("3th.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h4>파라미터</h4>");
out.print("name : "+name);
out.print("<br>");
out.print("age : "+age);
out.print("<br>");
out.print(request);
out.print("<br>");
out.print(response);
//요청메소드 POST 는 데이터 저장(db insert) 동작
//response.sendRedirect(url); //출력내용 확인하기 위해 생략.
}
}
| 9aa7a7827f5dbabbe4b81f8226d9e7f3e1b9d15c | [
"Java"
] | 1 | Java | kimminjae7608/jsp3 | 671f1ed1ec0a079148a77c6f7637249a571de184 | 000fe014237612f75e697b112208167f3dc01eb4 |
refs/heads/master | <file_sep><?php
//require_once("includes/config.php");
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "fyp_management_system";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
$cms = $_POST['cms'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$batchId = $_POST['batch'];
$password = $_POST['password'];
$isActive = 1;
//get selected project name
$projectName = $_POST['pname'];
//get id of the suggested topic select tag
$projectId = $_POST['st'];
//get id of the supervisor
$facultyId = $_POST['sid'];
mysql_query("INSERT INTO student (studentName, studentCMS, studentEmail, studentPhoneNo, studentGender, studentPassword, batchId, isActive)
VALUES ('$name', '$cms', '$email', '$contact', '$gender', '$password', '$batchId', '$isActive')");
$studentId = mysql_insert_id();
mysql_query("INSERT INTO student_group (projectName, batchId, leaderId) VALUES ('$projectName', '$batchId', '$studentId')");
$groupId = mysql_insert_id();
mysql_query("UPDATE student SET groupId='$groupId' , isLeader = '1' WHERE studentId = '$studentId'");
// insert/assign supervisor
mysql_query("INSERT INTO faculty_student_group (groupId, facultyId) VALUES ('$groupId', '$facultyId')");
mysql_query("UPDATE suggested_topics SET assigned='1' WHERE id = '$projectId'");
echo '<script language="javascript" type="text/javascript"> alert("Registration Succesfull!!");</script>';
echo '<script language="javascript" type="text/javascript"> window.location="index.php";</script>';
?><file_sep><?php
session_start();
$_SESSION['fullname'] = $_SESSION["usrnm"];
$host = "localhost";
$user = "root";
$pass = "";
$database = "fyp_management_system";
$selected_username = $_SESSION["usrnm"];
$connection_String = mysqli_connect($host,$user,$pass,$database);
$command_query = "SELECT * FROM student WHERE studentName = '$selected_username' ";
$execute_command_query = mysqli_query($connection_String,$command_query);
while($row = mysqli_fetch_assoc($execute_command_query)){
if($row["studentImage"]==""){
echo "<img class='my_profile_pic' src='Profile_Pictures/default.png' title='Click to change profile picture'/>";
}else{
$picture_holder = $row["studentImage"];
echo "<img class='my_profile_pic' src='Profile_Pictures/$picture_holder' title='Click to change profile picture'/>";
}
}
mysqli_close($connection_String);
?>
<file_sep><?php
require_once("includes/header.php");
require_once("includes/config.php");
?>
<?php
//php section for getting area interest and suggested topics
$db = new mysqli('localhost','root','','fyp_management_system');
$query = "SELECT id,name FROM area_interest";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$ais[] = array("id" => $row['id'], "val" => $row['name']);
}
$query = "SELECT id, aid, name FROM suggested_topics where assigned = 0";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$st[$row['aid']][] = array("id" => $row['id'], "val" => $row['name']);
}
//convert origins and destination gotten to JSON format
$Ais = json_encode($ais);
$St = json_encode($st);
?>
<title>Register | FYP Management System</title>
<script type='text/javascript'>
<?php
//receive and store JSON formatted origins and destination gotten above
echo "var ais = $Ais; \n";
echo "var st = $St; \n";
?>
function loadais(){
var select = document.getElementById("ai");
select.onchange = updatest;
for(var i = 0; i < ais.length; i++){
select.options[i] = new Option(ais[i].val,ais[i].id);
}
}
//update suggested topics
function updatest(){
var AiSelect = this;
var aiid = this.value;
var stSelect = document.getElementById("st");
stSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < st[aiid].length; i++){
stSelect.options[i] = new Option(st[aiid][i].val,st[aiid][i].id);
}
var sele = document.getElementById("st");
var b = sele.options[sele.selectedIndex].value;
//get projectName i.e selected text
var a = sele.options[sele.selectedIndex].text;
document.getElementById("pname").value=a;
//get supervisors name and ID
$.ajax({
type: 'post',
url: 'getsupervisor.php',
data: {
get_sel:b
},
success: function (response) {
var res = response.split("-");
document.getElementById("sid").value=res[0];
document.getElementById("sname").value=res[1];
}
});
}
function setSupervisor(sel)
{
var sel = sel.options[sel.selectedIndex].value;
//get projectName i.e selected text
var sele = document.getElementById("st");
var a = sele.options[sele.selectedIndex].text;
document.getElementById("pname").value=a;
//get supervisor
$.ajax({
type: 'post',
url: 'getsupervisor.php',
data: {
get_sel:sel
},
success: function (response) {
var res = response.split("-");
document.getElementById("sid").value=res[0];
document.getElementById("sname").value=res[1];
}
});
}
</script>
</head>
<body class="hold-transition login-page" onload='loadais()'>
<section>
<div class="login-logo">
<a href="<?php echo siteroot;?>"><img src="./img/logo_type.png" alt="fyp_logo" width="360" length="52"></a>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<!--Code for register student starts here-->
<div class="register-box-body">
<div class="box-header">
<h4 class="text-center ">Register Here</h4>
</div>
<form id="registerStudent" name="registerStudent" action="insert.php" method="post" data-toggle="validator">
<div class="form-group has-feedback">
<input type="number" min="000001" max="99999" name="cms" class="form-control" placeholder="Enter regno" required/>
<span class="glyphicon glyphicon-asterisk form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="text" name="name" pattern="[a-zA-Z][a-zA-Z ]{4,}" class="form-control" placeholder="Enter Full name" maxlength="30" minlength="5" required/> <!--TODO : Regex for name-->
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label>Gender </label>
<input type="radio" name="gender" value="male" checked> Male
<input type="radio" name="gender" value="female"> Female<br>
</div>
<div class="form-group has-feedback">
<input type="email" name="email" class="form-control" placeholder="Enter Email" required/>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="text" name="contact" pattern="[0-9]+" minlength="10" maxlength="11" class="form-control bfh-phone" placeholder="Phone Number" /> <!--TODO : Add pattern for number here-->
<span class="glyphicon glyphicon-phone form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<select name="batch" class="form-control" required>
<?php
$sqlGet = "SELECT * FROM batch WHERE isActive= 1 ORDER BY createdDtm DESC";
$result = $conn->query($sqlGet);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) { ?>
<option value="<?php echo $row['batchId'];?>"><?php echo $row['batchName']; ?></option>
<?php
}
}
?>
</select>
</div>
<div class="form-group has-feedback">
<input type="text" name="password" class="form-control" placeholder="Enter Password" />
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
Area of Interest
<div class="form-group has-feedback">
<select id="ai" name="ai" class="form-control" required>
</select>
</div>
Suggested Topics
<div class="form-group has-feedback">
<select id="st" onchange="setSupervisor(this);" name="st" class="form-control" required>
</select>
<input id="pname" type="hidden" name="pname" required/>
</div>
Assigned Supervisor
<div class="form-group has-feedback">
<input id="sname" type="text" name="sname" class="form-control" placeholder="Supervisor" maxlength="70" minlength="5" required/>
<input id="sid" type="hidden" name="sid" required/>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="box-footer ">
<div class="checkbox pull-left">
<label>
<input type="checkbox" name="emailSend" value="false" checked> Do not send email to user
</label>
</div>
<div class="form-group pull-right">
<a href="<?php echo siteroot; ?>" class="btn btn-default btn-sm "> Back</a>
<button type="submit" name="btnRegisterStudent" class="btn btn-primary btn-sm">Register</button>
</div>
</div>
</form>
</div>
<!--Code for register student ends here-->
</div>
<div class="col-md-2"></div>
</div>
</section>
<?php require_once("includes/required_js.php");?>
</body>
</html>
<file_sep><?php
$title = "FYPMS";
$subtitle = "Project Repository";
require_once("includes/header.php");
require_once("includes/config.php");
session_start();
if (!isset($_SESSION["usrCMS"])) {
header('Location: ' . 'index.php');
}
$studentId = $_SESSION['usrId'];
//Getting group id
$sql = "SELECT * FROM student WHERE student.studentId = '$studentId' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$groupId = $row['groupId'];
}
}else{
$groupId = $_SESSION["GroupID"];
}
//Get Project name
if (!is_null($groupId)){
//Getting group id and Project Name from DATABASE
//If groupLeader
$sql = "SELECT * FROM student_group WHERE student_group.leaderId = '$studentId' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$projectName = $row['projectName'];
}
}
else{
$projectName = $conn->query("SELECT projectName FROM student JOIN student_group ON student.groupId = student_group.groupId WHERE student.studentId = '$studentId' LIMIT 1" )->fetch_object()->projectName;
}
}
//Getting supervisor id and name
$sql = "SELECT facultyId FROM faculty_student_group WHERE faculty_student_group.groupId = '$groupId' LIMIT 1 ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$supervisorId = $row["facultyId"];
}
$sql_name = "SELECT facultyName FROM faculty WHERE faculty.facultyId = '$supervisorId' ";
$result = $conn->query($sql_name);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$supervisorName = $row["facultyName"];
}
}
}
//Check if form is submitted by GET
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
}
//Check if form is submitted by POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}
?>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<?php require_once("includes/main-header.php"); ?>
<?php require_once("includes/main-sidebar.php"); ?>
<div class="content-wrapper">
<?php require_once("includes/content-header.php"); ?>
<section class="content" style="min-height: 700px">
<div class="row">
<?php
if (!is_null($groupId) ) { ?>
<div class="col-md-12">
<div class="box box-solid">
<!-- /.box-header -->
<div class="box-body">
<h3>Project Name:<?php echo $projectName?></h3>
<!--Supervisor Name-->
<h4>Supervisor:<?php
if (isset($supervisorName)){
echo $supervisorName;
}else{
echo ' --- ';
}
?></h4>
</div>
<!-- /.box-body -->
<div class="box no-border">
<div class="box-header with-border">
<h3 class="box-title">Project Repository</h3>
</div>
<!-- /.box-header -->
<div class="box-body ">
<table class="table table-condensed ">
<tr>
<th>Title</th>
<th>Project Material</th>
<th>Uploaded <i class="fa fa-clock-o"></i></th>
<th>Uploaded by</th>
</tr>
<?php
//Getting group id
$sql = "SELECT * FROM student WHERE student.studentId = '$studentId' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$groupId = $row['groupId'];
}
}
// delete//$groupId = filter_input(INPUT_GET,'uploads',FILTER_SANITIZE_NUMBER_INT);
//good way// $sql = "SELECT * FROM group_uploads WHERE groupId = '$groupId'";
$sql = "SELECT * FROM tbl_projects JOIN student ON tbl_projects.studentid = student.studentID WHERE tbl_projects.studentid = '$studentId' LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php
$studentId = $row['studentid'];
$taskName = $conn->query("SELECT title FROM tbl_projects WHERE studentid = '$studentId' LIMIT 10")->fetch_object()->title;
echo $taskName;
?>
</td>
<td><?php
$deliverableName=$row['projectfile'];
//$groupId = $row['groupId'];
//Getting batchId,batch Name from groupId
/* $batchId = $conn->query("SELECT batchId FROM student_group WHERE groupId = '$groupId' ")->fetch_object()->batchId;
$batchName = $conn->query("SELECT batchName FROM batch WHERE batchId = '$batchId' ")->fetch_object()->batchName;
$group = 'Group '.$groupId;*/
$location = siteroot."projectFiles/"."/".$deliverableName;
echo "<a href=\"$location\">$deliverableName</a>" ;
?></td>
<td><?php echo $row['dateadded'];?></td>
<td><?php
$studentId =$row['studentId'];
//$studentName = $conn->query("SELECT studentName FROM student WHERE studentId = '$studentId' LIMIT 1")->fetch_object()->studentName;
//echo "<a href=\"studentProfile.php?id=$studentId\">$studentName</a>" ;
echo $row['studentName'];
?>
</td>
</tr>
<?php
}
}
?>
</table>
</div>
<!-- /.box-body -->
</div>
<div class="box-footer">
<a href="<?php echo siteroot;?>" class="btn btn-default btn-sm">Back</a>
<a href="addProject.php" class="btn btn-default btn-sm">Add Project</a>
</div>
</div>
<!-- /.box -->
</div>
<?php } else if (is_null($groupId)) { ?>
<div class="col-md-12">
<div class="callout callout-info">
<h4>Can not show details</h4>
<p>You are not part of any group.Please form a group and try again</p>
</div>
</div>
<?php
}
?>
</div>
</section>
</div>
<?php
require_once("includes/main-footer.php");
?>
</div>
<?php
require_once("includes/required_js.php");
?>
</body>
</html><file_sep><?php
// require_once("includes/header.php");
require_once("includes/config.php");
$clicked_on_username = $_COOKIE["default_clicked_on_username"];
$host = "localhost";
$user = "root";
$pass = "";
$database = "fyp_management_system";
$connection_String = mysqli_connect($host,$user,$pass,$database);
$get_user_profile_command = "SELECT * FROM student WHERE studentName='$clicked_on_username' LIMIT 1";
$execute_get_profile_command = mysqli_query($connection_String,$get_user_profile_command);
$get_individual_files = mysqli_fetch_assoc($execute_get_profile_command);
$profile_user_first_name = $get_individual_files["studentName"];
$profile_user_email = $get_individual_files["studentEmail"];
$profile_user_profile_pic = $get_individual_files["studentImage"];
echo "<div id='my_profile_holder'>";
if( $profile_user_profile_pic == "" ){
echo "<img class='user_picture' src='Profile_Pictures/default.png'/>";
}else{
echo "<img class='user_picture' src='Profile_Pictures/$profile_user_profile_pic'/>";
}
echo "</div>";
echo "<div id='details_holder'>";
echo "<span><strong class='heading-style'>Email </strong>: <br><span class='word-styling'>".$profile_user_email."</span></span><br>";
echo "</div>";
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 3.3.9
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 16, 2020 at 03:51 PM
-- Server version: 5.5.8
-- PHP Version: 5.3.5
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `fyp_management_system`
--
-- --------------------------------------------------------
--
-- Table structure for table `area_interest`
--
CREATE TABLE IF NOT EXISTS `area_interest` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
--
-- Dumping data for table `area_interest`
--
INSERT INTO `area_interest` (`id`, `name`) VALUES
(1, 'Select Area of Interest'),
(2, 'Accountancy'),
(3, 'Expert System'),
(4, 'Multimedia'),
(5, 'Banking and Finance'),
(6, 'Civil Engineering'),
(7, 'Electrical Engineering'),
(8, 'Auditing'),
(9, 'Building Technology'),
(10, 'Education'),
(11, 'Estate Management'),
(12, 'Computer Science'),
(13, 'Political Science');
-- --------------------------------------------------------
--
-- Table structure for table `batch`
--
CREATE TABLE IF NOT EXISTS `batch` (
`batchId` int(255) NOT NULL AUTO_INCREMENT,
`batchName` varchar(255) NOT NULL,
`startingDate` date DEFAULT NULL,
`isActive` tinyint(4) DEFAULT '0' COMMENT '0= inactive , 1= active',
`sdpPart` tinyint(1) DEFAULT '1' COMMENT '0 or 1',
`createdDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`batchId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='batchDeadlinesInfo' AUTO_INCREMENT=20 ;
--
-- Dumping data for table `batch`
--
INSERT INTO `batch` (`batchId`, `batchName`, `startingDate`, `isActive`, `sdpPart`, `createdDtm`) VALUES
(18, 'Harmattan 2016', '2016-02-07', 1, 2, '2019-04-04 14:51:21'),
(19, 'Rain 2016', '2016-04-28', 1, 1, '2019-04-04 14:51:31');
-- --------------------------------------------------------
--
-- Table structure for table `batch_settings`
--
CREATE TABLE IF NOT EXISTS `batch_settings` (
`id` int(11) NOT NULL,
`batchId` int(11) NOT NULL DEFAULT '0',
`male_female_group` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0=no;1=yes',
`sdp1_grading` tinyint(1) NOT NULL DEFAULT '0',
`internal_evaluation` tinyint(1) NOT NULL DEFAULT '0',
`sdp2_grading` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `batch_settings`
--
INSERT INTO `batch_settings` (`id`, `batchId`, `male_female_group`, `sdp1_grading`, `internal_evaluation`, `sdp2_grading`) VALUES
(1, 18, 0, 0, 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `batch_tasks`
--
CREATE TABLE IF NOT EXISTS `batch_tasks` (
`taskId` int(11) NOT NULL AUTO_INCREMENT,
`batchId` int(11) DEFAULT NULL,
`sdpPart` tinyint(1) DEFAULT '1',
`taskName` text,
`taskDetail` text,
`taskWeek` int(11) DEFAULT NULL,
`taskDeadline` datetime DEFAULT NULL,
`templateId` int(11) DEFAULT NULL,
`hasDeliverable` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1=has deliverable',
`createdDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`taskId`),
KEY `FK_batch_tasks_batch` (`batchId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `batch_tasks`
--
INSERT INTO `batch_tasks` (`taskId`, `batchId`, `sdpPart`, `taskName`, `taskDetail`, `taskWeek`, `taskDeadline`, `templateId`, `hasDeliverable`, `createdDtm`) VALUES
(1, 18, 1, 'Deliverable 01: Project Team List', '<p>\r\n\r\n</p><ul><li>Use <b>“Template-01â€</b> to fill in the details of project team members and submit hard copy to Project Coordinator .</li><li>Due Date: Monday, 25th April 2016 (Before 3:30pm)</li></ul>\r\n\r\n<br><p></p>', 3, '2016-04-25 15:30:00', 4, 1, '2016-04-21 22:48:26'),
(2, 19, 1, 'Start your project', '<p>Start your project<br></p>', 1, '2019-05-31 00:00:00', NULL, 1, '2019-05-11 19:41:45');
-- --------------------------------------------------------
--
-- Table structure for table `batch_templates`
--
CREATE TABLE IF NOT EXISTS `batch_templates` (
`templateId` int(11) NOT NULL AUTO_INCREMENT,
`batchId` int(11) DEFAULT NULL,
`templateName` varchar(100) DEFAULT NULL,
`templateLocation` varchar(150) DEFAULT NULL,
`uploadedDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`templateId`),
KEY `FK_batch_templates_batch` (`batchId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `batch_templates`
--
INSERT INTO `batch_templates` (`templateId`, `batchId`, `templateName`, `templateLocation`, `uploadedDtm`) VALUES
(3, 18, 'Handbook-Version-2-0.pdf', 'Handbook-Version-2-0.pdf', '2016-04-21 21:26:59'),
(4, 18, 'Template - 01 - Project Team.doc', 'Template - 01 - Project Team.doc', '2016-04-21 21:27:02'),
(5, 18, 'Template - 02 - Inital Proposal.doc', 'Template - 02 - Inital Proposal.doc', '2016-04-21 21:27:06'),
(6, 18, 'Template - 04 - Proposal Plan.doc', 'Template - 04 - Proposal Plan.doc', '2016-04-21 21:27:56'),
(7, 18, 'Template - 05 - Project Report.doc', 'Template - 05 - Project Report.doc', '2016-04-21 21:27:59'),
(8, 18, '2019 template', '2019 template.jpg', '2019-08-28 17:22:38');
-- --------------------------------------------------------
--
-- Table structure for table `external_examiner`
--
CREATE TABLE IF NOT EXISTS `external_examiner` (
`examinerId` int(255) NOT NULL AUTO_INCREMENT,
`examinerName` varchar(100) NOT NULL,
`examinerEmail` varchar(255) NOT NULL,
`examinerPhone` varchar(50) NOT NULL,
`examinerPassword` varchar(255) NOT NULL,
`company` varchar(255) NOT NULL,
`designation` varchar(255) NOT NULL,
`isActive` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`examinerId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='examinerGroupInfo' AUTO_INCREMENT=2 ;
--
-- Dumping data for table `external_examiner`
--
INSERT INTO `external_examiner` (`examinerId`, `examinerName`, `examinerEmail`, `examinerPhone`, `examinerPassword`, `company`, `designation`, `isActive`) VALUES
(1, '<NAME>', '<EMAIL>', '1234567890', '123', 'Microsoft', 'CEO', 1);
-- --------------------------------------------------------
--
-- Table structure for table `faculty`
--
CREATE TABLE IF NOT EXISTS `faculty` (
`facultyId` int(255) NOT NULL AUTO_INCREMENT,
`facultyName` varchar(255) NOT NULL,
`facultyPhoneNo` varchar(50) NOT NULL,
`facultyEmail` varchar(255) NOT NULL,
`designation` varchar(255) NOT NULL,
`facultyImage` varchar(255) DEFAULT NULL,
`facultyPassword` varchar(255) NOT NULL,
`isAdmin` tinyint(1) DEFAULT '0',
`isActive` tinyint(4) NOT NULL,
`isCoordinator` tinyint(1) DEFAULT NULL,
`createdDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`facultyId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Faculty Details' AUTO_INCREMENT=28 ;
--
-- Dumping data for table `faculty`
--
INSERT INTO `faculty` (`facultyId`, `facultyName`, `facultyPhoneNo`, `facultyEmail`, `designation`, `facultyImage`, `facultyPassword`, `isAdmin`, `isActive`, `isCoordinator`, `createdDtm`) VALUES
(0, 'Super Admin', '', '<EMAIL>', '--', NULL, '123', 1, 1, 0, '2019-04-04 14:00:21'),
(18, '<NAME>', '+233458541454', '<EMAIL>', 'Coordinator', 'NULL', '123', 0, 1, 1, '2019-05-11 14:28:08'),
(19, '<NAME>', '12345678', '<EMAIL>', 'Supervisor', NULL, '123', 0, 1, NULL, '2019-04-04 14:57:50'),
(20, '<NAME>', '12345678', '<EMAIL>', 'Supervisor', NULL, '123', 1, 1, NULL, '2019-05-10 16:32:09'),
(21, '<NAME>', '12345678', '<EMAIL>', 'Supervisor', NULL, '123', 0, 1, NULL, '2019-05-11 07:02:40'),
(22, '<NAME>', '12345678', '<EMAIL>', 'Supervisor', NULL, '123', 0, 1, NULL, '2019-05-11 07:02:26'),
(23, '<NAME>', '12345678', '<EMAIL>', 'Supervisor', NULL, '123', 0, 1, NULL, '2019-04-04 14:58:01'),
(24, '<NAME>', '08076565435', '<EMAIL>', 'Dr', NULL, '123', 0, 1, 1, '2019-05-11 14:48:04'),
(25, '<NAME>', '23376565435', '<EMAIL>', 'Mr', NULL, '123', 0, 1, 1, '2019-05-11 14:47:54'),
(26, '<NAME>', '23376565098', '<EMAIL>', 'Mrs', NULL, '123', 0, 1, 1, '2019-05-11 14:48:12'),
(27, '<NAME>', '23370065435', '<EMAIL>', 'Mr', NULL, '123', 0, 1, 1, '2019-05-11 14:47:46');
-- --------------------------------------------------------
--
-- Table structure for table `faculty_student_group`
--
CREATE TABLE IF NOT EXISTS `faculty_student_group` (
`facultyStudentId` int(255) NOT NULL AUTO_INCREMENT,
`groupId` int(255) NOT NULL,
`facultyId` int(255) NOT NULL,
PRIMARY KEY (`facultyStudentId`),
KEY `fk_group_id` (`groupId`),
KEY `fk_faculty_id` (`facultyId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='facultyGroupInfo' AUTO_INCREMENT=7 ;
--
-- Dumping data for table `faculty_student_group`
--
INSERT INTO `faculty_student_group` (`facultyStudentId`, `groupId`, `facultyId`) VALUES
(2, 1, 21),
(3, 4, 23),
(4, 6, 23),
(5, 7, 20),
(6, 8, 18);
-- --------------------------------------------------------
--
-- Table structure for table `faculty_student_request`
--
CREATE TABLE IF NOT EXISTS `faculty_student_request` (
`requestId` int(11) NOT NULL AUTO_INCREMENT,
`facultyId` int(11) DEFAULT NULL,
`groupId` int(11) DEFAULT NULL,
`requestDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`requestId`),
KEY `FK_faculty_student_request_faculty` (`facultyId`),
KEY `FK_faculty_student_request_faculty_student_group` (`groupId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `faculty_student_request`
--
-- --------------------------------------------------------
--
-- Table structure for table `grades`
--
CREATE TABLE IF NOT EXISTS `grades` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`studentId` int(11) DEFAULT NULL,
`groupId` int(11) DEFAULT NULL,
`sdpPart` int(11) DEFAULT NULL,
`comments` text,
`grade` varchar(50) DEFAULT NULL,
`gradedBy` int(11) DEFAULT NULL COMMENT 'User id of user',
`gradeDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `FK_grades_student` (`studentId`),
KEY `FK_grades_student_group` (`groupId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf32 AUTO_INCREMENT=10 ;
--
-- Dumping data for table `grades`
--
INSERT INTO `grades` (`id`, `studentId`, `groupId`, `sdpPart`, `comments`, `grade`, `gradedBy`, `gradeDtm`) VALUES
(4, 14, 1, 2, '', 'A', 1, '2016-04-22 01:31:52'),
(5, 15, 1, 2, '', 'A', 1, '2016-04-22 01:31:52'),
(6, 21, 1, 2, '', 'B', 1, '2016-04-22 01:31:53'),
(7, 14, 1, 1, '', 'A', 21, '2016-04-22 01:34:28'),
(8, 15, 1, 1, '', 'A', 21, '2016-04-22 01:34:28'),
(9, 21, 1, 1, '', 'B+', 21, '2016-04-22 01:34:28');
-- --------------------------------------------------------
--
-- Table structure for table `group_requests`
--
CREATE TABLE IF NOT EXISTS `group_requests` (
`requestId` int(255) NOT NULL AUTO_INCREMENT,
`studentId` int(255) NOT NULL,
`groupId` int(255) NOT NULL,
PRIMARY KEY (`requestId`),
KEY `FK_group_requests_student` (`studentId`),
KEY `FK_group_requests_student_group` (`groupId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `group_requests`
--
-- --------------------------------------------------------
--
-- Table structure for table `group_uploads`
--
CREATE TABLE IF NOT EXISTS `group_uploads` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`groupId` int(11) NOT NULL,
`taskId` int(11) NOT NULL,
`uploadFile` varchar(50) NOT NULL,
`uploadedBy` int(11) NOT NULL COMMENT 'userId of uploader',
`uploadedDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `FK_group_uploads_faculty_student_group` (`groupId`),
KEY `FK_group_uploads_batch_tasks` (`taskId`),
KEY `FK_group_uploads_student` (`uploadedBy`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `group_uploads`
--
INSERT INTO `group_uploads` (`id`, `groupId`, `taskId`, `uploadFile`, `uploadedBy`, `uploadedDtm`) VALUES
(1, 1, 1, 'group_1_deliverable_1.doc', 15, '2016-04-21 22:49:18'),
(2, 7, 2, 'group_7_deliverable_2.jpg', 102, '2019-05-11 19:43:11'),
(3, 8, 1, 'group_8_deliverable_1.jpg', 103, '2020-02-16 16:18:54');
-- --------------------------------------------------------
--
-- Table structure for table `meeting_logs`
--
CREATE TABLE IF NOT EXISTS `meeting_logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`supervisor_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
`meeting_title` varchar(50) NOT NULL,
`meeting_dtm` datetime NOT NULL,
`comments` text,
`meeting_status` enum('Pending','Done','Cancelled','Postponed') NOT NULL DEFAULT 'Pending',
`created_dtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `FK_meeting_logs_faculty` (`supervisor_id`),
KEY `FK_meeting_logs_faculty_student_group` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Maintain all meeting logs of supervisors with students' AUTO_INCREMENT=2 ;
--
-- Dumping data for table `meeting_logs`
--
INSERT INTO `meeting_logs` (`id`, `supervisor_id`, `group_id`, `meeting_title`, `meeting_dtm`, `comments`, `meeting_status`, `created_dtm`) VALUES
(1, 21, 1, 'Meeting 01 - Group Formation', '2016-04-30 15:30:00', '', 'Done', '2016-04-21 23:16:54');
-- --------------------------------------------------------
--
-- Table structure for table `project_repository`
--
CREATE TABLE IF NOT EXISTS `project_repository` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`batchId` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `FK_project_repository_batch` (`batchId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `project_repository`
--
INSERT INTO `project_repository` (`id`, `batchId`) VALUES
(1, 18);
-- --------------------------------------------------------
--
-- Table structure for table `repository_users`
--
CREATE TABLE IF NOT EXISTS `repository_users` (
`user_id` int(11) NOT NULL,
`user_name` varchar(50) NOT NULL DEFAULT '0',
`user_email` varchar(50) NOT NULL DEFAULT '0',
`user_password` varchar(50) DEFAULT NULL,
`access_type` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1= full-access '
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `repository_users`
--
-- --------------------------------------------------------
--
-- Table structure for table `student`
--
CREATE TABLE IF NOT EXISTS `student` (
`studentId` int(255) NOT NULL AUTO_INCREMENT,
`studentName` varchar(255) CHARACTER SET utf8 NOT NULL,
`studentCMS` varchar(50) CHARACTER SET utf8 NOT NULL,
`studentEmail` varchar(255) CHARACTER SET utf8 NOT NULL,
`studentPhoneNo` varchar(50) CHARACTER SET utf8 NOT NULL,
`studentGender` varchar(10) CHARACTER SET utf8 NOT NULL,
`studentPassword` varchar(255) CHARACTER SET utf8 NOT NULL,
`studentImage` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
`groupId` int(255) DEFAULT NULL,
`isLeader` int(1) DEFAULT NULL,
`batchId` int(4) DEFAULT NULL,
`isActive` tinyint(1) NOT NULL DEFAULT '1',
`createdDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`studentId`),
KEY `FK_student_batch` (`batchId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='FYP Student Records' AUTO_INCREMENT=104 ;
--
-- Dumping data for table `student`
--
INSERT INTO `student` (`studentId`, `studentName`, `studentCMS`, `studentEmail`, `studentPhoneNo`, `studentGender`, `studentPassword`, `studentImage`, `groupId`, `isLeader`, `batchId`, `isActive`, `createdDtm`) VALUES
(14, '<NAME>', '7757', '<EMAIL>', '01234565', 'male', '123', '56fff928b82971.36534035.jpg', 1, NULL, 18, 1, '2019-04-04 14:05:24'),
(15, '<NAME>', '10776', '<EMAIL>', '03458541454', 'male', '123', '57178d49d31f15.75642865.jpg', 1, 1, 18, 1, '2016-04-03 14:30:06'),
(21, '<NAME>', '7471', '<EMAIL>', '+2330900039339', 'male', '123', '56fff9374231d1.64504225.jpg', 1, NULL, 18, 1, '2019-05-02 12:47:09'),
(43, '<NAME>', '7736', '<EMAIL>', '923211234567', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-10 15:28:47'),
(44, '<NAME>', '8781', '<EMAIL>', '1234567', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:47:48'),
(45, '<NAME>', '7740', '<EMAIL>', '033569870', 'female', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:48:18'),
(46, '<NAME>', '7759', '<EMAIL>', '03356980', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:51:02'),
(47, '<NAME>', '8658', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:54:05'),
(48, '<NAME>', '8627', '<EMAIL>', '033564897', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:48:38'),
(49, '<NAME>', '8939', '<EMAIL>', '03369872', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:07:23'),
(50, '<NAME>', '8660', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:08:05'),
(51, '<NAME>', '8617', '<EMAIL>', '0336589741', 'female', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:49:10'),
(52, '<NAME>', '9214', '<EMAIL>', '033658970', 'female', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:09:52'),
(53, '<NAME>', '9331', '<EMAIL>', '033658970', 'female', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:11:07'),
(54, '<NAME>', '9231', '<EMAIL>', '03325689', 'female', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:52:34'),
(55, '<NAME>', '8659', '<EMAIL>', '033658970', 'male', '123', NULL, 4, 1, 18, 1, '2016-04-14 23:12:34'),
(56, '<NAME>', '8621', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:49:45'),
(57, '<NAME>', '8857', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:50:06'),
(58, '<NAME>', '7735', '<EMAIL>', '0335698741', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:51:25'),
(59, '<NAME>', '7337', '<EMAIL>', '03236116360', 'male', '123', NULL, 9, 1, 18, 1, '2020-02-16 15:58:34'),
(60, '<NAME>', '7752', '<EMAIL>', '03135122852', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:18:17'),
(61, '<NAME>', '8990', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:53:46'),
(62, '<NAME>', '8647', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:19:46'),
(63, '<NAME>', '8940', '<EMAIL>', '03445986007', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:21:41'),
(64, '<NAME>', '9011', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:51:55'),
(65, '<NAME>', '7530', '<EMAIL>', '03004368436', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:53:00'),
(66, '<NAME>', '8861', '<EMAIL>', '0335698712', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:52:18'),
(67, '<NAME>', '8648', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:30:51'),
(68, '<NAME>', '9305', '<EMAIL>', '023115864977', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:53:25'),
(69, '<NAME>', '7655', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2019-05-02 12:50:42'),
(70, '<NAME>', '9268', '<EMAIL>', '03361445566', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:36:26'),
(71, '<NAME>', '8023', '<EMAIL>', '03315613839', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:38:52'),
(72, '<NAME>', '7414', '<EMAIL>', '03341561011', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:41:07'),
(73, '<NAME>', '8691', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:42:32'),
(74, '<NAME>', '9764', '<EMAIL>', '03356890', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:44:19'),
(75, '<NAME>', '9759', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:45:09'),
(76, '<NAME>', '9215', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:45:59'),
(77, '<NAME>', '9251', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:47:03'),
(78, '<NAME>', '9264', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:48:02'),
(79, '<NAME>', '9574', '<EMAIL>', '03337390718', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:49:56'),
(80, '<NAME>', '9380', '<EMAIL>', '033568970', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:51:03'),
(81, '<NAME>', '9808', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:52:13'),
(82, '<NAME>', '9675', '<EMAIL>', '03135769291', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:54:24'),
(83, '<NAME>', '9189', '<EMAIL>', '033569872', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:55:08'),
(84, '<NAME>', '9556', '<EMAIL>', '03254698', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:55:48'),
(85, '<NAME>', '9272', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:57:44'),
(86, '<NAME>', '9548', '<EMAIL>', '032569871', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-14 23:58:32'),
(87, '<NAME>', '9525', '<EMAIL>', '03315458369', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:00:37'),
(88, '<NAME>', '9402', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:04:32'),
(89, '<NAME>', '9184', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:11:45'),
(90, '<NAME>', '9220', '<EMAIL>', '03315810211', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:13:45'),
(91, '<NAME>', '9260', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:16:38'),
(92, '<NAME>', '9269', '<EMAIL>', '033658970', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:20:13'),
(93, '<NAME>', '9258', '<EMAIL>', '033569870', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:21:57'),
(94, '<NAME>', '9155', '<EMAIL>', '033569810', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:24:16'),
(95, '<NAME>', '7531', '<EMAIL>', '03015631656', 'male', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:26:36'),
(96, '<NAME>', '9271', '<EMAIL>', '0335698721', 'female', '123', NULL, 5, NULL, 18, 1, '2016-04-15 00:27:33'),
(97, '<NAME>', '9270', '<EMAIL>', '03358976', 'female', '123', NULL, 5, 1, 18, 1, '2016-04-15 00:28:45'),
(98, '<NAME>', '9807', '<EMAIL>', '033569870', 'female', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:58:18'),
(99, '<NAME>', '9734', '<EMAIL>', '033569870', 'female', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 00:59:34'),
(100, '<NAME>', '9584', 'irfah<EMAIL>', '033569870', 'female', '123', NULL, NULL, NULL, 18, 1, '2016-04-15 01:00:34'),
(101, '<NAME>', '9008', '<EMAIL>', '09032343432', 'male', '123', NULL, 6, 1, 19, 1, '2019-05-10 16:01:55'),
(102, '<NAME>', '2332', '<EMAIL>', '09032343432', 'female', '123', NULL, 7, 1, 19, 1, '2019-05-11 13:56:59'),
(103, '<NAME>', '20176', '<EMAIL>', '09089876765', 'male', 'damian', NULL, 8, 1, 18, 1, '2019-12-18 13:02:30');
-- --------------------------------------------------------
--
-- Table structure for table `student_group`
--
CREATE TABLE IF NOT EXISTS `student_group` (
`groupId` int(255) NOT NULL AUTO_INCREMENT,
`projectName` varchar(255) DEFAULT NULL,
`batchId` int(11) DEFAULT NULL,
`sdpPart` int(1) NOT NULL DEFAULT '1' COMMENT 'Here to check before deleting group',
`groupLimit` int(1) NOT NULL DEFAULT '3',
`inGroup` int(255) NOT NULL DEFAULT '1',
`leaderId` int(255) NOT NULL,
`createdDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`groupId`),
KEY `FK_student_group_batch` (`batchId`),
KEY `FK_student_group_student` (`leaderId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='groupInfo' AUTO_INCREMENT=10 ;
--
-- Dumping data for table `student_group`
--
INSERT INTO `student_group` (`groupId`, `projectName`, `batchId`, `sdpPart`, `groupLimit`, `inGroup`, `leaderId`, `createdDtm`) VALUES
(1, 'Design and Implementation of a project allocation management system', 18, 1, 3, 3, 15, '2019-04-04 14:49:05'),
(4, 'Design and Implementation of a digital library system', 18, 1, 3, 1, 55, '2019-04-04 14:48:07'),
(5, 'Online food ordering system', 18, 1, 3, 2, 97, '2019-04-04 14:49:37'),
(6, 'Design and Implementation of restaurant management system', 19, 1, 3, 1, 101, '2019-05-10 16:01:55'),
(7, 'Inventory management for a company', 19, 1, 3, 1, 102, '2019-05-11 13:56:59'),
(8, 'Property rating as a source of local government revenue in Ghana', 18, 1, 3, 1, 103, '2019-12-18 13:02:29'),
(9, 'Library management', 18, 1, 3, 1, 59, '2020-02-16 15:58:31');
-- --------------------------------------------------------
--
-- Table structure for table `student_group_request`
--
CREATE TABLE IF NOT EXISTS `student_group_request` (
`requestId` int(11) NOT NULL AUTO_INCREMENT,
`studentId` int(11) NOT NULL COMMENT 'Request sent by',
`groupId` int(11) NOT NULL COMMENT 'Request sent to group',
`requestDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`requestId`),
KEY `FK_student_group_request_student` (`studentId`),
KEY `FK_student_group_request_student_group` (`groupId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Requests sent to join a group a stored here temporarilty' AUTO_INCREMENT=1 ;
--
-- Dumping data for table `student_group_request`
--
-- --------------------------------------------------------
--
-- Table structure for table `suggested_topics`
--
CREATE TABLE IF NOT EXISTS `suggested_topics` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`aid` int(4) NOT NULL,
`name` varchar(500) NOT NULL,
`assigned` int(4) NOT NULL,
`supervisorFaculty` int(4) NOT NULL,
`supervisorFacultyName` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
KEY `aid` (`aid`),
KEY `supervisorFaculty` (`supervisorFaculty`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
--
-- Dumping data for table `suggested_topics`
--
INSERT INTO `suggested_topics` (`id`, `aid`, `name`, `assigned`, `supervisorFaculty`, `supervisorFacultyName`) VALUES
(1, 2, 'Inventory management for a company', 1, 20, '<NAME>'),
(2, 2, 'The effect of internal control system as a tool to for preventing and detecting fraud', 0, 21, '<NAME>'),
(3, 2, 'Debt management of Ghana commercial bank in Ghana', 0, 22, '<NAME>'),
(4, 2, 'The role financial institution in improving banks performance', 0, 19, '<NAME>'),
(5, 2, 'E-taxation administration Ghana', 0, 18, '<NAME>'),
(6, 2, 'An empirical assessment of firm in Ghana ', 0, 23, '<NAME>'),
(7, 3, 'Expert System for automobile diagnosis', 0, 21, '<NAME>'),
(8, 3, 'Artificial Intelligence syste for malaria diagnosis', 0, 19, '<NAME>'),
(9, 3, 'Expert System for clinical diagnosis', 0, 25, '<NAME>'),
(10, 3, 'Expert System for treatment of breast cancer', 0, 24, '<NAME>'),
(11, 4, 'Animated cartoon movies for advert', 0, 25, '<NAME>'),
(12, 4, 'Animation for corporate branding', 0, 26, '<NAME>'),
(13, 5, 'Current and future imperatives and prevention and management in financial services industry ', 0, 26, '<NAME>'),
(14, 5, 'Fraud and forgeries in banking industry-causes, effect and The way forward', 0, 26, '<NAME>'),
(15, 5, 'The impact of Ghanaian stock exchange in the developing of Ghana', 0, 24, '<NAME>'),
(16, 5, 'The role of budgeting in the private sector management', 0, 24, '<NAME>'),
(17, 6, 'Causes of road pavement failure and possible solution', 0, 27, '<NAME>'),
(18, 6, 'Domestic waste management system in Ghana', 0, 27, '<NAME>'),
(19, 7, 'Construction of light sensitive alarm', 0, 24, '<NAME>'),
(20, 7, 'Construction of electronic board', 0, 24, '<NAME>'),
(21, 7, 'Design and implementation of automatic battery charger', 0, 27, '<NAME>'),
(22, 8, 'The role of audit in small scale industries', 0, 26, '<NAME>'),
(23, 8, 'Audit price strategy system', 0, 26, '<NAME>'),
(24, 8, 'The role of internal audit in managing fraud in Ghana', 0, 26, '<NAME>'),
(25, 8, 'The influence of employee behaviour on the internal audit of an organization', 0, 26, '<NAME>'),
(26, 9, 'Housing finance management system', 0, 22, '<NAME>'),
(27, 9, 'Residential building management system', 0, 22, '<NAME>'),
(28, 10, 'Taboo and women', 0, 27, '<NAME>'),
(29, 10, 'Effect of unemployment on computer graduates', 0, 27, '<NAME>'),
(30, 11, 'Property rating as a source of local government revenue in Ghana', 1, 18, '<NAME>'),
(31, 11, 'The effect of slum on rental property value', 0, 18, '<NAME>'),
(32, 12, 'Design and implementation of library system', 0, 24, '<NAME>'),
(33, 12, 'Design and implementation of cargo shippment', 0, 24, '<NAME>'),
(34, 13, 'Women empowerment in Ghanaian politics', 0, 19, '<NAME>'),
(35, 13, 'The impact of public opinion on public policy in Ghana', 0, 19, '<NAME>');
-- --------------------------------------------------------
--
-- Table structure for table `timeline_faculty`
--
CREATE TABLE IF NOT EXISTS `timeline_faculty` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text,
`details` text,
`type` varchar(50) DEFAULT NULL,
`batchId` int(11) DEFAULT NULL,
`sdpPart` int(11) DEFAULT NULL,
`createdDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `FK_timeline_faculty_batch` (`batchId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='timeline for faculty' AUTO_INCREMENT=5 ;
--
-- Dumping data for table `timeline_faculty`
--
INSERT INTO `timeline_faculty` (`id`, `title`, `details`, `type`, `batchId`, `sdpPart`, `createdDtm`) VALUES
(4, 'Batch Upgraded', 'Spring 2016has been upgraded to Senior Design Project Part 2', 'info', 18, 2, '2016-04-23 01:10:17');
-- --------------------------------------------------------
--
-- Table structure for table `timeline_student`
--
CREATE TABLE IF NOT EXISTS `timeline_student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text,
`details` text,
`type` varchar(50) DEFAULT NULL,
`taskId` int(11) DEFAULT NULL,
`batchId` int(11) DEFAULT NULL,
`sdpPart` int(11) DEFAULT NULL,
`createdDtm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `FK_timeline_student_batch_tasks` (`taskId`),
KEY `FK_timeline_student_batch_tasks_2` (`batchId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Timeline for students' AUTO_INCREMENT=9 ;
--
-- Dumping data for table `timeline_student`
--
INSERT INTO `timeline_student` (`id`, `title`, `details`, `type`, `taskId`, `batchId`, `sdpPart`, `createdDtm`) VALUES
(1, '<i class="fa fa-info-circle" aria-hidden="true"></i> Info', '<NAME> is now supervising group FYP Management System', 'info', NULL, 18, 1, '2016-04-23 00:57:34'),
(2, '<i class="fa fa-info-circle" aria-hidden="true"></i> Info', '<NAME> is now supervising group RSATS', 'info', NULL, 18, 1, '2016-04-23 00:57:33'),
(3, 'Deliverable 01: Project Team List', '<p>\r\n\r\n</p><ul><li>Use <b>“Template-01â€</b> to fill in the details of project team members and submit hard copy to Project Coordinator .</li><li>Due Date: Monday, 25th April 2016 (Before 3:30pm)</li></ul>\r\n\r\n<br><p></p>', 'task', 1, 18, 1, '2016-04-21 22:48:26'),
(7, 'Batch Upgraded', 'Spring 2016has been upgraded to Senior Design Project Part 2', 'info', NULL, 18, 2, '2016-04-23 01:10:17'),
(8, 'Start your project', '<p>Start your project<br></p>', 'task', 2, 19, 1, '2019-05-11 19:41:45');
-- --------------------------------------------------------
--
-- Table structure for table `work_load`
--
CREATE TABLE IF NOT EXISTS `work_load` (
`loadId` int(255) NOT NULL AUTO_INCREMENT,
`facultyId` int(255) NOT NULL,
`totalLoad` int(255) NOT NULL,
`currentLoad` int(11) DEFAULT '0',
PRIMARY KEY (`loadId`),
KEY `FK_work_load_faculty` (`facultyId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='workload_Info' AUTO_INCREMENT=19 ;
--
-- Dumping data for table `work_load`
--
INSERT INTO `work_load` (`loadId`, `facultyId`, `totalLoad`, `currentLoad`) VALUES
(9, 18, 5, 0),
(10, 19, 5, 0),
(11, 20, 2, 0),
(12, 21, 5, 1),
(13, 22, 5, 0),
(14, 23, 5, 1),
(15, 24, 5, 0),
(16, 25, 5, 0),
(17, 26, 5, 0),
(18, 27, 5, 0);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `batch_tasks`
--
ALTER TABLE `batch_tasks`
ADD CONSTRAINT `FK_batch_tasks_batch` FOREIGN KEY (`batchId`) REFERENCES `batch` (`batchId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `batch_templates`
--
ALTER TABLE `batch_templates`
ADD CONSTRAINT `FK_batch_templates_batch` FOREIGN KEY (`batchId`) REFERENCES `batch` (`batchId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `faculty_student_group`
--
ALTER TABLE `faculty_student_group`
ADD CONSTRAINT `fk_faculty_id` FOREIGN KEY (`facultyId`) REFERENCES `faculty` (`facultyId`),
ADD CONSTRAINT `fk_group_id` FOREIGN KEY (`groupId`) REFERENCES `student_group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `faculty_student_request`
--
ALTER TABLE `faculty_student_request`
ADD CONSTRAINT `FK_faculty_student_request_faculty` FOREIGN KEY (`facultyId`) REFERENCES `faculty` (`facultyId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_faculty_student_request_faculty_student_group` FOREIGN KEY (`groupId`) REFERENCES `faculty_student_group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `grades`
--
ALTER TABLE `grades`
ADD CONSTRAINT `FK_grades_student` FOREIGN KEY (`studentId`) REFERENCES `student` (`studentId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_grades_student_group` FOREIGN KEY (`groupId`) REFERENCES `student_group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `group_requests`
--
ALTER TABLE `group_requests`
ADD CONSTRAINT `FK_group_requests_student` FOREIGN KEY (`studentId`) REFERENCES `student` (`studentId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_group_requests_student_group` FOREIGN KEY (`groupId`) REFERENCES `student_group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `group_uploads`
--
ALTER TABLE `group_uploads`
ADD CONSTRAINT `FK_group_uploads_batch_tasks` FOREIGN KEY (`taskId`) REFERENCES `batch_tasks` (`taskId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_group_uploads_faculty_student_group` FOREIGN KEY (`groupId`) REFERENCES `faculty_student_group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_group_uploads_student` FOREIGN KEY (`uploadedBy`) REFERENCES `student` (`studentId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `meeting_logs`
--
ALTER TABLE `meeting_logs`
ADD CONSTRAINT `FK_meeting_logs_faculty` FOREIGN KEY (`supervisor_id`) REFERENCES `faculty` (`facultyId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_meeting_logs_faculty_student_group` FOREIGN KEY (`group_id`) REFERENCES `faculty_student_group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `project_repository`
--
ALTER TABLE `project_repository`
ADD CONSTRAINT `FK_project_repository_batch` FOREIGN KEY (`batchId`) REFERENCES `batch` (`batchId`);
--
-- Constraints for table `student`
--
ALTER TABLE `student`
ADD CONSTRAINT `FK_student_batch` FOREIGN KEY (`batchId`) REFERENCES `batch` (`batchId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `student_group`
--
ALTER TABLE `student_group`
ADD CONSTRAINT `FK_student_group_student` FOREIGN KEY (`leaderId`) REFERENCES `student` (`studentId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `student_group_request`
--
ALTER TABLE `student_group_request`
ADD CONSTRAINT `FK_student_group_request_student` FOREIGN KEY (`studentId`) REFERENCES `student` (`studentId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_student_group_request_student_group` FOREIGN KEY (`groupId`) REFERENCES `student_group` (`groupId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `suggested_topics`
--
ALTER TABLE `suggested_topics`
ADD CONSTRAINT `suggested_topics_ibfk_1` FOREIGN KEY (`aid`) REFERENCES `area_interest` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `suggested_topics_ibfk_2` FOREIGN KEY (`supervisorFaculty`) REFERENCES `faculty` (`facultyId`) ON DELETE CASCADE;
--
-- Constraints for table `timeline_faculty`
--
ALTER TABLE `timeline_faculty`
ADD CONSTRAINT `FK_timeline_faculty_batch` FOREIGN KEY (`batchId`) REFERENCES `batch` (`batchId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `timeline_student`
--
ALTER TABLE `timeline_student`
ADD CONSTRAINT `FK_timeline_student_batch_tasks` FOREIGN KEY (`taskId`) REFERENCES `batch_tasks` (`taskId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_timeline_student_batch_tasks_2` FOREIGN KEY (`batchId`) REFERENCES `batch` (`batchId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `work_load`
--
ALTER TABLE `work_load`
ADD CONSTRAINT `FK_work_load_faculty` FOREIGN KEY (`facultyId`) REFERENCES `faculty` (`facultyId`) ON DELETE NO ACTION ON UPDATE NO ACTION;
<file_sep><?php
require_once("includes/config.php");
session_start();
$_SESSION['fullname'] = $_SESSION["usrnm"];
$selectedID = $_POST["userID"];
$selectedUsername = $_POST['username'];
$selected_Username_Table = $_SESSION["usrnm"]."_".$selectedUsername;
$reversed_selected_Username_Table = $selectedUsername."_".$_SESSION["usrnm"];
$selected_Username_Table_uploads = $_SESSION["usrnm"]."_".$selectedUsername."_uploads";
$reversed_selected_Username_Table_uploads = $selectedUsername."_".$_SESSION["usrnm"]."_uploads";
setcookie("default_clicked_on_username",$selectedUsername,time() + (86400 * 30));
setcookie("Selected_Username_Table",$selected_Username_Table,time() + (86400 * 30));
setcookie("Reversed_selected_Username_Table",$reversed_selected_Username_Table,time() + (86400 * 30));
setcookie("selected_Username_Table_uploads",$selected_Username_Table_uploads,time() + (86400 * 30));
setcookie("reversed_selected_Username_Table_uploads",$reversed_selected_Username_Table_uploads,time() + (86400 * 30));
?>
<head>
<style type="text/css">
.sender,.receiver{
background-color: #d8d4d4;
width: 70%;
margin-top: 2px;
margin-bottom: 2px;
}
.receiver{
float: left;
text-align: left;
margin-left: 15px;
}
.sender{
float:right;
text-align: right;
}
div[class="shape_receiver"]{
background-color: white;
padding: 5px 10px 5px 10px;
border-radius: 0px 20px 20px 20px;
}
div[class="shape_sender"]{
background-color: rgba(69, 162, 255, 0.93);
padding: 0px 10px 5px 10px;
border-radius: 20px 3px 20px 20px;
}
span[class="original_sender"]{
color: white;
display: inline-block;
text-align: right;
}
span[class="original_receiver"]{
color: gray;
display: inline-block;
text-align: left;
}
.general_profile_sender{
border-radius: 50%;
position: relative;
}
.general_profile_receiver{
border-radius: 50%;
margin-right: 4px;
}
</style>
</head>
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "fyp_management_system";
$connection_String = mysqli_connect($host,$user,$password,$database);
require "includes/config.php";
$query = "SELECT * FROM correcttable ORDER BY ID";
$run = $conn->query($query);
while($row = $run->fetch_array()) :
$username = $row["Usernames"];
$profile_pic_query = "SELECT * FROM student WHERE studentName = '$username'";
$execute_command_query = mysqli_query($connection_String,$profile_pic_query);
$get_profile = mysqli_fetch_assoc($execute_command_query);
if($row["Usernames"]==$_SESSION["usrnm"]){
if($get_profile["studentImage"]==""){
echo "<div class='sender'><span class='original_sender'><div class='shape_sender'>".$row["Messages"]."</div></span><img class='general_profile_sender' src='Profile_Pictures/default.png' height='35' width='35' title='".$row["Usernames"]."'/></div>";
}else{
$username_picture = $get_profile["studentImage"];
echo "<div class='sender'><span class='original_sender'><div class='shape_sender'>".$row["Messages"]."</div></span><img class='general_profile_sender' src='Profile_Pictures/$username_picture' height='35' width='35' title='".$row["Usernames"]."'/></div>";
}
}else{
if($get_profile["studentImage"]==""){
echo "<div class='receiver'><img class='general_profile_receiver' src='Profile_Pictures/default.png' height='35' width='35' title='".$row["Usernames"]."'/><span class='original_receiver'><div class='shape_receiver'>".$row["Messages"]."</div></span></div>";
setcookie("last_username",$row["Usernames"],time() + (86400 * 30));
echo "<script>$('#get_chat_logs').stop().animate({scrollTop:$('#get_chat_logs')[0].scrollHeight},800);</script>";
}else{
$username_picture = $get_profile["studentImage"];
echo "<div class='receiver'><img class='general_profile_receiver' src='Profile_Pictures/$username_picture' height='35' width='35' title='".$row["Usernames"]."'/><span class='original_receiver'><div class='shape_receiver'>".$row["Messages"]."</div></span></div>";
setcookie("last_username",$row["Usernames"],time() + (86400 * 30));
echo "<script>$('#get_chat_logs').stop().animate({scrollTop:$('#get_chat_logs')[0].scrollHeight},800);</script>";
}
}
endwhile;
$host = "localhost";
$user = "root";
$password = "";
$database = "fyp_management_system";
$connection_String = mysqli_connect($host,$user,$password,$database);
$execute_command_query = mysqli_query($connection_String,$command_query);
$check_table_existence = mysqli_num_rows($execute_command_query);
$execute_command_query_uploads = mysqli_query($connection_String,$command_query_uploads);
$check_uploads_table_existence = mysqli_num_rows($execute_command_query_uploads);
if($check_table_existence>0){
include "Chat_Log.php";
}else{
$create_table_query = "CREATE TABLE $selected_Username_Table(ID INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, Messages LONGTEXT NOT NULL, Time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, Usernames VARCHAR(50) NOT NULL)";
$execute_create_table_query = mysqli_query($connection_String,$create_table_query)or die(mysqli_error($connection_String));
if($execute_create_table_query){
include "Chat_Log.php";
}
}
if($check_uploads_table_existence>0){
include "Chat_Log.php";
}else{
$create_uploads_table_query = "CREATE TABLE $selected_Username_Table_uploads(ID INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, File VARCHAR(100) NOT NULL, Type VARCHAR(10) NOT NULL, Size INT(11) NOT NULL)";
$execute_create_uploads_table_query = mysqli_query($connection_String,$create_uploads_table_query)or die(mysqli_error($connection_String));
if($execute_create_uploads_table_query){
include "Chat_Log.php";
}
}
?>
<file_sep><?php
//require_once("includes/config.php");
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "fyp_management_system";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
$res = $_POST['get_sel'];
$find=mysql_query("select * from suggested_topics where id='$res'");
//error handle using if statement to check if any row is returned
if(mysql_num_rows($find) == 0){
echo 'No record';
}else{
while($row = mysql_fetch_array($find))
{
$sf=$row['supervisorFaculty'];
$sfn=$row['supervisorFacultyName'];
//$regno=$row['RegNo'];
//$phoneno=$row['Phoneno'];
}
echo $sf."-".$sfn;
}
exit;
?> | 5f3a9cb609d17088489854ed7d5121cacbee6150 | [
"SQL",
"PHP"
] | 8 | PHP | Abdulmalik-ye/FinalYearProjectManagementSystem | 407d4296a391d3efe4e0dc147862207b99a3e64c | b7e9eed83e3f67e2dba0024a87ae328b9c773ed2 |
refs/heads/master | <file_sep>#!/bin/bash
######### Variables
CONFIGPATH=~/.config/hddStats
CONFIGFILE=$CONFIGPATH/hddStats.config
HELP="
########### hddStats ############
## github.com/Isotop7/hddStats ##
Usage:
-h / --help : Shows this help
--cli : Enters cli mode and no notifications are created
--conf : Path to a valid config file
"
INITIAL_CONF="# Partitions have to be valid and separated by ;
PARTITIONS=\"/dev/sda1;/dev/sda4\"
# Settings for levels and value at which level is applied
LOW=\"yes\"
LOW_PERC=10
NORMAL=\"yes\"
NORMAL_PERC=25
CRITICAL=\"yes\"
CRITICAL_PERC=30
# Verbose output
LONG_OUTPUT=\"yes\"
# Duration for notification
TIME=2000"
######### Other runtime data
# Declare level string
LEVEL=""
# Check for given parameters
if ! [ -z "$*" ]; then
for value in $*
do
case $1 in
-h)
echo "$HELP" && exit 98;;
--help)
echo "$HELP" && exit 98;;
--cli)
NO_VERBOSE="yes";;
--conf)
CONFIGFILE="$1";;
*)
echo "ERROR: Invalid parameter. Leave empty or run with -h / --help." && exit 97;;
esac
shift
done
fi
#######################################
########## Functions
function check_config {
# Testing settings
# Level LOW
if [ "$LOW" == "" ] || ! [ "$LOW" == "yes" ] && ! [ "$LOW" == "no" ]; then
echo "Setting LOW is not valid. Please check!" >&2 && exit 10
# Percentage LOW
elif ((0>$LOW_PERC && $LOW_PERC>100)); then
echo "Percentage for Level LOW is not valid. Please check!" >&2 && exit 11
# Level NORMAL
elif [ "$NORMAL" == "" ] || ! [ "$NORMAL" == "yes" ] && ! [ "$NORMAL" == "no" ]; then
echo "Setting NORMAL is not valid. Please check!" >&2 && exit 12
# Percentage NORMAL
elif ((0>$NORMAL_PERC && $NORMAL_PERC>100)); then
echo "Percentage for Level NORMAL is not valid. Please check!" >&2 && exit 13
# Level CRITICAL
elif [ "$CRITICAL" == "" ] || ! [ "$CRITICAL" == "yes" ] && ! [ "$CRITICAL" == "no" ]; then
echo "Setting CRITICAL is not valid. Please check!" >&2 && exit 14
# Percentage CRITICAL
elif ((0>$CRITICAL_PERC && $CRITICAL_PERC>100)); then
echo "Percentage for Level CRITICAL is not valid. Please check!" >&2 && exit 15
# Verbosity
elif [ "$VERBOSE" == "" ] || ! [ "$VERBOSE" == "yes" ] && ! [ "$VERBOSE" == "no" ]; then
echo "Setting VERBOSE is not valid. Please check!" >&2 && exit 30
# TIME positive or not valid
elif ((0>$TIME)) || [ -z "$TIME" ]; then
echo "Time is negative and not valid. Please check!" >&2 && exit 40
fi
}
function read_config {
source $CONFIGFILE
}
function set_env {
if ! [ -d $CONFIGPATH ]; then
mkdir -p $CONFIGPATH
fi
if ! [ -e $CONFIGFILE ]; then
touch $CONFIGFILE && echo "$INITIAL_CONF" > $CONFIGFILE
fi
}
function check_needs {
# Check if notify-send is available, otherwise exit
if ! which notify-send >/dev/null; then
echo "ERROR: notify-send is not available." >&2 && exit 99
# Check if df is available, otherwise exit
elif ! which df >/dev/null; then
echo "ERROR: df is not available." >&2 && exit 99
fi
}
function build_message {
# Setting given parameters
DRIVE=$1
LABEL=$2
LEVEL=$3
PERCENTAGE=$4
# Append Strings to message after check of verbosity
if [ "$LONG_OUTPUT" == "yes" ]; then
MESSAGE="Used space on drive $DRIVE mounted on $LABEL is $LEVEL ($PERCENTAGE%)"
notify-send -t $TIME "hddStats" "$MESSAGE" && echo "$MESSAGE"
elif [ "$NO_VERBOSE" == "yes" ]; then
MESSAGE="Used space on drive $DRIVE mounted on $LABEL is $LEVEL ($PERCENTAGE%)"
echo "$MESSAGE"
elif [ "$LONG_OUTPUT" == "no" ]; then
MESSAGE="Drive $DRIVE is $LEVEL"
notify-send -t $TIME "hddStats" "$MESSAGE" && echo "$MESSAGE"
fi
}
function check_level {
# Setting given parameters
DRIVE=$1
PERCENTAGE=$2
# Getting the name of the drive for a nicer message
LABEL=$(mount -l | grep $DRIVE | cut -d" " -f3)
# Check if label is valid
if [ "$LABEL" == "" ]; then
echo "Label of drive $DRIVE could not be determined!" >&2 && return
fi
# Check urgency level
if (($LOW_PERC<=$PERCENTAGE && $PERCENTAGE<$NORMAL_PERC))
then
if [ "$LOW" == "yes" ]; then
LEVEL="low"
else
return
fi
elif (($NORMAL_PERC<=$PERCENTAGE && $PERCENTAGE<$CRITICAL_PERC))
then
if [ "$NORMAL" == "yes" ]; then
LEVEL="normal"
else
return
fi
elif (($CRITICAL_PERC<=$PERCENTAGE))
then
if [ "$CRITICAL" == "yes" ]; then
LEVEL="critical"
else
return
fi
else
LEVEL="nothing"
fi
# Pass it to next function if LEVEL is valid
if ! [ "$LEVEL" == "nothing" ]; then
build_message $DRIVE $LABEL $LEVEL $PERCENTAGE
else
echo "Level could not be determined for drive $DRIVE on $LABEL" >&2
fi
}
function check_drive {
# Setting given Parameters
DRIVE=$1
# Getting used percentage
VALUE=$(df -h $DRIVE | tail -n1 | grep -Eo '[0-9]{1,2}%' | cut -d"%" -f1)
# Pass value to next function
check_level $DRIVE $VALUE
}
########################################
########## Main
# Check if we can work
check_needs
# Check for configfile
if ! [ -e $CONFIGFILE ]; then
set_env && echo "Environment set." >&2
fi
# Read config
read_config
# Check the config
check_config
# Iterate through drives and collect data
while IFS=';' read -ra PARTITION_ARRAY;
do
for ELEMENT in "${PARTITION_ARRAY[@]}";
do
check_drive $ELEMENT
done
done <<< "$PARTITIONS"
<file_sep># hddStats
This tool monitors your HDDs and generates notifications.
Tested under:
- Ubuntu 14.04 w/ Unity
- Debian Wheezy w/ Openbox
The tools need _notify-send_ and _df_.
Edit your configuration located in _~/.config/hddStats/hddStats.config_
You can add it to your _crontab_ to let the script check the drives periodically.
You can also start the python script hddStats_indicator.py which runs the bash script in cli-mode and displays the output.
More changes to come.
## Configuration notes:
1) Specify your drives in the string partitions separated by __;__
PARTITIONS="/dev/sda1;/dev/sda4"
2) Specify if you want notifications for the levels low, normal and critical. Valid values are "yes" and "no".
LOW="yes"
NORMAL="yes"
CRITICAL="yes"
3) Specify at which value the partition is reported as "low", "normal" and "critical". These values have to be normal integers between 0 and 100.
LOW_PERC=10
NORMAL_PERC=25
CRITICAL_PERC=30
4) Specify if you want more output. Valid values are "yes" and "no".
LONG_OUTPUT="yes"
5) Specify how long each notification should be visible. Value has to be a positive integer. NOTICE: Value represents time in milliseconds.
TIME=2000
<file_sep># TODO.md
* ~~per user configuration~~
* ~~function to read configuration~~
* adapting urgency level of drive to notification
* adding own icon to notification
* own icon
* ~~indicator for ubuntu~~
* rewrite bash script to python
* rewrite everything to c or c++
<file_sep>#!/usr/bin/python
# Imports
import appindicator, pynotify, gtk, re, subprocess, sys, getopt
# Build main indicator
app = appindicator.Indicator('hddStats', '', appindicator.CATEGORY_APPLICATION_STATUS)
app.set_status( appindicator.STATUS_ACTIVE )
menu = gtk.Menu()
runscript = gtk.MenuItem( 'Run' )
qt = gtk.MenuItem( 'Quit' )
delimiter = gtk.SeparatorMenuItem()
label = gtk.MenuItem()
menu.append(runscript)
menu.append(qt)
menu.append(delimiter)
app.set_menu(menu)
runscript.show()
qt.show()
delimiter.show()
# Processes for running hddStats
# Open Path
#def open_path(path):
#os.system("xdg-open",path)
# Make items
def make_items(text):
label = gtk.MenuItem()
menu.append(label)
label.set_label(text)
label.show()
#path = re.search('mounted on (.*?) is', text).group(1)
#label.connect('activate', open_path)
# Running script and reading file
def run(item):
hddStats = subprocess.Popen(['./hddStats.sh', '--cli'], stdout=subprocess.PIPE)
result = hddStats.communicate()
result = filter(None, result)
result = "".join(result)
result = result.split('\n')
result = filter(None, result)
for element in result:
make_items(element)
runscript.connect('activate', run)
# Exit indicator
def quit(item):
gtk.main_quit()
qt.connect('activate', quit)
# Start Indicator
gtk.main()
| 8453a95ff62a18cc2799a479c2b796ddcdc00254 | [
"Markdown",
"Python",
"Shell"
] | 4 | Shell | Isotop7/hddStats | df25172302b9b85bc07fabb47fb35f71a8924051 | cef3afb8c61cba0392122730642152e2c58b8ab3 |
refs/heads/master | <repo_name>EnderHDMC/DarkIsle<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/delib/engine/tile/Tile.java
package com.delib.engine.tile;
import com.badlogic.gdx.math.*;
import com.badlogic.gdx.graphics.g2d.*;
public class Tile
{
public static TextureRegion[][] tileSetTexture;
public static int tileWidth = 48;
public static int tileHeight = 48;
static public TextureRegion GetSourceTexture(int tileIndex)
{
int tileX = tileIndex / 16;
int tileY = tileIndex % 16;
return tileSetTexture[tileX][tileY];
}
}
<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/delib/engine/tile/MapCell.java
package com.delib.engine.tile;
import java.util.*;
public class MapCell
{
public ArrayList<Integer> BaseTiles = new ArrayList<Integer>();
public MapCell(int tileID)
{
setTileID(tileID);
}
public void setTileID(int tileID)
{
if (BaseTiles.size() > 0)
BaseTiles.set(0, tileID);
else
AddBaseTile(tileID);
}
public int getTileID(int index)
{
return (BaseTiles.size() > 0 && BaseTiles.size() > index) ? BaseTiles.get(index) : 0;
}
public int getTileID()
{
return (BaseTiles.size() > 0) ? BaseTiles.get(0) : 0;
}
public void AddBaseTile(int tileID)
{
BaseTiles.add(tileID);
}
}
<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/delib/generator/CellularAutomata.java
package com.delib.generator;
import java.util.*;
import com.delib.engine.tile.data.*;
public class CellularAutomata
{
public int width = 150;
public int height = 41;
public String seed = "Hello";
public boolean useRandomSeed = true;
public int randomFillPercent = 40;
int[][] map;
Random pseudoRandom = new Random();
public CellularAutomata()
{
width = 40;
height = 20;
randomFillPercent = 40;
useRandomSeed = true;
}
public CellularAutomata(int setWidth, int setHeight)
{
width = setWidth;
height = setHeight;
randomFillPercent = 40;
useRandomSeed = true;
}
public CellularAutomata(int setWidth, int setHeight, int setWallPercent)
{
width = setWidth;
height = setHeight;
randomFillPercent = setWallPercent;
useRandomSeed = true;
}
public CellularAutomata(int setWidth, int setHeight, int setWallPercent, boolean setUseRandomSeed, String seed)
{
width = setWidth;
height = setHeight;
randomFillPercent = 40;
useRandomSeed = setUseRandomSeed;
this.seed = seed;
}
public void Generate()
{
GenerateMap();
}
void GenerateMap()
{
map = new int[width][height];
RandomFillMap();
for (int i = 0; i < 5; i++)
{
SmoothMap();
}
ProcessMap();
TranslateMap();
DecorateMap();
}
void RandomFillMap()
{
if (useRandomSeed)
seed = Integer.toString(pseudoRandom.nextInt(2147483647));
pseudoRandom = new Random(seed.hashCode());
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (x == 0 || x == width - 1 || y == 0 || y == height - 1)
map[x][y] = 1;
else
map[x][y] = (pseudoRandom.nextInt(101) < randomFillPercent) ? 1 : 0;
}
}
}
void SmoothMap()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int neighborWallTiles = GetSurroundWallCount(x, y);
if (neighborWallTiles > 4)
map[x][y] = 1;
else if (neighborWallTiles < 4)
map[x][y] = 0;
}
}
}
public int GetTile(int x, int y)
{
int tile = map[x][y];
return tile * 32;
}
int GetSurroundWallCount(int gridX, int gridY)
{
int wallCount = 0;
for (int neighborX = gridX - 1; neighborX <= gridX + 1; neighborX++)
{
for (int neighborY = gridY - 1; neighborY <= gridY + 1; neighborY++)
{
if (IsInMapRange(neighborX, neighborY))
{
if (neighborX != gridX || neighborY != gridY)
{
wallCount += map[neighborX][neighborY];
}
}
else
wallCount++;
}
}
return wallCount;
}
boolean IsInMapRange(int x, int y)
{
return x >= 0 && x < width && y >= 0 && y < height;
}
@Override
public String toString()
{
String returnString;
StringBuilder sb = new StringBuilder();
sb.append(" ").append("Width:").append(width).append(
"\tHeight:").append(height).append(
"\tWalls").append(randomFillPercent).append(
"\t% Walls").append(randomFillPercent).append(
"\tSeed:").append(seed).append(
"\tSeed Hash:").append(seed.hashCode()).append(
System.lineSeparator());
for (int column = 0, row = 0; row < height; row++)
{
for (column = 0; column < width; column++)
{
sb.append(map[column][row]);
}
sb.append(System.lineSeparator());
}
returnString = sb.toString();
return returnString;
}
void ProcessMap()
{
ArrayList<ArrayList<TileCoord>> wallRegions = GetRegions(1);
int wallThresholdSize = 100;
for (ArrayList<TileCoord> wallRegion : wallRegions)
{
if (wallRegion.size() < wallThresholdSize)
{
for (TileCoord tile : wallRegion)
{
map[tile.tileX][tile.tileY] = 0;
}
}
}
ArrayList<ArrayList<TileCoord>> roomRegions = GetRegions(0);
int roomThresholdSize = 25;
ArrayList<Room> survivingRooms = new ArrayList<Room>();
for (ArrayList<TileCoord> roomRegion : roomRegions)
{
if (roomRegion.size() < roomThresholdSize)
{
for (TileCoord tile : roomRegion)
{
map[tile.tileX][tile.tileY] = 1;
}
}
else
{
survivingRooms.add(new Room(roomRegion, map));
}
}
Collections.sort(survivingRooms);
survivingRooms.get(0).isMainRoom = true;
survivingRooms.get(0).isAccessibleFromMainRoom = true;
ConnectClosestRooms(survivingRooms, false);
}
void TranslateMap()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (map[x][y] == 0)
map[x][y] = 3;
else if (map[x][y] == 1)
map[x][y] = 0;
}
}
}
void DecorateMap()
{
// Place sand at edges of island
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (CheckSurroundTiles(new TileCoord(x, y), map[x][y], 0, 2) > 0)
map[x][y] = 1;
}
}
// Place stone on grass
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (map[x][y] == 3)
{
if (CheckTilesInCircle(new TileCoord(x, y), map[x][y], 1, 14) < 1)
map[x][y] = (pseudoRandom.nextInt(101) < 90) ? 4 : map[x][y];
}
}
}
}
int CheckSurroundTiles(TileCoord c, int tile, int wantedTile, int offset)
{
int wallCount = 0;
for (int neighborX = c.tileX - offset + 1; neighborX < c.tileX + offset; neighborX++)
{
for (int neighborY = c.tileY - offset + 1; neighborY < c.tileY + offset; neighborY++)
{
if (IsInMapRange(neighborX, neighborY))
{
if (neighborX == c.tileX && neighborY == c.tileY)
continue;
else if (map[neighborX][neighborY] == wantedTile && tile != wantedTile)
wallCount++;
}
}
}
return wallCount;
}
int CheckTilesInCircle(TileCoord c, int tile, int wantedTile, int r)
{
int wallCount = 0;
for (int x = -r; x <= r; x++)
{
for (int y = -r; y <= r; y++)
{
if (x * x + y * y <= r * r)
{
int currentX = c.tileX + x;
int currentY = c.tileY + y;
if (IsInMapRange(currentX, currentY))
{
if (map[currentX][currentY] == wantedTile && tile != wantedTile)
wallCount++;
}
}
}
}
return wallCount;
}
void ConnectClosestRooms(List<Room> allRooms, boolean forceAccessibilityFromMainRoom)
{
List<Room> roomListA = new ArrayList<Room>();
List<Room> roomListB = new ArrayList<Room>();
if (forceAccessibilityFromMainRoom)
{
for (Room room : allRooms)
{
if (room.isAccessibleFromMainRoom)
roomListB.add(room);
else
roomListA.add(room);
}
}
else
{
roomListA = allRooms;
roomListB = allRooms;
}
int bestDistance = 0;
TileCoord bestTileA = new TileCoord();
TileCoord bestTileB = new TileCoord();
Room bestRoomA = new Room();
Room bestRoomB = new Room();
boolean possibleConnectionFound = false;
for (Room roomA : roomListA)
{
if (!forceAccessibilityFromMainRoom)
{
possibleConnectionFound = false;
if (roomA.connectedRooms.size() > 0)
continue;
}
for (Room roomB : roomListB)
{
if (roomA == roomB || roomA.isConnected(roomB))
continue;
for (int tileIndexA = 0; tileIndexA < roomA.edgeTiles.size(); tileIndexA++)
{
for (int tileIndexB = 0; tileIndexB < roomB.edgeTiles.size(); tileIndexB++)
{
TileCoord tileA = roomA.edgeTiles.get(tileIndexA);
TileCoord tileB = roomB.edgeTiles.get(tileIndexB);
int distanceBetweenRooms = (int)(Math.pow(tileA.tileX - tileB.tileX, 2) +
Math.pow(tileA.tileY - tileB.tileY, 2));
if (distanceBetweenRooms < bestDistance || !possibleConnectionFound)
{
bestDistance = distanceBetweenRooms;
possibleConnectionFound = true;
bestTileA = tileA;
bestTileB = tileB;
bestRoomA = roomA;
bestRoomB = roomB;
}
}
}
}
if (possibleConnectionFound && !forceAccessibilityFromMainRoom)
{
CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
}
}
if (possibleConnectionFound && forceAccessibilityFromMainRoom)
{
CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
ConnectClosestRooms(allRooms, true);
}
if (!forceAccessibilityFromMainRoom)
ConnectClosestRooms(allRooms, true);
}
void CreatePassage(Room roomA, Room roomB, TileCoord tileA, TileCoord tileB)
{
Room.ConnectRooms(roomA, roomB);
List<TileCoord> line = GetLine(tileA, tileB);
for (TileCoord c : line)
{
DrawCircle(c, 3, 0);
}
}
void DrawCircle(TileCoord c, int r, int tile)
{
for (int x = -r; x <= r; x++)
{
for (int y = -r; y <= r; y++)
{
if (x * x + y * y <= r * r)
{
int drawX = c.tileX + x;
int drawY = c.tileY + y;
if (IsInMapRange(drawX, drawY))
{
map[drawX][drawY] = tile;
}
}
}
}
}
List<TileCoord> GetLine(TileCoord from, TileCoord to)
{
List<TileCoord> line = new ArrayList<TileCoord>();
int x = from.tileX;
int y = from.tileY;
int dx = to.tileX - from.tileX;
int dy = to.tileY - from.tileY;
boolean inverted = false;
int step = (int) Math.signum(dx);
int gradientStep = (int) Math.signum(dy);
int longest = Math.abs(dx);
int shortest = Math.abs(dy);
if (longest < shortest)
{
inverted = true;
longest = Math.abs(dy);
shortest = Math.abs(dx);
step = (int) Math.signum(dy);
gradientStep = (int) Math.signum(dx);
}
int gradientAccumulation = longest / 2;
for (int i = 0; i < longest; i++)
{
line.add(new TileCoord(x, y));
if (inverted)
y += step;
else
x += step;
gradientAccumulation += shortest;
if (gradientAccumulation >= longest)
{
if (inverted)
x += gradientStep;
else
y += gradientStep;
gradientAccumulation -= longest;
}
}
return line;
}
ArrayList<TileCoord> GetRegionTiles(int startX, int startY)
{
ArrayList<TileCoord> tiles = new ArrayList<TileCoord>();
int[][] mapFlags = new int[width][height];
int tileType = map[startX][startY];
Queue<TileCoord> queue = new ArrayDeque<TileCoord>();
queue.add(new TileCoord(startX, startY));
mapFlags[startX][startY] = 1;
while (queue.size() > 0)
{
TileCoord tile = queue.remove();
tiles.add(tile);
for (int x = tile.tileX - 1; x <= tile.tileX + 1; x++)
{
for (int y = tile.tileY - 1; y <= tile.tileY + 1; y++)
{
if (IsInMapRange(x, y) && (y == tile.tileY || x == tile.tileX))
{
if (mapFlags[x][y] == 0 && map[x][y] == tileType)
{
mapFlags[x][y] = 1;
queue.add(new TileCoord(x, y));
}
}
}
}
}
return tiles;
}
ArrayList<ArrayList<TileCoord>> GetRegions(int tileType)
{
ArrayList<ArrayList<TileCoord>> regions = new ArrayList<ArrayList<TileCoord>>();
int[][] mapFlags = new int[width][height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (mapFlags[x][y] == 0 && map[x][y] == tileType)
{
ArrayList<TileCoord> newRegion = GetRegionTiles(x, y);
regions.add(newRegion);
for (TileCoord tile : newRegion)
{
mapFlags[tile.tileX][tile.tileY] = 1;
}
}
}
}
return regions;
}
}
<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/darkstudio/darkisle/screens/GameScreen.java
package com.darkstudio.darkisle.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.darkstudio.darkisle.DarkIsle;
import com.delib.engine.tile.Tile;
import com.delib.engine.tile.TileMap;
/**
* Created by DarkEnder on 2017/07/04.
*/
public class GameScreen implements Screen
{
final DarkIsle game;
OrthographicCamera camera;
private Texture texture;
private float cameraWidth, cameraHeight;
private int squaresAcross, squaresDown;
private int firstTileX, firstTileY;
private float renderOffsetX, renderOffsetY;
private TileMap currentMap;
GameScreen(final DarkIsle game)
{
texture = new Texture(Gdx.files.internal("WorldTiles.png"));
Tile.tileSetTexture = TextureRegion.split(texture, 48, 48);
for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 8; y++)
{
Tile.tileSetTexture[y][x].flip(false, true);
}
}
this.game = game;
camera = new OrthographicCamera();
configureCamera();
currentMap = new TileMap(true, "There");
}
@Override
public void render(float p1)
{
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
update();
game.batch.begin();
for (int y = -1; y < squaresDown; y++)
{
for (int x = -1; x < squaresAcross; x++)
{
for (int i = 0; i < currentMap.getNumBaseTiles(x + firstTileX, y + firstTileY); i++)
{
game.batch.draw(Tile.GetSourceTexture(currentMap.getTileAtCoord(x + firstTileX, y + firstTileY, i)),
(x * Tile.tileWidth) + renderOffsetX,
(y * Tile.tileHeight) + renderOffsetY);
}
}
}
game.batch.end();
}
@Override
public void resize(int p1, int p2)
{
configureCamera();
}
@Override
public void show()
{
// TODO: Implement this method
}
@Override
public void hide()
{
// TODO: Implement this method
}
@Override
public void pause()
{
// TODO: Implement this method
}
@Override
public void resume()
{
// TODO: Implement this method
}
@Override
public void dispose()
{
}
private void configureCamera()
{
Vector3 camPos = new Vector3(camera.position.x - camera.viewportWidth / 2f, camera.position.y - camera.viewportHeight / 2f, 0);
float size = 800;
if (Gdx.graphics.getHeight() < Gdx.graphics.getWidth())
{
cameraWidth = size;
cameraHeight = size * Gdx.graphics.getHeight() / Gdx.graphics.getWidth();
}
else
{
cameraWidth = size * Gdx.graphics.getWidth() / Gdx.graphics.getHeight();
cameraHeight = size;
}
camera.setToOrtho(true, cameraWidth, cameraHeight);
camera.position.set(camPos.x + camera.viewportWidth / 2f, camPos.y + camera.viewportHeight / 2f, 0);
squaresAcross = (((int)(cameraWidth) - 1) / Tile.tileWidth + 1) + 1;
squaresDown = (((int)(cameraHeight) - 1) / Tile.tileHeight + 1) + 1;
}
private void update ()
{
if (Gdx.input.isTouched(0))
{
camera.position.add(-Gdx.input.getDeltaX(0), -Gdx.input.getDeltaY(0), 0);
}
camera.update();
game.batch.setProjectionMatrix(camera.combined);
Vector2 firstSquare = new Vector2((camera.position.x - cameraWidth / 2) / Tile.tileWidth, (camera.position.y - cameraHeight / 2) / Tile.tileHeight);
firstTileX = (int)firstSquare.x;
firstTileY = (int)firstSquare.y;
Vector2 squareOffset = new Vector2((camera.position.x - cameraWidth / 2) % Tile.tileWidth, (camera.position.y - cameraHeight / 2) % Tile.tileHeight);
int tileOffsetX = (int) squareOffset.x;
int tileOffsetY = (int)squareOffset.y;
renderOffsetX = -tileOffsetX + camera.position.x - cameraWidth / 2;
renderOffsetY = -tileOffsetY + camera.position.y - cameraHeight / 2;
}
}<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/delib/engine/tile/data/Room.java
package com.delib.engine.tile.data;
import java.util.ArrayList;
import com.delib.engine.tile.data.*;
public class Room implements Comparable<Room>
{
public ArrayList<TileCoord> tiles;
public ArrayList<TileCoord> edgeTiles;
public ArrayList<Room> connectedRooms;
public int roomSize;
public boolean isAccessibleFromMainRoom;
public boolean isMainRoom;
public Room()
{
}
public Room(ArrayList<TileCoord> roomTiles, int[][] map)
{
tiles = roomTiles;
roomSize = tiles.size();
connectedRooms = new ArrayList<Room>();
edgeTiles = new ArrayList<TileCoord>();
for (TileCoord tile : tiles)
{
for (int x = tile.tileX - 1; x <= tile.tileX + 1; x++)
{
for (int y = tile.tileY - 1; y <= tile.tileY + 1; y++)
{
if (x == tile.tileX || y == tile.tileY)
{
if (map[x][y] == 1)
{
edgeTiles.add(tile);
}
}
}
}
}
}
public void SetAccesibleFromMainRoom()
{
if (!isAccessibleFromMainRoom)
{
isAccessibleFromMainRoom = true;
for (Room connectedRoom : connectedRooms)
{
connectedRoom.isAccessibleFromMainRoom = true;
}
}
}
public static void ConnectRooms(Room roomA, Room roomB)
{
if (roomA.isAccessibleFromMainRoom)
{
roomB.SetAccesibleFromMainRoom();
}
else if (roomB.isAccessibleFromMainRoom)
{
roomA.SetAccesibleFromMainRoom();
}
roomA.connectedRooms.add(roomB);
roomB.connectedRooms.add(roomA);
}
public boolean isConnected(Room otherRoom)
{
return connectedRooms.contains(otherRoom);
}
@Override
public int compareTo(Room otherRoom) {
return 0;
}
}
<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/delib/engine/sprite/SpriteAnimation.java
package com.delib.engine.sprite;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.delib.engine.sprite.data.*;
public class SpriteAnimation {
// The TextureRegion that holds the images for this sprite
TextureRegion[][] texture;
// True if animations are being played
boolean animating = true;
// If set to anything other than Color.WHITE, it will colour
// the sprite with that colour.
Color colorTint = Color.WHITE;
// Screen position of the sprite
Vector2 position = new Vector2(0, 0);
Vector2 prevPosition = new Vector2(0, 0);
// Map holding all of the FrameAnimation objects
// associated with this sprite.
Map<String, FrameAnimation> animations = new HashMap<String, FrameAnimation>();
// Which frame animation from the dictionary above is playing.
String currentAnimation = null;
// If true, the sprite will automatically rotate to align itself
// with the angle difference between it's new position and
// it's previous position. In this case, the 0 rotation point
// is to the right (so the sprite should start out facing to the right)
boolean rotateByPosition = false;
// How much the sprite should be rotated when drawn
// Value is in Radians, 0 indicates no rotation.
float rotationRad = 0f;
// How much the sprite should be rotated when drawn
// Value is in Degrees, 0 indicates no rotation.
// Simply a helper value for degree based rotation.
float rotationDeg = 0f;
// Calculated center of the sprite.
Vector2 center;
// Calculated width and height of the sprite
int width, height;
// Vector2 representing the position of the sprite's upper left corner pixel
public Vector2 getPosition() { return position; }
public void setPosition( Vector2 value )
{
prevPosition = new Vector2(position);
position = value;
updateRotation();
}
// The x position of the sprite's upper left corner pixel.
public int getX() { return (int)position.x; }
public void setX(int value)
{
prevPosition.x = position.x;
position.x = value;
updateRotation();
}
// The y position of the sprite's upper left corner pixel.
public int getY() { return (int)position.y; }
public void setY(int value)
{
prevPosition.y = position.y;
position.y = value;
updateRotation();
}
// Width (in pixels) of the sprite animation frames
public int getWidth() { return width; }
// Height (in pixels) of the sprite animation frames
public int getHeight() { return height; }
// If true, the sprite will automatically rotate in the direction
// of motion whenever the sprite's position changes.
public boolean getAutoRotate() { return rotateByPosition; }
public void setAutoRotate(boolean value) { rotateByPosition = value; }
// The degree of rotation (in radians) to be applied to the
// sprite when drawn.
public float getRotationRad() { return rotationRad; }
public void setRotationRad(float value) { rotationRad = value; }
// The degree of rotation (in degrees) to be applied to the
// sprite when drawn.
public float getRotationDeg() { return rotationDeg; }
public void setRotationDeg(float value) { rotationDeg = value; }
// Screen coordinates of the bounding box surrounding this sprite
public Frame getBoundingBox() { return new Frame(getX(), getY(), width, height); }
// The texture associated with this sprite. All FrameAnimations will be
// relative to this texture.
public TextureRegion[][] getTexture() { return texture; }
// Color value to tint the sprite with when drawing. Color.WHITE
// (the default) indicates no tinting.
public Color getTint() { return colorTint; }
public void setTint(Color value) { colorTint = value; }
// True if the sprite is (or should be) playing animation frames. If this value is set
// to false, the sprite will not be drawn (a sprite needs at least 1 single frame animation
// in order to be displayed.
public boolean getIsAnimating() { return animating; }
public void setIsAnimating(boolean value) { animating = value; }
// The FrameAnimation object of the currently playing animation
public FrameAnimation getCurrentFrameAnimation()
{
if (currentAnimation != null && !currentAnimation.isEmpty())
return animations.get(currentAnimation);
else
return null;
}
// The string name of the currently playing animation. Setting the animation
// resets the CurrentFrame and PlayCount properties to zero.
public String getCurrentAnimation() { return currentAnimation; }
public void setCurrentAnimation(String value)
{
if (animations.containsKey(value))
{
currentAnimation = value;
animations.get(currentAnimation).setCurrentFrame(0);
animations.get(currentAnimation).setPlayCount(0);
}
}
public SpriteAnimation(Texture texture, int width, int height)
{
this.texture = TextureRegion.split(texture, width, height);
}
void updateRotation()
{
if (rotateByPosition)
{
Vector2 rotationVector = new Vector2(position.x - prevPosition.x, position.y - prevPosition.y);
rotationRad = rotationVector.angleRad();
rotationDeg = rotationRad * MathUtils.radiansToDegrees;
}
}
public void AddAnimation(String Name, int X, int Y, int Width, int Height, int Frames, float FrameLength)
{
animations.put(Name, new FrameAnimation(X, Y, Width, Height, Frames, FrameLength));
width = Width;
height = Height;
center = new Vector2(width / 2, height / 2);
}
public void AddAnimation(String Name, int X, int Y, int Width, int Height, int Frames,
float FrameLength, String NextAnimation)
{
animations.put(Name, new FrameAnimation(X, Y, Width, Height, Frames, FrameLength, NextAnimation));
width = Width;
height = Height;
center = new Vector2(width / 2, height / 2);
}
public FrameAnimation GetAnimationByName(String Name)
{
if (animations.containsKey(Name))
{
return animations.get(Name);
}
else
{
return null;
}
}
public void MoveBy(int x, int y)
{
prevPosition = new Vector2(position);
position.x += x;
position.y += y;
updateRotation();
}
public void Update(float deltaTime)
{
// Don't do anything if the sprite is not animating
if (animating)
{
// If there is not a currently active animation
if (getCurrentFrameAnimation() == null)
{
// Make sure we have an animation associated with this sprite
if (animations.size() > 0)
{
// Set the active animation to the first animation
// associated with this sprite
String[] sKeys = new String[animations.size()];
int index = 0;
for (Entry<String, FrameAnimation> mapEntry : animations.entrySet()) {
sKeys[index] = mapEntry.getKey();
index++;
}
setCurrentAnimation(sKeys[0]);
}
else
{
return;
}
}
// Run the Animation's update method
getCurrentFrameAnimation().Update(deltaTime);
// Check to see if there is a "follow-up" animation named for this animation
if (getCurrentFrameAnimation().getNextAnimation() != null && !getCurrentFrameAnimation().getNextAnimation().isEmpty())
{
// If there is, see if the currently playing animation has
// completed a full animation loop
if (getCurrentFrameAnimation().getPlayCount() > 0)
{
// If it has, set up the next animation
setCurrentAnimation(getCurrentFrameAnimation().getNextAnimation());
}
}
}
}
public void Draw(SpriteBatch spriteBatch, int xOffset, int yOffset)
{
updateRotation();
spriteBatch.draw(getCurrentTextureRegion(), getPosition().x + xOffset - center.x, getPosition().y + yOffset - center.y, center.x, center.y, getCurrentFrameAnimation().getFrameWidth(), getCurrentFrameAnimation().getFrameHeight(), 1.0f, 1.0f, rotationRad);
}
private TextureRegion getCurrentTextureRegion() {
int x = getCurrentFrameAnimation().getCurrentFrame();
int y = getCurrentFrameAnimation().getFrame().y / getCurrentFrameAnimation().getFrame().height;
return texture[y][x];
}
}
<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/delib/engine/tile/data/TileCoord.java
package com.delib.engine.tile.data;
public class TileCoord {
public int tileX;
public int tileY;
public TileCoord()
{
tileX = 0;
tileY = 0;
}
public TileCoord(int x, int y)
{
tileX = x;
tileY = y;
}
}
<file_sep>/.AndroidStudioProjects/DarkIsle/core/src/com/darkstudio/darkisle/DarkIsle.java
package com.darkstudio.darkisle;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.darkstudio.darkisle.screens.*;
/**
* Created by DarkEnder on 2017/07/04.
*/
public class DarkIsle extends Game
{
public SpriteBatch batch;
public BitmapFont font;
public void create()
{
batch = new SpriteBatch();
// Use libGDX default Arial font
// and set it to render upside-down
font = new BitmapFont(true);
this.setScreen(new MainMenuScreen(this));
}
public void render()
{
super.render(); // Important
}
public void dispose()
{
batch.dispose();
font.dispose();
}
} | b8e1438d17e3a40007cbb3ccd0df797a8d616e10 | [
"Java"
] | 8 | Java | EnderHDMC/DarkIsle | 8ec935efe48e7928e76fdae297da79f3b82a02c9 | 6b62b7c31d27be0777b3a53447629b6bf1b46302 |
refs/heads/master | <repo_name>sivan123/plicku-flowla<file_sep>/src/main/java/com/plicku/flowla/util/StepContentParserUitl.java
package com.plicku.flowla.util;
import com.plicku.flowla.exceptions.FlowContentParsingException;
import com.plicku.flowla.exceptions.ValidationException;
import com.plicku.flowla.model.FlowValidationError;
import com.plicku.flowla.model.vo.FlowContentEntry;
import com.plicku.flowla.processor.StepinProcessor;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.plicku.flowla.util.Constants.*;
public class StepContentParserUitl
{
public static final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";
private static final String VARIABLE_DECLARATION_AS= ".*\\sas\\s\\$\\{(.*)\\s*$}";
private static final String VARIABLE_DECLARATION_IN= "^\\$\\{(.*)}\\s+in\\s+";
final static Pattern variableAsDeclarePattern = Pattern.compile(VARIABLE_DECLARATION_AS);
final static Pattern variableInDeclarePattern = Pattern.compile(VARIABLE_DECLARATION_IN+".*");
public static List<FlowContentEntry> getFlowConentSteps(String flowContent, String delimter, boolean validate) throws FlowContentParsingException, ValidationException {
AtomicInteger lineNumCounter = new AtomicInteger(0);
flowContent=Arrays.asList(flowContent.split("\n")).stream().map(s -> s+LINE_NUM_SEPERATOR+lineNumCounter.incrementAndGet()).collect(Collectors.joining(System.lineSeparator()));
List<FlowContentEntry> entries = new ArrayList<>();
String[] entryStr = flowContent.split(String.format(WITH_DELIMITER, delimter));
String declaredVariable=null;
int depth=1;
for (int i = 0; i < entryStr.length; i++) {
try{
if(entryStr[i].trim().startsWith(COMMENT)) continue;
if("".equals(entryStr[i].replaceAll(LINE_NUM_SEPERATOR+"\\d*","").trim())) continue;
String keyword=(END_IF.equals(entryStr[i].trim())|| OTHERWISE.equals(entryStr[i].trim()) || END_FOR.equals(entryStr[i].trim())) ?entryStr[i].trim():entryStr[i].trim()+" ";
String stepname="";
StringBuilder stringBuilder = new StringBuilder();
int j = 0;
if(!(END_IF.equals(keyword)||END_FOR.equals(keyword)||END_REPEAT.equals(keyword))){
String[] stepNamedata = entryStr[i+1].split(System.lineSeparator());
boolean stepNameSet=false;
for (j = 0; j < stepNamedata.length; j++) {
if(!"".equals(stepNamedata[j].trim())&&!stepNameSet)
{
stepname=stepNamedata[j];
stepNameSet=true;
}
else if(stepNameSet && !"".equals(stepNamedata[j]))
{
stepNamedata[j]=stepNamedata[j].replaceAll(LINE_NUM_SEPERATOR+"\\d*","");
if ("".equals(stringBuilder.toString())) {
stringBuilder.append(stepNamedata[j]);
} else {
stringBuilder.append(System.lineSeparator()).append(stepNamedata[j]);
}
}
}
}
if(IF.equals(keyword)){
depth++;
}
else if (FOR_EACH.equals(keyword))
{
depth++;
declaredVariable=getInDeclaredVariable(stepname);
if(declaredVariable!=null)
stepname=stepname.replaceAll(VARIABLE_DECLARATION_IN,"");
}
else if(END_IF.equals(keyword) || END_FOR.equals(keyword) || END_REPEAT.equals(keyword))
{
depth--;
}
FlowContentEntry entry = new FlowContentEntry(keyword,stepname,stringBuilder.toString(),declaredVariable,depth);
i++;
entries.add(entry);
}catch (Exception e){
throw new FlowContentParsingException("Error parsing block "+Arrays.asList(entryStr));
}
}
if(validate){
List<FlowValidationError> errors =validateFlowContentList(entries);
if(errors.size()>0)
throw new ValidationException("Validation Errors in the flow definition - "+errors.toString());
}
return entries;
}
public static List<FlowValidationError> validateFlowContentList(List<FlowContentEntry> entries) {
List<FlowValidationError> errors = new ArrayList<>();
if(entries==null||entries.size()==0)
return errors;
//check for matching closing
if(entries.get(entries.size()-1).getDepth()==0)
errors.add(new FlowValidationError("Opening Key Words not matching with closing ones"));
//check for each steps return a collection or a Datatable
entries.forEach(entry -> {
if (entry.isEndFor() || entry.isEndIf() || entry.isEndRepeat() || entry.isOtherWise()){
if(!(entry.getStepName()==null||entry.getStepName().isEmpty())) errors.add(new FlowValidationError(entry.getKeyword()+" "+entry.getStepName(),"Invalid Step. Step not allowed with the keyword "+entry.getKeyword()+". Consider moving '"+entry.getStepName()+"' to the next line along with an appropriate processing key word."));
}
else {
if(StepinProcessor.methodMap.get(entry.getStepName())==null)
System.out.println(entry.getStepName());
Class aClass = StepinProcessor.methodMap.get(entry.getStepName()).getMethodReturnType();
if (entry.isIfOrElseIf() || entry.isRepeatWhile()) {
if (!(Boolean.class.isAssignableFrom(aClass) || boolean.class.isAssignableFrom(aClass)))
errors.add(new FlowValidationError(entry.getStepName(), "Invalid Step Definition. Method is expected to return a true or false"));
}
if (entry.isRepeatFor()) {
if (!(Number.class.isAssignableFrom(aClass)))
errors.add(new FlowValidationError(entry.getStepName(), "Invalid Step Definition. Method is expected to return a number"));
}
}
});
return errors;
}
public static String getInDeclaredVariable(String stepName)
{
Matcher matcher=variableInDeclarePattern.matcher(stepName);
if (matcher.lookingAt()) {
System.out.println(matcher.groupCount());
for (int i = 1; i <= matcher.groupCount(); i++) {
return matcher.group(i);
}
}
return null;
}
}
<file_sep>/src/main/java/com/plicku/flowla/util/Constants.java
package com.plicku.flowla.util;
import java.util.Arrays;
import java.util.List;
public class Constants {
public static final String AND="And ";
public static final String WHEN="When ";
public static final String GIVEN="Given ";
public static final String THEN="Then ";
public static final String BUT="But ";
public static final String FOR_EACH="For Each ";
public static final String END_FOR = "EndFor";
public static final String IF="If ";
public static final String ELSE_IF="Else If ";
public static final String END_IF="EndIf";
public static final String OTHERWISE ="Otherwise";
public static final String REPEAT_FOR ="Repeat Step(s) For ";
public static final String REPEAT_WHILE ="Repeat Step(s) while ";
public static final String END_REPEAT="EndRepeat";
public static final List<String> PROCESS_KEYWORDS = Arrays.asList(AND,WHEN,GIVEN,THEN,BUT);
public static final List<String> CONDITIONAL_KEYWORDS = Arrays.asList(IF,END_IF,ELSE_IF);
public static final List<String> LOOPING_KEYWORDS = Arrays.asList(FOR_EACH);
public static final List<String> ALL_KEYWORDS= Arrays.asList(AND,WHEN,GIVEN,THEN,BUT,END_IF,IF,OTHERWISE,ELSE_IF,FOR_EACH,END_FOR);
public static final String COMMENT="#";
public static final String KEYWD_BEGIN_PTTN ="((^\\s{0,100})|^|(\n\\s{0,100})|\n)";
public static final String SUCCESS="success";
public static final String SKIPPED="skipped";
public static final String FAILED="failed";
public static Long MAX_REPEAT_CNT_ALLOWED =10000L;
public static final String LINE_NUM_SEPERATOR="LINE_NUM";
}
<file_sep>/src/test/java/com/plicku/flowla/processor/beans/SimpleTestBean.java
package com.plicku.flowla.processor.beans;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SimpleTestBean {
String name;
String address1;
Integer zip;
}
<file_sep>/src/main/java/com/plicku/flowla/stepdefintions/BuiltInStepDefintions.java
package com.plicku.flowla.stepdefintions;
import com.plicku.flowla.anotations.operators.ForEach;
import com.plicku.flowla.anotations.operators.Repeat;
import com.plicku.flowla.anotations.operators.RepeatUntil;
import com.plicku.flowla.anotations.parameters.DataTableParameter;
import com.plicku.flowla.anotations.types.StepDefinitions;
import com.plicku.flowla.model.DataTable;
@StepDefinitions
public class BuiltInStepDefintions {
@ForEach("row in the following data table")
public DataTable getEachRowInDataTable(@DataTableParameter DataTable dataTable)
{
return dataTable;
}
@Repeat("the following steps (\\d+) times")
public int repeatSteps(int times)
{
return times;
}
}
<file_sep>/src/main/java/com/plicku/flowla/model/contexts/VariableMap.java
package com.plicku.flowla.model.contexts;
import com.plicku.flowla.exceptions.ProcessingException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class VariableMap {
private Map<String,Object> variableMap= new ConcurrentHashMap<>();
public Object getVariableVal(String variable) throws ProcessingException {
if(!this.variableMap.containsKey(variable)){
throw new ProcessingException(variable+" not found. Make sure the variable is set in the flow");
}
else
return this.variableMap.get(variable);
}
public void removeVariable(String variable)
{
if(variable!=null)
variableMap.remove(variable);
}
public boolean containsVariable(String variable){
return variableMap.containsKey(variable);
}
public void setVariable(String variable,Object val)
{
this.variableMap.put(variable,val);
}
}
<file_sep>/src/main/java/com/plicku/flowla/exceptions/ProcessingException.java
package com.plicku.flowla.exceptions;
public class ProcessingException extends Exception {
public ProcessingException(String s, Throwable throwable) {
super(s, throwable);
}
public ProcessingException(String s) {
}
}
<file_sep>/src/main/java/com/plicku/flowla/processor/StepExecutor.java
package com.plicku.flowla.processor;
import com.plicku.flowla.anotations.parameters.DataTableParameter;
import com.plicku.flowla.anotations.parameters.JSONParameter;
import com.plicku.flowla.anotations.parameters.YAMLParameter;
import com.plicku.flowla.model.MethodParameter;
import com.plicku.flowla.model.StepMethodProperties;
import com.plicku.flowla.model.contexts.GlobalContext;
import com.plicku.flowla.model.contexts.SequenceContext;
import com.plicku.flowla.model.contexts.VariableMap;
import com.plicku.flowla.util.ParamDataUtil;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class StepExecutor {
private boolean methodToBeExecuted=false;
private StepMethodProperties stepMethodProperties;
private String paramData = "";
public String getKeyword()
{
return stepMethodProperties.getKeyword();
}
public void setParamData(String paramData) {
this.paramData = paramData;
}
public void setStepMethodProperties(StepMethodProperties stepMethodProperties) {
this.stepMethodProperties = stepMethodProperties;
this.methodToBeExecuted=true;
}
public Object executeMethod(SequenceContext sequenceContext, VariableMap variableMap) throws Exception {
Object returnValue= null;
try {
Method method = stepMethodProperties.getMatchedMethod();
method.setAccessible(true);
if (stepMethodProperties.getMethodParameters().size() == 0)
returnValue= method.invoke(StepinProcessor.classMap.get(stepMethodProperties.getDeclaringClass()));
else //create bean an inject
{
List<Object> params = new ArrayList<>();
int methodArgConsumedIndex=-1;
for (MethodParameter methodParameter : stepMethodProperties.getMethodParameters()) {
Object currArgValue=null;
Object bean = null;
//check if datatable
if (methodParameter.getArgAnnotation() != null &&
methodParameter.getArgAnnotation().stream().anyMatch(annotation -> annotation.annotationType().equals(DataTableParameter.class))) {
params.add(ParamDataUtil.getBean(this.paramData, methodParameter.getParameterType()));
} else if (methodParameter.getArgAnnotation() != null &&
methodParameter.getArgAnnotation().stream().anyMatch(annotation -> annotation.annotationType().equals(JSONParameter.class))) {
params.add(ParamDataUtil.getBeanFromJson(this.paramData, methodParameter.getParameterType()));
} else if (methodParameter.getArgAnnotation() != null &&
methodParameter.getArgAnnotation().stream().anyMatch(annotation -> annotation.annotationType().equals(YAMLParameter.class))) {
params.add(ParamDataUtil.getBeanFromYaml(this.paramData, methodParameter.getParameterType()));
} else if (SequenceContext.class.equals(methodParameter.getParameterType())) {
params.add(sequenceContext);
} else if (GlobalContext.class.equals(methodParameter.getParameterType())) {
params.add(StepinProcessor.globalContext);
} else {
currArgValue=stepMethodProperties.getNextArgValue(methodParameter.getParameterType(),methodArgConsumedIndex,variableMap);
params.add(currArgValue);
methodArgConsumedIndex++;
}
}
returnValue= method.invoke(StepinProcessor.classMap.get(this.stepMethodProperties.getDeclaringClass()), params.toArray());
}
this.setMethodToBeExecuted(false);
}catch (Exception e){
throw new Exception("Error Executiing step "+stepMethodProperties.getStepName(),e);
}
return returnValue;
}
public boolean isMethodToBeExecuted() {
return methodToBeExecuted;
}
public void setMethodToBeExecuted(boolean methodToBeExecuted) {
this.methodToBeExecuted = methodToBeExecuted;
}
}
<file_sep>/src/main/java/com/plicku/flowla/model/contexts/GlobalContext.java
package com.plicku.flowla.model.contexts;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class GlobalContext {
private Map<String,Object> globalContextProperties = new ConcurrentHashMap();
public Object getProperty(String key)
{
return this.globalContextProperties.get(key);
}
public void setProperty(String key, Object value)
{
this.globalContextProperties.put(key, value);
}
}
<file_sep>/src/main/java/com/plicku/flowla/model/MethodParameter.java
package com.plicku.flowla.model;
import lombok.Data;
import java.lang.annotation.Annotation;
import java.util.List;
@Data
public class MethodParameter {
Class parameterType;
boolean annotated=false;
List<Annotation> argAnnotation;
}
<file_sep>/src/main/java/com/plicku/flowla/model/MethodMap.java
package com.plicku.flowla.model;
import com.plicku.flowla.util.PatternArgumentMatcher;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
public class MethodMap{
private Map<String,StepMethodProperties> plainMethodMap = new ConcurrentHashMap<>();
//cache for faster look up the second time
private ConcurrentHashMap<String, StepMethodProperties> cachedRegMethodMap = new ConcurrentHashMap<>();
public void put(String stepname, Method method)
{
plainMethodMap.put(stepname,new StepMethodProperties(method,stepname));
}
public StepMethodProperties get(String srchStepname)
{
if(plainMethodMap.containsKey(srchStepname)) return plainMethodMap.get(srchStepname);
else if(cachedRegMethodMap.containsKey(srchStepname)) return cachedRegMethodMap.get(srchStepname);
else {
for (String stepname : plainMethodMap.keySet()) {
Pattern pattern = Pattern.compile(stepname);
if (pattern.matcher(srchStepname).matches()) {
StepMethodProperties stepMethodProperties = new StepMethodProperties(plainMethodMap.get(stepname).getMatchedMethod(),srchStepname);
stepMethodProperties.setStepAurguments(new PatternArgumentMatcher(pattern).argumentsFrom(srchStepname));
cachedRegMethodMap.put(srchStepname, stepMethodProperties);
return stepMethodProperties;
}
}
return null;
}
}
}
<file_sep>/src/main/java/com/plicku/flowla/util/PatternArgumentMatcher.java
package com.plicku.flowla.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternArgumentMatcher {
private final Pattern pattern;
public PatternArgumentMatcher(Pattern pattern) {
this.pattern = pattern;
}
public List<String> argumentsFrom(String stepname) {
Matcher matcher = pattern.matcher(stepname);
if (matcher.lookingAt()) {
List<String> arguments = new ArrayList<>(matcher.groupCount());
for (int i = 1; i <= matcher.groupCount(); i++) {
arguments.add( matcher.group(i));
}
return arguments;
} else {
return null;
}
}
}
<file_sep>/src/main/java/com/plicku/flowla/util/Report.java
package com.plicku.flowla.util;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Data
public class Report {
List<StepResult> stepResults = new ArrayList<>();
}
class StepResult{
String keyword;
String stepName;
String status;
String errors;
Map output;
}
<file_sep>/src/test/java/com/plicku/flowla/model/StepMethodPropertiesTest.java
package com.plicku.flowla.model;
import com.plicku.flowla.model.contexts.VariableMap;
import org.apache.commons.beanutils.PropertyUtils;
import org.assertj.core.api.SoftAssertions;
import org.junit.Test;
import java.util.Arrays;
public class StepMethodPropertiesTest {
@Test
public void getNextArgValue() throws Exception {
SoftAssertions assertions = new SoftAssertions();
StepMethodProperties stepMethodProperties = new StepMethodProperties();
stepMethodProperties.setStepAurguments(Arrays.asList("10","${item}","${basket.name}","${basket.basketItems[0]}"));
VariableMap variableMap = new VariableMap();
assertions.assertThat(stepMethodProperties.getNextArgValue(int.class,-1,variableMap)).isEqualTo(10);
variableMap.setVariable("item","apple");
assertions.assertThat(stepMethodProperties.getNextArgValue(String.class,0,variableMap)).isEqualTo("apple");
ParamTestBean paramTestBean = new ParamTestBean();
variableMap.setVariable("basket", paramTestBean);
assertions.assertThat(stepMethodProperties.getNextArgValue(String.class,1,variableMap)).isEqualTo("gifthamper");
assertions.assertThat(stepMethodProperties.getNextArgValue(String.class,2,variableMap)).isEqualTo("pen");
assertions.assertAll();
}
}<file_sep>/src/main/java/com/plicku/flowla/model/contexts/SequenceContext.java
package com.plicku.flowla.model.contexts;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SequenceContext {
private Map<String,Object> contextPropeties = new ConcurrentHashMap();
public Object getProperty(String key)
{
return this.contextPropeties.get(key);
}
public void setProperty(String key, Object value)
{
this.contextPropeties.put(key, value);
}
}
<file_sep>/src/test/java/com/plicku/flowla/processor/MethodCallRegistryEntry.java
package com.plicku.flowla.processor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MethodCallRegistryEntry {
String name;
Boolean expectedToBeCalled=false;
Boolean called =false;
public MethodCallRegistryEntry(String name, Boolean called) {
this.name = name;
this.called = called;
}
}
<file_sep>/src/main/java/com/plicku/flowla/util/ParamDataUtil.java
package com.plicku.flowla.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.plicku.flowla.exceptions.DataParsingException;
import com.plicku.flowla.model.DataTable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ParamDataUtil {
private static final ObjectMapper jsonMapper = new ObjectMapper();
private static final ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());
public static Object getBean(String data, Class parameterType) throws DataParsingException {
DataTable dataTable = new DataTable(Arrays.asList(data.split("\\r?\\n")));
try {
if(DataTable.class.equals(parameterType))
return dataTable;
else
return dataTable.getBean(parameterType);
} catch (Exception e) {
throw new DataParsingException("Unable to process the data table correctly. Please check the validity of how the data is provided",e);
}
}
public static Object getBeanFromJson(String paramData, Class parameterType) throws DataParsingException {
try {
return jsonMapper.readValue(paramData,parameterType);
} catch (IOException e) {
throw new DataParsingException("Unable to process json data correctly. Please check the validity of the json data",e);
}
}
public static Object getBeanFromYaml(String paramData, Class parameterType) throws DataParsingException {
try {
return yamlMapper.readValue(paramData,parameterType);
} catch (IOException e) {
throw new DataParsingException("Unable to process yaml data correctly. Please check the validity of the yaml data",e);
}
}
}
<file_sep>/src/main/java/com/plicku/flowla/model/DataTable.java
package com.plicku.flowla.model;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;
public class DataTable {
public List<List<Object>> datatable = new ArrayList<>();
public DataTable(List<String> datalines) {
datalines.forEach((String line) -> {
line=line.trim();
if(!"".equals(line.trim())) datatable.add(Arrays.asList(StringUtils.split(line,"\\|")));
});
}
public List<String> getHeaders()
{
return datatable.get(0).stream().map(o -> o.toString()).collect(Collectors.toList());
}
public Object elementAt(int row,int col)
{
return datatable.get(row).get(col);
}
public List<Object> getRow(int row)
{
return datatable.get(row);
}
public List<Object> getColumn(int col)
{
return datatable.stream().map(objects -> {return objects.get(col);}).collect(Collectors.toList());
}
public List<Map<String,Object>> getRowMapList()
{
List<Map<String,Object>> rowMapList = new ArrayList<>();
int tableheight = datatable.size();
for (int i = 1; i < tableheight; i++) {
LinkedHashMap rowMap = new LinkedHashMap();
List<String> headers = this.getHeaders();
for (int j = 0, headersSize = headers.size(); j < headersSize; j++) {
rowMap.put(headers.get(j),elementAt(i,j));
}
rowMapList.add(rowMap);
}
return rowMapList;
}
public <T> T getBean(Class<T> beanType) throws IllegalAccessException, InstantiationException, InvocationTargetException {
if(Collection.class.isAssignableFrom(beanType))
{
Collection collections = new ArrayList<>() ;
for(List row:datatable)
{
T bean = beanType.newInstance();
for(Object list :datatable.get(0))
{
int i =0;
BeanUtils.setProperty(bean,list.toString(),elementAt(1,i));
i++;
}
collections.add(bean);
}
return (T) collections;
}
else if(Map.class.isAssignableFrom(beanType))
{
Map map = new LinkedHashMap();
for(Object list :datatable.get(0))
{
int i =0;
map.put(list.toString(),elementAt(1,i));
i++;
}
return (T) map;
}
else
{
T bean = beanType.newInstance();
int i =0;
for(Object list :datatable.get(0))
{
BeanUtils.setProperty(bean,list.toString(),elementAt(1,i));
i++;
}
return bean;
}
}
}
<file_sep>/src/main/java/com/plicku/flowla/model/FlowValidationError.java
package com.plicku.flowla.model;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class FlowValidationError {
String stepName;
int lineNo;
String message;
public FlowValidationError(String stepName, String message) {
this.stepName = stepName;
this.message = message;
}
public FlowValidationError(String message) {
this.message = message;
}
}
| 1ba64ecc747620524d9a7ff1dc28b1a73eda7847 | [
"Java"
] | 18 | Java | sivan123/plicku-flowla | 75beafe72656cb733bdf5876cbb3a6f146777b8c | 4bc9033d65333800064540ef3bf43dea5591e6e8 |
refs/heads/master | <repo_name>melindadiaz/Pursuit-Core-iOS-ColorGuessingGameExercise<file_sep>/ColorGuessingGame/ColorGuessingGame/ViewController.swift
//
// ViewController.swift
// ColorGuessingGame
//
// Created by <NAME> on 10/29/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var colorGenerated = RGBValues()
var score = 0
var highScore = 0
@IBOutlet weak var blueOutlet: UIButton!
@IBOutlet weak var redOutlet: UIButton!
@IBOutlet weak var greenOutlet: UIButton!
@IBOutlet weak var currentScore: UILabel!
@IBOutlet weak var highScoreLabel: UILabel!
@IBOutlet weak var randomColorImage: UIView!
@IBOutlet weak var guessThatColor: UILabel!
@IBAction func playAgain(_ sender: UIButton) {
}
func currentScoreGenerator() {
score += 1
}
func highScoreGenerator() {
highScore += 1
}
@IBAction func randomColorButtons(_ sender: UIButton) {
switch sender.tag {
case 0:
if colorGenerated.highestRGB() == colorGenerated.green {
currentScoreGenerator()
guessThatColor.text = "You win! 🥳"
currentScore.text = "Your current score is \(score)"
// highScore.text = "HighScore = \(highScore)"
randomColorImage.backgroundColor = colorGenerated.rgbColor()
} else {
guessThatColor.text = "Loser!😢"
[redOutlet, blueOutlet, greenOutlet].forEach({$0?.isEnabled = false})
//you need to set a new game
}
case 1: if colorGenerated.highestRGB() == colorGenerated.blue {
currentScoreGenerator()
guessThatColor.text = "You win! 🥳"
currentScore.text = "Your current score is \(score)"
// highScore.text = "HighScore = \(highScore)"
randomColorImage.backgroundColor = colorGenerated.rgbColor()
} else {
guessThatColor.text = "Loser!😢"
[redOutlet, blueOutlet, greenOutlet].forEach({$0?.isEnabled = false})
//you need to set a new game
}
case 2: if colorGenerated.highestRGB() == colorGenerated.red {
currentScoreGenerator()
guessThatColor.text = "You win! 🥳"
currentScore.text = "Your current score is \(score)"
// highScore.text = "HighScore = \(highScore)"
randomColorImage.backgroundColor = colorGenerated.rgbColor()
} else {
guessThatColor.text = "Loser!😢"
[redOutlet, blueOutlet, greenOutlet].forEach({$0?.isEnabled = false})
//you need to set a new game
}
default:
print("not found")
}
}
override func viewDidLoad() {
super.viewDidLoad()
redOutlet.backgroundColor = .red
greenOutlet.backgroundColor = .green
blueOutlet.backgroundColor = .blue
randomColorImage.backgroundColor = colorGenerated.rgbColor()
}
}
| 450d97e5a5f5c562f05ad11f4f3b2f799668c724 | [
"Swift"
] | 1 | Swift | melindadiaz/Pursuit-Core-iOS-ColorGuessingGameExercise | 048c1fb795580352d57c7dafc93b32bfc54a88a9 | e6e405d920199211281fc1824491f24f6bb1458a |
refs/heads/main | <file_sep># rest framework imports
from rest_framework import serializers
# local imports
from events.models import (
Event,
)
class EventSerializer(serializers.ModelSerializer):
date_time = serializers.SerializerMethodField()
area_name = serializers.SerializerMethodField()
city_name = serializers.SerializerMethodField()
class Meta:
model = Event
fields = (
'username',
'title',
'content',
'date_time',
'longitude',
'latitude',
'area_name',
'city_name',
)
extra_kwargs = {
'longitude': {'write_only': True, },
'latitude': {'write_only': True, },
}
def get_date_time(self, obj):
return obj.get_date_time()
def get_area_name(self, obj):
return obj.area.area_name
def get_city_name(self, obj):
return obj.city.city_name
<file_sep>import { useEffect, useState } from 'react'
import axios from 'axios'
export function useFetchCity({latitude, longitude}) {
const [city, setCity] = useState('Your City')
const [data, setData] = useState()
const [loading, setLoading] = useState(false)
const [cityError, setCityError] = useState(null)
const fetchCity = ({latitude, longitude}) => {
setLoading(true)
}
useEffect(() => {
fetchCity({latitude,longitude})
}, [city])
return [city, loading, cityError]
}
export function useFetchPosts() {
const [posts, setPosts] = useState([])
const [loading, setLoading] = useState(false)
const [postsError, setPostsError] = useState(null)
useEffect(() => {
setLoading(true)
axios({
method: "GET",
url: "https://adherent.herokuapp.com/api/events",
}).then(response => {
setPosts(response.data.results)
setLoading(false);
}).catch(error => setPostsError(error))
}, [posts])
return [posts, loading, postsError]
}
export function useAdherentPost() {
} <file_sep>## Adherent Backend
Adherent uses Python Django framework as the backend.<file_sep>from django.contrib import admin
# importing models
from .models import (
Area,
City,
Event,
)
@admin.register(Area)
class AreaAdmin(admin.ModelAdmin):
list_display = ('area_name',)
@admin.register(City)
class CityAdmin(admin.ModelAdmin):
list_display = ('city_name',)
@admin.register(Event)
class EventAdmin(admin.ModelAdmin):
'''Admin View for Event'''
list_display = ('username', 'title',)
list_display_links = ('title',)
list_per_page = 15
search_fields = ('area__area_name', 'city__city_name',)
<file_sep>## Adherent Web
Adherent uses ReactJS framework for front-end web-app.<file_sep>from rest_framework.filters import SearchFilter
from rest_framework.generics import ListCreateAPIView
# local imports
from helper.utility import get_city_id
from events.models import (
Area,
City,
Event,
)
from .serializers import (
EventSerializer,
)
class EventsAPI(ListCreateAPIView):
queryset = Event.objects.all()
serializer_class = EventSerializer
filter_backends = [SearchFilter, ]
search_fields = [
'title',
'area__name',
]
def get_queryset(self):
latitude = self.request.GET.get("latitude")
longitude = self.request.GET.get("longitude")
if latitude and longitude:
result = get_city_id(latitude, longitude)
if result == None:
return Event.objects.none()
city, _ = City.objects.get_or_create(
city_id=result["cityId"],
city_name=result["cityName"]
)
return Event.objects.filter(city=city).distinct()
else:
return Event.objects.all()
<file_sep>from django.urls import path
from .apis import EventsAPI
urlpatterns = [
path("events", EventsAPI.as_view(), name="events"),
]
<file_sep>import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.bundle";
// importing components
import Navbar from "./components/Navbar";
import Login from "./pages/Login";
import Feed from "./pages/Feed";
import { checkLogin } from "./hooks/useLogin";
import "./css/styles.css";
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom";
function App() {
const loggedIn = checkLogin()
return (
<div>
<Router>
<Switch>
<Route exact path='/'>
{/* {loggedIn ? <Redirect to="/feed" /> : <Redirect to="/login" />} */}
</Route>
<Route exact path='/login'>
{/* {loggedIn ? <Redirect to="/feed" /> : <Login />} */}
<Login />
</Route>
<Route exact path='/feed'>
{/* {loggedIn ? <Feed /> : <Redirect to="/login" />} */}
<Feed />
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
<file_sep>from django.urls import path, include
app_name = "events"
urlpatterns = [
path('api/', include("events.api.urls")),
]
<file_sep>import React, { useState, useEffect } from "react";
import useLocation from "./useLocation";
import { useFetchCity } from "./useFetchData";
export function checkLogin() {
return localStorage.getItem("username") ? true : false;
}
export function useLogin() {
const { coordinates, error } = useLocation();
const [city, loading, cityError] = useFetchCity(coordinates);
if (error || cityError) {
console.error(error, cityError);
window.alert("Error. Try again with proper permissions and internet");
}
if (error === null && cityError === null) {
if (!localStorage.getItem("city")) {
localStorage.setItem("city", city);
}
}
}
export function getCityfromStorage() {
return localStorage.getItem("city");
}
<file_sep>## Adherent App
Adherent uses Flutter for Android app.<file_sep>import React, { memo } from "react";
import { NavLink } from "react-router-dom";
export default memo(function Navbar() {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container">
<NavLink className="navbar-brand" to="/">
Adherent
</NavLink>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
</div>
</nav>
);
});
<file_sep># Adherent

We all are different, experience various things happening around us but we stick together. We are all a part of a greater community. As humans, we've the tendency to share, someway to help others.
We all reside in a city but we rely on our locals news networks and friends to get to know about events happening around us.
To cutdown the delay in the updates to reach us, our team came up with Adherent.
Adherent is a community network for cities. When you join, you have instant access to everything happening in your city all at once.
Adherent enables us to filter down posts from a specific locality and type of updates as well.
___
## Tech-Stack
Backend: Python Django
Database: postgresql
Mobile App: Flutter
Web App: ReactJS
## Team
- <NAME>
- <NAME>
- <NAME>
- <NAME>
We are all residents of Raipur, Chhattisgarh and II year CSE students currently pursuing B.Tech at Shri Shankaracharya Institute Of Professional Management And Technology.
<file_sep># python imports
import os
import dotenv
from pathlib import Path
import requests
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# setting up dot env
dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
dotenv.load_dotenv(dotenv_file)
def get_city_id(lat, lon):
"""This function takes latitude and longitude as arguments and returns city id. NOTE: For this function to work
you have to set API_KEY in .evn file. You can get API_KEY from mapbox website."""
api_key = os.environ["API_KEY"]
params = {
'access_token': api_key,
'types': "district",
}
url = f"https://api.mapbox.com/geocoding/v5/mapbox.places/{lat},{lon}.json"
request = requests.get(url, params=params)
features = request.json()["features"]
if len(features) == 0: # meaning there is no such district with provided latitude & longitude
return None
else:
cityId = features[0]["id"].replace("district.", "")
cityName = features[0]["text"]
result = {
"cityId": cityId,
"cityName": cityName,
}
return results
def get_area_detail(lat, lon):
"""This function takes latitude & longitude as arguments and returns unique id for an area(data will be fetched from
API). NOTE: For this function to work you have to set API_KEY in .evn file. You can get API_KEY from mapbox website."""
api_key = os.environ["API_KEY"]
params = {
'access_token': api_key,
'types': "locality,district",
}
url = f"https://api.mapbox.com/geocoding/v5/mapbox.places/{lat},{lon}.json"
request = requests.get(url, params=params)
features = request.json()["features"]
if len(features) == 0: # meaning there is no such locality or district with provided latitude & longitude
return None
areaPrimartId = features[0]["id"].replace("locality.", "")
areaName = features[0]["text"]
cityPrimartId = features[1]["id"].replace("district.", "")
cityName = features[1]["text"]
result = {
"areaPrimartId": areaPrimartId,
"areaName": areaName,
"cityPrimartId": cityPrimartId,
"cityName": cityName,
}
return result
<file_sep>from django.db import models
from django.contrib.humanize.templatetags.humanize import naturaltime
class City(models.Model):
"""This is city model, which will be used in Event model for fetching data according to user location."""
city_name = models.CharField(max_length=255)
city_id = models.CharField(max_length=255)
class Meta:
"""Meta definition for City."""
verbose_name = 'City'
verbose_name_plural = 'Cities'
def __str__(self):
return self.city_name
class Area(models.Model):
"""This is area model, which will be used in Event model to further fetch data according to user location."""
area_name = models.CharField(max_length=255)
area_id = models.CharField(max_length=255)
def __str__(self):
return self.area_name
class Event(models.Model):
"""This is the main Event model. This model is the model returned to the user. This model have Area & City model as
foreign keys to filter data."""
# basic info
username = models.CharField(max_length=50)
title = models.CharField(max_length=50)
content = models.CharField(max_length=255)
# location info
latitude = models.CharField(max_length=255)
longitude = models.CharField(max_length=255)
area = models.ForeignKey(Area, on_delete=models.CASCADE)
city = models.ForeignKey(City, on_delete=models.CASCADE)
date_time = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-id',)
def get_date_time(self):
return naturaltime(self.date_time)
def __str__(self):
return f"{self.username} added {self.title}"
<file_sep>import { useState, useEffect } from 'react'
export default function useLocation() {
const [coordinates, setCoordinates] = useState({
longitude: null,
latitude: null
})
const [error, setError] = useState(null)
const getLocation = () => {
if(!navigator.geolocation) {
setError('Location Service Unavailable')
}
else {
navigator.geolocation.getCurrentPosition((position) => {
setError(null)
setCoordinates({
latitude: position.coords.latitude,
longitude: position.coords.longitude
})
}, (error) => {
console.error(error)
setError('There was a problem retrieving location, try again later')
})
}
}
useEffect(()=>{
getLocation()
}, [coordinates])
return {
coordinates: coordinates,
error: error
}
}<file_sep>from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.core.exceptions import ValidationError
from .models import (
Area,
City,
Event,
)
from helper.utility import get_area_detail
@receiver(pre_save, sender=Event)
def event_pre_save(sender, instance, *args, **kwargs):
"""This function runs before the model is saved. This function calls helper function we made to get user location details."""
result = get_area_detail(
instance.latitude, instance.longitude)
if result is None:
raise ValidationError(
"We can't find any location with this latitude and longitude.")
area, created = Area.objects.get_or_create(
area_name=result["areaName"],
area_id=result["areaPrimartId"]
)
city, _created = City.objects.get_or_create(
city_name=result["cityName"],
city_id=result["cityPrimartId"]
)
instance.area = area
instance.city = city
| 0a2661dbfd9d374e51610592b1e8f0fd9bdeaee3 | [
"JavaScript",
"Python",
"Markdown"
] | 17 | Python | shreydan/adherent-hacknitr-submission | 618c511f152e9126ee660973864dde3a88a7ed66 | 37ef12e35d3d8149323c05c2bf87a2c34bcca3ed |
refs/heads/master | <file_sep>package com.example.mvvmdemo.ui.users
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mvvmdemo.ui.users.usersListAdapter.UsersListAdapter
import dagger.Module
import dagger.Provides
@Module
class UsersListActivityModul {
@Provides
fun providePlacesAdapter(): UsersListAdapter {
return UsersListAdapter()
}
@Provides
fun provideLinearLayoutManager(context: Context): LinearLayoutManager {
return LinearLayoutManager(context)
}
}<file_sep>package com.example.mvvmdemo
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.mvvmdemo.data.local.DataManager
import com.example.mvvmdemo.ui.users.UsersListActivityViewModel
import com.example.mvvmdemo.utils.rx.SchedulerProvider
import retrofit2.Retrofit
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ViewModelProviderFactory @Inject constructor(
var schedulerProvider: SchedulerProvider,
var retrofit: Retrofit,
var mDataManager: DataManager
) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
when {
modelClass.isAssignableFrom(UsersListActivityViewModel::class.java) -> {
return UsersListActivityViewModel(schedulerProvider, retrofit, mDataManager) as T
}
else -> throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.name)
}
}
}<file_sep>package com.example.mvvmdemo.ui.users
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mvvmdemo.data.local.DataManager
import com.example.mvvmdemo.data.model.userResponse.Data
import com.example.mvvmdemo.ui.base.BaseViewModel
import com.example.mvvmdemo.utils.rx.SchedulerProvider
import retrofit2.Retrofit
class UsersListActivityViewModel(
schedulerProvider: SchedulerProvider,
retrofit: Retrofit,
mDataManager: DataManager
) : BaseViewModel<UsersListNavigater>(
schedulerProvider, retrofit, mDataManager
) {
var data: MutableLiveData<List<Data>> = MutableLiveData()
fun ApiCallPlaces() {
setIsLoading(true)
getCompositeDisposable()?.add(
getDataManager()?.GET_USERDATA(1)
?.subscribeOn(getSchedularProvider()?.io())
?.observeOn(getSchedularProvider()?.ui())
?.subscribe({
setIsLoading(false)
data.value = it.data
}, {
setIsLoading(false)
})!!
)
}
fun response(): LiveData<List<Data>> {
return data
}
init {
ApiCallPlaces()
}
}<file_sep>package com.example.mvvmdemo.di
import javax.inject.Qualifier
@Qualifier
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
annotation class PreferenceInfo{}
<file_sep>package com.example.mvvmdemo.utils
object AppContants {
const val PREF_NAME = "MvvmDemo"
}<file_sep>package com.example.mvvmdemo.data.local
import com.example.mvvmdemo.data.local.prefs.PreferencesHelper
import com.example.mvvmdemo.data.local.remote.ApiHelper
interface DataManager: PreferencesHelper,
ApiHelper {
}<file_sep>package com.example.mvvmdemo.data.local.remote
import com.example.mvvmdemo.data.model.userResponse.UserResponse
import io.reactivex.Observable
import retrofit2.http.*
interface ApiHelper {
@GET(ApiEndPoint.USERS)
fun GET_USERDATA(@Query("page") Page: Int): Observable<UserResponse>
}<file_sep>package com.example.mvvmdemo.data.local
import com.example.mvvmdemo.data.local.prefs.PreferencesHelper
import com.example.mvvmdemo.data.local.remote.ApiHelper
import com.example.mvvmdemo.data.model.userResponse.UserResponse
import io.reactivex.Observable
import javax.inject.Inject
class AppDataManager @Inject constructor(
var mPreferencesHelper: PreferencesHelper,
var mApiHelper: ApiHelper
) : DataManager {
override fun getAccessToken(): String {
return mPreferencesHelper.getAccessToken()
}
override fun setAccessToken(accessToken: String) {
return mPreferencesHelper.setAccessToken("")
}
override fun GET_USERDATA(Page: Int): Observable<UserResponse> {
return mApiHelper.GET_USERDATA(Page)
}
}<file_sep>package com.example.mvvmdemo.di.builder
import com.example.mvvmdemo.ui.users.UsersListActivity
import com.example.mvvmdemo.ui.users.UsersListActivityModul
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class ActivityBuilder {
@ContributesAndroidInjector(modules = [UsersListActivityModul::class])
abstract fun bindPlacesActivity(): UsersListActivity
}<file_sep>package com.example.mvvmdemo.ui.base
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.ViewModel
import com.example.mvvmdemo.data.local.DataManager
import com.example.mvvmdemo.utils.rx.SchedulerProvider
import io.reactivex.disposables.CompositeDisposable
import retrofit2.Retrofit
import java.lang.ref.WeakReference
open class BaseViewModel<N>(
schedulerProvider: SchedulerProvider,
retrofit: Retrofit,
mDataManager: DataManager
) : ViewModel() {
private var mIsLoading: ObservableBoolean = ObservableBoolean()
private var mSchedulerProvider: SchedulerProvider? = null
private var mCompositeDisposable: CompositeDisposable? = null
// private var mSchedulerProvider:SchedulerProvider? = null
lateinit var mNavigator: WeakReference<N>
private var mRetrofit: Retrofit? = null
private var mDataManager: DataManager? = null
init {
mSchedulerProvider = schedulerProvider
mCompositeDisposable = CompositeDisposable()
mRetrofit = retrofit
this.mDataManager = mDataManager
}
override fun onCleared() {
mCompositeDisposable?.clear()
super.onCleared()
}
fun setIsLoading(isLoading: Boolean) {
mIsLoading.set(isLoading)
}
fun getIsLoading(): ObservableBoolean {
return mIsLoading
}
fun setNavigator(navigator: N) {
this.mNavigator = WeakReference(navigator)
}
fun getNavigator(): N {
return mNavigator.get()!!
}
fun getDataManager(): DataManager? {
return mDataManager
}
fun getCompositeDisposable(): CompositeDisposable? {
return mCompositeDisposable
}
fun getSchedularProvider(): SchedulerProvider? {
return mSchedulerProvider
}
}<file_sep>package com.example.mvvmdemo.ui.base
import android.content.Context
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import dagger.android.AndroidInjection
abstract class BaseActivity<T : ViewDataBinding, V : BaseViewModel<*>?> : AppCompatActivity(),BaseFragment.Callback {
lateinit var mViewDataBinding: T
var mViewModel: V? = null
@LayoutRes
abstract fun getLayoutId(): Int
abstract fun getViewModel(): V
open fun getViewDataBinding(): T {
return mViewDataBinding
}
abstract fun getBindingVariable(): Int
override fun onCreate(savedInstanceState: Bundle?) {
performDependencyInjection()
super.onCreate(savedInstanceState)
performViewBainding()
}
override fun onFragmentAttached() {
}
override fun onFragmentDetached(tag: String?) {
}
open fun hideKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
open fun openActivityOnTokenExpire() {
// startActivity(LoginActivity.newIntent(this))
finish()
}
fun performDependencyInjection() {
AndroidInjection.inject(this)
}
fun performViewBainding() {
mViewDataBinding = DataBindingUtil.setContentView(this, getLayoutId())
mViewModel = if (mViewModel == null) getViewModel() else mViewModel
mViewDataBinding.setVariable(getBindingVariable(), mViewModel)
mViewDataBinding.executePendingBindings()
}
}<file_sep>package com.example.mvvmdemo.utils
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.mvvmdemo.data.model.userResponse.Data
import com.example.mvvmdemo.data.model.userResponse.UserResponse
import com.example.mvvmdemo.ui.users.usersListAdapter.UsersListAdapter
object BindingUtils {
@JvmStatic
@BindingAdapter("addPlacesItems")
fun addPlaceItems(recyclerView: RecyclerView, list: List<Data>?) {
if (recyclerView.adapter != null) {
var mUsersListAdapter: UsersListAdapter? = checkNotNull(recyclerView.adapter) as UsersListAdapter?
mUsersListAdapter?.let {
it.clearItems()
list?.let { it1 -> it.addItems(it1) }
}
}
}
@JvmStatic
@BindingAdapter("lodeImage")
fun imageBinding(imageView: ImageView, url: String) {
Glide.with(imageView.context).load(url).into(imageView)
}
}<file_sep>package com.example.mvvmdemo.data.local.prefs
public interface PreferencesHelper {
fun getAccessToken():String
fun setAccessToken(accessToken:String)
}<file_sep>package com.example.mvvmdemo.ui.users.usersListAdapter
class UsersListEmptyViewModel(var mClickListener: PlacesEmptyViewHolderEmptyClickListener) {
fun OnRetryClick() {
mClickListener.onRetryClick()
}
interface PlacesEmptyViewHolderEmptyClickListener {
fun onRetryClick()
}
}<file_sep>package com.example.mvvmdemo.ui.users.usersListAdapter
import androidx.databinding.ObservableField
import com.example.mvvmdemo.data.model.userResponse.Data
class UsersListViewModel constructor(
val mListener: PlacesItemViewModelListener,
mResult: Data
) {
var image: ObservableField<String>
var name: ObservableField<String>
fun onItemClickListener() {
mListener.OnItemClickListener()
}
interface PlacesItemViewModelListener {
fun OnItemClickListener()
}
init {
image = ObservableField(mResult.avatar!!)
name = ObservableField(mResult.email!!)
}
}<file_sep>package com.example.mvvmdemo.data.local.prefs
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.Nullable
import com.example.mvvmdemo.di.PreferenceInfo
import javax.inject.Inject
open class AppPreferencesHelper @Inject constructor(
@Nullable context: Context,
@PreferenceInfo prefFileName: String?
) : PreferencesHelper {
var mPrefs: SharedPreferences? = null
private val PREF_KEY_ACCESS_TOKEN = "PREF_KEY_ACCESS_TOKEN"
private val PREF_KEY_CURRENT_USER_EMAIL = "PREF_KEY_CURRENT_USER_EMAIL"
private val PREF_KEY_CURRENT_USER_ID = "PREF_KEY_CURRENT_USER_ID"
private val PREF_KEY_CURRENT_USER_NAME = "PREF_KEY_CURRENT_USER_NAME"
private val PREF_KEY_CURRENT_USER_PROFILE_PIC_URL = "PREF_KEY_CURRENT_USER_PROFILE_PIC_URL"
override fun getAccessToken(): String {
return mPrefs!!.getString(PREF_KEY_ACCESS_TOKEN, "").toString()
}
override fun setAccessToken(accessToken: String) {
mPrefs!!.edit().putString(PREF_KEY_ACCESS_TOKEN, accessToken).apply()
}
init {
mPrefs = context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE)
}
}<file_sep>package com.example.mvvmdemo.ui.users
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mvvmdemo.BR
import com.example.mvvmdemo.R
import com.example.mvvmdemo.ViewModelProviderFactory
import com.example.mvvmdemo.databinding.ActivityUsersListBinding
import com.example.mvvmdemo.ui.base.BaseActivity
import com.example.mvvmdemo.ui.users.usersListAdapter.UsersListAdapter
import kotlinx.android.synthetic.main.activity_users_list.*
import javax.inject.Inject
class UsersListActivity : BaseActivity<ActivityUsersListBinding, UsersListActivityViewModel>(),
UsersListNavigater, UsersListAdapter.BlogAdapterListener {
lateinit var foctory: ViewModelProviderFactory
@Inject set
lateinit var mAdapter: UsersListAdapter
@Inject set
lateinit var mLayoutManager: LinearLayoutManager
@Inject set
lateinit var mUsersListActivityViewModel: UsersListActivityViewModel
lateinit var mActivityUsersListBinding: ActivityUsersListBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mUsersListActivityViewModel.setNavigator(this)
mActivityUsersListBinding = getViewDataBinding()
mActivityUsersListBinding.lifecycleOwner = this
rvPlaces.layoutManager = mLayoutManager
rvPlaces.adapter = mAdapter
mAdapter.setListner(this)
}
override fun getLayoutId(): Int {
return R.layout.activity_users_list
}
override fun getViewModel(): UsersListActivityViewModel {
mUsersListActivityViewModel =
ViewModelProvider(this, foctory).get(UsersListActivityViewModel::class.java)
return mUsersListActivityViewModel
}
override fun getBindingVariable(): Int {
return BR.viewModel
}
override fun placesApiCall() {
mUsersListActivityViewModel.ApiCallPlaces()
}
override fun onRetryClick() {
mUsersListActivityViewModel.ApiCallPlaces()
}
}
<file_sep>package com.example.mvvmdemo.ui.users.usersListAdapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.mvvmdemo.data.model.userResponse.Data
import com.example.mvvmdemo.databinding.ItemEmptyUserBinding
import com.example.mvvmdemo.databinding.ItemUserBinding
import com.example.mvvmdemo.ui.base.BaseViewHolder
class UsersListAdapter : RecyclerView.Adapter<BaseViewHolder>() {
val VIEW_TYPE_NORMAL: Int = 1
val VIEW_TYPE_Empty: Int = 0
var listOfPlaces: ArrayList<Data> = arrayListOf()
lateinit var mListener: BlogAdapterListener
override fun getItemViewType(position: Int): Int {
return if (listOfPlaces.size > 0) VIEW_TYPE_NORMAL else VIEW_TYPE_Empty
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
when (viewType) {
VIEW_TYPE_Empty -> {
val mbinding = ItemEmptyUserBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return EmptyViewHolder(mbinding)
}
else -> {
val mbinding =
ItemUserBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return PlacesViewHolder(mbinding)
}
}
}
fun addItems(list: List<Data>) {
listOfPlaces = list as ArrayList<Data>
notifyDataSetChanged()
}
fun clearItems() {
listOfPlaces.clear()
}
fun setListner(mListener: BlogAdapterListener) {
this.mListener = mListener
}
interface BlogAdapterListener {
fun onRetryClick()
}
override fun getItemCount(): Int {
return if (listOfPlaces.size > 0) listOfPlaces.size else 1
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
holder.onBind(position)
}
inner class EmptyViewHolder constructor(binding: ItemEmptyUserBinding) :
BaseViewHolder(binding.root),
UsersListEmptyViewModel.PlacesEmptyViewHolderEmptyClickListener {
var mbinding: ItemEmptyUserBinding
lateinit var mUsersListEmptyViewModel: UsersListEmptyViewModel
override fun onBind(Position: Int) {
mUsersListEmptyViewModel = UsersListEmptyViewModel(this)
mbinding.viewModel = mUsersListEmptyViewModel
}
override fun onRetryClick() {
mListener.onRetryClick()
}
init {
this.mbinding = binding
}
}
inner class PlacesViewHolder(binding: ItemUserBinding) : BaseViewHolder(binding.root),
UsersListViewModel.PlacesItemViewModelListener {
var mbinding: ItemUserBinding
lateinit var mPlacesViewModel: UsersListViewModel
override fun onBind(Position: Int) {
val result: Data = listOfPlaces.get(Position)
mbinding.viewModel = UsersListViewModel(this, result)
mbinding.executePendingBindings()
}
override fun OnItemClickListener() {
// Toast.makeText()
}
init {
this.mbinding = binding
}
}
}<file_sep>package com.example.mvvmdemo.di.module
import android.app.Application
import android.content.Context
import com.androidnetworking.interceptors.HttpLoggingInterceptor
import com.example.mvvmdemo.data.local.AppDataManager
import com.example.mvvmdemo.data.local.DataManager
import com.example.mvvmdemo.data.local.prefs.AppPreferencesHelper
import com.example.mvvmdemo.data.local.prefs.PreferencesHelper
import com.example.mvvmdemo.data.local.remote.ApiEndPoint
import com.example.mvvmdemo.data.local.remote.ApiHelper
import com.example.mvvmdemo.di.PreferenceInfo
import com.example.mvvmdemo.utils.AppContants
import com.example.mvvmdemo.utils.rx.AppSchedulerProvider
import com.example.mvvmdemo.utils.rx.SchedulerProvider
import dagger.Module
import dagger.Provides
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
open class AppModule {
@Provides
@Singleton
fun provideApiHelper(retrofit: Retrofit): ApiHelper {
return retrofit.create(ApiHelper::class.java)
}
@Provides
@Singleton
fun provideOkHttpClient(cache: Cache): OkHttpClient {
val intersapter = HttpLoggingInterceptor()
intersapter.level = HttpLoggingInterceptor.Level.BODY
val client: OkHttpClient =
OkHttpClient.Builder().addInterceptor(intersapter).cache(cache).build()
client.newBuilder()
.writeTimeout(180, TimeUnit.SECONDS)
.connectTimeout(3, TimeUnit.MINUTES)
.readTimeout(3, TimeUnit.MINUTES)
.addInterceptor { chain ->
val original = chain.request()
val originalHttpUrl = original.url()
val url = originalHttpUrl.newBuilder()
.addQueryParameter("user_lang", Locale.getDefault().language)
.addQueryParameter("app_version", "v3/")
.addQueryParameter("user_role", "")
.addQueryParameter("device_type", "1")
.build()
val requestBuilder = original.newBuilder().url(url)
.addHeader("session_id", "")
val request = requestBuilder.build()
chain.proceed(request)
}
return client
}
@Provides
@Singleton
fun provideRetrofitInstance(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(ApiEndPoint.BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
fun provideContext(application: Application): Context {
return application
}
@Provides
@Singleton
fun cache(context: Context): Cache {
val cacheSize = (5 * 1024 * 1024).toLong()
val myCache = Cache(context.cacheDir!!, cacheSize)
return myCache
}
@Provides
@PreferenceInfo
open fun providePreferenceName(): String {
return AppContants.PREF_NAME
}
@Provides
@Singleton
fun providerPreferenceHelper(appPreferencesHelper: AppPreferencesHelper): PreferencesHelper {
return appPreferencesHelper
}
@Provides
fun provideSchedulerProvider(): SchedulerProvider {
return AppSchedulerProvider()
}
@Provides
@Singleton
fun providerDataManager(mAppDataManager: AppDataManager): DataManager {
return mAppDataManager
}
}<file_sep>package com.example.mvvmdemo.ui.users
interface UsersListNavigater {
fun placesApiCall()
}<file_sep>package com.example.mvvmdemo.data.local.remote
object ApiEndPoint {
const val USERS = "users"
const val BASE_URL = "https://reqres.in/api/"
}<file_sep>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
ndkVersion "21.1.6352462"
defaultConfig {
applicationId "com.example.mvvmdemo"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
dataBinding = true
viewBinding = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.2.18'
// RxAndroid
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
// network
implementation "com.amitshekhar.android:rx2-android-networking:$rootProject.rx2FastAndroidNetworking"
// font
implementation "uk.co.chrisjenx:calligraphy:$rootProject.calligraphyVersion"
// image
implementation "com.github.bumptech.glide:glide:$rootProject.glideVersion"
// debug database
debugImplementation "com.amitshekhar.android:debug-db:$rootProject.debugDBVersion"
// dependency injection
implementation "com.google.dagger:dagger-android:$rootProject.dagger2Version"
implementation "com.google.dagger:dagger-android-support:$rootProject.dagger2Version"
kapt "com.google.dagger:dagger-android-processor:$rootProject.dagger2Version"
kapt "com.google.dagger:dagger-compiler:$rootProject.dagger2Version"
// reactive
implementation "io.reactivex.rxjava2:rxjava:$rootProject.rxjava2Version"
implementation "io.reactivex.rxjava2:rxandroid:$rootProject.rxandroidVersion"
// swipe view
implementation "com.mindorks:placeholderview:$rootProject.placeholderviewVersion"
// logger
implementation "com.jakewharton.timber:timber:$rootProject.timberVersion"
// view model
implementation "androidx.lifecycle:lifecycle-extensions:$rootProject.lifecycleVersion"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$rootProject.lifecycleVersion"
//retrofit
implementation "com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion"
implementation "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofitrxjavaVersion"
implementation "com.squareup.retrofit2:converter-gson:$rootProject.retrofitGsonConveterVersion"
//sdp
implementation "com.intuit.sdp:sdp-android:$rootProject.sdp"
// //leak cannry
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.3'
//navigation component
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
}
| 655e3f8d27e78125861f6722a74723e7c7013247 | [
"Kotlin",
"Gradle"
] | 22 | Kotlin | naimishmodi39/MvvmDemo | 51ac6fc662e45d9f89b4a2fba1a011ec8ba10f24 | 24111686a3551f57e03897b0c85548f787a7214e |
refs/heads/master | <file_sep>#include "main.h"
#include "customizeScreen.h"
int customizeSplash(FILE *file, SDL_Renderer *m_renderer, SDL_Event event) {
int quit = 0, menu = 0;
file = fopen("cars.ini", "wb");
TTF_Font *font = TTF_OpenFont("sources/Fonts/segoeui.ttf", 24);
SDL_Color color = {255, 255, 255, 0};
SDL_Surface *surface;
SDL_Texture *backImage, *redCar, *blueCar, *greenCar, *yellowCar, *save, *car, *track, *box;
SDL_Rect thumbnails, words1, words2, boxRect, boxCrop, saveR, blueR, greenR, yellowR;
backImage = IMG_LoadTexture(m_renderer, "sources/Images/01titleImage.jpg");
box = IMG_LoadTexture(m_renderer, "sources/Images/05titleImage.png");
surface = TTF_RenderText_Solid(font, "Press Enter to Save", color);
save = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "Customize Cars", color);
car = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "Customize Tracks", color);
track = SDL_CreateTextureFromSurface(m_renderer, surface);
SDL_FreeSurface(surface);
redCar = IMG_LoadTexture(m_renderer, "sources/Images/p_redcar.png");
blueCar = IMG_LoadTexture(m_renderer, "sources/Images/p_bluecar.png");
greenCar = IMG_LoadTexture(m_renderer, "sources/Images/p_greencar.png");
yellowCar = IMG_LoadTexture(m_renderer, "sources/Images/p_yellowcar.png");
words1.x = 300;
words1.y = 150;
words2.x = 300;
words2.y = 200;
boxRect.y = 5;
boxRect.x = 250;
boxRect.w = 200;
boxRect.h = 170;
boxCrop.x = 250;
boxCrop.y = 200;
boxCrop.w = 800;
boxCrop.h = 200;
saveR.x = 0;
saveR.y = 500;
SDL_QueryTexture(save, 0, 0, &saveR.w, &saveR.h);
SDL_QueryTexture(car, 0, 0, &words1.w, &words1.h);
SDL_QueryTexture(track, 0, 0, &words2.w, &words2.h);
thumbnails.x = blueR.x = yellowR.x = greenR.x = 300;
thumbnails.y = 50;
blueR.y = 180;
yellowR.y = 310;
greenR.y = 440;
thumbnails.w = 500;
blueR.w = 500;
yellowR.w = 500;
greenR.w = 500;
thumbnails.h = 500;
blueR.h = 500;
yellowR.h = 500;
greenR.h = 500;
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, backImage, 0, 0);
SDL_RenderCopy(m_renderer, redCar, 0, &thumbnails);
SDL_RenderCopy(m_renderer, blueCar, 0, &blueR);
SDL_RenderCopy(m_renderer, yellowCar, 0, &yellowR);
SDL_RenderCopy(m_renderer, greenCar, 0, &greenR);
SDL_RenderCopy(m_renderer, box, &boxCrop, &boxRect);
SDL_RenderPresent(m_renderer);
while(!quit) {
while(SDL_PollEvent(&event)){
if (event.type == SDL_QUIT) {
quit = 1;
}
switch(event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_DOWN:
if (menu !=3) {
menu++;
boxRect.y += 130;
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, backImage, 0, 0);
SDL_RenderCopy(m_renderer, redCar, 0, &thumbnails);
SDL_RenderCopy(m_renderer, blueCar, 0, &blueR);
SDL_RenderCopy(m_renderer, yellowCar, 0, &yellowR);
SDL_RenderCopy(m_renderer, greenCar, 0, &greenR);
SDL_RenderCopy(m_renderer, box, &boxCrop, &boxRect);
SDL_RenderPresent(m_renderer);
}
break;
case SDLK_UP:
if (menu != 0) {
menu--;
boxRect.y -=130;
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, backImage, 0, 0);
SDL_RenderCopy(m_renderer, redCar, 0, &thumbnails);
SDL_RenderCopy(m_renderer, blueCar, 0, &blueR);
SDL_RenderCopy(m_renderer, yellowCar, 0, &yellowR);
SDL_RenderCopy(m_renderer, greenCar, 0, &greenR);
SDL_RenderCopy(m_renderer, box, &boxCrop, &boxRect);
SDL_RenderPresent(m_renderer);
}
break;
case SDLK_RETURN:
switch (menu) {
case 0:
fprintf(file, "r");
break;
case 1:
fprintf(file, "b");
break;
case 2:
fprintf(file, "y");
break;
case 3:
fprintf(file, "g");
break;
default:
fprintf(file, "b");
break;
}
break;
case SDLK_BACKSPACE:
SDL_DestroyTexture(backImage);
fclose(file);
return 0;
break;
}
break;
}
}
}
fclose(file);
SDL_DestroyTexture(backImage);
SDL_DestroyTexture(save);
SDL_DestroyTexture(redCar);
SDL_DestroyTexture(blueCar);
SDL_DestroyTexture(yellowCar);
SDL_DestroyTexture(greenCar);
return 1;
}
<file_sep>#include "main.h"
#include "creditsScreen.h"
int creditsSplash(FILE *file, SDL_Renderer *m_renderer, SDL_Event event) {
int quit = 0, i;
SDL_Texture *m_texture, *t_texture, *t2, *t3, *t4, *t5, *t6, *t7, *t8;
SDL_Color font_color = {255, 255, 0, 0};
TTF_Font *m_font = TTF_OpenFont("sources/Fonts/segoeui.ttf", 12);
SDL_Surface *surface = TTF_RenderText_Solid(m_font, "Programmers of ProjectCruiser v. 1.2: ", font_color);
SDL_Surface *s2, *s3, *s4, *s5, *s6, *s7, *s8;
SDL_Rect tRect[8];
s2 = TTF_RenderText_Solid(m_font, "1. <NAME>", font_color);
s3 = TTF_RenderText_Solid(m_font, "2. <NAME>", font_color);
s4 = TTF_RenderText_Solid(m_font, "3. <NAME>", font_color);
s5 = TTF_RenderText_Solid(m_font, "4. <NAME>", font_color);
s6 = TTF_RenderText_Solid(m_font, "The program was made entirely in C programming language with additional API derived from SDL2 which is freely distributed.", font_color);
s7 = TTF_RenderText_Solid(m_font, "Title Screen image was taken from : https://www.pexels.com/search/car/", font_color);
s8 = TTF_RenderText_Solid(m_font, "This program can be freely edited and distributed around using its source code at Github", font_color);
m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, 800, 600);
t_texture = SDL_CreateTextureFromSurface(m_renderer, surface);
t2 = SDL_CreateTextureFromSurface(m_renderer, s2);
t3 = SDL_CreateTextureFromSurface(m_renderer, s3);
t4 = SDL_CreateTextureFromSurface(m_renderer, s4);
t5 = SDL_CreateTextureFromSurface(m_renderer, s5);
t6 = SDL_CreateTextureFromSurface(m_renderer, s6);
t7 = SDL_CreateTextureFromSurface(m_renderer, s7);
t8 = SDL_CreateTextureFromSurface(m_renderer, s8);
SDL_FreeSurface(surface);
SDL_FreeSurface(s2);
SDL_FreeSurface(s3);
SDL_FreeSurface(s4);
SDL_FreeSurface(s5);
SDL_FreeSurface(s6);
SDL_FreeSurface(s7);
SDL_FreeSurface(s8);
for (i = 0; i<8; i++) {
tRect[i].x = 0;
tRect[i].y = 50*i;
}
SDL_QueryTexture(t_texture, 0, 0, &tRect[0].w, &tRect[0].h);
SDL_QueryTexture(t2, 0, 0, &tRect[1].w, &tRect[1].h);
SDL_QueryTexture(t3, 0, 0, &tRect[2].w, &tRect[2].h);
SDL_QueryTexture(t4, 0, 0, &tRect[3].w, &tRect[3].h);
SDL_QueryTexture(t5, 0, 0, &tRect[4].w, &tRect[4].h);
SDL_QueryTexture(t6, 0, 0, &tRect[5].w, &tRect[5].h);
SDL_QueryTexture(t7, 0, 0, &tRect[6].w, &tRect[6].h);
SDL_QueryTexture(t8, 0, 0, &tRect[7].w, &tRect[7].h);
if (m_texture == 0) {
printf("\nError creating texture");
SDL_DestroyRenderer(m_renderer);
return 1;
}
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, m_texture, 0, 0);
SDL_RenderCopy(m_renderer, t_texture, 0, &tRect[0]);
SDL_RenderCopy(m_renderer, t2, 0, &tRect[1]);
SDL_RenderCopy(m_renderer, t3, 0, &tRect[2]);
SDL_RenderCopy(m_renderer, t4, 0, &tRect[3]);
SDL_RenderCopy(m_renderer, t5, 0, &tRect[4]);
SDL_RenderCopy(m_renderer, t6, 0, &tRect[5]);
SDL_RenderCopy(m_renderer, t7, 0, &tRect[6]);
SDL_RenderCopy(m_renderer, t8, 0, &tRect[7]);
SDL_RenderPresent(m_renderer);
while(!quit){
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT){
quit = 1;
}
switch(event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_BACKSPACE:
SDL_DestroyTexture(t_texture);
SDL_DestroyTexture(t2);
SDL_DestroyTexture(t3);
SDL_DestroyTexture(t4);
SDL_DestroyTexture(t5);
SDL_DestroyTexture(t6);
SDL_DestroyTexture(t7);
SDL_DestroyTexture(t8);
return 0;
break;
}
break;
default:
break;
}
}
}
SDL_DestroyTexture(t_texture);
SDL_DestroyTexture(t2);
SDL_DestroyTexture(t3);
SDL_DestroyTexture(t4);
SDL_DestroyTexture(t5);
SDL_DestroyTexture(t6);
SDL_DestroyTexture(t7);
SDL_DestroyTexture(t8);
return 1;
}
<file_sep>#ifndef MAIN_H_
#define MAIN_H_
#include <stdio.h>
#include <string.h>
#include "SDL2/SDL.h"
#include "SDL2/SDL_ttf.h"
#include "SDL2/SDL_image.h"
#include <conio.h>
#include <stdlib.h>
#include <time.h>
void destroyEverything(SDL_Window *, SDL_Renderer *);
void initiate(FILE*, SDL_Renderer*, SDL_Event, SDL_Window*);
#endif // MAIN_H_
<file_sep>#include "main.h"
#include "overScreen.h"
int overSplash(FILE *file, SDL_Renderer *m_renderer, SDL_Event event, long int scoreN) {
int quit = 0;
TTF_Font *font = TTF_OpenFont("sources/Fonts/DESTROY_.TTF", 70);
TTF_Font *elsem = TTF_OpenFont("sources/Fonts/segoeui.ttf", 24);
SDL_Color color = {255, 255, 255, 0};
SDL_Texture *gameOver, *enter, *score, *back;
SDL_Rect over, ente, scor;
SDL_Surface *surface;
surface = TTF_RenderText_Solid(font, "GAME OVER", color);
gameOver = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(elsem, "Score = ", color);
score = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(elsem, "Press Enter to go to main Menu", color);
enter = SDL_CreateTextureFromSurface(m_renderer, surface);
back = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, 800, 600);
SDL_FreeSurface(surface);
over.x = 175;
over.y = 300;
ente.x = 0;
ente.y = 0;
scor.x = 0;
scor.y = 570;
SDL_QueryTexture(gameOver, 0, 0, &over.w, &over.h);
SDL_QueryTexture(score, 0, 0, &scor.w, &scor.h);
SDL_QueryTexture(enter, 0, 0, &ente.w, &ente.h);
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, back, 0, 0);
SDL_RenderCopy(m_renderer, gameOver, 0, &over);
SDL_RenderCopy(m_renderer, score, 0, &scor);
displayScore(m_renderer, scoreN, elsem);
SDL_RenderCopy(m_renderer, enter, 0, &ente);
SDL_RenderPresent(m_renderer);
while(!quit){
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT){
quit = 1;
}
switch(event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym){
case SDLK_RETURN:
return 10;
}
break;
}
}
}
SDL_DestroyTexture(back);
SDL_DestroyTexture(enter);
SDL_DestroyTexture(score);
SDL_DestroyTexture(gameOver);
return 1;
}
<file_sep>#ifndef OVERSCREEN_H_
#define OVERSCREEN_H_
int overSplash(FILE*, SDL_Renderer*, SDL_Event, long int);
#endif // OVERSCREEN_H_
<file_sep>#ifndef CUSTOMIZESCREEN_H_
#define CUSTOMIZESCREEN_H_
int customizeSplash(FILE *, SDL_Renderer *, SDL_Event);
#endif // CUSTOMIZESCREEN_H_
<file_sep>#ifndef GAMESCREEN_H_
#define GAMESCREEN_H_
int gameSplash(FILE*, SDL_Renderer*, SDL_Event);
int getCarColor(FILE *);
int getTrack();
int displayScore(SDL_Renderer*, long int, TTF_Font*);
#endif // GAMESCREEN_H_
<file_sep>#ifndef HOMESCREEN_H_
#define HOMESCREEN_H_
int homeSplash(FILE*, SDL_Renderer*, SDL_Event);
#endif // HOMESCREEN_H_
<file_sep>#include "main.h"
#include "homeScreen.h"
#include "gameScreen.h"
#include "creditsScreen.h"
#include "customizeScreen.h"
#include "overScreen.h"
int homeSplash(FILE *file, SDL_Renderer *m_renderer, SDL_Event event) {
SDL_Rect rect, crop, nameRect, nameCrop, tRect, cRect, cuRect, eRect, boxRect, boxCrop;
SDL_Color text_color = {0, 255, 255, 0};
SDL_Color title_color = {0, 0, 100, 0};
TTF_Font *textFont = TTF_OpenFont("sources/Fonts/boul.ttf", 40);
TTF_Font *titleFont = TTF_OpenFont("sources/Fonts/DESTROY_.TTF", 65);
SDL_Surface *playSurface;
int quit = 0, menu = 0;
SDL_Texture *image, *titleImage, *playText, *customizeText, *creditsText, *exitText, *box;
SDL_RenderClear(m_renderer);
SDL_RenderPresent(m_renderer);
image = IMG_LoadTexture(m_renderer, "sources/Images/01titleImage.jpg");
box = IMG_LoadTexture(m_renderer, "sources/Images/05titleImage.png");
playSurface = TTF_RenderText_Solid(titleFont, "Project CRUISER", title_color);
titleImage = SDL_CreateTextureFromSurface(m_renderer, playSurface);
playSurface = TTF_RenderText_Solid(textFont, "Play Now!", text_color);
playText = SDL_CreateTextureFromSurface(m_renderer, playSurface);
playSurface = TTF_RenderText_Solid(textFont, "Customize Car", text_color);
customizeText = SDL_CreateTextureFromSurface(m_renderer, playSurface);
playSurface = TTF_RenderText_Solid(textFont, "Credits", text_color);
creditsText = SDL_CreateTextureFromSurface(m_renderer, playSurface);
playSurface = TTF_RenderText_Solid(textFont, "Quit", text_color);
exitText = SDL_CreateTextureFromSurface(m_renderer, playSurface);
if (image <= 0 || titleImage <= 0 || box <= 0) {
IMG_Quit();
return 0;
}
tRect.x = cRect.x = cuRect.x = eRect.x = 15;
tRect.y = 300;
cuRect.y = 350;
cRect.y = 400;
eRect.y = 450;
boxRect.y = 290;
boxRect.x = 0;
boxRect.w = 500;
boxRect.h = 100;
rect.x = 0;
rect.y = 0;
nameRect.x = 20;
nameRect.y = 20;
rect.w = 800;
rect.h = 600;
crop.x = nameCrop.x = 0;
crop.y = nameCrop.y = 0;
boxCrop.x = 250;
boxCrop.y = 200;
boxCrop.w = 800;
boxCrop.h = 600;
SDL_QueryTexture(playText, 0, 0, &tRect.w, &tRect.h);
SDL_QueryTexture(customizeText, 0, 0, &cuRect.w, &cuRect.h);
SDL_QueryTexture(creditsText, 0, 0, &cRect.w, &cRect.h);
SDL_QueryTexture(exitText, 0, 0, &eRect.w, &eRect.h);
SDL_QueryTexture(image, 0, 0, &crop.w, &crop.h);
SDL_QueryTexture(titleImage, 0, 0, &nameRect.w, &nameRect.h);
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, image, &crop, &rect);
SDL_RenderCopy(m_renderer, titleImage, 0, &nameRect);
SDL_RenderCopy(m_renderer, playText, 0, &tRect);
SDL_RenderCopy(m_renderer, customizeText, 0, &cuRect);
SDL_RenderCopy(m_renderer, creditsText, 0, &cRect);
SDL_RenderCopy(m_renderer, exitText, 0, &eRect);
SDL_RenderCopy(m_renderer, box, &boxCrop, &boxRect);
SDL_RenderPresent(m_renderer);
while(!quit){
srand(time(0));
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT){
quit = 1;
}
switch(event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_DOWN:
if (menu != 3) {
menu++;
boxRect.y += 50;
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, image, &crop, &rect);
SDL_RenderCopy(m_renderer, titleImage, 0, &nameRect);
SDL_RenderCopy(m_renderer, playText, 0, &tRect);
SDL_RenderCopy(m_renderer, customizeText, 0, &cuRect);
SDL_RenderCopy(m_renderer, creditsText, 0, &cRect);
SDL_RenderCopy(m_renderer, exitText, 0, &eRect);
SDL_RenderCopy(m_renderer, box, &boxCrop, &boxRect);
SDL_RenderPresent(m_renderer);
}
break;
case SDLK_UP:
if (menu != 0) {
menu--;
boxRect.y -= 50;
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, image, &crop, &rect);
SDL_RenderCopy(m_renderer, titleImage, 0, &nameRect);
SDL_RenderCopy(m_renderer, playText, 0, &tRect);
SDL_RenderCopy(m_renderer, customizeText, 0, &cuRect);
SDL_RenderCopy(m_renderer, creditsText, 0, &cRect);
SDL_RenderCopy(m_renderer, exitText, 0, &eRect);
SDL_RenderCopy(m_renderer, box, &boxCrop, &boxRect);
SDL_RenderPresent(m_renderer);
}
break;
case SDLK_RETURN:
switch(menu) {
case 0:
quit = gameSplash(file, m_renderer, event);
break;
case 1:
quit = customizeSplash(file, m_renderer, event);
break;
case 2:
quit = creditsSplash(file, m_renderer, event);
break;
case 3:
quit = 1;
break;
}
}
break;
default:
break;
}
}
}
SDL_DestroyTexture(image);
SDL_DestroyTexture(titleImage);
SDL_DestroyTexture(playText);
SDL_DestroyTexture(customizeText);
SDL_DestroyTexture(creditsText);
return 0;
}
<file_sep># Project Cruiser
Project work done for the completion of Bachelors degree in Computer Engineering. It was submitted for the subject of C Programming.
## Description
Project was created in Code::Blocks using SDL and C Programming language.
<file_sep>#include "main.h"
#include "beginScreen.h"
int beginSplash(FILE *file, SDL_Renderer *m_renderer, SDL_Event event) {
int elapsed = SDL_GetTicks(); // stores time from when SDL was initialized
SDL_Texture *m_texture, *t_texture; //Creates two variables from which individual pixels of the window
SDL_Color font_color = {255, 255, 255, 0}; //defines color in Red, green and blue format
TTF_Font *m_font = TTF_OpenFont("sources/Fonts/segoeui.ttf", 18); //opens font which is located in fonts folder of size 18
SDL_Surface *surface = TTF_RenderText_Solid(m_font, "Through the joint collaboration of <NAME>, <NAME>, <NAME> and <NAME>", font_color);
m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, 800, 600);
t_texture = SDL_CreateTextureFromSurface(m_renderer, surface);
SDL_FreeSurface(surface);
SDL_Rect tRect;
tRect.x = 15;
tRect.y = 300;
SDL_QueryTexture(t_texture, 0, 0, &tRect.w, &tRect.h); //width and height of the rectangle where we display the text from surface
if (m_texture == 0) { // if m_texture is not initailized or gets some error while storing data then t_texture store 0
printf("\nError creating texture");
SDL_DestroyRenderer(m_renderer);
return 1;
}
SDL_RenderClear(m_renderer); //clears the memory of renderer(pixel controller)
SDL_RenderCopy(m_renderer, m_texture, 0, 0); // copies the data of m_texture in the memory
SDL_RenderCopy(m_renderer, t_texture, 0, &tRect); //copies the data of t_texture in the memory at the location of tRect
SDL_RenderPresent(m_renderer); //transfers the contents of memory in renderer in the display
while(elapsed < 5000){ // loops until time spent in the beginscreen is 5 sec
elapsed = SDL_GetTicks(); // stores new data of elapsed
while (SDL_PollEvent(&event)) { // if any event happens the this loop is run
if (event.type == SDL_QUIT){ //if the event is clicked on X mark the program closes
SDL_DestroyTexture(m_texture);
return 1;
}
}
}
SDL_DestroyTexture(m_texture); //destroys everything
SDL_DestroyTexture(t_texture);
SDL_RenderClear(m_renderer);
SDL_RenderPresent(m_renderer);
return 0;
}
<file_sep>#ifndef BEGINSCREEN_H_
#define BEGINSCREEN_H_
int beginSplash(FILE *, SDL_Renderer *, SDL_Event);
#endif // BEGINSCREEN_H_
<file_sep>#include "main.h"
#include "gameScreen.h"
int gameSplash(FILE *file, SDL_Renderer *m_renderer, SDL_Event event) {
int obstacle = 0, i, instant, lane = 2, count = 0, count2 = 0;
long int score = 0, speed = 2, mark = 50;
int choice = getCarColor(file), choice2 = getTrack();
int randomTruck[2], randomLane, randomX;
long int timel = SDL_GetTicks(), timel2;
SDL_Color color = {255,255,255,0};
TTF_Font *goFont = TTF_OpenFont("sources/Fonts/DESTROY_.ttf", 24);
SDL_Surface *surface;
SDL_Texture *road, *road2, *prot, *obs[4], *go[6];
SDL_Rect roadRect, road2Rect, crop, obsR[4], goR[3], protR;
srand(time(0));
randomTruck[0] = rand() % 4;
randomTruck[1] = rand() % 4;
randomLane = rand() % 4;
if (randomTruck[1] == 4) {randomTruck[1] = 1;}
switch (randomLane) {
case 0:
randomX = 120;
break;
case 1:
randomX = 260;
break;
case 2:
randomX = 480;
break;
case 3:
randomX = 540;
break;
}
SDL_RenderClear(m_renderer);
SDL_RenderPresent(m_renderer);
surface = TTF_RenderText_Solid(goFont, "3", color);
go[0] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(goFont, "2", color);
go[1] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(goFont, "1", color);
go[2] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(goFont, "GO", color);
go[3] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(goFont, "Press Escape to return to Main Menu", color);
go[4] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(goFont, "Score : ", color);
go[5] = SDL_CreateTextureFromSurface(m_renderer, surface);
SDL_FreeSurface(surface);
switch (choice2) {
case 0:
road = IMG_LoadTexture(m_renderer, "sources/Images/iceRoad.png");
break;
case 1:
road = IMG_LoadTexture(m_renderer, "sources/Images/cityRoad.png");
break;
default:
road = IMG_LoadTexture(m_renderer, "sources/Images/desertRoad.png");
break;
}
road2 = road;
switch (choice) {
case 0:
prot = IMG_LoadTexture(m_renderer, "sources/Images/p_redcar.png");
break;
case 1:
prot = IMG_LoadTexture(m_renderer, "sources/Images/p_bluecar.png");
break;
case 2:
prot = IMG_LoadTexture(m_renderer, "sources/Images/p_yellowcar.png");
break;
case 3:
prot = IMG_LoadTexture(m_renderer, "sources/Images/p_greencar.png");
break;
}
obs[0] = IMG_LoadTexture(m_renderer, "sources/Images/o_yellowtruck.png");
obs[1] = IMG_LoadTexture(m_renderer, "sources/Images/o_redtruck.png");
obs[2] = IMG_LoadTexture(m_renderer, "sources/Images/o_bluetruck.png");
obs[3] = IMG_LoadTexture(m_renderer, "sources/Images/o_greentruck.png");
roadRect.x = roadRect.y = road2Rect.x = 0;
road2Rect.y = 0;
crop.x = 0;
crop.y = 600;
goR[0].x = goR[0].y = 0;
goR[1].x = 375;
goR[1].y = 300;
goR[2].x = 0;
goR[2].y = 570;
protR.x = 400;
protR.y = 500;
obsR[0].x = randomX + 120;
obsR[1].x = randomX;
obsR[0].y = 0;
if (obsR[0].x > 540) {obsR[0].x = 120;}
SDL_QueryTexture(go[5], 0, 0, &goR[2].w, &goR[2].h);
SDL_QueryTexture(obs[0], 0, 0, &obsR[0].w, &obsR[0].h);
SDL_QueryTexture(prot, 0, 0, &protR.w, &protR.h);
SDL_QueryTexture(go[0], 0, 0, &goR[1].w, &goR[1].h);
SDL_QueryTexture(go[4], 0, 0, &goR[0].w, &goR[0].h);
SDL_QueryTexture(road, 0, 0, &roadRect.w, &roadRect.h);
road2Rect.w = roadRect.w;
road2Rect.h = crop.h = 600-crop.y;
crop.w = 800;
obsR[1].w = obsR[0].w;
obsR[1].h = obsR[0].h;
while((instant = SDL_GetTicks()-timel) <= 4000) {
if (instant < 1000) {i = 0;}
else if (instant < 2000) {i = 1;}
else if (instant < 3000) {i = 2;}
else if (instant < 4000) {i = 3;}
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, road2, &crop, &road2Rect);
SDL_RenderCopy(m_renderer, road, 0, &roadRect);
SDL_RenderCopy(m_renderer, go[4], 0, &goR[0]);
SDL_RenderCopy(m_renderer, go[i], 0, &goR[1]);
SDL_RenderPresent(m_renderer);
}
while(!obstacle){
crop.y-=speed;
if (crop.y == -speed) {crop.y = 600;}
road2Rect.h = 600-crop.y;
crop.h = road2Rect.h;
roadRect.y+=speed;
if(roadRect.y == 600+speed) {roadRect.y = 0;}
obsR[0].y+=(speed/2);
obsR[1].y+=(speed/2);
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, road2, &crop, &road2Rect);
SDL_RenderCopy(m_renderer, road, 0, &roadRect);
SDL_RenderCopy(m_renderer, prot, 0, &protR);
if (obsR[0].y > 600) {count++;}
if (obsR[1].y > 600) {count2++;}
SDL_RenderCopy(m_renderer, obs[0], 0, &obsR[1]);
SDL_RenderCopy(m_renderer, obs[randomTruck[0]], 0, &obsR[0]);
SDL_RenderCopy(m_renderer, go[5], 0, &goR[2]);
displayScore(m_renderer, score, goFont);
SDL_RenderPresent(m_renderer);
for (i = 0; i < 2; i++) {
if ((protR.x >= obsR[i].x && protR.x <= obsR[i].x + 135) && (protR.y >= obsR[i].y && protR.y <= obsR[i].y+250)) {
obstacle = overSplash(file, m_renderer, event, score);
}
}
if (obstacle == 1) {return 1;}
else if (obstacle == 10) {return 0;}
if (SDL_GetTicks()-timel > 3000) {
score += speed*0.5;
timel = SDL_GetTicks();
}
if (score >= mark * 2) {
mark = score;
speed+=2;
}
if (count == 1) {
randomTruck[0] = rand() % 4;
count--;
obsR[0].x = (rand() % 4)*140 + 120;
obsR[0].y = 0;
}
if (count2 == 1) {
randomTruck[1] = rand() % 4;
count2--;
obsR[1].x = (rand() % 4)*140 + 120;
obsR[1].y = 0;
}
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT){
return 1;
}
switch(event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_ESCAPE:
obstacle = 1;
break;
case SDLK_LEFT:
if (lane >= 1) {
protR.x -= 140;
lane --;
//printf("\nx = %d, y = %d", obsR[0].x, obsR[1].x);
}
break;
case SDLK_RIGHT:
if (lane <=2) {
protR.x += 140;
lane++;
// printf("\nx = %d, y = %d", protR.x, protR.y);
}
break;
case SDLK_UP:
if (protR.y > 300) {
protR.y -= 50;
}
break;
case SDLK_DOWN:
if (protR.y < 550) {
protR.y += 50;
}
break;
}
break;
default:
break;
}
}
}
/*for(i = 0; i< 5; i++) {
SDL_DestroyTexture(go[i]);
SDL_DestroyTexture(obs[i]);
}*/
SDL_DestroyTexture(prot);
SDL_DestroyTexture(road);
SDL_DestroyTexture(road2);
return 0;
}
int getCarColor(FILE *file) {
file = fopen("cars.ini", "rb");
char send;
int color;
send = fgetc(file);
if (send == 'b') {
color = 1;
}
else if (send == 'r') {
color = 0;
}
else if (send == 'y') {
color = 2;
}
else {
color = 3;
}
return color;
}
int getTrack() {
int elapsed = SDL_GetTicks();
srand(elapsed);
return (rand() % 3);
}
int displayScore(SDL_Renderer *m_renderer, long int score, TTF_Font *font) {
int rem, count = 0, i;
SDL_Color color = {255, 255, 255, 0};
SDL_Surface *surface;
SDL_Rect txRect;
SDL_Texture *tx[10];
long int temp = score;
surface = TTF_RenderText_Solid(font, "0", color);
tx[0] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "1", color);
tx[1] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "2", color);
tx[2] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "3", color);
tx[3] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "4", color);
tx[4] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "5", color);
tx[5] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "6", color);
tx[6] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "7", color);
tx[7] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "8", color);
tx[8] = SDL_CreateTextureFromSurface(m_renderer, surface);
surface = TTF_RenderText_Solid(font, "9", color);
tx[9] = SDL_CreateTextureFromSurface(m_renderer, surface);
SDL_FreeSurface(surface);
txRect.x = 200;
txRect.y = 570;
SDL_QueryTexture(tx[0], 0, 0, &txRect.w, &txRect.h);
while (temp != 0) {
count++;
temp /= 10;
}
temp = score;
while (temp != 0) {
rem = temp % 10;
txRect.x -= 20*count;
SDL_RenderCopy(m_renderer, tx[rem], 0, &txRect);
count--;
temp /= 10;
}
for (i = 0; i<10;i++) {
SDL_DestroyTexture(tx[i]);
}
return 0;
}
<file_sep>#include "main.h"
#include "beginScreen.h"
#include "homeScreen.h"
int main(int argc, char* args[] )
{
FILE *file;
SDL_Window *m_window;
SDL_Renderer *m_renderer;
SDL_Event event;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("\nError initializing SDL\n");
return 0;
}
if (TTF_Init() < 0) {
printf("\nError loading font\n");
return 0;
}
m_window = SDL_CreateWindow("ProjectCruiser", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN);
if (m_window == 0) {
SDL_Quit();
printf("\nError creating window\n");
return 0;
}
m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_PRESENTVSYNC);
if (m_renderer == 0){
SDL_DestroyWindow(m_window);
SDL_Quit();
printf("\nError creating renderer\n");
return 0;
}
initiate(file, m_renderer, event, m_window);
IMG_Quit();
TTF_Quit();
SDL_Quit();
return 0;
}
void initiate(FILE*file, SDL_Renderer *m_renderer, SDL_Event event, SDL_Window *m_window) {
int check;
check = beginSplash(file, m_renderer, event);
if (check == 1) {
return;
}
homeSplash(file, m_renderer, event);
destroyEverything(m_window, m_renderer);
}
void destroyEverything(SDL_Window* m_window, SDL_Renderer* m_renderer) {
SDL_DestroyRenderer(m_renderer);
SDL_DestroyWindow(m_window);
}
<file_sep>#ifndef CREDITSSCREEN_H_
#define CREDITSSCREEN_H_
int creditsSplash(FILE* , SDL_Renderer* , SDL_Event);
#endif // CREDITSSCREEN_H_
| 65411a47398d1d86599d68a2cf82ab2b4fda2cb2 | [
"Markdown",
"C"
] | 15 | C | abiral001/ProjectCruiser | ef27a9df85e2d6f2620e65e6a203c1945675cae3 | 5b16e5ebb58443d0258062573d7fe13351a84bfa |
refs/heads/main | <repo_name>abraham-berlin/Base64URL<file_sep>/base64.c
#include <string.h>
#include "base64.h"
static const unsigned char pr2six[256] =
{
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};
int Base64decode_len(const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
return nbytesdecoded + 1;
}
int Base64decode(char *bufplain, const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register unsigned char *bufout;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
bufout = (unsigned char *) bufplain;
bufin = (const unsigned char *) bufcoded;
while (nprbytes > 4) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
bufin += 4;
nprbytes -= 4;
}
/* Note: (nprbytes == 1) would be an error, so just ingore that case */
if (nprbytes > 1) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
}
if (nprbytes > 2) {
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
}
if (nprbytes > 3) {
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
}
*(bufout++) = '\0';
nbytesdecoded -= (4 - nprbytes) & 3;
return nbytesdecoded;
}<file_sep>/README.md
# Base64URL
## Description
Takes a base64 URL and opens it in default web browser.
## Usage
```
base64URL <base64>
```
## Installlation
### Install GCC
- [Windows](https://dev.to/gamegods3/how-to-install-gcc-in-windows-10-the-easier-way-422j)
- MacOS
```
brew install gcc
```
- Linux - You already know :)
### Build
- Open a terminal in the downloaded folder and run `make`. This will build you program into an exicutable file.
### BOOM done
## Install it as a service (MacOS Only)
1. Open up Automator
2. Create a new Quick Action
3. Change workflow to text
4. Search "Run Shell Script" and add it
5. Paste the following changing DIR to the directory you build you exicutable
```
#! /bin/sh
cd DIR
./base64URL "$1"
```
<file_sep>/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "base64.h"
int main(int argc, char *argv[]) {
if (argc == 2) {
const char *buff_base64 = argv[1];
char *url = malloc(Base64decode_len(buff_base64));
Base64decode(url, buff_base64);
char * open = malloc(strlen(url)+5);
sprintf(open, "open %s", url);
system(open);
free(url);
free(open);
} else {
fprintf(stderr, "Incorrect Arguments");
exit(0);
}
}<file_sep>/base64.h
#ifndef BASE64_H_
#define BASE64_H_
int Base64decode_len(const char *);
int Base64decode(char *, const char *);
#endif<file_sep>/makefile
CC=gcc
CFLAGS=-g -c -Wall -Wextra -Wwrite-strings
LFLAGS=-g
base64URL: main.o base64.o
${CC} ${LFLAGS} -o base64URL main.o base64.o
main.o: main.c
${CC} ${CFLAGS} main.c
base64.o: base64.c base64.h
${CC} ${CFLAGS} base64.c
clean:
rm -f *.o
rm -f base64URL | db08e5d33ba970d7555ca223c5aac3d9a17642de | [
"Markdown",
"C",
"Makefile"
] | 5 | C | abraham-berlin/Base64URL | d98b4d61fbc3719bf6dc22eeff36b76c6e5a5210 | bf2a2e0cfc8642244d7a8aca095cdcb46105e39c |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers\Stripe;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\StripePay;
use App\Model\Order;
use Stripe;
use App\Model\Product;
use Auth;
use Session;
class StripeController extends Controller
{
public function index(){
$allProduct = Product::orderBy('id', 'DESC')->get();
return view('stripe.stripe_home', compact('allProduct'));
}
public function userProfile(){
$urerOrders = Order::get();
$urerOrders->transform(function($urerOrder, $key){
$urerOrder->cart = unserialize($urerOrder->cart);
return $urerOrder;
});
return view('stripe.stripeUser.userProfile', compact('urerOrders'));
}
public function getAddToCart(Request $request, $id){
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new StripePay($oldCart);
$cart->add($product, $product->id);
$request->session()->put('cart', $cart);
/*dd($request->session()->get('cart'));*/
return redirect('/stripe-home');
}
public function getCart(){
if(!Session::has('cart')){
return view('stripe.stripeUser.getCart');
}
$oldCart = Session::get('cart');
$cart = new StripePay($oldCart);
return view('stripe.stripeUser.getCart', ['products'=>$cart->items, 'totalPrice'=> $cart->totalPrice]);
}
public function cartCheckout(){
/*Checking, the user is loged-in or not, if not, it will redirect to the login page*/
$this->stripeAuthCheck();
if(!Session::has('cart')){
return view('stripe.stripeUser.stripeCheckOut');
}
$oldCart = Session::get('cart');
$cart = new StripePay($oldCart);
$total = $cart->totalPrice;
return view('stripe.stripeUser.stripeCheckOut', ['products'=>$cart->items, 'total' => $total]);
}
/*Making the payment to the 'Stripe Account'*/
public function stripePay(Request $request){
/*Checking, the user is loged-in or not, if not, it will redirect to the login page*/
$this->stripeAuthCheck();
if(!Session::has('cart')){
return redirect('stripe.home');
}
Stripe\Stripe::setApiKey('test_api_key_would_be_here');
$token = Stripe\Token::create([
'card' => [
'name' => request('card_name'),
'number' => request('card_number'),
'cvc' => request('card_cvc'),
'exp_month' => request('exp_month'),
'exp_year' => request('exp_year')
]
]);
try{
$oldCart = Session::get('cart');
$cart = new StripePay($oldCart);
$total = $cart->totalPrice;
$charge = Stripe\Charge::create ( array (
"amount" => $total * 100,
"currency" => "usd",
"source" => $token['id'], // obtained with Stripe.js
"description" => "Test payment."
/*'receipt_email' => 'email would be here'*/
) );
$order = new Order();
$orderUser = Session::get('id');
$order->first_name = $request->first_name;
$order->user_id = $orderUser;
$order->last_name = $request->last_name;
$order->user_name = $request->user_name;
$order->email = $request->email;
$order->address = $request->address;
$order->address_2 = $request->address_2;
$order->district = $request->district;
$order->street = $request->street;
$order->zip = $request->zip;
$order->cart = serialize($cart);
$order->card_name = $request->card_name;
$order->payment_id = $charge->id;
$order->save();
}catch(\Exception $e){
return redirect('/stripe-checkout')->with('error', $e->getMessage());
}
Session::forget('cart');
return redirect('/stripe-home');
}
/*Checking, the user is loged-in or not, if not, it will redirect to the login page*/
public function stripeAuthCheck(){
$authId = Session::get('id');
if($authId){
return redirect('/stripe-checkout');
}else{
/*Conditioning, after loged-in, it will go to the previous link*/
/*Session::put('oldUrl', $request->oldUrl);*/
return redirect('/stripe-login')->send();
}
}
public function addQty($id){
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new StripePay($oldCart);
$cart->addQtyByOne($id);
Session::put('cart', $cart);
return redirect('/stripe-getCart');
}
public function reduceQty($id){
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new StripePay($oldCart);
$cart->reduceQtyByOne($id);
if(count($cart->items) > 0){
Session::put('cart', $cart);
}else{
Session::forget('cart');
}
return redirect('/stripe-getCart');
}
}
<file_sep><?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class StripeUser extends Model
{
protected $fillable = [
'name', 'email', 'password',
];
public function orders(){
return $this->hasMany(Order::class, 'id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Paypal;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PaypalController extends Controller
{
public function index(){
return view('paypal.paypal_home');
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Session;
class ConfirmRegistration extends Controller
{
public function varify($remember_token)
{
$user = User::where('remember_token', $remember_token)->first();
$user->status = 1;
$user->remember_token = null;
$user->save();
if(!is_null($user)){
Session::flash('message', 'You have successfully confirm your registration!!');
return redirect('login');
}else{
Session::flash('errors', 'Sorry !! Your token is not matched');
return redirect('front-page');
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Product;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\Product;
use Session;
class ProductController extends Controller
{
public function index(){
return view('admin.product.manageProduct');
}
public function addProduct(){
return view('admin.product.addProduct');
}
public function saveProduct(Request $request){
$request->validate([
'product_name' => 'required',
'product_price' => 'required',
'category' => 'required'
]);
$product = null;
try
{
$image = $request->file('product_image');
$fileExt = $image->getClientOriginalExtension();
$fileName = date('ymdhis.') . $fileExt;
$image->move(public_path('uploads/product/'), $fileName);
$product = new Product();
$product->product_name = $request->product_name;
$product->product_price = $request->product_price;
$product->product_image = $fileName;
$product->description = $request->description;
$product->category = $request->category;
$product->save();
}catch(Exception $exception){
$product = false;
}
if($product){
Session::flash('success', 'Product added successfully');
}
return back();
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'front\HomeController@index')->name('front-page');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/token/{remember_token}', 'Admin\ConfirmRegistration@varify')->name('user.verification');
/*Manually Add to cart routes*/
Route::get('carts', 'front\CartController@index')->name('carts');
Route::post('/addtocart', 'front\CartController@store')->name('cart.store');
Route::post('/update/{id}', 'front\CartController@updateCart')->name('update');
Route::post('/cartDelete/{id}', 'front\CartController@deleteCart')->name('cartDelete');
Route::get('/checkout', 'front\CartController@checkoutCart')->name('checkout');
Route::get('/invoice', 'front\CartController@createInvoice')->name('invoice');
Route::post('/payment', 'front\CartController@manualStripePay')->name('stripe.payment');
/*Add to cart routes using Package*/
Route::get('/cartHome', 'front\CartPackageController@packageHome')->name('cartHome');
Route::post('/cartStore', 'front\CartPackageController@cartStore')->name('package.cartStore');
Route::get('empty', function(){
Cart::clear();
});
Route::get('items', function(){
$cartCollection = Cart::getContent();
$cartCollection->count();
return $cartCollection;
});
Route::get('/packageManage', 'front\CartPackageController@packageManage')->name('packageManage');
Route::get('/packageCheckout', 'front\CartPackageController@packageCheckout')->name('packageCheckout');<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use Session;
class CategoryController extends Controller
{
/*Route redirect to the manageCategory page*/
public function manageCategory(){
$categories = Category::orderBy('id', 'DESC')->get();
return view('admin.category.manageCategory', compact('categories'));
}
/*Route redirect to the add-category page*/
public function addCategory(){
return view('admin.category.addCategory');
}
/*Adding category to the database*/
public function saveCategory(Request $request){
$request->validate([
'category_name' => 'required'
]);
$category = new Category();
$category->category_name = $request->category_name;
$category->slug = $this->slugGenerator($request->category_name);
$category->save();
Session::flash('message', 'Category added successfully');
return back();
}
public function categoryStatus($id, $status){
$categoryStatus = Category::find($id);
$categoryStatus->status = $status;
$categoryStatus->save();
return response()->json(['message' => 'Success']);
}
public function editCategory($id){
$editCategory = Category::find($id);
return view('admin.category.editCategory', compact('editCategory'));
}
public function updateCategory(Request $request){
$category = Category::find($request->id);
$category->category_name = $request->category_name;
$category->slug = $this->slugGenerator($request->category_name);
$category->update();
Session::flash('message', 'Category updated successfully');
return redirect('/category/all-category');
}
public function deleteCategory($id){
$deleteCategory = Category::find($id);
$deleteCategory->delete();
Session::flash('message', 'Category deleted successfully');
return back();
}
/*Slug Generator to prevent the special carecter*/
public function slugGenerator($string){
$string = str_replace(' ', '-', $string);
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
return strtolower(preg_replace('/-+/', '-', $string));
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Brand;
use Session;
class BrandController extends Controller
{
public function addBrand(){
return view('admin.brand.addBrand');
}
public function saveBrand(Request $request){
$request->validate([
'brand_name' => 'required'
]);
$brand = new Brand();
$brand->brad_name = $request->brand_name;
$brand->brand_slugs = $this->slugGenerator($request->brand_name);
$brand->save();
//return back()->with('message', 'Brand added successfully!');
Session::flash('message', 'Brand added successfully');
return back();
}
public function allBrand(){
$allBrand = Brand::orderBy('id', 'DESC')->get();
return view('admin.brand.allBrand', compact('allBrand'));
}
/*Updating data using ajax*/
public function brandStatus($id, $status){
$activeBrand = Brand::find($id);
$activeBrand->brand_status = $status;
$activeBrand->save();
return response()->json(['message' => 'Success']);
}
public function editBrand($id){
$editBrand = Brand::find($id);
return view('admin.brand.editBrand', compact('editBrand'));
}
public function updateBrand(Request $request){
$brand = Brand::find($request->id);
$brand->brad_name = $request->brand_name;
$brand->brand_slugs = $this->slugGenerator($request->brand_name);
$brand->save();
Session::flash('message', 'Brand Updated Successfully');
return redirect('/brand/all-brand');
}
public function deleteBrand($id){
$deleteBrand = Brand::find($id);
$deleteBrand->delete();
Session::flash('message', ' Brand delete successfylly');
return back();
}
/*Slug Generator to prevent the special carecter*/
public function slugGenerator($string){
$string = str_replace(' ', '-', $string);
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
return strtolower(preg_replace('/-+/', '-', $string));
}
}
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Notifications\ConfirmRegistration;
use Illuminate\Http\Request;
use Session;
use App\User;
use Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => '<PASSWORD>',
]);
$user = User::where('email', $request->email)->first();
if($user->status == 1)
{
if(Auth::guard('web')->attempt(['email'=>$request->email, 'password'=>$request->password], $request->remember))
{
return redirect()->intended(route('front-page'));
}
}else{
if(!is_null($user))
{
$user->notify(new ConfirmRegistration($user));
Session::flash('message', 'A new confirm message has been sent to your email, please confirm it!');
return redirect('front-page');
}else{
Session::flash('message', 'You are not a member! Please register first');
return redirect('front-page');
}
}
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'SiteController@index')->name('index');
Route::get('/product', 'ProductController@index')->name('product');
Auth::routes();
Route::middleware(['auth'])->group(function(){
/**
*Routes of redirection to the dashboard
*/
Route::get('/admin', 'HomeController@index')->name('admin');
/**
*Routes of Brand
*/
Route::prefix('brand')->group(function(){
Route::get('/add-brand', 'BrandController@addBrand')->name('add-brand');
Route::post('/save-brand', 'BrandController@saveBrand')->name('save-brand');
Route::get('/all-brand', 'BrandController@allBrand')->name('all-brand');
Route::get('/delete/{id}', 'BrandController@deleteBrand')->name('delete-brand');
Route::get('/edit/{id}', 'BrandController@editBrand')->name('edit-brand');
Route::post('/update-brand', 'BrandController@updateBrand')->name('update-brand');
/**
*Updating status using ajax
*/
Route::get('/brandStatus/{id}/{s}', 'BrandController@brandStatus')->name('brandStatus');
});
/**
*Route for Category
*/
Route::prefix('category')->group(function(){
Route::get('/all-category', 'CategoryController@manageCategory')->name('manage-category');
Route::get('/add-category', 'CategoryController@addCategory')->name('add-category');
Route::post('/save-category', 'CategoryController@saveCategory')->name('save-category');
Route::get('/edit-category/{id}', 'CategoryController@editCategory')->name('edit-category');
Route::get('/categoryStatus/{id}/{status}', 'CategoryController@categoryStatus')->name('categoryStatus');
Route::get('/delete-category/{id}', 'CategoryController@deleteCategory')->name('delete-category');
Route::post('/update-category', 'CategoryController@updateCategory')->name('update-category');
});
/**
*Route for sub-category
*/
Route::prefix('category')->group(function(){
Route::get('/sub-category', 'SubCategoryController@manageSubCategory')->name('sub-category');
Route::get('/add-subcategory', 'SubCategoryController@addSubCategory')->name('add-subcategory');
Route::post('/save-subcategory', 'SubCategoryController@saveSubCategory')->name('save-subcategory');
Route::get('/subCategoryStatus/{id}/{status}', 'SubCategoryController@subCategoryStatus')->name('subCategoryStatus');
Route::get('/edit-sub-category/{id}', 'SubCategoryController@editSubCategory')->name('edit-sub-category');
Route::post('/update-subcategory', 'SubCategoryController@updateSubCategory')->name('update-subcategory');
Route::get('/delete-subCategory/{id}', 'SubCategoryController@deleteSubCategory')->name('delete-subCategory');
});
Route::get('/category/sub-subcategory', 'SubSubCategoryController@manageSubSubCategory')->name('sub-subcategory');
Route::prefix('slider')->group(function(){
Route::get('/manage-slide', 'SliderController@manageSlide')->name('manage-slide');
Route::get('/add-slider', 'SliderController@addSlider')->name('add-slider');
Route::post('/save-slider', 'SliderController@saveSlider')->name('save-slider');
Route::get('/edit-slider', 'SliderController@editSlide')->name('edit-slider');
Route::get('/delete-slider/{id}', 'SliderController@deleteSlide')->name('delete-slider');
Route::get('/sliderStatus/{id}/{status}', 'SliderController@sliderStatus')->name('sliderStatus');
});
});<file_sep><?php
namespace App\Http\Controllers\front;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Session;
use Cart;
class CartPackageController extends Controller
{
public function packageHome(){
return view('frontend.packageCart.packageHome');
}
public function cartStore(Request $request){
/*Cart::add(455, 'Sample Item', 100.99, 2, array());*/
Cart::add($request->id, $request->name, $request->price, 1,)
->associate('App\Product');
return redirect()->route('cartHome')->with('success', 'Item added successfully');
}
public function packageManage(){
return view('frontend.packageCart.packageCartManage');
}
public function packageCheckout(){
return view('frontend.packageCart.packageCheckout');
}
}
<file_sep><?php
namespace App\Helpers;
use App\User;
use App\Helpers\GravatarHelper;
/**
*
*/
class ImgHelper
{
public static function getUserImg($id){
$user = User::find($id);
$avatar_url = '';
if(!is_null($user)){
if($user->avatar == null){
if(GravatarHelper::validate_gravatar($user->email)){
$avatar_url = GravatarHelper::gravatar_img($user->email, 80);
}else{
$avatar_url = url('asset/admin/images/admin.jpg');
}
}else{
$avatar_url = url('asset/admin/images/users' . $user->avatar);
}
}else{
return redirect('/');
}
return $avatar_url;
}
}<file_sep><?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public function stripeUser(){
return $this->belongsTo(StripeUser::class, 'id');
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/**
* Auth Route
*
* Auth Route is for the authentigation of the user
* user route is defiened from here
* this route redirection the app home page
*/
Auth::routes();
Route::get('/home', 'Home\HomeController@index')->name('home');
/**
* Admin Route
*
* All route for the admin is defined here
* the admin is defined from here
*/
Route::post('/admin-dashboard', 'Admin\AdminController@index')->name('admin.home');
/**
* Product-Category Route
*
* All route for the product is defined here
* the product is defined from here
*/
Route::get('/manage-category', 'Product\CategoryController@index')->name('category');
Route::get('/add-category', 'Product\CategoryController@addCategory')->name('add.category');
Route::post('/save-category', 'Product\CategoryController@saveCategory')->name('save.category');
/**
* Product Route
*
* All route for the product is defined here
* the product is defined from here
*/
Route::get('/manage-product', 'Product\ProductController@index')->name('manage.product');
Route::get('/add-product', 'Product\ProductController@addProduct')->name('add.product');
Route::post('save-product', 'Product\ProductController@saveProduct')->name('save.product');
/*
|--------------------------------------------------------------------------
| All Front-end Route is starting from here
|--------------------------------------------------------------------------
*
* Home Route
*
* This route if for the home page
*
*/
Route::get('/', function () {
return view('welcome');
});
/**
* Stripe-Cart Route
*
* All route for the stripe payment is defined here
* the stripe cart is defined from here
*/
/*Stripe-Login system is here*/
Route::get('/stripe-home', 'Stripe\StripeController@index')->name('stripe.home');
Route::get('/stripe-login', 'Stripe\UserController@getLogin')->name('stripe.login');
Route::post('/stripe-login', 'Stripe\UserController@postLogin')->name('stripe.login');
Route::get('/stripe-register', 'Stripe\UserController@userRegister')->name('stripe.register');
Route::get('/stripe-logout', 'Stripe\UserController@stripeLogout')->name('stripe.logout');
Route::post('/stripe-register', 'Stripe\UserController@addUser')->name('stripe.register');
/*Stripe Payment Route*/
Route::get('/stripe-user', 'Stripe\StripeController@userProfile')->name('stripe.user.profile');
Route::get('/add-to-cart/{id}', 'Stripe\StripeController@getAddToCart')->name('product.addToCart');
Route::get('/stripe-getCart', 'Stripe\StripeController@getCart')->name('stripe.getCart');
Route::get('/stripe-addQty/{id}', 'Stripe\StripeController@addQty')->name('stripe.addQty');
Route::get('/stripe-reduceQty/{id}', 'Stripe\StripeController@reduceQty')->name('stripe.reduceQty');
Route::get('/stripe-checkout', 'Stripe\StripeController@cartCheckout')->name('stripe.checkout');
Route::post('/stripe-payment', 'Stripe\StripeController@stripePay')->name('stripe.payment');
/*Route::get('/stripe-checkout', [
'users' => 'Stripe\StripeController@cartCheckout',
'as' => 'stripe.checkout',
'middleware' => 'auth'
] );
Route::post('/stripe-payment', [
'users' => 'Stripe\StripeController@stripePay',
'as' => 'stripe.payment',
'middleware' => 'auth'
] );*/
/**
* Paypal-Cart Route
*
* All route for the paypal payment is defined here
* the paypal cart is defined from here
*/
Route::get('/paypal-home', 'Paypal\PaypalController@index')->name('paypal.home');<file_sep><?php
namespace App\Http\Controllers\Product;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\Category;
use Session;
class CategoryController extends Controller
{
public function index(){
return view('admin.category.manageCategory');
}
public function addCategory(){
return view('admin.category.addCategory');
}
public function saveCategory(Request $request){
$request->validate([
'category_name' => 'required|unique:categories'
]);
$category = new Category();
$img = $request->file('category_image');
if(!is_null($img))
{
$image = $request->file('category_image');
$fileExt = $image->getClientOriginalExtension();
$fileName = date('ymdhis.') . $fileExt;
$image->move(public_path('uploads/category/'), $fileName);
$category->category_name = $request->category_name;
$category->category_image = $fileName;
$category->save();
}else
{
$category->category_name = $request->category_name;
$category->category_image = $request->category_image;
$category->save();
}
Session::flash('success', 'Category added successfully');
return back();
}
}
<file_sep><?php
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Cart extends Model
{
protected $fillable = [ 'product_id', 'user_id', 'order_id', 'ip_address', 'product_quentity',];
/**
*
*
* These functions are for relation to the database table.
*
* @return carts
*/
public function user(){
return $this->belongsTo(User::class);
}
public function order(){
return $this->belongsTo(Order::class);
}
public function product(){
return $this->belongsTo(Product::class);
}
/**
*
*
* These function is for showing how many product is at the card.
*
* @return carts
*/
public static function totalCarts(){
/*Manage total cart*/
if(Auth::check()){
$carts = Cart::orWhere('user_id', Auth::id())
->orWhere('ip_address', request()->ip())
->get();
}else{
$carts = Cart::orWhere('ip_address', request()->ip())->get();
}
return $carts;
}
/**
*
*
* These function is for adding the product, when user add product at the card.
*
* @return Total product
*/
public static function totalItems(){
/*Total product added to the cart*/
if(Auth::check()){
$carts = Cart::orWhere('user_id', Auth::id())
->orWhere('ip_address', request()->ip())
->get();
}else{
$carts = Cart::orWhere('ip_address', request()->ip())->get();
}
$total_item = 0;
foreach($carts as $cart){
$total_item += $cart->product_quentity;
}
return $total_item;
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Slider;
use Session;
use Illuminate\Http\Request;
class SliderController extends Controller
{
public function manageSlide(){
$sliders = Slider::latest()->get();/*showing sub-category data with 'category id'*/
return view('admin.slider.manageSlider', compact('sliders'));
}
public function create(){
return view('admin.slider.create');
}
public function addSlider(){
return view('admin.slider.addslider');
}
public function saveSlider(Request $request){
$request->validate([
'title' => 'required|min:5|max:25',
'subtitle' => 'required|min:5|max:25',
'image' => 'required',
'url' => 'required',
'startdate' => 'required',
'enddate' => 'required'
]);
$slider = null;
try{
$image = $request->file('image');
$fileExt = $image->getClientOriginalExtension();
$fileName = date('ymdhis.') . $fileExt;
$image->move(public_path('uploads/slider/'), $fileName);
$slider = Slider::create([
'title' => $request->title,
'subtitle' => $request->subtitle,
'img' => $fileName,
'url' => $request->url,
'startdate' => $request->startdate,
'enddate' => $request->enddate,
]);
}catch(Exception $exception){
$slider = false;
}
if($slider){
Session::flash('message', 'Slider added successfully');
}
return back();
}
public function sliderStatus($id, $status){
$subStatus = Slider::find($id);
$subStatus->status = $status;
$subStatus->save();
return response()->json(['message' => 'Success']);
}
public function editSlider($id){
$subId = Slider::find($id);
$category = Category::orderBy('category_name', 'ASC')->get();
return view('admin.subcategory.editsub', compact('subId', 'category'));
}
public function updateSlider(Request $request){
$request->validate([
'category_id' => 'required',
'subCategory_name' => 'required'
]);
$category = null;
try{
$name = $request->subCategory_name;
$success = Slider::create([
'cat_id' => $request->category_id,
'name' => $name,
'slug' => $this->slugGenerator($request->$name)
]);
}catch(Exception $exception){
$success = false;
}
if($success){
Session::flash('message', 'Sub Category updated successfully');
}
return redirect('/category/sub-category');
}
public function deleteSlide($id){
$deleteSlider = Slider::find($id);
$deleteSlider->delete();
Session::flash('message', 'Slider deleted successfully');
return back();
}
/*Slug Generator to prevent the special carecter*/
public function slugGenerator($string){
$string = str_replace(' ', '-', $string);
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
return strtolower(preg_replace('/-+/', '-', $string));
}
}
<file_sep><?php
namespace App\Http\Controllers\Stripe;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Model\StripeUser;
use Session;
use DB;
class UserController extends Controller
{
public function getLogin(){
return view('stripe.stripeUser.stripeLogin');
}
public function postLogin(Request $request){
$request->validate([
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string'],
]);
$email = $request->email;
$password = md5($request['password']);
$result = DB::table('stripe_users')
->where('email', $email)
->where('password', $password)
->first();
if($result){
/*Checking, if the cart has product or not, if has, it will redirect to the previous link/directory*/
if(Session::has('oldUrl')){
$oldUrl = Session::get('oldUrl');
Session::forget('oldUrl');
return redirect()->to($oldUrl);
}
/*if cart has no item it will redirect to the home page*/
Session::put('name', $result->name);
Session::put('id', $result->id);
return redirect('/stripe-home');
}
Session::flash('error', 'Email or Password is incorrect');
return back();
}
public function stripeLogout(){
Session::flush();
return back();
}
public function userRegister(){
return view('stripe.stripeUser.stripeRegister');
}
public function addUser(Request $request){
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
$user = new StripeUser([
'name' => $request['name'],
'email' => $request['email'],
'password' => md5($request['password']),
]);
$user->save();
/*Checking, if the cart has product or not, if has, it will redirect to the previous link/directory*/
if(Session::has('oldUrl')){
$oldUrl = Session::get('oldUrl');
Session::forget('oldUrl');
return redirect($oldUrl);
}
/*if cart has no item it will redirect to the home page*/
return redirect('/stripe-home');
}
}
<file_sep><?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = ['user_id', 'name', 'ip_address', 'phone_number', 'shipping_address', 'email', 'message', 'is_paid', 'is_completed', 'is_seen',];
public function user(){
return $this->belongsTo(User::class);
}
public function cart(){
return $this->belongsTo(Cart::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\SubCategory;
use App\Category;
use Session;
class SubCategoryController extends Controller
{
public function manageSubCategory(){
$subCat = SubCategory::with('category')->get();/*showing sub-category data with 'category id'*/
return view('admin.subcategory.manageSubCategory', compact('subCat'));
}
public function addSubCategory(){
$category = Category::
where('status', 1)
->orderBy('category_name', 'ASC')/*showing category name from category table*/
->get();
return view('admin.subcategory.addSubCategory', compact('category'));
}
public function saveSubCategory(Request $request){
$request->validate([
'category' => 'required',
'subCategory_name' => 'required'
]);
$subCategory = new SubCategory();
$subCategory->name = $request->subCategory_name;
$subCategory->cat_id = $request->category;
$subCategory->slug = $this->slugGenerator($request->subCategory_name);
$subCategory->save();
Session::flash('message', 'Sub-Category added successfully');
return back();
}
public function subCategoryStatus($id, $status){
$subStatus = SubCategory::find($id);
$subStatus->status = $status;
$subStatus->save();
return response()->json(['message' => 'Success']);
}
public function editSubCategory($id){
$subId = SubCategory::find($id);
$category = Category::orderBy('category_name', 'ASC')->get();
return view('admin.subcategory.editsub', compact('subId', 'category'));
}
public function updateSubCategory(Request $request){
$request->validate([
'category_id' => 'required',
'subCategory_name' => 'required'
]);
$category = null;
try{
$name = $request->subCategory_name;
$success = SubCategory::create([
'cat_id' => $request->category_id,
'name' => $name,
'slug' => $this->slugGenerator($request->$name)
]);
}catch(Exception $exception){
$success = false;
}
if($success){
Session::flash('message', 'Sub Category updated successfully');
}
return redirect('/category/sub-category');
}
public function deleteSubCategory($id){
$deleteSubCate = SubCategory::find($id);
$deleteSubCate->delete();
Session::flash('message', 'Sub Category deleted successfully');
return back();
}
/*Slug Generator to prevent the special carecter*/
public function slugGenerator($string){
$string = str_replace(' ', '-', $string);
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
return strtolower(preg_replace('/-+/', '-', $string));
}
}
<file_sep>/*Updating Brand-Status using ajax*/
$(document).ready(function(){
$('body').on('change', '#brandStatus', function(){
var id = $(this).attr('data-id');
if(this.checked){
var status = 1;
}else{
var status = 0;
}
$.ajax({
url: 'brandStatus/'+id+'/'+status,
method: 'get',
success: function(result){
console.log(result);
}
});
});
/*Updating Category-Status using ajax*/
$('body').on('change', '#categoryStatus', function(){
var id = $(this).attr('data-id');
if(this.checked){
var status = 1;
}else{
var status = 0;
}
$.ajax({
url: 'categoryStatus/'+id+'/'+status,
method: 'get',
success: function(result){
console.log(result);
}
});
});
/*Updating subCategory-Status using ajax*/
$('body').on('change', '#subCategoryStatus', function(){
var id = $(this).attr('data-id');
if(this.checked){
var status = 1;
}else{
var status = 0;
}
$.ajax({
url: 'subCategoryStatus/'+id+'/'+status,
method: 'get',
success: function(result){
console.log(result);
}
});
});
/*Updating Slider-Status using ajax*/
$('body').on('change', '#sliderStatus', function(){
var id = $(this).attr('data-id');
if(this.checked){
var status = 1;
}else{
var status = 0;
}
$.ajax({
url: 'sliderStatus/'+id+'/'+status,
method: 'get',
success: function(result){
console.log(result);
}
});
});
});
/*Delete conformation pop-up*/
$(document).on("click", "#delete", function(e) {
e.preventDefault();
var link = $(this).attr("href");
bootbox.confirm("Are you want to delete permanently!", function(confirmed) {
if(confirmed){
window.location.href = link;
};
});
});<file_sep><?php
namespace App\Http\Controllers\front;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Stripe;
use App\Order;
use App\Cart;
use PDF;
use Auth;
use Session;
class CartController extends Controller
{
public function index(){
return view('frontend.cart.manageCart');
}
public function store(Request $request)
{
if(Auth::check()){
/*if user is loged in then, it will check*/
$cart = Cart::where('user_id', Auth::id())
->where('product_id', $request->product_id)
->first();
}else{
/*if user is not loged in then, check it*/
$cart = Cart::where('ip_address', request()->ip())
->where('product_id', $request->product_id)
->first();
}
if(!is_null($cart)){
/*if there is product at the cart then add another product*/
$cart->increment('product_quentity');
}else{
/*if there is no item at cart then add one product*/
$cart = new Cart();
if( Auth::check() ){
$cart->user_id = Auth::id();
}
}
$cart->ip_address = request()->ip();
$cart->product_id = $request->product_id;
$cart->save();
Session::flash('message', 'Product added successfully');
return back();
}
public function updateCart(Request $request, $id){
$cart = Cart::find($id);
if( !is_null($cart )){
$cart->product_quentity = $request->product_quentity;
$cart->save();
}else{
return redirect('carts');
}
Session::flash('message', 'Product updated successfully');
return back();
}
public function deleteCart($id){
$cart = Cart::find($id);
if( !is_null($cart )){
$cart->delete();
}else{
return redirect('carts');
}
Session::flash('message', 'Cart deleted successfully');
return back();
}
public function checkoutCart(){
return view('frontend.cart.checkout');
}
public function createInvoice(){
$order = Order::where('id', 1)->first();
$pdf = PDF::loadView('frontend.cart.pdfview', compact('order'));
return $pdf->stream('pdfview.pdf');
}
public function manualStripePay(){
Stripe\Stripe::setApiKey('stripe_api_key_would_be_here');
$token = Stripe\Token::create([
'card' => [
'number' => request('card_number'),
'cvc' => request('card_cvc'),
'exp_month' => request('exp_month'),
'exp_year' => request('exp_year')
]
]);
Stripe\Charge::create ( array (
/*"amount" => request('input_amount') * 100,*/
"amount" => 200 * 100,
"currency" => "usd",
"source" => $token['id'], // obtained with Stripe.js
"description" => "Test payment."
) );
Session::flash('success', 'Payment successful!');
return back();
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class SubCategory extends Model
{
protected $fillable = ['cat_id', 'name', 'slug'];
/*Relation to the sub_categories table*/
public function category(){
return $this->belongsTo(Category::class, 'cat_id');
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Slider;
class SlidersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker\Factory::create();
foreach(range(1, 7) as $index){
$slider = $faker->name;
Slider::create([
'title' => $faker->sentence,
'subtitle' => $faker->paragraph,
'img' => $faker->imageUrl(),
'url' => $faker->imageUrl(),
'startdate' => $faker->date(),
'enddate' => $faker->date(),
'status' => rand(0, 1)
]);
}
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Brand;
class BrandsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker\Factory::create();
foreach(range(1, 10) as $index){
Brand::create([
'brad_name' => $faker->name,
'brand_status' => rand(0, 1),
'brand_slugs' => $faker->slug
]);
}
}
}
| 8e770b73638ade2e1bb2057f7cdd86f96fbd08ae | [
"JavaScript",
"PHP"
] | 25 | PHP | mdashikul798/Laravel-multiple-projects | 638645e79755870f84d333681ecd6a54d8727f8c | 3002c9090d9b3ecdb125433c1a308d9df4895bc8 |
refs/heads/master | <file_sep>package Product_Activation_Queue;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AccessExcel
{
private static final String screenshotpath = new File(System.getProperty("user.dir")).getParent() + "\\Results\\";
WebElement element = null;
String req = null;
public static WebDriverWait wait;
int checkcount,total = 0;
int count, countfordp,countfordpstarting, logicdp =0;
String prdctName,status;
static int exitqueue,firstTime= 0;
readingZPL_File read = new readingZPL_File();
ArrayList<String> queueCheck = new ArrayList<String>();
public WebElement getElement(WebDriver driver,Map<String, String> objects,Logger logger) throws InterruptedException
{
String selectorType = objects.get("Selectortype");
String selector = objects.get("Selector");
String conditions = objects.get("Conditions");
String keyboard = objects.get("Keyboard");
String functions = objects.get("Functions");
String date = date();
int time=0;
if(objects.get("Time")!="")
{
time = Integer.parseInt(objects.get("Time"));
}
String wait = objects.get("Wait");
try
{
if(selectorType.equals("xpath")&& conditions.isEmpty() && keyboard.isEmpty() && functions.isEmpty())
{
element = driver.findElement(By.xpath(selector));
}
else if(selectorType.equals("xpath")&& wait.contains("wait") && functions.isEmpty())
{
eWait(driver, conditions, selector, time);
}
else if(selectorType.equals("xpath")&& keyboard.contains("k_enter"))
{
Thread.sleep(3000);
driver.findElement(By.xpath(selector)).sendKeys(Keys.ENTER);
}
else if(selectorType.equals("xpath")&& keyboard.contains("k_down"))
{
Thread.sleep(3000);
driver.findElement(By.xpath(selector)).sendKeys(Keys.DOWN);
}
else if(selectorType.equals("xpath")&& keyboard.contains("k_backspace"))
{
Thread.sleep(3000);
driver.findElement(By.xpath(selector)).sendKeys(Keys.BACK_SPACE);
}
else if(selectorType.equals("xpath")&& keyboard.contains("k_cntrl_A"))
{
Thread.sleep(3000);
driver.findElement(By.xpath(selector)).sendKeys(Keys.chord(Keys.CONTROL,"a"));
}
else if(selectorType.equals("xpath") && functions.contains("is"))
{
checkbox_Checking(driver,selectorType, selector,objects, logger);
}
else if(selectorType.equals("id"))
{
element = driver.findElement(By.id(selector));
}
else if(selectorType.equals("xpath") && functions.equals("WaitForQueue"))
{
logger.info("Sleeping for 3 minutes.");
Thread.sleep(180000);
logger.info("Sleep Time Over.");
}
else if(selectorType.equals("Screenshot"))
{
captureScreenshot(driver,objects,date,logger);
}
else if (selectorType.equals("") || !functions.isEmpty())
{
}
else
{
System.out.println("invalid selector");
logger.info("invalid selector Provided");
}
}
catch(Exception e)
{
read.createErrorFile(driver, logger);
logger.error("An Exception has occured in getElement method --> "+e.toString());
driver.quit();
System.exit(0);
}
return element;
}
public void doAction(WebDriver driver,WebElement element,Map<String, String> objects,String productname2,String getGroupname, Logger logger) throws InterruptedException, IOException
{
String action = objects.get("Action");
String input = objects.get("Input");
String selector = objects.get("Selector");
String key_function = objects.get("Functions");
List<String> tcdetails = new ArrayList<String>();
tcdetails = read.readTCDetailsFile(driver, logger);
String zplno = tcdetails.get(1).toUpperCase();
String grpname = getGroupname;
try
{
if(action.equals("click"))
{
try
{
element.click();
Thread.sleep(2000);
infoLog(objects, logger);
}
catch (InterruptedException e)
{
e.printStackTrace();
logger.info("Exception occur in do_action method, in Click action");
driver.quit();
System.exit(0);
}
}
else if(action.equals("sendkeys"))
{
element.sendKeys(input);
infoLog(objects, logger);
}
else if(action.equals("sendkeysfordrpdown"))
{
Thread.sleep(3000);
element.sendKeys(input);
}
else if(action.contentEquals("ZPLNO"))
{
element.sendKeys(zplno);
infoLog(objects, logger);
}
else if(action.contentEquals("GroupName"))
{
element.sendKeys(grpname);
}
else if(action.contentEquals("ProductName"))
{
element.sendKeys(productname2);
}
else if(action.equals("compare"))
{
WebDriverWait wait1 = new WebDriverWait(driver, 30);
wait1.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(".//*[@id='aw-console']/div[3]/div[2]")));
boolean TxtBoxContent = IsRequiredTextPresent(driver,selector);
if(TxtBoxContent==false)
{
read.createErrorFile(driver, logger);
logger.info("ZPL number Already Exists !!!!!");
logger.info("Terminating the script!!!!");
driver.quit();
System.exit(0);
}
}
else if(action.equals("Alert"))
{
boolean popupdlg = IsPopupDialogPresent(driver,selector);
if(popupdlg==true)
{
element.click();
}
infoLog(objects, logger);
logger.info(" Popup dialog Appearence in the Airwatch Console ==> "+popupdlg);
}
else if(action.equals("hover"))
{
Thread.sleep(2000);
//action1.moveToElement(element).build().perform();
}
else if(action.equals("getTextBoxValue"))
{
String getTextBoxvalue = element.getText();
getTextBoxvalue.trim();
logger.info("Added ZPL is find in the Group =>"+getTextBoxvalue);
if(getTextBoxvalue.contains(zplno))
{
logger.info("Checking whether Zpl is added or not in Group,ZPL is matching in the console");
}
else
{
logger.info("Checking whether Zpl is added or not in Group,ZPL is not matching in the console");
logger.info("Terminating the Program..");
driver.quit();
System.exit(0);
}
}
else if(action.equals("ProductQueueCheck"))
{
String getTextvalue = element.getText();
getTextvalue.trim();
queueCheck.add(getTextvalue);
}
else if(key_function.equals("setdropdown"))
{
dynamicDropdown(driver, selector, action, input, zplno, logger);
}
else if(key_function.equals("CheckQueue"))
{
exitqueue++;
checkingQueued_Product(driver,productname2,exitqueue,queueCheck,getGroupname,logger);
}
else if(key_function.equals("isNewProduct"))
{
infoLog(objects, logger);
if(driver.findElement(By.xpath(".//*[@id='addRule']/input")).isDisplayed())
{
logger.info("It is New Product Clicking Add Rules.");
driver.findElement(By.xpath(".//*[@id='addRule']/input")).click();
}
else if(driver.findElement(By.xpath("//a[@class='edit-rules']")).isDisplayed())
{
logger.info("It is Existing Product Clicking Edit Rules.");
driver.findElement(By.xpath("//a[@class='edit-rules']")).click();
}
}
else if(action.isEmpty())
{
}
else
{
System.out.println("invalid action");
}
}
catch(Exception e)
{
read.createErrorFile(driver, logger);
logger.error("An Exception has occured in doAction method --> "+e.toString());
driver.quit();
System.exit(0);
}
}
public boolean IsRequiredTextPresent(WebDriver driver,String selector)
{
try
{
driver.findElement(By.xpath(selector));
return true;
}
catch (Exception e)
{
return false;
}
}
public boolean IsPopupDialogPresent(WebDriver driver, String selector)
{
try
{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("selector"));
return true;
}
catch (Exception e)
{
return false;
}
}
public void checkbox_Checking(WebDriver driver,String selectorType,String selector,Map<String, String> objects,Logger logger)
{
String func = objects.get("Functions");
String doEnable = objects.get("Functions_do");
try
{
if(func.contentEquals("ischecked"))
{
Thread.sleep(2000);
boolean checkstatus = driver.findElement(By.xpath(selector)).isSelected();
if(doEnable.contains("uncheck") && checkstatus!=false)
{
driver.findElement(By.xpath(selector)).click();
}
else if(doEnable.contentEquals("check") && checkstatus!=true)
{
driver.findElement(By.xpath(selector)).click();
}
else
{
}
}
}
catch(Exception e)
{
logger.error("There is some problem in ischeckvalue method --> \n"+e.toString());
}
}
public void dynamicDropdown(WebDriver driver,String selector,String action,String input,String zplno,Logger logger)
{
try
{
if(count<1)
{
List<WebElement> xpath = driver.findElements(By.xpath(selector));
countfordpstarting =xpath.size();
countfordp = countfordpstarting * 2;
List<WebElement> xpath1 = driver.findElements(By.xpath("//select[@data-property='LogicalOperator']"));
logicdp = xpath1.size();
logicdp = countfordp - 1;
}
if((action.contains("Logic")) && (countfordpstarting > 0))
{
driver.findElement(By.xpath("//a[@class='add icon logicalOperator']")).click();
logger.info("Add Logical Operator is Clicked.");
if(logicdp > 1)
{
driver.findElement(By.xpath(".//*[@id='Rule_Steps["+logicdp+"]_LogicalOperator']")).sendKeys(input);
}
else
{
driver.findElement(By.xpath(".//*[@id='Rule_Steps[1]_LogicalOperator']")).sendKeys(input);
}
}
else if(action.contains("Rule"))
{
driver.findElement(By.xpath("//a[@class='add icon ruleStatement']")).click();
logger.info("Add Rule Button is Clicked.");
}
if(!(countfordpstarting >= 1))
{
countfordp = 0;
}
Thread.sleep(1000);
if(action.contains("Attribute"))
{
driver.findElement(By.xpath(".//*[@id='Rule_Steps["+ countfordp+"]_AttributeId']")).sendKeys(input);
Thread.sleep(2000);
}
else if(action.contains("Operator"))
{
driver.findElement(By.xpath(".//*[@id='Rule_Steps["+ countfordp+"]_Operator']")).sendKeys("=");
}
else if(action.contains("Value"))
{
driver.findElement(By.xpath("//select[@id='Rule_Steps["+ countfordp +"]_Value']")).click();
driver.findElement(By.xpath("//select[@id='Rule_Steps["+ countfordp +"]_Value']")).sendKeys(zplno);
driver.findElement(By.xpath("//select[@id='Rule_Steps["+ countfordp +"]_Value']")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
Select sel = new Select(driver.findElement(By.xpath("//select[@id='Rule_Steps["+ countfordp +"]_Value']")));
WebElement option = sel.getFirstSelectedOption();
String zplcompare = option.getText().trim();
if(zplcompare.contentEquals(zplno))
{
logger.info("Right ZPL is entered into the Edit rules in Product Activation");
}
else
{
logger.info("Right ZPL is not entered into the Edit rules in Product Activation");
read.createErrorFile(driver, logger);
driver.quit();
System.exit(0);
}
}
count++;
}
catch (Exception e)
{
read.createErrorFile(driver, logger);
logger.info("Problem ocuurs in dynamicDropdown function");
logger.info("program is terminating...");
driver.quit();
System.exit(0);
}
}
public void checkingQueued_Product(WebDriver driver,String productname,int exitqueue,ArrayList<String> queueCheck,String getGroupname, Logger logger) throws IOException
{
try
{
MasterRun run = new MasterRun();
logger.info("Checking for queued Product...");
prdctName = queueCheck.get(0).toLowerCase();
status = queueCheck.get(1);
logger.info("ProductName "+prdctName);
logger.info("Stauts For Queue is "+ status);
if (prdctName.contentEquals(productname.toLowerCase()) && status.contentEquals("Queued"))
{
total = 1;
read.createSuccessFile(driver, logger);
logger.info("Succesfully the product is queued and Succes Text file is created...");
}
if(total!=1)
{
logger.info("Product Queued is not found, Reactivating the Product.");
run.reactivationExcel(driver,productname,getGroupname,logger);
}
if(exitqueue > 3)
{
read.createErrorFile(driver, logger);
logger.info("Queue Product is checked "+ exitqueue + " Times in console, but it is not queued...");
logger.info("Error Txt file is created.");
logger.info("Program is Terminating...");
driver.quit();
System.exit(0);
}
}
catch(Exception e)
{
read.createErrorFile(driver, logger);
logger.info("Error in checkingQueued_Product method");
driver.quit();
System.exit(0);
}
}
public void eWait(WebDriver driver,String conditions, String selector, int time)
{
wait = new WebDriverWait(driver, time);
if(conditions.equals("vElement"))
{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(selector)));
}
else if(conditions.equals("ivElement"))
{
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(selector)));
}
else
{
System.out.println("Invalid wait condition");
}
}
public void captureScreenshot(WebDriver driver, Map<String, String> objects, String time,Logger logger)
{
try
{
List<String> testcaseid = read.readTCDetailsFile(driver, logger);
String tcID = testcaseid.get(0)+"_Results";
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File(screenshotpath+"\\"+tcID+"/"+"Screen_"+time+".png"));
}
catch (IOException e)
{
read.createErrorFile(driver, logger);
logger.error("There is some problem in Screen Capturing --> \n"+e.toString());
driver.quit();
System.exit(0);
}
}
public void infoLog(Map<String, String> objects,Logger logger)
{
String infoLog = objects.get("LoggerInfo");
if(!infoLog.isEmpty())
{
logger.info(infoLog);
}
}
public static String date()
{
DateFormat dateFormat = new SimpleDateFormat("hh_mm_ss");
Date now = new Date();
String nms_date = dateFormat.format(now);
return nms_date;
}
@Override
public String toString()
{
return "accessExcel []";
}
}
| aba85219519138afa87e2382d06e85781ff61861 | [
"Java"
] | 1 | Java | BalaKrishnanVPM/ProductActivation | 753bcbe53c741b01798762d6e15910182cb75517 | d5dbbeb796414874eb20f3724472ee35b7c905ee |
refs/heads/master | <repo_name>makbn/Image_Tagging_apis<file_sep>/src/main/java/Constant.java
/**
* Created by white on 2016-11-27.
*/
public class Constant {
public static final String SAMPLE_IMAGE="http://www.prateekgroup.com/images/grand-city-sample-flats-z2.jpg";
public static final String CLARIFAI_CLIENT_ID="gIPRQFYUEfxaGeDcOiTyf1cmtfE62KUQpVFxHhnM";
public static final String CLARIFAI_CLIENT_SECRET="<KEY>";
public static final String IMAGGA_CLIENT_ID="acc_2a0e5eaa3d8e35a";
public static final String IMAGGA_CLIENT_SECRET="0862a0c826987f168f0e0d5b596cc2c8";
public static final String EIGHTBIT_APIKEY="<KEY>";
public static final String CLOUDINARY_APIKEY="149862837211897";
public static final String CLOUDINARY_SECRETKEY="<KEY>";
public static final String CLOUDINARY_CLOUDNAME="mehdiakbn";
}
<file_sep>/src/main/java/UploadHandler.java
import com.cloudinary.Cloudinary;
import com.cloudinary.utils.ObjectUtils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* Created by white on 2016-12-19.
*/
public class UploadHandler {
private static UploadHandler mUploadHandler;
private static Cloudinary cloudinary;
private static Thread t;
private static Runnable r;
private UploadHandler(){
cloudinary=new Cloudinary(ObjectUtils.asMap(
"cloud_name", Constant.CLOUDINARY_CLOUDNAME,
"api_key", Constant.CLOUDINARY_APIKEY,
"api_secret", Constant.CLOUDINARY_SECRETKEY));
}
public static UploadHandler getInstance(){
if(mUploadHandler==null)
mUploadHandler=new UploadHandler();
return mUploadHandler;
}
public void asyncSingleUpload(final File file , final ResponseHandler responseHandler){
r=new Runnable() {
public void run() {
Map map=upload(file);
responseHandler.onUploadResponse(file.getName(),(String)map.get("url"));
}
};
t=new Thread(r);
t.start();
}
public Map upload(File file){
Map uploadResult=null;
try {
uploadResult = cloudinary.uploader().upload(file, ObjectUtils.emptyMap());
} catch (IOException e) {
e.printStackTrace();
}
return uploadResult;
}
public void asyncBatchUpload(final File dir,final ResponseHandler responseHandler) throws Exception {
if(dir.isDirectory()) {
for (File f:dir.listFiles()){
if(f.exists() && !f.isDirectory() && f.canRead()){
asyncSingleUpload(f,responseHandler);
}
}
}else {
throw new Exception("Direcotry?Directory NAMANA!");
}
}
}
| 55abd0d17ff8ddd3ea0567d5db8a10034181b828 | [
"Java"
] | 2 | Java | makbn/Image_Tagging_apis | ecdf717b0c5e11f895e0c24dee93ec6fc61250da | e4069352c319da0eb193524eeeeff90f54e0ce16 |
refs/heads/master | <repo_name>jgh0721/unarkwcx<file_sep>/dllmain.cpp
// dllmain.cpp : DLL 응용 프로그램의 진입점을 정의합니다.
#include "stdafx.h"
#include "ArkLib.h"
#include "UnArkWCX.h"
HINSTANCE g_hInst;
WCHAR gArkDLLFullPathName[ MAX_PATH ] = {0,};
WCHAR gCurrentArchiveExtension[ 32 ] = {0,};
WCHAR gConfigureINIFullPath[ MAX_PATH ] = {0,};
CArkEvent gClsArkEvent;
BOOL isInitLogger = FALSE;
SArkCompressorOpt gArkCompressorOpt;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_hInst = hModule;
GetModuleFileNameW( g_hInst, gArkDLLFullPathName, MAX_PATH );
PathRemoveFileSpecW( gArkDLLFullPathName );
PathAppendW( gArkDLLFullPathName, ARK_DLL_RELEASE_FILE_NAME );
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
void InitLogger()
{
#ifndef UNARKWCX_DEPLOY
if( isInitLogger == FALSE )
{
LM_INSTANCE()->SetLogLevel( LL_TRACE );
LM_INSTANCE()->SetLogTransfer( LT_DEBUGGER );
LM_INSTANCE()->SetLogPrefix( L"[%D-%t, %l, %F-%L] " );
}
#endif
}
<file_sep>/UnArkWCX_Test/UnArkWCX_Test_Util.cpp
#include "stdafx.h"
#include <iostream>
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi" )
#include "UnArkWCX_Test_Util.h"
#include "../UnArkWCX_Export.h"
#pragma warning( disable: 4996 )
std::wstring GetCurrentPath()
{
wchar_t wszBuffer[ MAX_PATH ] = {0,};
GetModuleFileName( NULL, wszBuffer, MAX_PATH - 1 );
PathRemoveFileSpec( wszBuffer );
return wszBuffer;
}
void SetDefaultPackerExtension( const wchar_t* wszExtension )
{
WritePrivateProfileString( CONFIGURE_INI_SECNAME, CONFIGURE_SELECT_EXTENSION, wszExtension, (GetCurrentPath() + L"\\" + CONFIGURE_INI_FILENAME).c_str() );
WritePrivateProfileString( NULL, NULL, NULL, NULL );
}
void SetINIFilePath( pFnPackSetDefaultParams pfnPackSetDefaultParams )
{
PackDefaultParamStruct dps;
memset( dps.DefaultIniName, '\0', sizeof( char ) * MAX_PATH );
dps.size = sizeof( dps );
strcpy( dps.DefaultIniName, CU2A( GetCurrentPath() + L"\\" + CONFIGURE_INI_FILENAME ).c_str() );
pfnPackSetDefaultParams( &dps );
}
wchar_t* GetAddList( const std::vector< std::wstring >& vecAddedFile, const std::wstring& strSubPath )
{
wchar_t* pwszBuffer = NULL;
wchar_t* pwszAddList = NULL;
do
{
int nAddListLength = 0;
for( size_t idx = 0; idx < vecAddedFile.size(); ++idx )
{
nAddListLength += vecAddedFile[ idx ].size();
nAddListLength += strSubPath.size();
nAddListLength += 1; // NULL 문자
}
nAddListLength += 1; // 문자열 목록 종료를 알리기 위한 널 문자 추가
pwszAddList = new wchar_t[ nAddListLength ];
if( pwszAddList == NULL )
break;
ZeroMemory( pwszAddList, sizeof( wchar_t ) * nAddListLength );
pwszBuffer = pwszAddList;
for( size_t idx = 0; idx < vecAddedFile.size(); ++idx )
{
if( strSubPath.empty() == false )
wcscpy( pwszBuffer, strSubPath.c_str() );
wcscpy( pwszBuffer, vecAddedFile[ idx ].c_str() );
pwszBuffer = pwszBuffer + wcslen( pwszBuffer ) + 1;
}
} while (false);
return pwszAddList;
}
<file_sep>/UnArkWCX_Test/UnArkWCX_Test.cpp
// UnArkWCX_Test.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//
#include "stdafx.h"
#include "../Library/gtest/gtest.h"
#include "UnArkWCX_Test.h"
#if _MSC_VER == 1600
#ifdef _WIN64
#ifdef _DEBUG
#pragma comment( lib, "gtest-v100-x64-d" )
#else
#pragma comment( lib, "gtest-v100-x64-r" )
#endif
#else
#ifdef _DEBUG
#pragma comment( lib, "gtest-v100-x86-d" )
#else
#pragma comment( lib, "gtest-v100-x86-r" )
#endif
#endif
#elif _MSC_VER == 1500
#ifdef _WIN64
#ifdef _DEBUG
#pragma comment( lib, "gtest-v90-x64-d" )
#else
#pragma comment( lib, "gtest-v90-x64-r" )
#endif
#else
#ifdef _DEBUG
#pragma comment( lib, "gtest-v90-x86-d" )
#else
#pragma comment( lib, "gtest-v90-x86-r" )
#endif
#endif
#endif
int _tmain(int argc, _TCHAR* argv[])
{
/*!
각 함수들이 EXPORT 되었는지 확인
*/
testing::InitGoogleTest( &argc, argv );
testing::AddGlobalTestEnvironment( new CEnvironment );
return RUN_ALL_TESTS();
}
int WINAPI ArchiveTest::processDataProcW( WCHAR *FileName, int Size )
{
return 1;
}
int WINAPI ArchiveTest::changeVolProcW( WCHAR *ArcName, int Mode )
{
return 1;
}
<file_sep>/UnArkWCX_Export.h
#pragma once
#include "wcxhead.h"
#include "ArkLib.h"
// 다음 ifdef 블록은 DLL에서 내보내기하는 작업을 쉽게 해 주는 매크로를 만드는
// 표준 방식입니다. 이 DLL에 들어 있는 파일은 모두 명령줄에 정의된 _EXPORTS 기호로
// 컴파일되며, 동일한 DLL을 사용하는 다른 프로젝트에서는 이 기호를 정의할 수 없습니다.
// 이렇게 하면 소스 파일에 이 파일이 들어 있는 다른 모든 프로젝트에서는
// UNARKWCX_API 함수를 DLL에서 가져오는 것으로 보고, 이 DLL은
// 이 DLL은 해당 매크로로 정의된 기호가 내보내지는 것으로 봅니다.
#ifdef UNARKWCX_EXPORTS
#define UNARKWCX_API __declspec(dllexport)
#else
#define UNARKWCX_API __declspec(dllimport)
#endif
const wchar_t* const CONFIGURE_INI_FILENAME = L"pkplugin.INI";
const wchar_t* const CONFIGURE_INI_SECNAME = L"UnArkWCX";
const wchar_t* const CONFIGURE_SELECT_EXTENSION = L"SelectArchiveExtension";
const wchar_t* const CONFIGURE_SaveNTFSTimeForZIP = L"SaveNTFSTimeForZIP";
const wchar_t* const CONFIGURE_CompressionMerhod = L"compressionMethod";
const wchar_t* const CONFIGURE_CompressionLevel = L"compressionLevel";
/*!
OpenArchive should perform all necessary operations when an archive is to be opened.
HANDLE __stdcall OpenArchive (tOpenArchiveData *ArchiveData);
Description
OpenArchive should return a unique handle representing the archive. The handle should remain valid until CloseArchive is called. If an error occurs, you should return zero, and specify the error by setting OpenResult member of ArchiveData.
You can use the ArchiveData to query information about the archive being open, and store the information in ArchiveData to some location that can be accessed via the handle.
*/
EXTERN_C UNARKWCX_API HANDLE WINAPI OpenArchive( tOpenArchiveData *pArchiveData );
EXTERN_C UNARKWCX_API HANDLE WINAPI OpenArchiveW( tOpenArchiveDataW *pArchiveData );
EXTERN_C UNARKWCX_API int WINAPI ReadHeader( HANDLE hArcData, tHeaderData *pHeaderData );
/*!
Totalcmd calls ReadHeaderEx to find out what files are in the archive. This function is always called instead of ReadHeader if it is present. It only needs to be implemented if the supported archive type may contain files >2 GB. You should implement both ReadHeader and ReadHeaderEx in this case, for compatibility with older versions of Total Commander.
int __stdcall ReadHeaderEx (HANDLE hArcData, tHeaderDataEx *HeaderDataEx);
Description
ReadHeaderEx is called as long as it returns zero (as long as the previous call to this function returned zero). Each time it is called, HeaderDataEx is supposed to provide Totalcmd with information about the next file contained in the archive. When all files in the archive have been returned, ReadHeaderEx should return E_END_ARCHIVE which will prevent ReaderHeaderEx from being called again. If an error occurs, ReadHeaderEx should return one of the error values or 0 for no error.
hArcData contains the handle returned by OpenArchive. The programmer is encouraged to store other information in the location that can be accessed via this handle. For example, you may want to store the position in the archive when returning files information in ReadHeaderEx.
In short, you are supposed to set at least PackSize, PackSizeHigh, UnpSize, UnpSizeHigh, FileTime, and FileName members of tHeaderDataEx. Totalcmd will use this information to display content of the archive when the archive is viewed as a directory.
*/
EXTERN_C UNARKWCX_API int WINAPI ReadHeaderExW( HANDLE hArcData, tHeaderDataExW *pHeaderDataExW );
/*!
ProcessFile should unpack the specified file or test the integrity of the archive.
int __stdcall ProcessFile (HANDLE hArcData, int Operation, char *DestPath, char *DestName);
Description
ProcessFile should return zero on success, or one of the error values otherwise.
hArcData contains the handle previously returned by you in OpenArchive. Using this, you should be able to find out information (such as the archive filename) that you need for extracting files from the archive.
Unlike PackFiles, ProcessFile is passed only one filename. Either DestName contains the full path and file name and DestPath is NULL, or DestName contains only the file name and DestPath the file path. This is done for compatibility with unrar.dll.
When Total Commander first opens an archive, it scans all file names with OpenMode==PK_OM_LIST, so ReadHeader() is called in a loop with calling ProcessFile(...,PK_SKIP,...). When the user has selected some files and started to decompress them, Total Commander again calls ReadHeader() in a loop. For each file which is to be extracted, Total Commander calls ProcessFile() with Operation==PK_EXTRACT immediately after the ReadHeader() call for this file. If the file needs to be skipped, it calls it with Operation==PK_SKIP.
Each time DestName is set to contain the filename to be extracted, tested, or skipped. To find out what operation out of these last three you should apply to the current file within the archive, Operation is set to one of the following:
Constant Value Description
PK_SKIP 0 Skip this file
PK_TEST 1 Test file integrity
PK_EXTRACT 2 Extract to disk
*/
EXTERN_C UNARKWCX_API int WINAPI ProcessFile( HANDLE hArcData, int Operation, char *DestPath, char *DestName);
EXTERN_C UNARKWCX_API int WINAPI ProcessFileW( HANDLE hArcData, int Operation, WCHAR* pwszDestPath, WCHAR* pwszDestName );
/*!
파일을 압축하는 방법
PackFiles specifies what should happen when a user creates, or adds files to the archive.
int __stdcall PackFiles (char *PackedFile, char *SubPath, char *SrcPath, char *AddList, int Flags);
Description
PackFiles should return zero on success, or one of the error values otherwise.
PackedFile refers to the archive that is to be created or modified. The string contains the full path.
SubPath is either NULL, when the files should be packed with the paths given with the file names, or not NULL when they should be placed below the given subdirectory within the archive. Example:
SubPath="subdirectory"Name in AddList="subdir2\filename.ext"-> File should be packed as "subdirectory\subdir2\filename.ext"
SrcPath contains path to the files in AddList. SrcPath and AddList together specify files that are to be packed into PackedFile. Each string in AddList is zero-delimited (ends in zero), and the AddList string ends with an extra zero byte, i.e. there are two zero bytes at the end of AddList.
Flags can contain a combination of the following values reflecting the user choice from within Totalcmd:
Constant Value Description
PK_PACK_MOVE_FILES 1 Delete original after packing
PK_PACK_SAVE_PATHS 2 Save path names of files
PK_PACK_ENCRYPT 4 Ask user for password, then encrypt file with that password
*/
EXTERN_C UNARKWCX_API int WINAPI PackFiles( char* PackedFile, char* SubPath, char* SrcPath, char* AddList, int Flags );
EXTERN_C UNARKWCX_API int WINAPI PackFilesW( wchar_t* PackedFile, wchar_t* SubPath, wchar_t* SrcPath, wchar_t* AddList, int Flags );
EXTERN_C UNARKWCX_API int WINAPI DeleteFiles( char *PackedFile, char *DeleteList );
EXTERN_C UNARKWCX_API int WINAPI DeleteFilesW( wchar_t *PackedFile, wchar_t *DeleteList );
EXTERN_C UNARKWCX_API void WINAPI ConfigurePacker( HWND Parent, HINSTANCE DllInstance );
EXTERN_C UNARKWCX_API int WINAPI CloseArchive( HANDLE hArcData );
EXTERN_C UNARKWCX_API void WINAPI SetChangeVolProc( HANDLE hArcData, tChangeVolProc pfnChangeVolProc );
EXTERN_C UNARKWCX_API void WINAPI SetChangeVolProcW( HANDLE hArcData, tChangeVolProcW pfnChangeVolProc );
EXTERN_C UNARKWCX_API void WINAPI SetProcessDataProc( HANDLE hArcData, tProcessDataProc pfnProcessDataProc );
EXTERN_C UNARKWCX_API void WINAPI SetProcessDataProcW( HANDLE hArcData, tProcessDataProcW pfnProcessDataProc );
EXTERN_C UNARKWCX_API int WINAPI GetPackerCaps();
EXTERN_C UNARKWCX_API BOOL WINAPI CanYouHandleThisFile( char *FileName );
EXTERN_C UNARKWCX_API BOOL WINAPI CanYouHandleThisFileW( WCHAR *FileName );
EXTERN_C UNARKWCX_API void WINAPI PackSetDefaultParams(PackDefaultParamStruct* dps);
typedef HANDLE (WINAPI *pFnOpenArchive)( tOpenArchiveData *pArchiveData );
typedef HANDLE (WINAPI *pFnOpenArchiveW)( tOpenArchiveDataW *pArchiveData );
typedef int (WINAPI *pFnReadHeader)( HANDLE hArcData, tHeaderData *pHeaderData );
typedef int (WINAPI *pFnReadHeaderExW)( HANDLE hArcData, tHeaderDataExW *pArchiveData );
typedef int (WINAPI *pFnProcessFile)( HANDLE hArcData, int Operation, char *DestPath, char *DestName);
typedef int (WINAPI *pFnProcessFileW)( HANDLE hArcData, int Operation, WCHAR* pwszDestPath, WCHAR* pwszDestName );
typedef int (WINAPI *pFnPackFiles)( char* PackedFile, char* SubPath, char* SrcPath, char* AddList, int Flags );
typedef int (WINAPI *pFnPackFilesW)( wchar_t* PackedFile, wchar_t* SubPath, wchar_t* SrcPath, wchar_t* AddList, int Flags );
typedef int (WINAPI *pFnDeleteFiles)( char *PackedFile, char *DeleteList );
typedef int (WINAPI *pFnDeleteFilesW)( wchar_t *PackedFile, wchar_t *DeleteList );
typedef void (WINAPI *pFnConfigurePacker)( HWND Parent, HINSTANCE DllInstance );
typedef int (WINAPI *pFnCloseArchive)( HANDLE hArcData );
typedef void (WINAPI *pFnSetChangeVolProc)( HANDLE hArcData, tChangeVolProc pfnChangeVolProc );
typedef void (WINAPI *pFnSetChangeVolProcW)( HANDLE hArcData, tChangeVolProcW pfnChangeVolProc );
typedef void (WINAPI *pFnSetProcessDataProc)( HANDLE hArcData, tProcessDataProc pfnProcessDataProc );
typedef void (WINAPI *pFnSetProcessDataProcW)( HANDLE hArcData, tProcessDataProcW pfnProcessDataProc );
typedef int (WINAPI *pFnGetPackerCaps)();
typedef BOOL (WINAPI *pFnCanYouHandleThisFile)( char *FileName );
typedef BOOL (WINAPI *pFnCanYouHandleThisFileW)( WCHAR *FileName );
typedef void (WINAPI *pFnPackSetDefaultParams)(PackDefaultParamStruct* dps);
<file_sep>/Library/CommonUtil.cpp
#include "stdafx.h"
#include <intrin.h>
#include "CommonUtil.h"
#include "ConvertStr.h"
#pragma comment( lib, "version.lib" )
const std::locale locEnUs( "English" );
/* 유용한 std::string 에 대한 formatting 함수 */
__inline std::string format_arg_list(const char *fmt, va_list args)
{
if (!fmt) return "";
int result = -1, length = 512;
char *buffer = 0;
while (result == -1) {
if (buffer)
delete [] buffer;
buffer = new char [length + 1];
memset(buffer, 0, (length + 1) * sizeof(char) );
// remove deprecate warning
//result = _vsnprintf(buffer, length, fmt, args);
result = _vsnprintf_s(buffer, length, _TRUNCATE, fmt, args);
length *= 2;
}
std::string s(buffer);
delete [] buffer;
return s;
}
__inline std::wstring format_arg_list(const wchar_t *fmt, va_list args)
{
if (!fmt) return L"";
int result = -1, length = 512;
wchar_t *buffer = 0;
while (result == -1) {
if (buffer)
delete [] buffer;
buffer = new wchar_t [length + 1];
memset(buffer, 0, (length + 1) * sizeof(wchar_t) );
// remove deprecate warning
//result = _vsnprintf(buffer, length, fmt, args);
result = _vsnwprintf_s(buffer, length, _TRUNCATE, fmt, args);
length *= 2;
}
std::wstring s(buffer);
delete [] buffer;
return s;
}
std::string format(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
std::string s = format_arg_list(fmt, args);
va_end(args);
return s;
}
std::wstring format(const wchar_t *fmt, ...)
{
va_list args;
va_start(args, fmt);
std::wstring s = format_arg_list(fmt, args);
va_end(args);
return s;
}
bool IsAlphabet( const std::string& strString )
{
for( std::string::const_iterator iterChar = strString.begin(); iterChar != strString.end(); ++iterChar )
if( isalpha( *iterChar, locEnUs ) == true )
return true;
return false;
}
bool IsAlphabet( const std::wstring& strString )
{
for( std::wstring::const_iterator iterChar = strString.begin(); iterChar != strString.end(); ++iterChar )
if( isalpha( *iterChar, locEnUs ) == true )
return true;
return false;
}
bool IsNumber( const std::string& strString )
{
for( std::string::const_iterator iterChar = strString.begin(); iterChar != strString.end(); ++iterChar )
if( isdigit( *iterChar, locEnUs ) == false )
return false;
return true;
}
bool IsNumber( const std::wstring& strString )
{
for( std::wstring::const_iterator iterChar = strString.begin(); iterChar != strString.end(); ++iterChar )
if( isdigit( *iterChar, locEnUs ) == false )
return false;
return true;
}
bool IsDate( const std::wstring& strString )
{
std::wstring::size_type pos = strString.find( L'-' );
if( pos == std::wstring::npos )
{
if( strString.length() >= wcslen( L"YYYYmmdd" ) )
{
unsigned int nYear = _wtoi( strString.substr( 0, 4 ).c_str() );
unsigned int nMonth = _wtoi( strString.substr( 4, 2 ).c_str() );
unsigned int nDay = _wtoi( strString.substr( 6, 2 ).c_str() );
if( nYear <= 0 || nYear > 3000 )
return false;
if( nMonth <= 0 || nMonth > 12 )
return false;
if( nDay <= 0 || nDay > 31 )
return false;
return true;
}
}
else
{
if( strString.length() >= wcslen( L"YYYY-mm-dd" ) )
{
unsigned int nYear = _wtoi( strString.substr( 0, 4 ).c_str() );
unsigned int nMonth = _wtoi( strString.substr( 5, 2 ).c_str() );
unsigned int nDay = _wtoi( strString.substr( 8, 2 ).c_str() );
if( nYear <= 0 || nYear > 3000 )
return false;
if( nMonth <= 0 || nMonth > 12 )
return false;
if( nDay <= 0 || nDay > 31 )
return false;
return true;
}
}
return false;
}
errno_t CopyAnsiString( char ** pszDest, const char * pszSrc, int srcLength /* = -1 */ )
{
assert( pszSrc != NULL );
assert( *pszDest == NULL );
int nSize = srcLength == -1 ? strlen( pszSrc ) + 1 : srcLength + 1;
*pszDest = new char[ nSize ];
memset( *pszDest, '\0', nSize * sizeof( char ) );
return strcpy_s( *pszDest, nSize, pszSrc );
}
errno_t CopyWideString( wchar_t ** pszDest, const wchar_t * pszSrc, int srcLength /* = -1 */ )
{
assert( pszSrc != NULL );
assert( *pszDest == NULL );
int nSize = srcLength == -1 ? wcslen( pszSrc ) + 1 : srcLength + 1;
*pszDest = new wchar_t[ nSize ];
memset( *pszDest, '\0', nSize * sizeof( wchar_t ) );
return wcscpy_s( *pszDest, nSize, pszSrc );
}
std::string string_replace_all( const std::string& src, const std::string& pattern, const std::string& replace )
{
std::string result = src;
std::string::size_type pos = 0;
std::string::size_type offset = 0;
std::string::size_type pattern_len = pattern.size();
std::string::size_type replace_len = replace.size();
while ( ( pos = result.find( pattern, offset ) ) != std::string::npos )
{
result.replace( result.begin() + pos,
result.begin() + pos + pattern_len,
replace );
offset = pos + replace_len;
}
return result;
}
std::wstring string_replace_all( const std::wstring& src, const std::wstring& pattern, const std::wstring& replace )
{
std::wstring result = src;
std::wstring::size_type pos = 0;
std::wstring::size_type offset = 0;
std::wstring::size_type pattern_len = pattern.size();
std::wstring::size_type replace_len = replace.size();
while ( ( pos = result.find( pattern, offset ) ) != std::wstring::npos )
{
result.replace( result.begin() + pos,
result.begin() + pos + pattern_len,
replace );
offset = pos + replace_len;
}
return result;
}
std::wstring formatElapsedTime( unsigned int elapsedTimeSec, const std::wstring& fmt /*= L"%H 시간 %M 분 %S 초" */ )
{
unsigned int hour = 0;
unsigned int minute = 0;
unsigned int sec = 0;
sec = elapsedTimeSec % 60;
minute = elapsedTimeSec / 60;
if( minute >= 60 )
{
hour = minute / 60;
minute = minute % 60;
}
std::wstring formatText;
if( fmt.find( L"%H" ) == std::wstring::npos )
{
formatText = string_replace_all( formatText, L"%M", format(L"%d", minute + (hour * 60) ) );
}
else
{
formatText = string_replace_all( fmt, L"%H", format(L"%d",hour) );
formatText = string_replace_all( formatText, L"%M", format(L"%d", minute) );
}
formatText = string_replace_all( formatText, L"%S", format(L"%d", sec) );
return formatText;
}
std::wstring GetFormattedDateText( __time64_t tmTime, std::wstring fmt /*= L"%Y-%m-%d" */ )
{
return GetFormattedDateTimeText( tmTime, fmt );
}
std::wstring GetFormattedTimeText( __time64_t tmTime, std::wstring fmt /*= L"%H:%M:%S" */ )
{
return GetFormattedDateTimeText( tmTime, fmt );
}
std::wstring GetFormattedDateTimeText( __time64_t tmTime, std::wstring fmt )
{
WCHAR wszBuffer[ 128 ] = {0,};
struct tm localTime;
errno_t errno_ = localtime_s( &localTime, &tmTime );
if( errno_ != 0 )
return L"";
if( wcsftime( wszBuffer, _countof( wszBuffer ), fmt.c_str(), &localTime ) == 0 )
return L"";
return wszBuffer;
}
std::wstring GetWordsUsingDelimiter( const std::wstring& strMessage, const std::wstring& delimiter )
{
bool isFoundQuote = false;
size_t delimLength = delimiter.size();
std::wstring::size_type startPos = strMessage.find( delimiter );
std::wstring::size_type endPos = std::wstring::npos;
if( startPos == std::wstring::npos )
return L"";
startPos += delimLength;
if( strMessage[ startPos ] == L'\"' )
{
isFoundQuote = true;
startPos++;
}
endPos = strMessage.find( isFoundQuote == false ? L" " : L"\"", startPos + 1 );
if( endPos == std::wstring::npos )
return strMessage.substr( startPos );
return strMessage.substr( startPos, endPos - startPos );
}
int _wcsicmp( const std::wstring& lhs, const std::wstring& rhs )
{
return _wcsicmp( lhs.c_str(), rhs.c_str() );
}
#ifdef _AFX
int _wcsicmp( const CString& lhs, const CString& rhs )
{
return _wcsicmp( lhs.GetString(), rhs.GetString() );
}
#endif
int _wtoi( const std::wstring& lhs )
{
return _wtoi( lhs.c_str() );
}
__int64 _wtoi64( const std::wstring& lhs )
{
return _wtoi64( lhs.c_str() );
}
int u8sicmp( const std::string& lhs, const std::string& rhs )
{
return _wcsicmp( CU82U( lhs ).c_str(), CU82U( rhs ).c_str() );
}
int u8toi( const std::string& lhs )
{
return _wtoi( CU82U( lhs ).c_str() );
}
__int64 u8toi64( const std::string& lhs )
{
return _wtoi64( CU82U( lhs ).c_str() );
}
__time64_t GetTimeValueFromFormat( const std::wstring& dateTimeText, const std::wstring& fmt /*= L"%Y-%m-%d %H:%M:%S" */ )
{
if( dateTimeText.empty() == true || fmt.empty() == true )
return 0;
int nIdx = 0;
struct tm tmDate;
tmDate.tm_year = 0; // 1900 년 이후 흘러간 연도 수
tmDate.tm_mon = 0; // 0 ~ 11 로 나타난 현재 월
tmDate.tm_mday = 1; // 1 ~ 31 로 나타난 현재 일
tmDate.tm_hour = 0; // 0 ~ 23
tmDate.tm_min = 0; // 0 ~ 59
tmDate.tm_sec = 0; // 0 ~ 59
tmDate.tm_wday = 0; // 0 ~ 6, 일주일 표시 0 = Sun
tmDate.tm_yday = 0; // 1월 1일을 0 으로 한 0 ~ 365
tmDate.tm_isdst = 0;
for( std::wstring::size_type nPos = 0; nPos < fmt.size(); ++nPos )
{
switch( fmt[ nPos ] )
{
case L'%':
if( fmt[ nPos + 1 ] == L'Y' )
{
tmDate.tm_year = _wtoi( dateTimeText.substr( nIdx, 4 ) ) - 1900;
nIdx += 3;
++nPos;
}
if( fmt[ nPos + 1 ] == L'm' )
{
tmDate.tm_mon = _wtoi( dateTimeText.substr( nIdx, 2 ) ) - 1;
nIdx += 1;
++nPos;
}
if( fmt[ nPos + 1 ] == L'd' )
{
tmDate.tm_mday = _wtoi( dateTimeText.substr( nIdx, 2 ) );
nIdx += 1;
++nPos;
}
if( fmt[ nPos + 1 ] == L'H' )
{
tmDate.tm_hour = _wtoi( dateTimeText.substr( nIdx, 2 ) );
nIdx += 1;
++nPos;
}
if( fmt[ nPos + 1 ] == L'p' )
{
std::wstring strAM, strPM;
if( strAM.empty() == true && strPM.empty() == true )
{
struct tm tmAM, tmPM;
tmAM.tm_year = 2012 - 1900; // 1900 년 이후 흘러간 연도 수
tmAM.tm_mon = 1; // 0 ~ 11 로 나타난 현재 월
tmAM.tm_mday = 1; // 1 ~ 31 로 나타난 현재 일
tmAM.tm_hour = 1; // 0 ~ 23
tmAM.tm_min = 1; // 0 ~ 59
tmAM.tm_sec = 1; // 0 ~ 59
tmAM.tm_wday = 0; // 0 ~ 6, 일주일 표시 0 = Sun
tmAM.tm_yday = 0; // 1월 1일을 0 으로 한 0 ~ 365
tmAM.tm_isdst = 0;
tmPM = tmAM;
tmPM.tm_hour = 13;
wchar_t szBuffer[ 64 ] = {0,};
wcsftime( szBuffer, 64, L"%p", &tmAM );
strAM = szBuffer;
memset( szBuffer, '\0', sizeof(wchar_t) * 64 );
wcsftime( szBuffer, 64, L"%p", &tmPM );
strPM = szBuffer;
}
if( nIdx + strAM.size() < dateTimeText.size() && strAM.size() > 0 )
{
if( _wcsicmp( dateTimeText.substr( nIdx, strAM.size() ), strAM ) == 0 )
tmDate.tm_hour = tmDate.tm_hour;
}
if( nIdx + strPM.size() < dateTimeText.size() && strPM.size() > 0 )
{
if( _wcsicmp( dateTimeText.substr( nIdx, strPM.size() ), strPM ) == 0 )
tmDate.tm_hour += 12;
}
nIdx += 1;
++nPos;
}
if( fmt[ nPos + 1 ] == L'I' )
{
tmDate.tm_hour += _wtoi( dateTimeText.substr( nIdx, 2 ) );
nIdx += 1;
++nPos;
}
if( fmt[ nPos + 1 ] == L'M' )
{
tmDate.tm_min = _wtoi( dateTimeText.substr( nIdx, 2 ) );
nIdx += 1;
++nPos;
}
if( fmt[ nPos + 1 ] == L'S' )
{
tmDate.tm_sec = _wtoi( dateTimeText.substr( nIdx, 2 ) );
nIdx += 1;
++nPos;
}
default:
nIdx++;
};
}
return _mktime64( &tmDate );
}
unsigned long getULONGFromIPAddress( BYTE lsb, BYTE lsbBy1, BYTE lsbBy2, BYTE lsbBy3 )
{
unsigned long ipaddress = 0;
ipaddress = lsb | ( lsbBy1 << 8 );
ipaddress = ipaddress | ( lsbBy2 << 16 );
ipaddress = ipaddress | ( lsbBy3 << 24 );
return ipaddress;
}
std::string getIPAddressFromULONG( unsigned long ulIPaddress )
{
if( ulIPaddress <= 0 )
"";
in_addr in;
in.S_un.S_addr = ulIPaddress;
return inet_ntoa( in );
}
bool is64BitOS()
{
//Windows 2000 이하의 제품군은 64bit 가 존재 하지 않으므로 무조건 32bit 동작
OSVERSIONINFO osi;
ZeroMemory(&osi, sizeof(osi));
osi.dwOSVersionInfoSize = sizeof(osi);
GetVersionEx(&osi);
if(osi.dwMajorVersion == 4)
return false;
if(osi.dwMajorVersion == 5 && osi.dwMinorVersion == 0 && osi.dwPlatformId == VER_PLATFORM_WIN32_NT)
return false;
BOOL bIsWoW64 = FALSE;
typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
HMODULE hModule = GetModuleHandle(TEXT("kernel32"));
fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress( hModule, "IsWow64Process") ;
if (NULL != fnIsWow64Process)
{
if (!fnIsWow64Process(GetCurrentProcess(),&bIsWoW64))
{
if( hModule )
FreeLibrary( hModule );
return false;
}
}
if( hModule )
FreeLibrary( hModule );
return bIsWoW64 != FALSE ? true : false;
}
std::wstring GetFileInfomation( const std::wstring& filePath, const int selectInfo )
{
if( filePath.empty() == true )
return L"";
std::wstring fileVersion;
struct LANGCODEPAGE
{
WORD wLanguage;
WORD wCodePage;
};
LANGCODEPAGE* lpLang = NULL;
UINT uiTranslate = 0;
UINT dwResultLenth = 0;
TCHAR* pszResult = NULL;
TCHAR* pszVer = NULL;
TCHAR szSub[MAX_PATH];
INT iVerSize = ::GetFileVersionInfoSize( filePath.c_str(), NULL );
if( iVerSize == 0 )
return fileVersion;
pszVer = (TCHAR*)malloc( sizeof(TCHAR) * iVerSize );
memset( pszVer, 0, sizeof( TCHAR ) * iVerSize );
if( ::GetFileVersionInfo( filePath.c_str(), 0, iVerSize, OUT pszVer ) == FALSE )
{
free( pszVer );
return fileVersion;
}
if( ::VerQueryValue( pszVer, L"\\VarFileInfo\\Translation", OUT (LPVOID *)&lpLang, OUT &uiTranslate ) == FALSE )
{
free( pszVer );
return fileVersion;
}
switch ( selectInfo )
{
case 1 :
wsprintf( szSub, L"\\StringFileInfo\\%04x%04x\\ProductVersion", lpLang[0].wLanguage, lpLang[0].wCodePage );
break;
case 2 :
wsprintf( szSub, L"\\StringFileInfo\\%04x%04x\\FileVersion", lpLang[0].wLanguage, lpLang[0].wCodePage );
break;
case 3 :
wsprintf( szSub, L"\\StringFileInfo\\%04x%04x\\Comments", lpLang[0].wLanguage, lpLang[0].wCodePage );
break;
case 4 :
wsprintf( szSub, L"\\StringFileInfo\\%04x%04x\\CompanyName", lpLang[0].wLanguage, lpLang[0].wCodePage );
break;
default :
wsprintf( szSub, L"\\StringFileInfo\\%04x%04x\\FileVersion", lpLang[0].wLanguage, lpLang[0].wCodePage );
break;
}
if( ::VerQueryValue( pszVer, szSub, OUT (LPVOID*)&pszResult, OUT &dwResultLenth ) == FALSE )
{
free( pszVer );
return fileVersion;
}
if (pszResult != NULL)
fileVersion = pszResult;
free( pszVer );
return fileVersion;
}
IMON_DLL_API std::string getCPUBrandString()
{
char CPUString[0x20];
char CPUBrandString[0x40];
int CPUInfo[4] = {-1};
unsigned nExIds, i;
// __cpuid with an InfoType argument of 0 returns the number of
// valid Ids in CPUInfo[0] and the CPU identification string in
// the other three array elements. The CPU identification string is
// not in linear order. The code below arranges the information
// in a human readable form.
__cpuid(CPUInfo, 0);
memset(CPUString, 0, sizeof(CPUString));
*((int*)CPUString) = CPUInfo[1];
*((int*)(CPUString+4)) = CPUInfo[3];
*((int*)(CPUString+8)) = CPUInfo[2];
// Calling __cpuid with 0x80000000 as the InfoType argument
// gets the number of valid extended IDs.
__cpuid(CPUInfo, 0x80000000);
nExIds = CPUInfo[0];
memset(CPUBrandString, 0, sizeof(CPUBrandString));
// Get the information associated with each extended ID.
for (i=0x80000000; i<=nExIds; ++i)
{
__cpuid(CPUInfo, i);
// Interpret CPU brand string and cache information.
if (i == 0x80000002)
memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
else if (i == 0x80000003)
memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
else if (i == 0x80000004)
memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
}
// Display all the information in user-friendly format.
printf_s("\n\nCPU String: %s\n", CPUString);
if( nExIds >= 0x80000004 )
return CPUBrandString;
else
return CPUString;
}
<file_sep>/Library/Ark.h
////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// Ark Library v6
///
/// ※ 만일 컴파일 오류등으로 인해서 이 파일을 수정하여야 하는 경우가 발생할 경우
/// 관련 내용을 꼭 알려주시기 바랍니다.
/// 알려주시면 매번 업데이트마다 사용자님이 헤더파일을 수정하는 불편이 발생하지 않도록
/// 전처리기등을 추가하도록 하겠습니다.
///
/// @author parkkh
/// @date Tuesday, December 22, 2009 9:22:23 AM
///
/// Copyright(C) 2008-2013 Bandisoft, All rights reserved.
///
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _ARK_H_
#define _ARK_H_
// ArkLibrary 버전 (Ark.h 와 ArkXX.dll 파일의 버전이 동일한지 여부 판단용)
#define ARK_LIBRARY_VERSION (0x20130710)
// 에러코드
enum ARKERR
{
ARKERR_NOERR = 0x00,
ARKERR_CANT_OPEN_FILE = 0x01, // 파일 열기 실패
ARKERR_CANT_READ_SIG = 0x02, // signature 읽기 실패
ARKERR_AT_READ_CONTAINER_HEADER = 0x03, // 컨테이너 헤더가 손상되었음
ARKERR_INVALID_FILENAME_LENGTH = 0x04, // 파일명 길이에 문제
ARKERR_READ_FILE_NAME_FAILED = 0x05, // 파일이름 읽기 실패
ARKERR_INVALID_EXTRAFIELD_LENGTH = 0x06, // extra field 읽기
ARKERR_READ_EXTRAFILED_FAILED = 0x07, // extra field 읽기 실패
ARKERR_CANT_READ_CENTRAL_DIRECTORY_STRUCTURE = 0x08, // (zip) Central Directory 정보를 읽는데 실패하였음
ARKERR_INVALID_FILENAME_SIZE = 0x09, // 파일명 길이 정보가 잘못되었음
ARKERR_INVALID_EXTRAFIELD_SIZE = 0x10, // (zip) ExtraField 정보 길이가 잘못되었음
ARKERR_INVALID_FILECOMMENT_SIZE = 0x11, // Comment 정보 길이가 잘못되었음
ARKERR_CANT_READ_CONTAINER_HEADER = 0x12, // 컨테이너의 헤더에 문제가 있음
ARKERR_MEM_ALLOC_FAILED = 0x13, // 메모리 할당 실패
ARKERR_CANT_READ_DATA = 0x15, // 압축 데이타 읽기 실패
ARKERR_INFLATE_FAILED = 0x16, // Inflate 함수 호출중 에러 발생
ARKERR_USER_ABORTED = 0x17, // 사용자 중지
ARKERR_INVALID_FILE_CRC = 0x18, // 압축 해제후 CRC 에러 발생
ARKERR_UNKNOWN_COMPRESSION_METHOD = 0x19, // 모르는(혹은 지원하지 않는) 압축방식
ARKERR_PASSWD_NOT_SET = 0x20, // 암호걸린 파일인데 암호가 지정되지 않았음
ARKERR_INVALID_PASSWD = 0x21, // 암호가 틀렸음
ARKERR_WRITE_FAIL = 0x30, // 파일 쓰다가 실패
ARKERR_CANT_OPEN_DEST_FILE = 0x31, // 대상 파일을 만들 수 없음
ARKERR_BZIP2_ERROR = 0x32, // BZIP2 압축해제중 에러 발생
ARKERR_INVALID_DEST_PATH = 0x33, // 경로명에 ../ 이 포함된 경우, 대상 경로에 접근이 불가능한 경우
ARKERR_CANT_CREATE_FOLDER = 0x34, // 경로 생성 실패
ARKERR_DATA_CORRUPTED = 0x35, // 압축푸는데 데이타가 손상됨 or RAR 분할 압축파일의 뒷부분이 없음
ARKERR_CANT_OPEN_FILE_TO_WRITE = 0x36, // 쓰기용으로 파일 열기 실패
ARKERR_INVALID_INDEX = 0x37, // 압축풀 대상의 index 파라메터가 잘못됨
ARKERR_CANT_READ_CODEC_HEADER = 0x38, // 압축 코덱의 헤더를 읽는데 에러
ARKERR_CANT_INITIALIZE_CODEC = 0x39, // 코덱 초기화 실패
ARKERR_LZMA_ERROR = 0x40, // LZMA 압축 해제중 에러 발생
ARKERR_PPMD_ERROR = 0x41, // ppmd 에러
ARKERR_CANT_SET_OUT_FILE_SIZE = 0x42, // 출력파일의 SetSize() 실패
ARKERR_NOT_MATCH_FILE_SIZE = 0x43, // 압축을 푼 파일 크기가 맞지 않음
ARKERR_NOT_A_FIRST_VOLUME_FILE = 0x44, // 분할 압축파일중 첫번째 파일이 아님
ARKERR_NOT_OPENED = 0x45, // 파일이 열려있지 않음
ARKERR_NOT_SUPPORTED_ENCRYPTION_METHOD = 0x46, // 지원하지 않는 암호 방식
ARKERR_INTERNAL = 0x47, // 내부 에러
ARKERR_NOT_SUPPORTED_FILEFORMAT = 0x48, // 지원하지 않는 파일 포맷
ARKERR_UNKNOWN_FILEFORMAT = 0x49, // 압축파일이 아님
ARKERR_FILENAME_EXCED_RANGE = 0x50, // 경로명이 너무 길어서 파일이나 폴더를 만들 수 없음
ARKERR_LZ_ERROR = 0x52, // lz 에러
ARKERR_NOTIMPL = 0x53, // not implemented
ARKERR_DISK_FULL = 0x54, // 파일 쓰다가 실패
ARKERR_FILE_TRUNCATED = 0x55, // 파일의 뒷부분이 잘렸음
ARKERR_CANT_DO_THAT_WHILE_WORKING = 0x56, // 압축 해제 작업중에는 파일을 열거나 닫을 수 없음
ARKERR_CANNOT_FIND_NEXT_VOLUME = 0x57, // 분할 압축된 파일의 다음 파일을 찾을 수 없음
ARKERR_NOT_ARCHIVE_FILE = 0x58, // 압축파일이 아님 (Open() 호출시 명백히 압축파일이 아닌 경우 발생)
ARKERR_USER_SKIP = 0x59, // 사용자가 건너띄기 했음.
ARKERR_INVALID_PASSWD_OR_BROKEN_ARCHIVE = 0x60, // 암호가 틀리거나 파일이 손상되었음 (rar 포맷)
ARKERR_ZIP_LAST_VOL_ONLY = 0x61, // 분할 zip 인데 마지막 zip 파일만 열려고 했음
ARKERR_ACCESS_DENIED_TO_DEST_PATH = 0x62, // 대상 폴더에 대해서 쓰기 권한이 없음
ARKERR_NOT_ENOUGH_MEMORY = 0x63, // 메모리가 부족함
ARKERR_NOT_ENOUGH_MEMORY_LZMA_ENCODE = 0x64, // LZMA 압축중 메모리가 부족함
ARKERR_CANT_OPEN_SHARING_VIOLATION = 0x65, // 파일이 잠겨있어서 열 수 없음 (ERROR_SHARING_VIOLATION, WIN32 전용)
ARKERR_CANT_OPEN_ERROR_LOCK_VIOLATION = 0x66, // 파일이 잠겨있어서 열 수 없음 (ERROR_LOCK_VIOLATION, WIN32 전용)
ARKERR_CANT_LOAD_UNACE = 0x67, // unace32.exe 혹은 unacev2.dll 파일을 로드할 수 없음 (WIN32 전용)
ARKERR_NOT_SUPPORTED_OPERATION = 0x68, // 지원하지 않는 작동입니다. (ACE 파일을 IArkSimpleOutStream 를 이용해 압축해제할 경우 발생)
ARKERR_CANT_CONVERT_FILENAME = 0x69, // 파일명이 잘못되어서 유니코드 파일명으로 바꿀 수 없음(posix 환경에서 iconv 사용시 코드페이지가 잘못된 경우 사용할 수 없는 문자 때문에 발생)
ARKERR_TOO_LONG_FILE_NAME = 0x70, // 파일명이 너무 길어서 처리할 수 없음
ARKERR_TOO_LONG_FILE_NAME_AND_TRUNCATED = 0x71, // 파일명이 너무 길어서 뒷부분이 잘렸습니다.
ARKERR_TOO_MANY_FILE_COUNT = 0x72, // 파일 갯수가 너무 길어서 처리할 수 없음
ARKERR_CORRUPTED_FILE = 0x100, // 파일이 손상되었음
ARKERR_INVALID_FILE = 0x101, // 포맷이 다르다
ARKERR_CANT_READ_FILE = 0x102, // 파일을 읽을 수 없음
ARKERR_INVALID_VERSION = 0x200, // 헤더파일과 dll 의 버전이 맞지 않음
ARKERR_ENCRYPTED_BOND_FILE = 0x201, // 압축 해제 불가(암호화된 bond 파일임)
ARKERR_7ZERR_BROKEN_ARCHIVE = 0x300, // 7z.dll 으로 열때 에러가 발생(깨진파일)
ARKERR_LOAD_7Z_DLL_FAILED = 0x301, // 7z.dll 열다가 에러 발생
ARKERR_CANT_CREATE_FILE = 0x401, // 파일을 쓰기용으로 생성하지 못함
ARKERR_INIT_NOT_CALLED = 0x402, // Init() 함수가 호출되지 않았음
ARKERR_INVALID_PARAM = 0x403, // 잘못된 파라메터로 호출하였음
ARKERR_CANT_OPEN_INPUT_SFX = 0x404, // SFX 파일을 열지 못함
ARKERR_SFX_SIZE_OVER_4GB = 0x405, // SFX 파일의 크기가 4GB를 넘었음
ARKERR_CANT_LOAD_ARKLGPL = 0x406, // ArkXXLgpl.dll 파일을 열지 못함
ARKERR_CANT_STORE_FILE_SIZE_OVER_4GB = 0x407, // 파일 크기가 4GB를 넘어서 저장할 수 없음
ARKERR_ALREADY_DLL_CREATED = 0x902, // (CArkLib) 이미 ARK DLL 파일을 로드하였음
ARKERR_LOADLIBRARY_FAILED = 0x903, // (CArkLib) LoadLibrary() 호출 실패
ARKERR_GETPROCADDRESS_FAILED = 0x904, // (CArkLib) GetProcAddress() 호출 실패
ARKERR_UNSUPPORTED_OS = 0x905, // (CArkLib) 지원하지 않는 os
ARKERR_LIBRARY_NOT_LOADED = 0x906, // (CArkLib) 라이브러리를 로드하지 않았거나 로드하는데 실패하였음
};
// ARK FILE FORMAT
enum ARK_FF
{
ARK_FF_ZIP, // zip, zipx
ARK_FF_ZIP_LASTVOLONLY, // 분할 zip 파일의 마지막 볼륨 (파일이 하나만 존재할 경우)
ARK_FF_ZIP_BANDIZIP_SFX, // 반디집 sfx
ARK_FF_ALZ,
ARK_FF_ALZ_SECONDVOL, // 분할 alz 파일의 2번째 이후 압축파일
ARK_FF_LZH,
ARK_FF_RAR,
ARK_FF_RAR_SECONDVOL, // 분할 RAR 파일의 2번째 이후 압축파일
ARK_FF_7Z,
ARK_FF_7ZSPLIT, // 7z 파일의 뒷부분이 잘렸고 확장자가 .001 인 파일 (.7z.001 ~ .7z.NNN)
ARK_FF_7ZBROKEN, // 7z 파일의 뒷부분이 잘렸거나 헤더가 손상된 파일
ARK_FF_TAR,
ARK_FF_CAB,
ARK_FF_CAB_NOTFIRSTVOL, //
ARK_FF_ISO, // iso, joliet
ARK_FF_IMG, // clone cd img (img, ccd)
ARK_FF_UDF,
ARK_FF_UDFBROKEN, // 뒷부분이 잘린 UDF
ARK_FF_SPLIT, // 확장자가 .001 인 파일 (.001 ~ .NNN)
ARK_FF_BOND, // hv3
ARK_FF_GZ,
ARK_FF_BZ2,
ARK_FF_LZMA,
ARK_FF_BH, // blakhole (not blackhole)
ARK_FF_EGG,
ARK_FF_EGG_NOTFIRSTVOL, // 분할 압축의 첫번째 볼륨이 아닌 파일
ARK_FF_XZ,
ARK_FF_WIM, // raw 만 사용하는 wim
ARK_FF_WIM_COMPRESSED, // 압축된 wim, Windows 에서만 지원
ARK_FF_FREEARC, // FreeArc
ARK_FF_Z, // .Z (unix compress)
ARK_FF_ARJ, // arj
ARK_FF_BAMSFX, // 밤톨이 sfx
ARK_FF_BAMSFX_NOTFIRSTVOL, //
ARK_FF_TGZ, // .tar.gz
ARK_FF_TBZ, // .tar.bz2
ARK_FF_J2J, // .j2j
ARK_FF_J2JBROKEN, // 뒷부분이 잘린 j2j
ARK_FF_K2K, // .k2k
ARK_FF_NSIS, // nsis exe
ARK_FF_ISZ, // EZBSystems(UltraISO) ZIPPED ISO
ARK_FF_UNKNOWN = 0x00ff, // 알 수 없는 파일 포맷
ARK_FF_UNSUPPORTED_FIRST = 0x0100, // 지원하지 않는 압축파일 포맷
ARK_FF_SIT = 0x0100, // sit
ARK_FF_BPE = 0x0101, // bpe
ARK_FF_ACE = 0x0102, // ace
ARK_FF_PAE = 0x0104, // PowerArchiver Encryption
ARK_FF_XEF = 0x0105, // Winace Encryption
ARK_FF_UNSUPPORTED_LAST = 0x0105,
ARK_FF_NOTARCHIVE_FIRST = 0x0200, // 명백히 압축파일이 아닌 파일 (실행파일, 이미지파일 등등..)
ARK_FF_NULL = 0x0201, // 파일의 앞부분이 전부 0 으로 채워져 있는 파일
ARK_FF_RIFF = 0x0202, // avi, wav
ARK_FF_EXE = 0x0203, // sfx 가 아닌 일반 PE 실행파일
ARK_FF_HTML = 0x0204, // HTML(정확하지는 않음)
ARK_FF_JPG = 0x0205, //
ARK_FF_PNG = 0x0206, //
ARK_FF_GIF = 0x0207, //
ARK_FF_OGGS = 0x0208, // OggS
ARK_FF_MATROSKA = 0x0209, // MKV
ARK_FF_PDF = 0x020a, // PDF
ARK_FF_MP4 = 0x020b, // MP4
ARK_FF_NOTARCHIVE_LAST = 0x020b,
};
// 암호화 방식
enum ARK_ENCRYPTION_METHOD
{
ARK_ENCRYPTION_METHOD_NONE = 0x00,
ARK_ENCRYPTION_METHOD_ZIP = 0x01, // ZipCrypto
ARK_ENCRYPTION_METHOD_AES128 = 0x02, // zip
ARK_ENCRYPTION_METHOD_AES192 = 0x03,
ARK_ENCRYPTION_METHOD_AES256 = 0x04,
ARK_ENCRYPTION_METHOD_EGG_ZIP = 0x05, // EGG 포맷에서 사용
ARK_ENCRYPTION_METHOD_EGG_AES128 = 0x06,
ARK_ENCRYPTION_METHOD_EGG_AES256 = 0x07,
ARK_ENCRYPTION_METHOD_RAR = 0x08, // RAR 암호 방식
ARK_ENCRYPTION_METHOD_ACE = 0x09, // ACE 암호
ARK_ENCRYPTION_METHOD_ETC = 0x99,
ARK_ENCRYPTION_METHOD_NOTSUPPORTED_FIRST= 0x100, // Not supported encryption method
ARK_ENCRYPTION_METHOD_GARBLE, // ARJ 암호 방식
ARK_ENCRYPTION_METHOD_DES,
ARK_ENCRYPTION_METHOD_RC2,
ARK_ENCRYPTION_METHOD_3DES168,
ARK_ENCRYPTION_METHOD_3DES112,
ARK_ENCRYPTION_METHOD_PKAES128,
ARK_ENCRYPTION_METHOD_PKAES192,
ARK_ENCRYPTION_METHOD_PKAES256,
ARK_ENCRYPTION_METHOD_RC2_2,
ARK_ENCRYPTION_METHOD_BLOWFISH,
ARK_ENCRYPTION_METHOD_TWOFISH,
ARK_ENCRYPTION_METHOD_RC4,
ARK_ENCRYPTION_METHOD_UNKNOWN,
};
// 압축 방식
enum ARK_COMPRESSION_METHOD
{
/////////////////////////////////////////////////////////////////
// zip 에서 사용하는것들, zip 포맷에 정의된 값과 동일하다.
// (http://www.pkware.com/documents/casestudies/APPNOTE.TXT 참고)
ARK_COMPRESSION_METHOD_STORE = 0,
ARK_COMPRESSION_METHOD_SHRINK = 1,
ARK_COMPRESSION_METHOD_IMPLODE = 6,
ARK_COMPRESSION_METHOD_DEFLATE = 8,
ARK_COMPRESSION_METHOD_DEFLATE64 = 9,
ARK_COMPRESSION_METHOD_BZIP2 = 12,
ARK_COMPRESSION_METHOD_LZMA = 14, // zipx, 7zip ...
ARK_COMPRESSION_METHOD_JPEG = 96, // zipx
ARK_COMPRESSION_METHOD_WAVPACK = 97, // zipx
ARK_COMPRESSION_METHOD_PPMD = 98, // zipx, 7zip
ARK_COMPRESSION_METHOD_AES = 99, // aes 로 암호화된 zip 파일. 실제 압축 방법은 다른곳에 저장된다.
//
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// ETC
ARK_COMPRESSION_METHOD_FUSE = 300, // bh 에서 사용
ARK_COMPRESSION_METHOD_FUSE6 = 301, // bh 에서 사용
ARK_COMPRESSION_METHOD_AZO = 302, // egg 에서 사용
ARK_COMPRESSION_METHOD_COMPRESS = 303, // .Z 에서 사용
ARK_COMPRESSION_METHOD_RAR15 = 400, // RAR 1.5
ARK_COMPRESSION_METHOD_RAR20 = 401, // RAR 2.X
ARK_COMPRESSION_METHOD_RAR26 = 402, // RAR 2.X & 2GB 이상
ARK_COMPRESSION_METHOD_RAR29 = 403, // RAR 3.X
ARK_COMPRESSION_METHOD_RAR36 = 404, // RAR 3.X alternative hash
ARK_COMPRESSION_METHOD_MSZIP = 500, // CAB
ARK_COMPRESSION_METHOD_LHA = 501, // lzh
ARK_COMPRESSION_METHOD_LZMA2 = 502, // 7z
ARK_COMPRESSION_METHOD_BCJ = 503, // 7z
ARK_COMPRESSION_METHOD_BCJ2 = 504, // 7z
ARK_COMPRESSION_METHOD_LZX = 505, // CAB
ARK_COMPRESSION_METHOD_LZXWIM = 506, // wim
ARK_COMPRESSION_METHOD_OBDEFLATE = 508, // Obfuscated deflate (alz)
ARK_COMPRESSION_METHOD_DELTA = 509, // 7z
ARK_COMPRESSION_METHOD_XPRESS = 510, // wim - xpress
ARK_COMPRESSION_METHOD_LH0 = 600, // -lh0-
ARK_COMPRESSION_METHOD_LH1 = 601, // -lh1-
ARK_COMPRESSION_METHOD_LH2 = 602, // -lh2-
ARK_COMPRESSION_METHOD_LH3 = 603, // -lh3-
ARK_COMPRESSION_METHOD_LH4 = 604, // -lh4-
ARK_COMPRESSION_METHOD_LH5 = 605, // -lh5-
ARK_COMPRESSION_METHOD_LH6 = 606, // -lh6-
ARK_COMPRESSION_METHOD_LH7 = 607, // -lh7-
ARK_COMPRESSION_METHOD_LZS = 608, // -lzs-
ARK_COMPRESSION_METHOD_LZ5 = 609, // -lz5-
ARK_COMPRESSION_METHOD_LZ4 = 610, // -lz4-
ARK_COMPRESSION_METHOD_LHD = 611, // -lhd-
ARK_COMPRESSION_METHOD_PM0 = 612, // -pm0-
ARK_COMPRESSION_METHOD_PM2 = 613, // -pm2-
ARK_COMPRESSION_METHOD_LZX15 = 715, // LZX (WINDOW SIZE 15bit)
ARK_COMPRESSION_METHOD_LZX16 = 716, //
ARK_COMPRESSION_METHOD_LZX17 = 717, //
ARK_COMPRESSION_METHOD_LZX18 = 718, //
ARK_COMPRESSION_METHOD_LZX19 = 719, //
ARK_COMPRESSION_METHOD_LZX20 = 720, //
ARK_COMPRESSION_METHOD_LZX21 = 721, // LZX (WINDOW SIZE 21bit)
ARK_COMPRESSION_METHOD_QUANTUM10 = 810, // QTMD(WINDOW SIZE 10bit)
ARK_COMPRESSION_METHOD_QUANTUM11 = 811, //
ARK_COMPRESSION_METHOD_QUANTUM12 = 812, //
ARK_COMPRESSION_METHOD_QUANTUM13 = 813, //
ARK_COMPRESSION_METHOD_QUANTUM14 = 814, //
ARK_COMPRESSION_METHOD_QUANTUM15 = 815, //
ARK_COMPRESSION_METHOD_QUANTUM16 = 816, //
ARK_COMPRESSION_METHOD_QUANTUM17 = 817, //
ARK_COMPRESSION_METHOD_QUANTUM18 = 818, //
ARK_COMPRESSION_METHOD_QUANTUM19 = 819, //
ARK_COMPRESSION_METHOD_QUANTUM20 = 820, //
ARK_COMPRESSION_METHOD_QUANTUM21 = 821, // QTMD(WINDOW SIZE 21bit)
ARK_COMPRESSION_METHOD_ARJ1 = 901, // Arj Method 1
ARK_COMPRESSION_METHOD_ARJ2 = 902, // 2
ARK_COMPRESSION_METHOD_ARJ3 = 903, // 3
ARK_COMPRESSION_METHOD_ARJ4 = 904, // 4
ARK_COMPRESSION_METHOD_ACELZ77 = 910, // ace lz77
ARK_COMPRESSION_METHOD_ACE20 = 911, // ace v20
ARK_COMPRESSION_METHOD_ACE = 912, // ace 최신?
ARK_COMPRESSION_METHOD_GRZIP = 1000, // FreeARC
ARK_COMPRESSION_METHOD_4x4 = 1001,
ARK_COMPRESSION_METHOD_DISPACK = 1002,
ARK_COMPRESSION_METHOD_PMM = 1003,
ARK_COMPRESSION_METHOD_LZ4B = 1004,
ARK_COMPRESSION_METHOD_LZP = 1005,
ARK_COMPRESSION_METHOD_MM = 1006,
ARK_COMPRESSION_METHOD_REP = 1007,
ARK_COMPRESSION_METHOD_TORNADO = 1008,
ARK_COMPRESSION_METHOD_TTA = 1009,
ARK_COMPRESSION_METHOD_DICT = 1010,
ARK_COMPRESSION_METHOD_CRC = 1011,
ARK_COMPRESSION_METHOD_FAKE = 1012,
//
/////////////////////////////////////////////////////////////////
ARK_COMPRESSION_METHOD_UNKNOWN = 9999, // unknown
};
// 분할 압축 스타일
enum ARK_MULTIVOL_STYLE
{
ARK_MULTIVOL_STYLE_NONE, // 분할 압축파일이 아님
ARK_MULTIVOL_STYLE_001, // 7zip 의 001, 002, .. 스타일
ARK_MULTIVOL_STYLE_WINZIP, // winzip 스타일 (z01, z02 ..... zip)
ARK_MULTIVOL_STYLE_ZIPX, // winzip zipx 스타일 (zx01, zx02 ..... zipx)
ARK_MULTIVOL_STYLE_ALZ, // alzip 의 alz, a00, a01, a02, .. 스타일
ARK_MULTIVOL_STYLE_EGG, // vol1.egg vol2.egg vol3.egg ... 스타일
ARK_MULTIVOL_STYLE_RAR, // part1.rar part2.rar ... 스타일
ARK_MULTIVOL_STYLE_R00, // .rar .r00 .r01 스타일
ARK_MULTIVOL_STYLE_ARJ, // .arj .a01 .a02 스타일
ARK_MULTIVOL_STYLE_BAMSFX, // 밤톨이 sfx (exe, .002 .003 ...)
ARK_MULTIVOL_STYLE_BDZSFX, // 반디집 SFX (exe, .e01 .e02 ...)
ARK_MULTIVOL_STYLE_CAB, // 분할 cab 파일
ARK_MULTIVOL_STYLE_ISZ0, // 분할 ISZ 파일 (isz, i01, i02... )
ARK_MULTIVOL_STYLE_ISZ1, // 분할 ISZ 파일 (part01.isz, part02.isz...)
ARK_MULTIVOL_STYLE_ISZ2, // 분할 ISZ 파일 (part001.isz, part002.isz...)
};
// 파일 속성
#define ARK_FILEATTR unsigned int
#define ARK_FILEATTR_NONE 0x00
#define ARK_FILEATTR_READONLY 0x01 // FILE_ATTRIBUTE_READONLY
#define ARK_FILEATTR_HIDDEN 0x02 // FILE_ATTRIBUTE_HIDDEN
#define ARK_FILEATTR_SYSTEM 0x04 // FILE_ATTRIBUTE_SYSTEM
#define ARK_FILEATTR_DIRECTORY 0x10 // FILE_ATTRIBUTE_DIRECTORY
#define ARK_FILEATTR_FILE 0x20 // FILE_ATTRIBUTE_ARCHIVE
// 코드 페이지
#define ARK_CP_ACP 0 // == CP_ACP
#define ARK_CP_OEM 1 // == CP_OEMCP
#define ARK_CP_KOR 949 // EUC-KR, CP949
#define ARK_CP_JPN 932 // SHIFT-JIS, CP932
#define ARK_CP_UTF8 65001 // == CP_UTF8
#define ARK_CP_UTF8_MAC 65002 // 맥용 utf8 코드 페이지
// 기타 정의
#define ARK_FILESIZE_UNKNOWN (0xffffffffffffffffLL) // 파일 크기를 알 수 없을때 사용되는 값
// WIN32 이외의 시스템일 경우 기본 타입 정의
#ifndef TRUE
#define FALSE 0
#define TRUE 1
typedef char CHAR;
typedef wchar_t WCHAR;
typedef unsigned int UINT32;
typedef const char* LPCSTR;
typedef const wchar_t* LPCWSTR;
#endif
// BOOL 대신 BOOL32 를 사용한다.
typedef int BOOL32;
typedef unsigned char ARKBYTE;
#ifndef PURE
# define PURE = 0
#endif
#ifdef _WIN32
typedef signed __int64 INT64;
#define WINAPI __stdcall
#else
typedef signed long long INT64;
#define WINAPI
#define THREAD_PRIORITY_NORMAL 0
#endif
// use os default packing
#ifndef __APPLE__
# pragma pack()
#endif
// 인터페이스 메써드 타입 정의
#define ARKMETHOD(type) virtual type WINAPI
#define ARK_TIME_T INT64 // time_t 와 동일
struct SArkFileTime // FILETIME(ntfs)과 동일
{
UINT32 dwLowDateTime;
UINT32 dwHighDateTime;
};
struct SArkNtfsFileTimes // NTSF 파일 시간 정보
{
SArkFileTime mtime; // 마지막 수정 시간
SArkFileTime ctime; // 파일을 생성한 시간
SArkFileTime atime; // 마지막으로 파일에 접근한 시간
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 파일 아이템 정보
//
struct SArkFileItem
{
CHAR* fileName; // 압축파일에 저장된 파일명 (이 이름은 폴더 경로명도 포함한다)
WCHAR* fileNameW;
WCHAR* fileCommentW;
ARK_TIME_T fileTime; // last modified(write) time
INT64 compressedSize;
INT64 uncompressedSize;
ARK_ENCRYPTION_METHOD encryptionMethod;
ARK_FILEATTR attrib;
UINT32 crc32;
ARK_COMPRESSION_METHOD compressionMethod;
SArkNtfsFileTimes* ntfsFileTimes; // NTFS 파일 시간 정보. 압축파일에 NTFS 파일정보가 없으면 NULL임
BOOL32 isUnicodeFileName; // 유니코드를 지원하는 압축포맷을 통해서 가져온 파일 이름인가? (즉, fileNameW를 100% 믿을 수 있는가)
BOOL32 IsFolder() const { return attrib & ARK_FILEATTR_DIRECTORY ? TRUE : FALSE;}
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 압축 및 압축 해제 진행 상황 정보
//
struct SArkProgressInfo
{
float fCurPercent; // 현재 파일의 압축 해제 진행율(%)
float fTotPercent; // 전체 파일의 압축 해제 진행율(%)
BOOL32 bCompleting; // 마무리 중인가?
float fCompletingPercent; // 마무리 중일때 진행율(%)
int _processed; // undocumented - do not use
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Ark 옵션 설정
//
struct SArkGlobalOpt
{
SArkGlobalOpt()
{
bPrintAssert = TRUE;
bTreatTGZAsSolidArchive = FALSE;
bTreatTBZAsSolidArchive = FALSE;
bAzoSupport = FALSE;
bTreatUnixZipFileNameAsUTF8 = TRUE;
bConvertNFD2NFCWhenMacOS = FALSE;
bIgnoreMacOSXMetaFolder = FALSE;
bUseLongPathName = FALSE;
bOpenArchiveWithShareDelete = FALSE;
}
BOOL32 bPrintAssert; // ASSERT 발생시 stdout 에 출력 여부 결정(posix 전용)
BOOL32 bTreatTGZAsSolidArchive; // TGZ 파일을 솔리드 압축된 파일처럼 처리하기
BOOL32 bTreatTBZAsSolidArchive; // TBZ 파일을 솔리드 압축된 파일처럼 처리하기
BOOL32 bAzoSupport; // azo 알고리즘 지원 여부
BOOL32 bTreatUnixZipFileNameAsUTF8; // zip 파일이 unix 에서 압축된 경우 무조건 utf8 코드페이지 처리
BOOL32 bConvertNFD2NFCWhenMacOS; // MAC OS 에서 압축한 파일일 경우 NFD를 NFC로 자동 변환
BOOL32 bIgnoreMacOSXMetaFolder; // zip 포맷의 __MACOSX/ 폴더를 무시한다.
BOOL32 bUseLongPathName; // 경로명이 260자가 넘어도 파일이나 폴더를 생성하기(Win32 전용)
BOOL32 bOpenArchiveWithShareDelete; // 압축파일 열때 FILE_SHARE_DELETE 속성으로 열기(Win32 전용)
};
// 코드페이지 관련
struct SArkDetectCodepage
{
SArkDetectCodepage()
{ fileCount2Detect=100; codePage = 0; codePageName[0] = 0; confidence=0; have2change=FALSE; }
int fileCount2Detect; // [in] 앞에서 부터 몇개의 파일명을 가지고 처리할 것인가?
int codePage; // [out] windows 용 codepage 숫자
char codePageName[128]; // [out] codepage 문자열 이름
int confidence; // [out] 인식된 코드페이지의 신뢰도 (0~100)
BOOL32 have2change; // [out] 현재 코드페이지에 문제가 있는듯 하다. confidence 수치가 낮아도 바꾸는게 좋을듯.
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 압축 해제 진행 상황
//
enum ARK_OVERWRITE_MODE // 파일 덮어쓰기 질문에 대한 사용자 대답
{
ARK_OVERWRITE_MODE_OVERWRITE,
ARK_OVERWRITE_MODE_SKIP,
ARK_OVERWRITE_MODE_RENAME,
};
enum ARK_PASSWORD_RET // 파일 암호 질문에 대한 사용자 대답
{
ARK_PASSWORD_RET_OK,
ARK_PASSWORD_RET_CANCEL,
};
enum ARK_PASSWORD_ASKTYPE // OnAskPassword() 호출 이유
{
ARK_PASSWORD_ASKTYPE_PASSWDNOTSET, // 암호가 지정되지 않았음
ARK_PASSWORD_ASKTYPE_INVALIDPASSWD, // 기존에 지정된 암호가 틀렸음
};
#define ARK_MAX_PATH 300
#define ARK_MAX_PASS 300
struct IArkEvent
{
ARKMETHOD(void) OnOpening(const SArkFileItem* pFileItem, float progress, BOOL32& bStop) PURE;
ARKMETHOD(void) OnStartFile(const SArkFileItem* pFileItem, BOOL32& bStopCurrent, BOOL32& bStopAll, int index) PURE;
ARKMETHOD(void) OnProgressFile(const SArkProgressInfo* pProgressInfo, BOOL32& bStopCurrent, BOOL32& bStopAll) PURE;
ARKMETHOD(void) OnCompleteFile(const SArkProgressInfo* pProgressInfo, ARKERR nErr) PURE;
ARKMETHOD(void) OnError(ARKERR nErr, const SArkFileItem* pFileItem, BOOL32 bIsWarning, BOOL32& bStopAll) PURE;
ARKMETHOD(void) OnMultiVolumeFileChanged(LPCWSTR szPathFileName) PURE;
ARKMETHOD(void) OnAskOverwrite(const SArkFileItem* pFileItem, LPCWSTR szLocalPathName, ARK_OVERWRITE_MODE& overwrite, WCHAR pathName2Rename[ARK_MAX_PATH]) PURE;
ARKMETHOD(void) OnAskPassword(const SArkFileItem* pFileItem, ARK_PASSWORD_ASKTYPE askType, ARK_PASSWORD_RET& ret, WCHAR passwordW[ARK_MAX_PASS]) PURE;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 압축파일 출력 스트림
//
struct IArkSimpleOutStream
{
ARKMETHOD(BOOL32) Open(LPCWSTR szPathName) PURE;
ARKMETHOD(BOOL32) SetSize(INT64 nSize) PURE;
ARKMETHOD(BOOL32) Write(const void* lpBuffer, UINT32 nNumberOfBytesToWrite) PURE;
ARKMETHOD(BOOL32) Close() PURE;
ARKMETHOD(BOOL32) CreateFolder(LPCWSTR szPathName) PURE;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 압축파일 입력 스트림
//
struct IArkSimpleInStream
{
ARKMETHOD(BOOL32) Read(void* lpBuffer, UINT32 nNumberOfBytesToRead, UINT32* lpNumberOfBytesRead) PURE;
ARKMETHOD(INT64) SetPos(INT64 pos) PURE;
ARKMETHOD(INT64) GetPos() PURE;
ARKMETHOD(INT64) GetSize() PURE;
ARKMETHOD(BOOL32) Close() PURE;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// MBCS 처리용 코드페이지
//
struct SArkCodepage
{
SArkCodepage(){Init();}
SArkCodepage(int a, int b, int c, int d) {}
void Init()
{
#ifdef _WIN32
fileSystem = ARK_CP_ACP;
#else
fileSystem = ARK_CP_UTF8; // POSIX 는 파일시스템에 보통 UTF8 코드페이지 사용
#endif
fileName = ARK_CP_OEM;
comment = ARK_CP_ACP;
password = <PASSWORD>;
}
int fileSystem; // 파일 시스템을 통해 압축파일을 열 때 사용하는 코드페이지. 보통 CP_ACP
int fileName; // 압축파일 내부의 파일명을 처리할때 사용하는 코드페이지. 보통 CP_OEM
int comment; // 압축파일 내부의 코멘트를 처리할때 사용하는 코드페이지. 보통 CP_ACP
int password; // MBCS 암호를 처리할때 사용하는 코드페이지. 보통 CP_ACP
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 압축파일의 압축 해제 인터페이스
//
struct IArk
{
ARKMETHOD(void) Release() PURE;
ARKMETHOD(BOOL32) Open(LPCSTR filePath, LPCSTR password) PURE;
ARKMETHOD(BOOL32) Open(LPCWSTR filePath, LPCWSTR password) PURE;
ARKMETHOD(BOOL32) Open(ARKBYTE* src, int srcLen, LPCWSTR password) PURE;
ARKMETHOD(BOOL32) Open(IArkSimpleInStream* srcStream, LPCWSTR password) PURE;
ARKMETHOD(void) Close() PURE;
ARKMETHOD(BOOL32) TestArchive() PURE;
ARKMETHOD(ARK_FF) CheckFormat(LPCSTR filePath) const PURE;
ARKMETHOD(ARK_FF) CheckFormat(LPCWSTR filePath) const PURE;
ARKMETHOD(ARK_FF) CheckFormat(const unsigned char* buffer, int bufLen) const PURE;
ARKMETHOD(void) SetPassword(LPCSTR password) PURE;
ARKMETHOD(void) SetPassword(LPCWSTR password) PURE;
ARKMETHOD(int) GetFileItemCount() const PURE;
ARKMETHOD(const SArkFileItem*) GetFileItem(int index) const PURE;
ARKMETHOD(ARK_FF) GetFileFormat() const PURE;
ARKMETHOD(BOOL32) IsBrokenArchive() const PURE;
ARKMETHOD(BOOL32) IsEncryptedArchive() const PURE;
ARKMETHOD(BOOL32) IsSolidArchive() const PURE;
ARKMETHOD(BOOL32) IsOpened() const PURE;
ARKMETHOD(BOOL32) ExtractAllTo(LPCSTR folderPath) PURE; // 전체 파일 풀기
ARKMETHOD(BOOL32) ExtractAllTo(LPCWSTR folderPath) PURE;
ARKMETHOD(BOOL32) ExtractAllTo(IArkSimpleOutStream* outStream) PURE;
ARKMETHOD(BOOL32) ExtractOneTo(int index, LPCWSTR folderPath) PURE; // 하나 파일 풀기
ARKMETHOD(BOOL32) ExtractOneTo(int index, LPCSTR folderPath) PURE;
ARKMETHOD(BOOL32) ExtractOneTo(int index, IArkSimpleOutStream* outStream) PURE;
ARKMETHOD(BOOL32) ExtractOneTo(int index, ARKBYTE* outBuf, int outBufLen) PURE;
ARKMETHOD(BOOL32) ExtractOneAs(int index, LPCWSTR filePathName, WCHAR resultPathName[ARK_MAX_PATH]) PURE; // 파일명을 지정해서 파일 하나 풀기
ARKMETHOD(BOOL32) AddIndex2ExtractList(int index) PURE; // 압축풀 파일 인덱스를 목록에 추가
ARKMETHOD(void) ClearExtractList() PURE; // 압축풀 파일 목록 삭제하기
ARKMETHOD(int) GetExtractListCount() const PURE; // 압축풀 파일 목록의 갯수
ARKMETHOD(BOOL32) ExtractMultiFileTo(LPCSTR szDestPath) PURE; // 몇개 파일 풀기
ARKMETHOD(BOOL32) ExtractMultiFileTo(LPCWSTR szDestPath, LPCWSTR szPath2Remove=NULL) PURE;
ARKMETHOD(BOOL32) ExtractMultiFileTo(IArkSimpleOutStream* outStream) PURE;
ARKMETHOD(BOOL32) SetEvent(IArkEvent* pEvent) PURE;
ARKMETHOD(ARKERR) GetLastError() const PURE;
ARKMETHOD(UINT32) GetLastSystemError() const PURE;
ARKMETHOD(void) SetCodePage(SArkCodepage cp) PURE;
ARKMETHOD(LPCWSTR) EncryptionMethod2Str(ARK_ENCRYPTION_METHOD method) const PURE;
ARKMETHOD(LPCWSTR) CompressionMethod2Str(ARK_COMPRESSION_METHOD method) const PURE;
ARKMETHOD(LPCWSTR) FileFormat2Str(ARK_FF ff) const PURE;
ARKMETHOD(void) SetGlobalOpt(const SArkGlobalOpt& opt) PURE;
ARKMETHOD(INT64) GetArchiveFileSize() const PURE;
ARKMETHOD(INT64) GetArchiveStartPos() const PURE;
ARKMETHOD(LPCWSTR) GetFilePathName() const PURE;
ARKMETHOD(int) FindIndex(LPCWSTR szFileNameW, LPCSTR szFileNameA, BOOL32 bCaseSensitive) const PURE;
ARKMETHOD(LPCWSTR) GetArchiveComment() const PURE;
ARKMETHOD(ARK_MULTIVOL_STYLE) GetMultivolStyle() const PURE;
ARKMETHOD(int) GetMultivolCount() const PURE;
ARKMETHOD(LPCWSTR) GetMultivolFilePathName(int volume) const PURE;
ARKMETHOD(BOOL32) DetectCurrentArchivesCodepage(SArkDetectCodepage& dcp) const PURE;
ARKMETHOD(BOOL32) ChangeCurrentArchivesCodepage(int codePage) PURE;
///////////////////////
// undocumented (do not use)
ARKMETHOD(void) _Test() PURE;
ARKMETHOD(const void*) _GetBondFileInfo() PURE;
ARKMETHOD(LPCWSTR) _GetAlias() PURE;
ARKMETHOD(void) _SetAlias(LPCWSTR szAlias) PURE;
ARKMETHOD(void) _SetUserKey(void* key) PURE;
ARKMETHOD(UINT32) _CheckCRC32(LPCWSTR filePath) PURE;
ARKMETHOD(void*) _GetExtractor() PURE;
ARKMETHOD(void*) _GetInStream() PURE;
ARKMETHOD(BOOL32) _DisableItem(int index) PURE;
// for c++ builder
ARKMETHOD(BOOL32) _OpenW(LPCWSTR filePath, LPCWSTR password) PURE;
ARKMETHOD(ARK_FF) _CheckFormatW(LPCWSTR filePath) const PURE;
ARKMETHOD(void) _SetPasswordW(LPCWSTR password) PURE;
ARKMETHOD(BOOL32) _ExtractAllToW(LPCWSTR folderPath) PURE;
ARKMETHOD(BOOL32) _ExtractOneToW(int index, LPCWSTR folderPath) PURE;
ARKMETHOD(BOOL32) _ExtractMultiFileToW(LPCWSTR szDestPath, LPCWSTR szPath2Remove=NULL) PURE;
};
/////////////////////////////////////////////////////////
//
// 압축 옵션
//
struct SArkCompressorOpt
{
SArkCompressorOpt(){Init();}
void Init()
{
ff = ARK_FF_ZIP;
deleteArchiveWhenFailed = TRUE;
saveNTFSTime = FALSE;
streamOutput = FALSE;
compressionMethod = ARK_COMPRESSION_METHOD_DEFLATE;
encryptionMethod = ARK_ENCRYPTION_METHOD_ZIP;
compressionLevel = -1; // -1 은 Z_DEFAULT_COMPRESSION
splitSize = 0;
forceZip64 = FALSE;
useDosTime2PasswordCheck = TRUE;
sfxPathName = NULL;
forceUtf8FileName = FALSE;
forceUtf8Comment = FALSE;
utf8FileNameIfNeeded = TRUE;
bypassWhenUncompressible = FALSE;
lzmaEncodeThreadCount = 2;
enableMultithreadDeflate = FALSE;
deflateEncodeThreadCount = 0;
_7zCompressHeader = TRUE;
_7zEncryptHeader = FALSE;
lzma2NumBlockThreads = -1;
threadPriority = THREAD_PRIORITY_NORMAL;
}
ARK_FF ff; // 파일 포맷 ARK_FF_ZIP, ARK_FF_TAR, ARK_FF_TGZ, ARK_FF_7Z, ARK_FF_LZH
BOOL32 deleteArchiveWhenFailed; // 압축중 에러 발생시 생성된 파일 삭제하기
BOOL32 saveNTFSTime; // ntfs 시간 저장 여부
BOOL32 streamOutput; // stream 형태로 저장 - 이 값이 TRUE 일 경우 열지 못하는 프로그램이 너무 많음.
ARK_COMPRESSION_METHOD compressionMethod; // 압축 방식 ( ARK_COMPRESSION_METHOD_STORE, ARK_COMPRESSION_METHOD_DEFLATE, ARK_COMPRESSION_METHOD_LZMA )
ARK_ENCRYPTION_METHOD encryptionMethod; // 파일에 암호를 걸 경우 사용할 암호 방식 ( ARK_ENCRYPTION_METHOD_ZIP, ARK_ENCRYPTION_METHOD_AES256 만 유효)
int compressionLevel; // 압축 레벨 ( Z_NO_COMPRESSION, Z_BEST_SPEED ~ Z_BEST_COMPRESSION )
INT64 splitSize; // 분할 압축 크기 (bytes, 0 이면 분할 압축 안함)
BOOL32 forceZip64; // 강제로 zip64 정보 저장
BOOL32 useDosTime2PasswordCheck; // 암호 체크 데이타를 crc 대신 dostime 을 사용한다. (사용시 압축 속도 향상). 단 분할압축시 이 옵션은 무시됨
LPCWSTR sfxPathName; // sfx를 만들경우 sfx 파일경로명. NULL 이면 사용하지 않음.
BOOL32 forceUtf8FileName; // 파일명을 모두 utf8 로 저장
BOOL32 forceUtf8Comment; // 압축파일 설명을 utf8 로 저장 (다른 프로그램과 호완되지 않음)
BOOL32 utf8FileNameIfNeeded; // 파일명에 유니코드가 포함되어 있을 경우 utf8 로 저장
BOOL32 bypassWhenUncompressible; // 압축중 압축이 안될경우 그냥 bypass
int lzmaEncodeThreadCount; // LZMA 압축시 쓰레드 카운트. 1~2
BOOL32 enableMultithreadDeflate; // Deflate 압축시 멀티쓰레드 사용
int deflateEncodeThreadCount; // Deflate 압축시 사용할 쓰래드 갯수. 0 이면 기본값 사용
BOOL32 _7zCompressHeader; // 7zip 압축시 헤더를 압축할 것인가?
BOOL32 _7zEncryptHeader; // 7zip 압축시 헤더를 암호화 할 것인가? (암호 지정시)
int lzma2NumBlockThreads; // lzma2 압축시 쓰레드 갯수, -1 이면 시스템 갯수만큼
int threadPriority; // 멀티코어를 이용해서 압축시 쓰레드 우선 순위
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 압축파일 만들기 인터페이스
//
struct IArkCompressor
{
ARKMETHOD(void) Release() PURE; // 객체 해제
ARKMETHOD(void) Init() PURE; // 초기화 (새로운 압축파일 생성 시작)
ARKMETHOD(void) SetEvent(IArkEvent* pEvent) PURE; // 반드시 Init() 호출후 매번 호출해야 한다.
ARKMETHOD(BOOL32) SetOption(SArkCompressorOpt& opt, const ARKBYTE* password, int pwLen) PURE;// CreateArchive() 호출전에만 호출하면 언제 호출해도 상관없고, 한번 호출하면 끝
ARKMETHOD(BOOL32) SetArchiveFile(IArk* pArchive) PURE; // 원본 파일 세팅
ARKMETHOD(BOOL32) AddFileItem(LPCWSTR szSrcPathName, LPCWSTR szTargetPathName, BOOL32 overwrite, LPCWSTR szFileComment=NULL, INT64 fileSize=-1) PURE;
ARKMETHOD(BOOL32) RenameItem(int index, LPCWSTR szPathName) PURE; // SetArchiveFile() 로 지정한 파일의 이름을 바꾼다.
ARKMETHOD(BOOL32) DeleteItem(int index) PURE; // SetArchiveFile() 로 지정한 파일을 삭제한다.
ARKMETHOD(int) FindFileItemIndex2Add(LPCWSTR szTargetPathName) PURE; // 기존 목록에 존재하는지 확인한다.
ARKMETHOD(BOOL32) GetFileItemInfo(int index, INT64& fileSize, ARK_TIME_T& fileTime) PURE; // 목록에 있는 파일의 정보 가져오기
ARKMETHOD(INT64) GetTotalFileSize2Archive() PURE;
ARKMETHOD(BOOL32) CreateArchive(LPCWSTR szPathName, LPCWSTR szArchiveComment=NULL) PURE;
ARKMETHOD(ARKERR) GetLastError() const PURE;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// IArk, IArkCompressor 객체를 생성합니다. SDKVersion 파라메터는 ARK_LIBRARY_VERSION 을 넘기면 됩니다.
//
#ifdef _WIN32
extern "C" __declspec(dllexport) IArk* CreateArk(UINT32 SDKVersion);
extern "C" __declspec(dllexport) IArkCompressor* CreateArkCompressor(UINT32 SDKVersion);
#endif
extern "C" IArk* CreateArkLib(UINT32 SDKVersion);
#endif // _ARK_H_
<file_sep>/UnArkWCX_Test/UnArkWCX_Test.h
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <tchar.h>
#include <Windows.h>
#include <vector>
#include <string>
#include <Shlwapi.h>
#pragma comment( lib, "shlwapi" )
#include "../Library/gtest/gtest.h"
#include "../UnArkWCX_Export.h"
#include "UnArkWCX_Test_Util.h"
#ifdef _WIN64
const wchar_t* const LIB_UNARKWCX_NAME = L"UnArkWCX.WCX64";
#else
const wchar_t* const LIB_UNARKWCX_NAME = L"UnArkWCX.WCX";
#endif
#pragma warning( disable: 4996 )
HMODULE hMod;
class CEnvironment : public ::testing::Environment
{
public:
virtual ~CEnvironment() {}
// Override this to define how to set up the environment.
virtual void SetUp()
{
std::cout << "fdsfds";
hMod = LoadLibrary( LIB_UNARKWCX_NAME );
ASSERT_EQ( true, hMod != NULL );
}
// Override this to define how to tear down the environment.
virtual void TearDown()
{
if( hMod != NULL )
FreeLibrary( hMod );
hMod = NULL;
}
};
TEST( ExportTest, OpenArchive )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, OpenArchiveW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, ReadHeader )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, ReadHeaderExW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, ProcessFile )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, ProcessFileW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, PackFiles )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, PackFilesW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, DeleteFiles )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, DeleteFilesW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, ConfigurePacker )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, CloseArchive )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, SetChangeVolProc )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, SetChangeVolProcW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, SetProcessDataProc )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, SetProcessDataProcW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, GetPackerCaps )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, CanYouHandleThisFile )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, CanYouHandleThisFileW )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
TEST( ExportTest, PackSetDefaultParams )
{
EXPECT_EQ( true,
GetProcAddress( hMod,
::testing::UnitTest::GetInstance()->current_test_info()->name()
) != NULL
);
}
class ArchiveTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
pwszAddList = NULL;
vecAddFile.clear();
ZeroMemory( wszSrcPath, sizeof( wchar_t ) * MAX_PATH );
pfnOpenArchiveW = (pFnOpenArchiveW)GetProcAddress( hMod, "OpenArchiveW" );
pfnReadHeaderExW = (pFnReadHeaderExW)GetProcAddress( hMod, "ReadHeaderExW" );
pfnProcessFileW = (pFnProcessFileW)GetProcAddress( hMod, "ProcessFileW" );
pfnPackFilesW = (pFnPackFilesW)GetProcAddress( hMod, "PackFilesW" );
pfnDeleteFilesW = (pFnDeleteFilesW)GetProcAddress( hMod, "DeleteFilesW" );
pfnSetChangeVolProcW = (pFnSetChangeVolProcW)GetProcAddress( hMod, "SetChangeVolProcW" );
pfnSetProcessDataProcW = (pFnSetProcessDataProcW)GetProcAddress( hMod, "SetProcessDataProcW" );
pfnCanYouHandleThisFileW = (pFnCanYouHandleThisFileW)GetProcAddress( hMod, "CanYouHandleThisFileW" );
pfnPackSetDefaultParams = (pFnPackSetDefaultParams)GetProcAddress( hMod, "PackSetDefaultParams" );
pfnSetChangeVolProcW( INVALID_HANDLE_VALUE, &ArchiveTest::changeVolProcW );
pfnSetProcessDataProcW( INVALID_HANDLE_VALUE, &ArchiveTest::processDataProcW );
}
virtual void TearDown()
{
Sleep(500);
if( pwszAddList != NULL )
delete [] pwszAddList;
pwszAddList = NULL;
}
static int WINAPI processDataProcW( WCHAR *FileName, int Size );
static int WINAPI changeVolProcW( WCHAR *ArcName, int Mode );
pFnOpenArchive pfnOpenArchive;
pFnOpenArchiveW pfnOpenArchiveW;
pFnReadHeader pfnReadHeader;
pFnReadHeaderExW pfnReadHeaderExW;
pFnProcessFile pfnProcessFile;
pFnProcessFileW pfnProcessFileW;
pFnPackFiles pfnPackFiles;
pFnPackFilesW pfnPackFilesW;
pFnDeleteFiles pfnDeleteFiles;
pFnDeleteFilesW pfnDeleteFilesW;
pFnConfigurePacker pfnConfigurePacker;
pFnCloseArchive pfnCloseArchive;
pFnSetChangeVolProcW pfnSetChangeVolProcW;
pFnSetProcessDataProcW pfnSetProcessDataProcW;
pFnGetPackerCaps pfnGetPackerCaps;
pFnCanYouHandleThisFileW pfnCanYouHandleThisFileW;
pFnPackSetDefaultParams pfnPackSetDefaultParams;
wchar_t* pwszAddList;
wchar_t wszSrcPath[ MAX_PATH ];
std::vector< std::wstring > vecAddFile;
};
TEST_F( ArchiveTest, SingleFileAddToZIP )
{
do
{
SetDefaultPackerExtension( L"ZIP" );
SetINIFilePath( pfnPackSetDefaultParams);
GetModuleFileName( NULL, wszSrcPath, MAX_PATH - 1 );
PathRemoveFileSpec( wszSrcPath );
vecAddFile.push_back( L"Ark64.dll" );
pwszAddList = GetAddList( vecAddFile, L"" );
ASSERT_EQ( 0, pfnPackFilesW( L"ArchiveTest_SingleFileAddToZIP.ZIP", NULL, wszSrcPath, pwszAddList, PK_PACK_SAVE_PATHS ) );
} while (false);
}
TEST_F( ArchiveTest, SingleFileMoveAndExtractToZIP )
{
do
{
SetDefaultPackerExtension( L"ZIP" );
SetINIFilePath( pfnPackSetDefaultParams);
GetModuleFileName( NULL, wszSrcPath, MAX_PATH - 1 );
PathRemoveFileSpec( wszSrcPath );
vecAddFile.push_back( L"Ark64.dll" );
pwszAddList = GetAddList( vecAddFile, L"" );
ASSERT_EQ( 0, pfnPackFilesW( L"ArchiveTest_SingleFileMoveAndExtractToZIP.ZIP", NULL, wszSrcPath, pwszAddList, PK_PACK_MOVE_FILES ) );
ASSERT_EQ( FALSE, PathFileExists( L"Ark64.dll" ) );
} while (false);
}
TEST_F( ArchiveTest, ListAllZIPFiles )
{
intptr_t hFind = -1;
tOpenArchiveDataW archiveData;
tHeaderDataExW headerDataExW;
archiveData.ArcName = NULL;
do
{
_wfinddata_t fd;
archiveData.ArcName = new wchar_t[ MAX_PATH ];
if( archiveData.ArcName == NULL )
break;
hFind = _wfindfirst( L"*.zip", &fd );
if( hFind == -1 )
break;
do
{
if( StrStrIW( fd.name, L".zip" ) == NULL )
continue;
wcscpy( archiveData.ArcName, fd.name );
archiveData.CmtBuf = NULL;
archiveData.CmtBufSize = NULL;
archiveData.CmtSize = NULL;
archiveData.CmtState = NULL;
archiveData.OpenMode = PK_OM_EXTRACT;
archiveData.OpenResult = 0;
HANDLE hArchive = pfnOpenArchiveW( &archiveData );
EXPECT_NE( (HANDLE)0, hArchive );
if( hArchive == NULL )
break;
int nResult = pfnReadHeaderExW( hArchive, &headerDataExW );
} while ( _wfindnext( hFind, &fd ) == 0 );
// while( pfnReadHeaderExW( hArchive, &headerDataExW ) == 0 )
// {
//
// }
//
} while (false);
if( hFind != -1 )
_findclose( hFind );
if( archiveData.ArcName != NULL )
delete [] archiveData.ArcName;
}
//
// TEST_F( ArchiveTest, SingleFileAddToISO )
// {
// do
// {
// SetDefaultPackerExtension( L"ISO" );
// SetINIFilePath( pfnPackSetDefaultParams);
//
// GetModuleFileName( NULL, wszSrcPath, MAX_PATH - 1 );
// PathRemoveFileSpec( wszSrcPath );
//
// vecAddFile.push_back( L"Ark64.dll" );
// pwszAddList = GetAddList( vecAddFile, L"" );
//
// ASSERT_EQ( 0, pfnPackFilesW( L"ArchiveTest_Method1.ISO", NULL, wszSrcPath, pwszAddList, PK_PACK_SAVE_PATHS ) );
//
// } while (false);
// }
//
//
// TEST_F( ArchiveTest, SingleFileAddTo7Z )
// {
// do
// {
// SetDefaultPackerExtension( L"7Z" );
// SetINIFilePath( pfnPackSetDefaultParams);
//
// GetModuleFileName( NULL, wszSrcPath, MAX_PATH - 1 );
// PathRemoveFileSpec( wszSrcPath );
//
// vecAddFile.push_back( L"Ark64.dll" );
// pwszAddList = GetAddList( vecAddFile, L"" );
//
// ASSERT_EQ( 0, pfnPackFilesW( L"ArchiveTest_Method1.7Z", NULL, wszSrcPath, pwszAddList, PK_PACK_SAVE_PATHS ) );
//
// } while (false);
// }
<file_sep>/Library/CommonLogger.h
#pragma once
#include <cassert>
#include <string>
#include <iostream>
#include <map>
#include <io.h>
#include <time.h>
#include <stdarg.h>
#include <vector>
#include <queue>
#include "CommonUtil.h"
#include "ConvertStr.h"
/*!
@file CommonLogger.h
@page hdrCmnLoggerLibrary 공통 로그 라이브러리
디버그 로그를 남기기위한 공통 라이브러리
작성자 : 헬마
최초 작성일 : 2009-07-21
참조 소스코드 : ACE Library 의 Log_Msg.cpp, Log_Msg.h
지원 OS : 윈도 NT 계열
지원하는 서식 문자열 \n
매개변수 필요없는 서식 문자열 \n
%% - %문자 \n
%T - 호출한 스레드ID ( 10진수 출력 ) \n
%P - 호출한 프로세스ID ( 10진수 출력 )
%N - 호출한 소스코드가 위치한 소스파일 이름
%L - 호출한 소스코드가 위치한 줄번호
%F - 호출한 함수 이름
%D - 호출한 날짜 ( 서식은 기본지정 되거나 별도로 변경가능 )
%t - 호출한 시간 ( 서식은 기본지정 되거나 별도로 변경가능 )
%l - 호출한 로그 레벨 ( 문자열로 표현 )
매개변수 필요한 서식 문자열
%o - 8진수
%x(X) - 16진수
%d - 32비트 부호 있는 정수
%u - 32비트 부호 없는 정수
%i(I)64d - 64비트 부호 있는 정수
%i(I)64u - 64비트 부호 없는 정수
%f - 부동소수점
%s - 문자열
%b(B) - bool 값을 받아서 TRUE, FALSE 문자열로 출력
%E - GetLastError() 가 반환한 오류코드를 받아서 문자열로 변환하여 출력
%H - HRESULT 형식의 오류코드를 받아서 문자열로 변환하여 출력
.2009-07-21 : 재설계시작
.2009-07-21 : 일부 서식화 문자열 변경
.2009-07-21 : 상수이름 변경
.2009-07-21 : ANSI 문자열, UNICODE 문자열 모두를 받을 수 있도록 두벌의 함수를 작성
.2009-07-21 : 로그수준을 설정할 수 있도록 추가
.2009-07-21 : 로그수준을 실시간으로 변경할 수 있도록 함.
.2009-07-21 : 동적 버퍼 관리 기능 추가
.2009-07-21 : 스트림으로 출력 떄는 파일 스트림이라도 용량제한등을 할 수 없음.
.2009-07-21 : COM 오류 코드 지원추가, %H
.2009-07-21 : 부동소수점 숫자를 서식화할 때 _CVTBUFSIZE 를 사용하여 버퍼크기를 요청하도록 변경
.2009-07-21 : 로그 클래스에 넘겨진 스트림클래스는 무조건 로그 클래스가 해제하도록 변경
.2009-07-21 : 로그 클래스에서 지원할 콜백함수 원형 추가
.2009-07-22 : 파일이름을 적으면 파일이름 뒤에 로그를 작성한 날짜와 분할파일 번호가 자동으로 붙도록 변경
.2009-07-22 : 로그레벨을 표시할 수 있는 서식화 문자열 추가
.2009-07-22 : 파일이 분할되어 있으면 가장 마지막 분할 파일에 이어서 붙이도록 함
.2009-07-22 : 로그 내용의 앞에 언제나 붙게될 내용을 설정할 수 있도록 변경
- 기본값 = [LEVEL=%I][DateTime=%D %T][PID=%P][TID=%t][File=%N-%L][Func=%F]
- 접두사 부분에는 매개변수가 필요없는 서식화 문자열만 가능.
- 기본값 중에서 골라서 사용하는 것을 권장
.2009-07-22 : 로그내용에 로그 레벨문자열이 정확히 출력되지 않는 문제 수정
.2009-07-22 : ANSI 문자열에 대한 지원 보류
.2009-07-22 : 콘솔창 출력 기능 구현
.2009-07-24 : if 문 안에 {} 없이 로그 매크로함수를 사용했을 때 경고가 나타나는 현상 수정
- 로그 매크로함수 끝에 반드시 ; 를 붙여서 문을 끝내야함
.2009-07-25 : x64 환경에서 컴파일시 발생하는 경고 수정
.2009-08-17 : 로그 생성 후 하루가 지나면 자동으로 파일을 날짜에 맞춰서 나누도록 변경
.2011-02-XX : 날짜, 시간 서식을 지정할 수 있도록함
: 속도 최적화를 위해 log_arg_list 가 string 를 반환하지 않음
: 몇몇 서식 문자열 변경
: 64비트 정수 지원 추가
: 로그 서식 문자열의 접두어 변경 ()
: 파일로 로그 저장할 때 날짜가 변경되면 로그파일이 분리되는 옵션 추가
: 주석 추가
: checkFileExist() 함수에서 _wfindfirst 함수로 생성한 파일검색 핸들을 닫지 않던 버그 수정
: 로그 파일의 용량 제한이 무제한이더라도 날짜가 지나면 로그 파일이 분할될 수 있도록 수정
.2011-07-07 : 콜백함수를 호출할 때 콜백함수가 기록할 FILE* 또는 ofstream 을 전달하도록 수정
: 콜백함수를 호출할 때 prefix 부분과 data 부분의 문자열을 분리하여 전달하도록 수정
: 로그를 기록할 때 prefix 부분과 data 부분으로 나눠서 기록하도록 수정
.2012-01-11 : LT_STDOUT 를 추가하여 현재 콘솔출력을 사용하는 옵션 추가
.2012-09-28 : 로거 출력문 사용방법 변경, 괄호를 2번 사용하지 않고 1번만 사용할 수 있도록 변경. 컴파일러 VS 2008 이상!!
*/
/*
간단한 로거 사용법
ㄱ). 로그를 출력할 대상을 결정한다. ( 로그 출력 대상은 비트 연산자 "OR" 를 이용하여 복수개를 지정할 수 있음 )
LM_INSTANCE()->SetLogTransfer()
ㄴ). 로그를 출력할 대상에 파일 또는 스트림을 지정했다면 해당 대상을 지정한다
LM_INSTANCE()->SetLogFile()
ㄷ). 로거 사용이 완전히 끝나면
LM_EXIT() 를 호출한다
*/
/// 로그 레벨을 나타내는 열거형 상수
enum CLOG_LEVEL
{
LL_NONE = 0,
LL_CRITICAL,
LL_ERROR,
LL_WARNING,
LL_DEBUG,
LL_TRACE
};
/// 로그 출력 대상을 나타내는 열거형 상수
enum CLOG_TRANSFER
{
LT_NONE = 0,
LT_STDERR = 1,
LT_STREAM = 2,
LT_FILE = 4,
LT_EVENTLOG = 8,
LT_CONSOLE = 16,
LT_DEBUGGER = 32,
LT_CALLBACK = 64,
LT_STDOUT = 128
};
// #pragma pack(push)
// #pragma pack(MEMORY_ALLOCATION_ALIGNMENT)
typedef struct tag_logdata
{
bool isUnicode;
char* szLogData;
wchar_t* wszLogData;
char* szNextMsgPtrA;
wchar_t* szNextMsgPtrW;
DWORD dwBufferSizeA;
DWORD dwBufferSizeW;
DWORD dwRemainBufferSizeA;
DWORD dwRemainBufferSizeW;
volatile LONG isUse;
tag_logdata() : isUse( 0 ), isUnicode( true ), szLogData( NULL ), wszLogData( NULL ), dwBufferSizeA( 0 ), dwBufferSizeW( 0 ),
dwRemainBufferSizeA( 0 ), dwRemainBufferSizeW( 0 ), szNextMsgPtrA( NULL ), szNextMsgPtrW( NULL ) {};
} LOGDATA, *PLOGDATA;
// #pragma pack(pop)
/// 로그 출력을 사용자정의 함수로 받기 위한 콜백 함수 정의 ( 유니코드버전 )
typedef void (*pfnLogCallbackW)
(
PVOID pParam,
CLOG_LEVEL prevLevel,
CLOG_LEVEL nextLevel,
const wchar_t* wszData
);
/// 로그 출력을 사용자정의 함수로 받기 위한 콜백 함수 정의 ( 멀티바이트버전 )
typedef void (*pfnLogCallbackA)
(
PVOID pParam,
CLOG_LEVEL prevLevel,
CLOG_LEVEL nextLevel,
const char* szData
);
class CLog
{
public:
~CLog();
static CLog* GetInstance( void );
static void CloseInstance( void );
bool IsLogging( CLOG_LEVEL logLevel );
size_t CLog::Log( const char* szFileName, const char* szFuncName, const wchar_t* wszFileName, const wchar_t* wszFuncName, unsigned int nLineNumber, const char* fmt, ... );
size_t CLog::Log( const char* szFileName, const char* szFuncName, const wchar_t* wszFileName, const wchar_t* wszFuncName, unsigned int nLineNumber, const wchar_t* fmt, ... );
// 콜백 추가, 삭제
bool AddCallbackA( pfnLogCallbackA pfnCallback, PVOID pParam );
bool AddCallbackW( pfnLogCallbackW pfnCallback, PVOID pParam );
void RemoveCallbackA( pfnLogCallbackA pfnCallback );
void RemoveCallbackW( pfnLogCallbackW pfnCallback );
// 로깅정보 설정
void SetLogLevel( CLOG_LEVEL logLevel );
void SetLogTransfer( DWORD logTransfer);
// 로그 문자열을 생성할 때 항상 앞에 생성될 문자열 설정, NULL 을 지정하면 기본값 설정, 설정하지 않으면 L"" 를 설정
void SetLogPrefix( const wchar_t* pwszLogPrefix = NULL );
// 로그 문자열을 생성할 때 사용할 날짜, 시간 서식 문자열, NULL 을 지정하면 기본 서식 지정
void SetDateFormat( const wchar_t* pwszDateFormat = NULL );
void SetTimeFormat( const wchar_t* pwszTimeFormat = NULL );
// 로그 출력대상 관련
bool SetLogFile( const wchar_t* szLogPath, const wchar_t* szLogName, const wchar_t* szLogExt );
void SetFileLimitSize( unsigned int nFileLimitSize = 0, bool IsFileSplit = true, bool IsFileSplitWhenDate = true );
unsigned int GetFileLimitSize( void );
// 현재 저장되고 있는 로그 파일이름( 완전한 경로 포함 )
std::wstring GetFileName( void );
private:
CLog();
CLog& operator =( const CLog& );
CLog( const CLog& );
void Lock();
void Unlock();
// 가변인자를 받아 실제로 로그 서식문자열을 생성, 반환값은 생성된 문자 수
size_t log_arg_list( const char* szFileName, const char* szFuncName, unsigned int nLineNumber, const char* fmt, bool isAppendNewLine, LOGDATA* pLOGDATA, va_list args );
size_t log_arg_list( const wchar_t* wszFileName, const wchar_t* wszFuncName, unsigned int nLineNumber, const wchar_t* fmt, bool isAppendNewLine, LOGDATA* pLOGDATA, va_list args );
bool getBufferA( UINT_PTR nRequiredSize, LOGDATA* pLOGDATA );
bool getBufferW( UINT_PTR nRequiredSize, LOGDATA* pLOGDATA );
const char* getLogLevelA();
const wchar_t* getLogLevelW();
// 디렉토리 존재여부를 확인한 후 재귀적으로 디렉토리 생성
DWORD checkDirectory( const wchar_t* szDirectory );
// 분할된 파일의 존재여부를 검사한 후 가장 마지막에 생성되어야할 분할 파일번호를 찾음
void checkFileExist( void );
// 파일 크기 점검, false = 함수 실패, 파일 기록 불가, true = 함수 성공, 파일 기록 가능
bool checkFileSizeAndTime( const wchar_t* szFileName );
bool createLogFile();
static unsigned int __stdcall processLOGThread( PVOID pParam );
// 내부 변수
static CLog* pClsLog;
static volatile bool isExit;
static const unsigned int MAX_MESSAGE_COUNT = 8192;
static const unsigned int MSG_BUFFER_SIZE = 2048;
static const unsigned int MAX_TIME_BUFFER_SIZE = 128;
volatile LONG m_lCurrentIndex;
CLOG_LEVEL m_eLogLevel;
CLOG_LEVEL m_eCurrentLogLevel;
DWORD m_eLogTransfer;
std::string m_strPreFixA;
std::wstring m_strPreFixW;
char m_szDateFormatA[64];
wchar_t m_szDateFormatW[64];
char m_szTimeFormatA[64];
wchar_t m_szTimeFormatW[64];
// 분할된 로그 파일 수
unsigned int m_nSplitCount;
// 최대 로그 파일 크기, MB 단위, 0 = 무제한
unsigned int m_nFileLimitSize;
// 최대 로그 파일 크기에 도달하면 파일을 분할할 지 여부, false 이고 꽉 차면 더 이상 기록안함
bool m_IsFileSplit;
// 날짜가 바뀌면 로그 파일을 분할할지 여부
bool m_IsFileSplitWhenDate;
// 로그파일을 생성한 시간
struct tm m_tmCreateLogTime;
// 저장될 로그파일 관련 변수들
// 파일 구조체
FILE* m_pLogFile;
wchar_t m_szLogPath[ MAX_PATH ];
wchar_t m_szLogName[ MAX_PATH ];
wchar_t m_szLogExt[ MAX_PATH ];
wchar_t m_szCurrentLogFile[ MAX_PATH ]; // 현재 로그가 기록중인 파일
std::map<pfnLogCallbackA, PVOID> m_lstCallbackA;
std::map<pfnLogCallbackW, PVOID> m_lstCallbackW;
std::vector< PLOGDATA > m_vecLOGData;
std::queue< int > m_queueLOGData;
CRITICAL_SECTION m_cs;
HANDLE m_hProcessLOGThread;
};
// 편의 매크로 모음
#define LM_INSTANCE() CLog::GetInstance()
#define LM_TRACE(...) \
do { \
if( LM_INSTANCE()->IsLogging( LL_TRACE ) ) \
{ \
LM_INSTANCE()->Log( __FILE__, __FUNCTION__, __FILEW__, __FUNCTIONW__, __LINE__, __VA_ARGS__ ); \
} \
} while(0)
#define LM_DEBUG(...) \
do { \
if( LM_INSTANCE()->IsLogging( LL_DEBUG ) ) \
{ \
LM_INSTANCE()->Log( __FILE__, __FUNCTION__, __FILEW__, __FUNCTIONW__, __LINE__, __VA_ARGS__ ); \
} \
} while(0)
#define LM_ERROR(...) \
do { \
if( LM_INSTANCE()->IsLogging( LL_ERROR ) ) \
{ \
LM_INSTANCE()->Log( __FILE__, __FUNCTION__, __FILEW__, __FUNCTIONW__, __LINE__, __VA_ARGS__ ); \
} \
} while(0)
#define LM_WARNING(...) \
do { \
if( LM_INSTANCE()->IsLogging( LL_WARNING ) ) \
{ \
LM_INSTANCE()->Log( __FILE__, __FUNCTION__, __FILEW__, __FUNCTIONW__, __LINE__, __VA_ARGS__ ); \
} \
} while(0)
#define LM_CRITICAL(...) \
do { \
if( LM_INSTANCE()->IsLogging( LL_CRITICAL ) ) \
{ \
LM_INSTANCE()->Log( __FILE__, __FUNCTION__, __FILEW__, __FUNCTIONW__, __LINE__, __VA_ARGS__ ); \
} \
} while(0)
#define LM_EXIT() \
do { \
CLog::CloseInstance(); \
} while( 0 )
<file_sep>/README.rst
============================
UnArkWCX for TotalCommander
=============================
UnArkWCX is a WCX plugin that unpack various file formats using Ark Library.
Author : DevTester ( http://jgh0721.homeip.net )
Development Environment
=========================
* Visual Studio 2012( Use Visual Studio 2008 SP1 Compiler, So need VS2008 SP1 Installation )
* Ark Library ( http://www.bandisoft.com/ark/ )
* Total Commadner 8.X
History
========
최종 수정 일 : 2012-10-XX
참조 : Kipple 님의 Unarkwcx
1.0 ( 2012-10-XX )
--------------------
* Ark Library 5.0 Beta 2 로 변경
* 압축 파일 생성 지원 시작
* 환경설정 대화상자 추가
* 압축 파일 생성 ( ZIP, 7Z, ISO )
* 압축 파일 해제 ( NSIS-EXE 추가 지원 )
* 플러그인을 설치할 때 모든 확장자를 등록하지 못하고 토탈 커맨더가 종료되는 문제 수정
* 토탈 커맨더의 기본 플러그인 설치 인터페이스는 각 확장자별로 압축 또는 해제를 지정할 수 없는 관계로 별도의 설치관리자 제작
* 토탈 커맨더에서 플러그인이 지원하는 기능을 정확히 파악하지 못하는 문제 수정
* 폴더가 포함된 압축파일을 열 때 오류가 발생하는 현상 수정
* 단위테스트를 위해 GoogleTest 1.6.0 도입
* 압축 한 후 원본 파일 삭제 기능 구현
* Visual Studio 2012 로 솔루션 파일 변경, 빌드는 VS 2008 SP1 을 사용하여 빌드함
0.9 ( 2012-10-XX )
--------------------
* Ark Library 5.0 Beta 1 로 변경
* Visual Studio 2008 SP1 프로젝트로 변경, CRT 에 의존하지 않도록 변경
* 파일 날짜를 잘 못 반환하여 발생하는 오류 수정
* 압축 해제 중 취소 눌렀을 때 취소 가능하도록 변경
0.5 ( 2011-10-03 )
--------------------
* 해당 플러그인을 통해서 작업한 파일이 계속 LOCK 를 소유하는 문제 수정
0.4 ( 2011-10-02 )
--------------------
* x64 지원 추가
0.3 ( 2011-10-02 )
--------------------
* GetPackerCaps 구현
* CanYouHandleThisFile 구현
0.2 ( 2011-10-01 )
--------------------
* Ark Library 의 ExtractOneAs 메소드의 우회책 작성
0.1 ( 2011-10-01 )
---------------------
* wcxtest 유틸리티의 시험 통과 ( -f, -l, -x )
<file_sep>/stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#define TEST_EXE_INCLUDE
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <Shlwapi.h>
#pragma comment( lib, "shlwapi.lib" )
#include "Library\wcxhead.h"
#include "Library\Ark.h"
#include "Library\ArkLib.h"
#include "Library\CommonUtil.h"
#include "Library\ConvertStr.h"
#include "Library\CommonLogger.h"
#include <Shlwapi.h>
#pragma comment( lib, "shlwapi" )
// TODO: reference additional headers your program requires here
<file_sep>/Library/ConvertStr.cpp
#include "stdafx.h"
#include "ConvertStr.h"
#pragma warning( disable: 4996 )
int getActualUTF8Length( const char* szUTF8 );
int convertUTF8toUTF16( const char* pszUTF8, wchar_t* pwszUTF16 );
int convertUTF16toUTF8( wchar_t* pwszUTF16, char* pszUTF8 );
int getBytesUTF16toUTF8( wchar_t* pwszUTF16 );
int getActualUTF8Length( const char* szUTF8 )
{
int nLength = 0;
while( *szUTF8 )
nLength += (*szUTF8++ & 0xc0) != 0x80;
return nLength;
}
int convertUTF8toUTF16( const char* pszUTF8, wchar_t* pwszUTF16 )
{
int nRetSize = 0;
int iIndex = 0;
wchar_t wChar;
while( 0 != pszUTF8[iIndex] )
{
if( ( 0xE0 == ( pszUTF8[iIndex] & 0xE0 ) ) )
{
wChar = ( ( pszUTF8[iIndex] & 0x0f ) << 12 ) |
( ( pszUTF8[iIndex+1]&0x3F ) << 6 ) |
( pszUTF8[iIndex+2] & 0x3F );
iIndex += 3;
}
else if( 0xC0 == ( pszUTF8[iIndex] & 0xC0 ) )
{
wChar = ( ( pszUTF8[iIndex] & 0x1F ) << 6 ) |
( pszUTF8[iIndex+1] & 0x3F );
iIndex += 2;
}
else
{
wChar = pszUTF8[iIndex] & 0x7F;
iIndex++;
}
pwszUTF16[nRetSize] = wChar;
nRetSize++;
}
pwszUTF16[nRetSize] = 0;
return nRetSize;
}
int getBytesUTF16toUTF8( wchar_t* pwszUTF16 )
{
int nBytes = 1; // NULL - Terminating 을 위한 1바이트 미리 잡음
wchar_t* wszBuffer = pwszUTF16;
while( *wszBuffer != L'\0' )
{
if( *wszBuffer < 0x80 )
nBytes += 1;
else if( *wszBuffer < 0x800 )
nBytes += 2;
else
nBytes += 3;
wszBuffer++;
}
return nBytes;
}
int convertUTF16toUTF8( wchar_t* pwszUTF16, char* pszUTF8 )
{
assert( pwszUTF16 != NULL );
assert( pszUTF8 != NULL );
int nTotalBytes = 0;
int nBytes = -1;
unsigned char szBytes[ 4 ] = {0,};
wchar_t wChar;
wchar_t* pwszBuffer = pwszUTF16;
while( *pwszBuffer != L'\0' )
{
wChar = *pwszBuffer;
if( wChar < 0x80 )
{
nBytes = 1;
szBytes[ 0 ] = (unsigned char)wChar;
}
else if( wChar < 0x800 )
{
nBytes = 2;
szBytes[ 1 ] = (wChar & 0x3f) | 0x80;
szBytes[ 0 ] = ( (wChar << 2) & 0xcf00 | 0xc000 ) >> 8;
}
else
{
nBytes = 3;
szBytes[2] = ( wChar & 0x3f ) | 0x80;
szBytes[1] = ( ( wChar << 2 ) & 0x3f00 | 0x8000) >> 8;
szBytes[0] = ( ( wChar << 4 ) & 0x3f0000 | 0xe00000) >> 16;
}
for( int j = 0; j < nBytes; ++j )
pszUTF8[ nTotalBytes++ ] = szBytes[ j ];
pwszBuffer++;
}
pszUTF8[ nTotalBytes ] = '\0';
return nTotalBytes;
}
CA2U::CA2U( const std::string& str )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
CopyAnsiString( &m_pszBuffer, str.c_str(), str.length() );
}
CA2U::CA2U( const char* pszStr )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
assert( pszStr != NULL );
CopyAnsiString( &m_pszBuffer, pszStr, -1 );
}
CA2U::operator const wchar_t*()
{
return c_str();
}
#ifdef _AFX
CA2U::operator const CStringW()
{
return c_str();
}
#endif
const wchar_t* CA2U::c_str()
{
assert( m_pszBuffer != NULL );
if( m_pwszBuffer != NULL )
return m_pwszBuffer;
#ifdef _WINDOWS_
int nReqSize = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, m_pszBuffer, -1, m_pwszBuffer, 0 );
m_pwszBuffer = new wchar_t[ nReqSize ];
memset( m_pwszBuffer, '\0', sizeof(wchar_t) * nReqSize );
int nRetSize = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, m_pszBuffer, -1, m_pwszBuffer, nReqSize );
if( nRetSize > 0 )
return m_pwszBuffer;
#else
int nReqSize = mbstowcs( NULL, m_pszBuffer, 0 );
m_pwszBuffer = new wchar_t[ ++nReqSize ];
memset( m_pwszBuffer, '\0', sizeof(wchar_t) * nReqSize );
int nRetSize = mbstowcs( m_pwszBuffer, m_pszBuffer, nReqSize );
if( nRetSize >= 0 )
return m_pwszBuffer;
#endif
return L"";
}
CA2U& CA2U::operator =( const char* pszStr )
{
assert( pszStr != NULL );
DeletePtrA< wchar_t* >( m_pwszBuffer );
DeletePtrA< char* >( m_pszBuffer );
CopyAnsiString( &m_pszBuffer, pszStr );
return *this;
}
CA2U& CA2U::operator =( const std::string& str )
{
DeletePtrA< wchar_t* >( m_pwszBuffer );
DeletePtrA< char* >( m_pszBuffer );
CopyAnsiString( &m_pszBuffer, str.c_str(), str.length() );
return *this;
}
//////////////////////////////////////////////////////////////////////////
CU2A::CU2A( const std::wstring& str )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
CopyWideString( &m_pwszBuffer, str.c_str(), str.length() );
}
CU2A::CU2A( const wchar_t* pwszStr )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
assert( pwszStr != NULL );
CopyWideString( &m_pwszBuffer, pwszStr );
}
#ifdef _AFX
CU2A::CU2A( const CStringW& str )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
assert( str.GetString() != NULL );
CopyWideString( &m_pwszBuffer, str.GetString() );
}
#endif
CU2A::operator const char*()
{
return c_str();
}
const char* CU2A::c_str()
{
assert( m_pwszBuffer != NULL );
if( m_pszBuffer != NULL )
return m_pszBuffer;
#ifdef _WINDOWS_
int nReqSize = WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS, m_pwszBuffer, -1, m_pszBuffer, 0, NULL, NULL );
m_pszBuffer = new char[ nReqSize ];
memset( m_pszBuffer, '\0', nReqSize * sizeof( char ) );
int nRetSize = WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS, m_pwszBuffer, -1, m_pszBuffer, nReqSize, NULL, NULL );
if( nRetSize > 0 )
return m_pszBuffer;
#else
int nReqSize = wcstombs( NULL, m_pwszBuffer, 0 );
m_pszBuffer = new char[ ++nReqSize ];
memset( m_pszBuffer, '\0', nReqSize * sizeof( char ) );
int nRetSize = wcstombs( m_pszBuffer, m_pwszBuffer, nReqSize );
if( nRetSize >= 0 )
return m_pszBuffer;
#endif
return "";
}
CU2A& CU2A::operator =( const wchar_t* pszStr )
{
assert( pszStr != NULL );
DeletePtrA< wchar_t* >( m_pwszBuffer );
DeletePtrA< char* >( m_pszBuffer );
CopyWideString( &m_pwszBuffer, pszStr );
return *this;
}
CU2A& CU2A::operator =( const std::wstring& str )
{
DeletePtrA< wchar_t* >( m_pwszBuffer );
DeletePtrA< char* >( m_pszBuffer );
CopyWideString( &m_pwszBuffer, str.c_str(), str.length() );
return *this;
}
//////////////////////////////////////////////////////////////////////////
CU82U::CU82U( const char* pszStr )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
assert( pszStr != NULL );
CopyAnsiString( &m_pszBuffer, pszStr );
}
CU82U::CU82U( const std::string& str )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
CopyAnsiString( &m_pszBuffer, str.c_str() );
}
//
// CU82U::operator const wchar_t*()
// {
// return c_str();
// }
#ifdef _AFX
CU82U::operator const CStringW()
{
return c_str();
}
#endif
const wchar_t* CU82U::c_str()
{
assert( m_pszBuffer != NULL );
if( m_pwszBuffer != NULL )
return m_pwszBuffer;
#ifdef _WINDOWS_
int nReqSize = MultiByteToWideChar( CP_UTF8, 0, m_pszBuffer, -1, m_pwszBuffer, 0 );
m_pwszBuffer = new wchar_t[ nReqSize ];
memset( m_pwszBuffer, '\0', nReqSize * sizeof( wchar_t ) );
int nRetSize = MultiByteToWideChar( CP_UTF8, 0, m_pszBuffer, -1, m_pwszBuffer, nReqSize );
if( nRetSize > 0 )
return m_pwszBuffer;
#else
// UTF-8 문자열의 실제 길이 구하기
int nReqSize = getActualUTF8Length( m_pszBuffer );
if( nReqSize <= 0 )
return L"";
m_pwszBuffer = new wchar_t[ nReqSize + 1 ];
memset( m_pwszBuffer, '\0', nReqSize * sizeof( wchar_t ) );
// 변환시작
int nRetSize = convertUTF8toUTF16( m_pszBuffer, m_pwszBuffer );
if( nRetSize > 0 )
return m_pwszBuffer;
#endif
return L"";
}
CU82U& CU82U::operator =( const char* pszStr )
{
assert( pszStr != NULL );
DeletePtrA< char* >( m_pszBuffer );
DeletePtrA< wchar_t* >( m_pwszBuffer );
CopyAnsiString( &m_pszBuffer, pszStr );
return *this;
}
CU82U& CU82U::operator =( const std::string& pszStr )
{
DeletePtrA< char* >( m_pszBuffer );
DeletePtrA< wchar_t* >( m_pwszBuffer );
CopyAnsiString( &m_pszBuffer, pszStr.c_str() );
return *this;
}
//////////////////////////////////////////////////////////////////////////
CU2U8::CU2U8( const wchar_t* pwszStr )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
assert( pwszStr != NULL );
CopyWideString( &m_pwszBuffer, pwszStr );
}
CU2U8::CU2U8( const std::wstring& str )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
assert( str.c_str() != NULL );
CopyWideString( &m_pwszBuffer, str.c_str() );
}
#ifdef _AFX
CU2U8::CU2U8( const CStringW& str )
: m_pszBuffer(NULL),m_pwszBuffer(NULL)
{
assert( str.GetString() != NULL );
CopyWideString( &m_pwszBuffer, str.GetString() );
}
#endif
// CU2U8::operator const char*()
// {
// return c_str();
// }
const char* CU2U8::c_str()
{
assert( m_pwszBuffer != NULL );
if( m_pszBuffer != NULL )
return m_pszBuffer;
#ifdef _WINDOWS_
int nReqSize = WideCharToMultiByte( CP_UTF8, 0, m_pwszBuffer, -1, m_pszBuffer, 0, NULL, NULL );
m_pszBuffer = new char[ nReqSize ];
memset( m_pszBuffer, '\0', nReqSize * sizeof( char ) );
int nRetSize = WideCharToMultiByte( CP_UTF8, 0, m_pwszBuffer, -1, m_pszBuffer, nReqSize, NULL, NULL );
if( nReqSize > 0 )
return m_pszBuffer;
#else
int nReqSize = getBytesUTF16toUTF8( m_pwszBuffer );
m_pszBuffer = new char[ nReqSize ];
memset( m_pszBuffer, '\0', nReqSize * sizeof( char ) );
int nRetSize = convertUTF16toUTF8( m_pwszBuffer, m_pszBuffer );
if( nRetSize > 0 )
return m_pszBuffer;
#endif
return "";
}
CU2U8& CU2U8::operator =( const wchar_t* pwszStr )
{
assert( pwszStr != NULL );
CopyWideString( &m_pwszBuffer, pwszStr );
return *this;
}
CU2U8& CU2U8::operator =( const std::wstring& str )
{
CopyWideString( &m_pwszBuffer, str.c_str(), str.length() );
return *this;
}
//////////////////////////////////////////////////////////////////////////
CA2U8::CA2U8( const char* pszStr )
: m_pszBufferA(NULL), m_pszBufferU8(NULL)
{
assert( pszStr != NULL );
CopyAnsiString( &m_pszBufferA, pszStr );
}
CA2U8::CA2U8( const std::string& str )
: m_pszBufferA(NULL), m_pszBufferU8(NULL)
{
CopyAnsiString( &m_pszBufferA, str.c_str() );
}
CA2U8::operator const char*()
{
return c_str();
}
const char* CA2U8::c_str()
{
assert( m_pszBufferA != NULL );
if( m_pszBufferU8 != NULL )
return m_pszBufferU8;
wchar_t* pwszBuffer = NULL;
// 윈도 환경에서는 ANSI -> UTF-16 -> UTF-8 로 변환해야함
#ifdef _WINDOWS_
int nReqSize = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, m_pszBufferA, -1, pwszBuffer, 0 );
pwszBuffer = new wchar_t[ nReqSize ];
memset( pwszBuffer, '\0', sizeof(wchar_t) * nReqSize );
int nRetSize = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, m_pszBufferA, -1, pwszBuffer, nReqSize );
if( nRetSize > 0 )
{
nReqSize = WideCharToMultiByte( CP_UTF8, 0, pwszBuffer, -1, m_pszBufferU8, 0, NULL, NULL );
m_pszBufferU8 = new char[ nReqSize ];
memset( m_pszBufferU8, '\0', nReqSize * sizeof( char ) );
nRetSize = WideCharToMultiByte( CP_UTF8, 0, pwszBuffer, -1, m_pszBufferU8, nReqSize, NULL, NULL );
DeletePtrA< wchar_t *>( pwszBuffer );
if( nRetSize > 0 )
return m_pszBufferU8;
}
#else
int nReqSize = mbstowcs( NULL, m_pszBufferA, 0 );
pwszBuffer = new wchar_t[ ++nReqSize ];
memset( pwszBuffer, '\0', sizeof(wchar_t) * nReqSize );
int nRetSize = mbstowcs( pwszBuffer, m_pszBufferA, nReqSize );
if( nRetSize >= 0 )
{
int nBytes = -1;
unsigned char szBytes[ 4 ] = {0,};
int iLength = wcslen( pwszBuffer );
wchar_t wChar;
int nLen = 0;
// 2바이트 한글자는 최대 4바이트로 커질 수 있으므로 넉넉하게 선언
m_pszBufferU8 = new char[ 3 * wcslen( pwszBuffer ) ];
memset( m_pszBufferU8, '\0', 3 * wcslen( pwszBuffer ) * sizeof( unsigned char ) );
for( int idx = 0; idx < iLength; ++idx )
{
wChar = pwszBuffer[ idx ];
if( wChar < 0x80 )
{
nBytes = 1;
szBytes[ 0 ] = (unsigned char)wChar;
}
else if( wChar < 0x800 )
{
nBytes = 2;
szBytes[ 1 ] = (wChar & 0x3f) | 0x80;
szBytes[ 0 ] = ( (wChar << 2) & 0xcf00 | 0xc000 ) >> 8;
}
else
{
nBytes = 3;
szBytes[2] = ( wChar & 0x3f ) | 0x80;
szBytes[1] = ( ( wChar << 2 ) & 0x3f00 | 0x8000) >> 8;
szBytes[0] = ( ( wChar << 4 ) & 0x3f0000 | 0xe00000) >> 16;
}
for( int j = 0; j < nBytes; ++j )
{
m_pszBufferU8[ nLen ] = szBytes[ j ];
nLen++;
}
}
m_pszBufferU8[ nLen ] = '\0';
DeletePtrA< wchar_t* >( pwszBuffer );
return m_pszBufferU8;
}
#endif
DeletePtrA< wchar_t* >( pwszBuffer );
return "";
}
CA2U8& CA2U8::operator =( const char* pszStr )
{
assert( pszStr != NULL );
DeletePtrA< char* >( m_pszBufferA );
DeletePtrA< char* >( m_pszBufferU8 );
CopyAnsiString( &m_pszBufferA, pszStr );
return *this;
}
CA2U8& CA2U8::operator =( const std::string& str )
{
DeletePtrA< char* >( m_pszBufferA );
DeletePtrA< char* >( m_pszBufferU8 );
CopyAnsiString( &m_pszBufferA, str.c_str() );
return *this;
}
//////////////////////////////////////////////////////////////////////////
CU82A::CU82A( const char* pszStr )
: m_pszBufferA(NULL), m_pszBufferU8(NULL)
{
assert( pszStr != NULL );
CopyAnsiString( &m_pszBufferU8, pszStr );
}
CU82A::CU82A( const std::string& str )
: m_pszBufferA(NULL), m_pszBufferU8(NULL)
{
CopyAnsiString( &m_pszBufferU8, str.c_str() );
}
CU82A::operator const char *()
{
return c_str();
}
const char* CU82A::c_str()
{
assert( m_pszBufferU8 != NULL );
if( m_pszBufferA != NULL )
return m_pszBufferA;
wchar_t* pwszBuffer = NULL;
#ifdef _WINDOWS_
int nReqSize = MultiByteToWideChar( CP_UTF8, 0, m_pszBufferU8, -1, pwszBuffer, 0 );
pwszBuffer = new wchar_t[ nReqSize ];
memset( pwszBuffer, '\0', nReqSize * sizeof( wchar_t ) );
int nRetSize = MultiByteToWideChar( CP_UTF8, 0, m_pszBufferU8, -1, pwszBuffer, nReqSize );
if( nRetSize > 0 )
{
nReqSize = WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS, pwszBuffer, -1, m_pszBufferA, 0, NULL, NULL );
m_pszBufferA = new char[ nReqSize ];
memset( m_pszBufferA, '\0', nReqSize * sizeof( char ) );
nRetSize = WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS, pwszBuffer, -1, m_pszBufferA, nReqSize, NULL, NULL );
DeletePtrA< wchar_t* >( pwszBuffer );
if( nRetSize > 0 )
return m_pszBufferA;
}
#else
int nReqSize = getActualUTF8Length( m_pszBufferU8 );
pwszBuffer = new wchar_t[ nReqSize ];
memset( pwszBuffer, '\0', nReqSize * sizeof( wchar_t ) );
convertUTF8toUTF16( m_pszBufferU8, pwszBuffer );
nReqSize = wcstombs( NULL, pwszBuffer, 0 );
m_pszBufferA = new char[ ++nReqSize ];
memset( m_pszBufferA, '\0', nReqSize * sizeof( char ) );
int nRetSize = wcstombs( m_pszBufferA, pwszBuffer, nReqSize );
if( nRetSize >= 0 )
return m_pszBufferA;
#endif
return "";
}
CU82A& CU82A::operator =( const char* pszStr )
{
assert( pszStr != NULL );
CopyAnsiString( &m_pszBufferU8, pszStr );
return *this;
}
CU82A& CU82A::operator =( const std::string& str )
{
CopyAnsiString( &m_pszBufferU8, str.c_str() );
return *this;
}
<file_sep>/UnArkWCX_Test/UnArkWCX_Test_Util.h
#pragma once
#include <string>
#include <vector>
#include "../UnArkWCX_Export.h"
std::wstring GetCurrentPath();
void SetDefaultPackerExtension( const wchar_t* wszExtension );
void SetINIFilePath( pFnPackSetDefaultParams pfnPackSetDefaultParams );
wchar_t* GetAddList( const std::vector< std::wstring >& vecAddedFile, const std::wstring& strSubPath );
<file_sep>/Library/CommonLogger.cpp
#include "stdafx.h"
#include "CommonLogger.h"
#include <io.h>
#include <process.h>
#include <iostream>
#include <shlwapi.h>
#pragma comment(lib, "shlwapi")
#include "ConvertStr.h"
#pragma warning( disable: 4996 )
CLog* CLog::pClsLog = NULL;
volatile bool CLog::isExit = false;
CLog::CLog()
: m_hProcessLOGThread( NULL )
, m_eCurrentLogLevel( LL_NONE ), m_eLogLevel( LL_NONE )
, m_lCurrentIndex( -1 )
, m_eLogTransfer( LT_DEBUGGER )
, m_nSplitCount(0)
, m_IsFileSplit( true )
, m_IsFileSplitWhenDate( true )
, m_nFileLimitSize( 0 )
, m_pLogFile( NULL )
{
memset( m_szCurrentLogFile, '\0', _countof( m_szCurrentLogFile ) * sizeof( wchar_t ) );
memset( m_szDateFormatA, '\0', _countof( m_szDateFormatA ) * sizeof( char ) );
memset( m_szDateFormatW, '\0', _countof( m_szDateFormatW ) * sizeof( wchar_t ) );
memset( m_szTimeFormatA, '\0', _countof( m_szTimeFormatA ) * sizeof( char ) );
memset( m_szTimeFormatW, '\0', _countof( m_szTimeFormatW ) * sizeof( wchar_t ) );
SetDateFormat( NULL );
SetTimeFormat( NULL );
InitializeCriticalSectionAndSpinCount( &m_cs, 4000 );
m_hProcessLOGThread = (HANDLE)_beginthreadex( NULL, 0, &CLog::processLOGThread, this, 0, NULL );
for( int idx = 0; idx < MAX_MESSAGE_COUNT; ++idx )
{
PLOGDATA pLogData = new LOGDATA;
pLogData->dwBufferSizeA += MSG_BUFFER_SIZE;
pLogData->dwBufferSizeW += MSG_BUFFER_SIZE;
pLogData->szLogData = new char[ pLogData->dwBufferSizeA ];
pLogData->wszLogData = new wchar_t[ pLogData->dwBufferSizeW ];
pLogData->dwRemainBufferSizeA = pLogData->dwBufferSizeA;
pLogData->dwRemainBufferSizeW = pLogData->dwBufferSizeW;
pLogData->szNextMsgPtrA = pLogData->szLogData;
pLogData->szNextMsgPtrW = pLogData->wszLogData;
InterlockedExchange( &pLogData->isUse, 0 );
m_vecLOGData.push_back( pLogData );
}
}
CLog::~CLog()
{
WaitForSingleObject( m_hProcessLOGThread, INFINITE );
CloseHandle( m_hProcessLOGThread );
m_hProcessLOGThread = NULL;
for( size_t idx = 0; idx < m_vecLOGData.size(); ++idx )
{
if( m_vecLOGData[ idx ]->wszLogData != NULL )
delete [] m_vecLOGData[ idx ]->wszLogData;
if( m_vecLOGData[ idx ]->szLogData != NULL )
delete [] m_vecLOGData[ idx ]->szLogData;
}
}
CLog* CLog::GetInstance( void )
{
if( CLog::pClsLog == NULL && CLog::isExit == false )
CLog::pClsLog = new CLog();
return CLog::pClsLog;
}
void CLog::CloseInstance( void )
{
if( CLog::pClsLog )
delete CLog::pClsLog;
CLog::pClsLog = NULL;
CLog::isExit = true;
}
bool CLog::IsLogging( CLOG_LEVEL logLevel )
{
m_eCurrentLogLevel = logLevel;
return m_eLogLevel >= m_eCurrentLogLevel;
}
void CLog::Lock()
{
EnterCriticalSection( &m_cs );
}
void CLog::Unlock()
{
LeaveCriticalSection( &m_cs );
}
size_t CLog::Log( const char* szFileName, const char* szFuncName, const wchar_t* wszFileName, const wchar_t* wszFuncName, unsigned int nLineNumber, const char* fmt, ... )
{
size_t ret = 0;
int logIndex = -1;
InterlockedCompareExchange( &m_lCurrentIndex, -1, MAX_MESSAGE_COUNT );
logIndex = InterlockedIncrement( &m_lCurrentIndex );
PLOGDATA pLogDATA = m_vecLOGData[ logIndex ];
while( InterlockedCompareExchange( &pLogDATA->isUse, 1, 0 ) != 0 && isExit == false )
SleepEx( 0, TRUE );
pLogDATA->isUnicode = false;
pLogDATA->dwRemainBufferSizeA = pLogDATA->dwBufferSizeA;
pLogDATA->szNextMsgPtrA = pLogDATA->szLogData;
ZeroMemory( pLogDATA->szLogData, pLogDATA->dwBufferSizeA * sizeof( char ) );
ret += log_arg_list( szFileName, szFuncName, nLineNumber, m_strPreFixA.c_str(), false, pLogDATA, NULL );
va_list args;
va_start( args, fmt );
ret += log_arg_list( szFileName, szFuncName, nLineNumber, fmt, true, pLogDATA, args );
va_end( args );
Lock();
m_queueLOGData.push( logIndex );
Unlock();
return ret;
}
size_t CLog::Log( const char* szFileName, const char* szFuncName, const wchar_t* wszFileName, const wchar_t* wszFuncName, unsigned int nLineNumber, const wchar_t* fmt, ... )
{
size_t ret = 0;
int logIndex = -1;
InterlockedCompareExchange( &m_lCurrentIndex, -1, MAX_MESSAGE_COUNT );
logIndex = InterlockedIncrement( &m_lCurrentIndex );
PLOGDATA pLogDATA = m_vecLOGData[ logIndex ];
while( InterlockedCompareExchange( &pLogDATA->isUse, 1, 0 ) != 0 && isExit == false )
SleepEx( 0, TRUE );
pLogDATA->isUnicode = true;
pLogDATA->dwRemainBufferSizeW = pLogDATA->dwBufferSizeW;
pLogDATA->szNextMsgPtrW = pLogDATA->wszLogData;
ZeroMemory( pLogDATA->wszLogData, pLogDATA->dwBufferSizeW * sizeof( wchar_t ) );
ret += log_arg_list( wszFileName, wszFuncName, nLineNumber, m_strPreFixW.c_str(), false, pLogDATA, NULL );
va_list args;
va_start( args, fmt );
ret += log_arg_list( wszFileName, wszFuncName, nLineNumber, fmt, true, pLogDATA, args );
va_end( args );
Lock();
m_queueLOGData.push( logIndex );
Unlock();
return ret;
}
bool CLog::AddCallbackA( pfnLogCallbackA pfnCallback, PVOID pParam )
{
if( pfnCallback == NULL )
return false;
bool isFound = false;
// 콜백 함수가 이미 있는지 검사 후 추가
for( std::map<pfnLogCallbackA, PVOID>::iterator iter = m_lstCallbackA.begin(); iter != m_lstCallbackA.end(); ++iter )
{
if( iter->first == pfnCallback )
isFound = true;
}
Lock();
if( isFound == false )
m_lstCallbackA.insert( std::make_pair( pfnCallback, pParam ) );
Unlock();
return true;
}
bool CLog::AddCallbackW( pfnLogCallbackW pfnCallback, PVOID pParam )
{
if( pfnCallback == NULL )
return false;
bool isFound = false;
// 콜백 함수가 이미 있는지 검사 후 추가
for( std::map<pfnLogCallbackW, PVOID>::iterator iter = m_lstCallbackW.begin(); iter != m_lstCallbackW.end(); ++iter )
{
if( iter->first == pfnCallback )
isFound = true;
}
Lock();
if( isFound == false )
m_lstCallbackW.insert( std::make_pair( pfnCallback, pParam ) );
Unlock();
return true;
}
void CLog::RemoveCallbackA( pfnLogCallbackA pfnCallback )
{
Lock();
if( m_lstCallbackA.empty() )
{
return ;
Unlock();
}
for( std::map<pfnLogCallbackA, PVOID>::iterator iter = m_lstCallbackA.begin(); iter != m_lstCallbackA.end(); ++iter )
{
if( iter->first == pfnCallback )
{
m_lstCallbackA.erase( iter );
Unlock();
return ;
}
}
Unlock();
}
void CLog::RemoveCallbackW( pfnLogCallbackW pfnCallback )
{
Lock();
if( m_lstCallbackW.empty() )
{
return ;
Unlock();
}
for( std::map<pfnLogCallbackW, PVOID>::iterator iter = m_lstCallbackW.begin(); iter != m_lstCallbackW.end(); ++iter )
{
if( iter->first == pfnCallback )
{
m_lstCallbackW.erase( iter );
Unlock();
return ;
}
}
Unlock();
}
void CLog::SetLogLevel( CLOG_LEVEL logLevel )
{
m_eLogLevel = logLevel;
}
void CLog::SetLogTransfer( DWORD logTransfer )
{
m_eLogTransfer = logTransfer;
}
void CLog::SetLogPrefix( const wchar_t* pwszLogPrefix /* = NULL */ )
{
if( pwszLogPrefix == NULL )
{
m_strPreFixA = "[LEVEL=%l][DateTime=%D %t][PID=%P][TID=%T][File=%N-%L][Func=%F]";
m_strPreFixW = L"[LEVEL=%l][DateTime=%D %t][PID=%P][TID=%T][File=%N-%L][Func=%F]";
}
else
{
m_strPreFixW = pwszLogPrefix;
m_strPreFixA = CU2A( pwszLogPrefix ).c_str();
}
}
void CLog::SetDateFormat( const wchar_t* pwszDateFormat /* = NULL */ )
{
if( pwszDateFormat == NULL )
{
strcpy( m_szDateFormatA, "%Y-%m-%d" );
wcscpy( m_szDateFormatW, L"%Y-%m-%d" );
}
else
{
strcpy( m_szDateFormatA, CU2A( pwszDateFormat ) );
wcscpy( m_szDateFormatW, pwszDateFormat );
}
}
void CLog::SetTimeFormat( const wchar_t* pwszTimeFormat /* = NULL */ )
{
if( pwszTimeFormat == NULL )
{
strcpy( m_szTimeFormatA, "%H:%M:%S" );
wcscpy( m_szTimeFormatW, L"%H:%M:%S" );
}
else
{
strcpy( m_szTimeFormatA, CU2A(pwszTimeFormat) );
wcscpy( m_szTimeFormatW, pwszTimeFormat );
}
}
bool CLog::SetLogFile( const wchar_t* szLogPath, const wchar_t* szLogName, const wchar_t* szLogExt )
{
assert( m_szLogName != NULL );
assert( m_szLogPath != NULL );
assert( m_szLogExt != NULL );
memset( m_szLogPath, '\0', _countof( m_szLogPath ) * sizeof( wchar_t ) );
memset( m_szLogName, '\0', _countof( m_szLogPath ) * sizeof( wchar_t ) );
memset( m_szLogExt, '\0', _countof( m_szLogPath ) * sizeof( wchar_t ) );
wcscpy( m_szLogPath, szLogPath );
if( m_szLogPath[0] == L'.' )
{
TCHAR wszBuffer[MAX_PATH] = {0,};
GetModuleFileName( NULL, wszBuffer, MAX_PATH );
PathRemoveFileSpec( wszBuffer );
wcscpy( m_szLogPath, string_replace_all( m_szLogPath, L".", wszBuffer ).c_str() );
}
if( m_szLogPath[ wcslen(m_szLogPath) - 1 ] != L'\\' )
wcscat( m_szLogPath, L"\\" );
wcscpy( m_szLogName, szLogName );
if( szLogExt[0] == L'.' )
wcscpy( m_szLogExt, szLogExt+1 );
else
wcscpy( m_szLogExt, szLogExt );
// 디렉토리 생성
if( checkDirectory( m_szLogPath ) != ERROR_SUCCESS && wcsicmp( m_szLogPath, L".\\" ) != 0 )
return false;
return createLogFile();
}
unsigned int CLog::GetFileLimitSize( void )
{
return m_nSplitCount;
}
void CLog::SetFileLimitSize( unsigned int nFileLimitSize /*= 0*/, bool IsFileSplit /*= true*/, bool IsFileSplitWhenDate /*= true */ )
{
m_nFileLimitSize = nFileLimitSize;
m_IsFileSplitWhenDate = IsFileSplitWhenDate;
m_IsFileSplit = IsFileSplit;
}
DWORD CLog::checkDirectory( const wchar_t* szDirectory )
{
const unsigned int MAX_FOLDER_DEPTH = 122;
DWORD dwRet = ERROR_SUCCESS;
size_t nLen = wcslen( szDirectory );
if( nLen < (_MAX_DRIVE + 1) || nLen > (MAX_PATH - 1) )
return ERROR_BAD_PATHNAME;
wchar_t szPath[MAX_PATH] = {0,};
INT_PTR offset = _MAX_DRIVE;
for(int i = 0; i < MAX_FOLDER_DEPTH; i++)
{
if( (UINT_PTR)offset >= nLen )
break;
const wchar_t * pos = szDirectory + offset;
const wchar_t * dst = wcschr(pos, L'\\');
if( dst == NULL )
{
wcsncpy_s(szPath, MAX_PATH, szDirectory, nLen);
i = MAX_FOLDER_DEPTH;
}
else
{
INT_PTR cnt = dst - szDirectory;
wcsncpy_s(szPath, MAX_PATH, szDirectory, cnt);
offset = cnt + 1;
}
if( ::CreateDirectoryW(szPath, NULL) == FALSE )
{
DWORD dwErr = GetLastError();
if( dwErr != ERROR_ALREADY_EXISTS )
{
dwRet = dwErr;
break;
}
}
}
return dwRet;
}
std::wstring CLog::GetFileName( void )
{
if( m_szCurrentLogFile[ 0 ] != L'\0' )
return m_szCurrentLogFile;
TCHAR szBuffer[ MAX_TIME_BUFFER_SIZE ] = {0,};
if( !wcsftime( szBuffer, MAX_TIME_BUFFER_SIZE, L"%Y-%m-%d", &m_tmCreateLogTime ) )
szBuffer[0] = L'\0';
wcscpy( m_szCurrentLogFile, format( L"%s%s_%s-[%02d].%s", m_szLogPath, m_szLogName, szBuffer[0] == NULL ? L"Unknown Date" : szBuffer, m_nSplitCount, m_szLogExt ).c_str() );
return m_szCurrentLogFile;
}
void CLog::checkFileExist( void )
{
wchar_t szBuffer[ MAX_TIME_BUFFER_SIZE ] = {0,};
if( !wcsftime( szBuffer, MAX_TIME_BUFFER_SIZE, L"%Y-%m-%d", &m_tmCreateLogTime ) )
szBuffer[0] = L'\0';
m_nSplitCount = 0;
std::wstring strFile = format( L"%s%s_%s-[*].%s", m_szLogPath, m_szLogName, szBuffer[0] == NULL ? L"Unknown Date" : szBuffer, m_szLogExt );
_wfinddata_t data;
intptr_t hSearch = _wfindfirst( strFile.c_str(), &data );
if( hSearch == -1 )
return;
while( _wfindnext( hSearch, &data) != -1 )
m_nSplitCount++;
_findclose( hSearch );
}
bool CLog::checkFileSizeAndTime( const wchar_t* szFileName )
{
bool isSplit = false;
do
{
// 파일 용량 관련 점검
if( m_nFileLimitSize == 0 )
break;
static const __int64 MEGABYTE = 1024 * 1024;
struct __stat64 statFile;
if( _wstat64( szFileName, &statFile ) == -1 )
break;
__int64 llFileSize = statFile.st_size;
if( llFileSize >= ( m_nFileLimitSize * MEGABYTE ) )
{
m_nSplitCount++;
isSplit = true;
}
} while( false );
do
{
// 날짜 관련 점검
if( m_IsFileSplitWhenDate == false )
break;
__time64_t currentTime = ::_time64(NULL);
struct tm tmCurrentTime;
errno_t err = _localtime64_s( &tmCurrentTime, ¤tTime );
if( err != 0 )
break;
if( tmCurrentTime.tm_yday > m_tmCreateLogTime.tm_yday )
{
m_tmCreateLogTime = tmCurrentTime;
m_nSplitCount = 0;
isSplit = true;
}
} while( false );
if( isSplit == true )
return createLogFile();
return true;
}
bool CLog::createLogFile()
{
bool isSuccess = false;
do
{
__time64_t tmCurrentTime = ::_time64( NULL );
errno_t err = _localtime64_s( &m_tmCreateLogTime, &tmCurrentTime );
if( err != 0 )
break;
checkFileExist();
m_pLogFile = _wfopen( GetFileName().c_str(), L"a+t, ccs=UTF-16LE" );
if( m_pLogFile == NULL )
break;
BYTE utf16_le_bom[] = { 0xFF, 0xFE };
fwrite( utf16_le_bom, sizeof(BYTE), _countof( utf16_le_bom ), m_pLogFile );
isSuccess = true;
} while( false );
return isSuccess;
}
unsigned int __stdcall CLog::processLOGThread( PVOID pParam )
{
CLog* pLogger = reinterpret_cast< CLog* >( pParam );
LOGDATA* logData = NULL;
int nLOGDataIndex = -1;
while( isExit == false )
{
do
{
pLogger->Lock();
if( pLogger->m_queueLOGData.empty() == false )
{
nLOGDataIndex = pLogger->m_queueLOGData.front();
pLogger->m_queueLOGData.pop();
pLogger->Unlock();
}
else
{
pLogger->Unlock();
break;
}
if( nLOGDataIndex < 0 )
break;
logData = pLogger->m_vecLOGData[ nLOGDataIndex ];
nLOGDataIndex = -1;
// 로그 처리
if( logData->isUnicode == true )
{
if( pLogger->m_eLogTransfer & LT_DEBUGGER )
OutputDebugStringW( logData->wszLogData );
if( pLogger->m_eLogTransfer & LT_STDERR )
std::wcerr << logData->wszLogData << std::endl;
if( pLogger->m_eLogTransfer & LT_STDOUT )
std::wcout << logData->wszLogData << std::endl;
if( pLogger->m_eLogTransfer & LT_FILE )
{
if( pLogger->m_pLogFile == NULL )
pLogger->createLogFile();
if( pLogger->checkFileSizeAndTime( pLogger->GetFileName().c_str() ) == true )
{
fputws( logData->wszLogData, pLogger->m_pLogFile );
fflush( pLogger->m_pLogFile );
}
}
if( pLogger->m_eLogTransfer & LT_CALLBACK )
{
pLogger->Lock();
for( std::map< pfnLogCallbackW, PVOID >::iterator it = pLogger->m_lstCallbackW.begin(); it != pLogger->m_lstCallbackW.end(); ++it )
(*it->first)( it->second, pLogger->m_eLogLevel, pLogger->m_eCurrentLogLevel, logData->wszLogData );
for( std::map< pfnLogCallbackA, PVOID >::iterator it = pLogger->m_lstCallbackA.begin(); it != pLogger->m_lstCallbackA.end(); ++it )
(*it->first)( it->second, pLogger->m_eLogLevel, pLogger->m_eCurrentLogLevel, CU2A(logData->wszLogData).c_str() );
pLogger->Unlock();
}
}
else
{
if( pLogger->m_eLogTransfer & LT_DEBUGGER )
OutputDebugStringA( logData->szLogData );
if( pLogger->m_eLogTransfer & LT_STDERR )
std::cerr << logData->szLogData << std::endl;
if( pLogger->m_eLogTransfer & LT_STDOUT )
std::cout << logData->szLogData << std::endl;
if( pLogger->m_eLogTransfer & LT_FILE )
{
if( pLogger->m_pLogFile == NULL )
pLogger->createLogFile();
if( pLogger->checkFileSizeAndTime( pLogger->GetFileName().c_str() ) == true )
{
fputws( CA2U(logData->szLogData), pLogger->m_pLogFile );
fflush( pLogger->m_pLogFile );
}
}
if( pLogger->m_eLogTransfer & LT_CALLBACK )
{
pLogger->Lock();
for( std::map< pfnLogCallbackW, PVOID >::iterator it = pLogger->m_lstCallbackW.begin(); it != pLogger->m_lstCallbackW.end(); ++it )
(*it->first)( it->second, pLogger->m_eLogLevel, pLogger->m_eCurrentLogLevel, CA2U(logData->szLogData).c_str() );
for( std::map< pfnLogCallbackA, PVOID >::iterator it = pLogger->m_lstCallbackA.begin(); it != pLogger->m_lstCallbackA.end(); ++it )
(*it->first)( it->second, pLogger->m_eLogLevel, pLogger->m_eCurrentLogLevel, logData->szLogData);
pLogger->Unlock();
}
}
InterlockedExchange( &logData->isUse, 0 );
} while (false);
SleepEx( 10, TRUE );
}
return 0;
}
size_t CLog::log_arg_list( const char* szFileName, const char* szFuncName, unsigned int nLineNumber, const char* fmt, bool isAppendNewLine, LOGDATA* pLOGDATA, va_list args )
{
assert( fmt != NULL );
int nRetSize = 0;
while( *fmt != '\0' )
{
if( (*fmt != '%') ||
(*fmt == '%' && fmt[1] == '%') )
{
// % 가 없으면 %가 나타날때까지 복사
*pLOGDATA->szNextMsgPtrA++ = *fmt++;
if( *fmt == '%' && fmt[1] == '%' )
++fmt;
--pLOGDATA->dwRemainBufferSizeA;
nRetSize++;
}
else
{
bool isDone = false;
const char* start_format = fmt;
char* fp = NULL;
char szFormat[ 64 ] = {0,};
int nResult = 0; // snprintf 가 기록한 양 또는 기록하는데 필요한 양
fp = szFormat;
*fp++ = *fmt++; // % 문자를 넣음
while( isDone == false )
{
isDone = true;
nResult = 0;
switch( *fmt )
{
case 'b':
case 'B':
strcpy( fp, "s" );
if( getBufferA( 6 /* FALSE 길이 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, va_arg( args, bool ) == true ? "TRUE" : "FALSE" );
break;
case 'D': // 날짜 출력
{
strcpy( fp, "s" );
struct tm tmTemp;
__time64_t tmCurrentTime = _time64( NULL );
errno_t err = ::_localtime64_s( &tmTemp, &tmCurrentTime );
char szBuffer[ MAX_TIME_BUFFER_SIZE ] = {0,};
if( err != 0 || !strftime( szBuffer, MAX_TIME_BUFFER_SIZE, m_szDateFormatA, &tmTemp ) )
{
if( getBufferA( 15 /* L"<Unknown Date>" 의 길이 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, "<Unknown Date>" );
}
else
{
if( getBufferA( strlen( szBuffer ), pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, szBuffer );
}
}
break;
case 'E': // GetLastError() 의 오류코드를 문자열 설명으로 변경
case 'H': // HRESULT 형식의 오류코드를 문자열 설명으로 변경
{
strcpy( fp, "s" );
HLOCAL hLocal = NULL;
BOOL IsResult = FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, va_arg( args, int ), MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ), (PSTR)&hLocal, 0, NULL );
if( IsResult != FALSE )
{
PSTR pszBuffer = (PSTR)::LocalLock( hLocal );
if( getBufferA( strlen( pszBuffer ), pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, pszBuffer );
LocalFree( hLocal );
}
else
{
if( getBufferA( strlen("<FormatMessage Fail>"), pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, "<FormatMessage Fail>" );
}
}
break;
case 'f': // 부동소수점, C 언어는 인자를 받을 때 float 와 double 을 모두 double 로 상승시켜서 받음
fp[0] = *fmt;
fp[1] = '\0';
if( getBufferA( _CVTBUFSIZE, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, va_arg( args, double ) );
break;
case 'F': // 소스코드 함수이름
strcpy( fp, "s" );
if( getBufferA( strlen( szFuncName ), pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, szFuncName );
break;
case 'i': // 64비트 정수
case 'I':
if( ( fmt[ 1 ] == '6' ) && ( fmt[ 2 ] == '4' ) && ( fmt[ 3 ] == 'd' || fmt[ 3 ] == 'u' ) )
{
*fp++ = 'I';
*fp++ = fmt[1];
*fp++ = fmt[2];
*fp++ = fmt[3];
*fp = '\0';
if( getBufferA( 21 /* 2 ^ 64 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, va_arg( args, __int64 ) );
}
break;
case 'l': // 로그 레벨 문자열로
strcpy( fp, "s" );
if( getBufferA( 14 /* 로그 레벨 최대 길이 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, getLogLevelA() );
break;
case 'L': // 소스코드 줄 번호
strcpy( fp, "u" );
if( getBufferA( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, nLineNumber );
break;
case 'N': // 소스코드 파일이름
strcpy( fp, "s" );
if( getBufferA( strlen( szFileName ), pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, szFileName );
break;
case 'P': // 프로세스 ID
strcpy( fp, "u" );
if( getBufferA( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, ::GetCurrentProcessId() );
break;
case 't': // 시간 출력
{
strcpy( fp, "s" );
struct tm tmTemp;
__time64_t tmCurrentTime = _time64( NULL );
errno_t err = ::_localtime64_s( &tmTemp, &tmCurrentTime );
char szBuffer[ MAX_TIME_BUFFER_SIZE ] = {0,};
if( err != 0 || !strftime( szBuffer, MAX_TIME_BUFFER_SIZE, m_szTimeFormatA, &tmTemp ) )
{
if( getBufferA( 15 /* L"<Unknown Date>" 의 길이 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, "<Unknown Time>" );
}
else
{
if( getBufferA( strlen( szBuffer ), pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, szBuffer );
}
}
break;
case 'T': // 스레드 ID
strcpy( fp, "u" );
if( getBufferA( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, ::GetCurrentThreadId() );
break;
case 's': // 문자열
{
char* pszArgs = va_arg( args, char* );
strcpy( fp, "s" );
if( pszArgs == NULL )
{
if( getBufferA( 7 /* L"(null)" 의 길이 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, "(null)" );
}
else
{
if( getBufferA( strlen( pszArgs ) + 1, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, pszArgs );
}
}
break;
case L'o': // 8진수
case L'x': // 16진수, 문자는 소문자
case L'X': // 16진수, 문자는 대문자
case L'd': // 부호있는 정수
case L'u': // 부호없는 정수
fp[0] = *fmt;
fp[1] = '\0';
if( getBufferA( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snprintf( pLOGDATA->szNextMsgPtrA, pLOGDATA->dwRemainBufferSizeA, szFormat, va_arg( args, int ) );
break;
default:
while( start_format != fmt && pLOGDATA->dwRemainBufferSizeA > 0 )
{
*pLOGDATA->szNextMsgPtrA++ = *start_format++;
--pLOGDATA->dwRemainBufferSizeA;
}
if( pLOGDATA->dwRemainBufferSizeA > 0 )
{
*pLOGDATA->szNextMsgPtrA++ = *fmt;
--pLOGDATA->dwRemainBufferSizeA;
}
break;
} // switch
if( nResult > 0 ) // snprintf 에 기록된 양이 있으면 그만큼 버퍼 포인터 이동 및 남은 버퍼크기 감소
{
pLOGDATA->szNextMsgPtrA += nResult;
pLOGDATA->dwRemainBufferSizeA -= nResult;
nRetSize += nResult;
}
++fmt;
} // while
} // if
} // while
if( isAppendNewLine == true &&
getBufferA( 1 /* L"\n" 의 길이 */, pLOGDATA ) == true )
{
strcpy( pLOGDATA->szNextMsgPtrA, "\n" );
pLOGDATA->szNextMsgPtrA += 1;
nRetSize += 1;
pLOGDATA->dwRemainBufferSizeA -= 1;
}
return nRetSize;
}
size_t CLog::log_arg_list( const wchar_t* wszFileName, const wchar_t* wszFuncName, unsigned int nLineNumber, const wchar_t* fmt, bool isAppendNewLine, LOGDATA* pLOGDATA, va_list args )
{
assert( fmt != NULL );
int nRetSize = 0;
while( *fmt != L'\0' )
{
if( (*fmt != L'%') ||
(*fmt == L'%' && fmt[1] == L'%') )
{
// % 가 없으면 %가 나타날때까지 복사
*pLOGDATA->szNextMsgPtrW++ = *fmt++;
if( *fmt == L'%' && fmt[1] == L'%' )
++fmt;
--pLOGDATA->dwRemainBufferSizeW;
nRetSize++;
}
else
{
bool isDone = false;
const wchar_t* start_format = fmt;
wchar_t* fp = NULL;
wchar_t szFormat[ 64 ] = {0,};
int nResult = 0; // snprintf 가 기록한 양 또는 기록하는데 필요한 양
fp = szFormat;
*fp++ = *fmt++; // % 문자를 넣음
while( isDone == false )
{
isDone = true;
nResult = 0;
switch( *fmt )
{
case L'b':
case L'B':
wcscpy( fp, L"s" );
if( getBufferW( 6 /* FALSE 길이 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, va_arg( args, bool ) == true ? L"TRUE" : L"FALSE" );
break;
case L'D': // 날짜 출력
{
wcscpy( fp, L"s" );
struct tm tmTemp;
__time64_t tmCurrentTime = _time64( NULL );
errno_t err = ::_localtime64_s( &tmTemp, &tmCurrentTime );
wchar_t szBuffer[ MAX_TIME_BUFFER_SIZE ] = {0,};
if( err != 0 || !wcsftime( szBuffer, MAX_TIME_BUFFER_SIZE, m_szDateFormatW, &tmTemp ) )
{
if( getBufferW( 15 /* L"<Unknown Date>" 의 길이 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, L"<Unknown Date>" );
}
else
{
if( getBufferW( wcslen( szBuffer ), pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, szBuffer );
}
}
break;
case L'E': // GetLastError() 의 오류코드를 문자열 설명으로 변경
case L'H': // HRESULT 형식의 오류코드를 문자열 설명으로 변경
{
wcscpy( fp, L"s" );
HLOCAL hLocal = NULL;
BOOL IsResult = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, va_arg( args, int ), MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ), (PWSTR)&hLocal, 0, NULL );
if( IsResult != FALSE )
{
PWSTR pwszBuffer = (PWSTR)::LocalLock( hLocal );
if( getBufferW( wcslen( pwszBuffer ), pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, pwszBuffer );
LocalFree( hLocal );
}
else
{
if( getBufferW( wcslen(L"<FormatMessage Fail>"), pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, L"<FormatMessage Fail>" );
}
}
break;
case L'f': // 부동소수점, C 언어는 인자를 받을 때 float 와 double 을 모두 double 로 상승시켜서 받음
fp[0] = *fmt;
fp[1] = L'\0';
if( getBufferW( _CVTBUFSIZE, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, va_arg( args, double ) );
break;
case L'F': // 소스코드 함수이름
wcscpy( fp, L"s" );
if( getBufferW( wcslen( wszFuncName ), pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, wszFuncName );
break;
case L'i': // 64비트 정수
case L'I':
if( ( fmt[ 1 ] == L'6' ) && ( fmt[ 2 ] == L'4' ) && ( fmt[ 3 ] == L'd' || fmt[ 3 ] == L'u' ) )
{
*fp++ = L'I';
*fp++ = fmt[1];
*fp++ = fmt[2];
*fp++ = fmt[3];
*fp = L'\0';
if( getBufferW( 21 /* 2 ^ 64 최대 정수형의 자리수 */,pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, va_arg( args, __int64 ) );
}
break;
case L'l': // 로그 레벨 문자열로
wcscpy( fp, L"s" );
if( getBufferW( 14 /* 로그 레벨 최대 길이 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, getLogLevelW() );
break;
case L'L': // 소스코드 줄 번호
wcscpy( fp, L"u" );
if( getBufferW( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, nLineNumber );
break;
case L'N': // 소스코드 파일이름
wcscpy( fp, L"s" );
if( getBufferW( wcslen( wszFileName ), pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, wszFileName );
break;
case L'P': // 프로세스 ID
wcscpy( fp, L"u" );
if( getBufferW( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, ::GetCurrentProcessId() );
break;
case L't': // 시간 출력
{
wcscpy( fp, L"s" );
struct tm tmTemp;
__time64_t tmCurrentTime = _time64( NULL );
errno_t err = ::_localtime64_s( &tmTemp, &tmCurrentTime );
wchar_t szBuffer[ MAX_TIME_BUFFER_SIZE ] = {0,};
if( err != 0 || !wcsftime( szBuffer, MAX_TIME_BUFFER_SIZE, m_szTimeFormatW, &tmTemp ) )
{
if( getBufferW( 15 /* L"<Unknown Date>" 의 길이 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, L"<Unknown Time>" );
}
else
{
if( getBufferW( wcslen( szBuffer ), pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, szBuffer );
}
}
break;
case L'T': // 스레드 ID
wcscpy( fp, L"u" );
if( getBufferW( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, ::GetCurrentThreadId() );
break;
case L's': // 문자열
{
wchar_t* pszArgs = va_arg( args, wchar_t* );
wcscpy( fp, L"s" );
if( pszArgs == NULL )
{
if( getBufferW( 7 /* L"(null)" 의 길이 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, L"(null)" );
}
else
{
if( getBufferW( wcslen( pszArgs ) + 1, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, pszArgs );
}
}
break;
case L'o': // 8진수
case L'x': // 16진수, 문자는 소문자
case L'X': // 16진수, 문자는 대문자
case L'd': // 부호있는 정수
case L'u': // 부호없는 정수
fp[0] = *fmt;
fp[1] = L'\0';
if( getBufferW( 11 /* 2 ^ 32, 최대 정수형의 자리수 */, pLOGDATA ) == false )
break;
nResult = _snwprintf( pLOGDATA->szNextMsgPtrW, pLOGDATA->dwRemainBufferSizeW, szFormat, va_arg( args, int ) );
break;
default:
while( start_format != fmt && pLOGDATA->dwRemainBufferSizeW > 0 )
{
*pLOGDATA->szNextMsgPtrW++ = *start_format++;
--pLOGDATA->dwRemainBufferSizeW;
}
if( pLOGDATA->dwRemainBufferSizeW > 0 )
{
*pLOGDATA->szNextMsgPtrW++ = *fmt;
--pLOGDATA->dwRemainBufferSizeW;
}
break;
} // switch
if( nResult > 0 ) // snprintf 에 기록된 양이 있으면 그만큼 버퍼 포인터 이동 및 남은 버퍼크기 감소
{
pLOGDATA->szNextMsgPtrW += nResult;
pLOGDATA->dwRemainBufferSizeW -= nResult;
nRetSize += nResult;
}
++fmt;
} // while
} // if
} // while
if( isAppendNewLine == true &&
getBufferW( 1 /* L"\n" 의 길이 */, pLOGDATA ) == true )
{
wcscpy( pLOGDATA->szNextMsgPtrW, L"\n" );
pLOGDATA->szNextMsgPtrW += 1;
nRetSize += 1;
pLOGDATA->dwRemainBufferSizeW -= 1;
}
return nRetSize;
}
bool CLog::getBufferA( UINT_PTR nRequiredSize, LOGDATA* pLOGDATA )
{
bool isSuccess = true;
do
{
if( pLOGDATA->dwRemainBufferSizeA > nRequiredSize )
break;
do
{
pLOGDATA->dwBufferSizeA += MSG_BUFFER_SIZE;
pLOGDATA->dwRemainBufferSizeA += MSG_BUFFER_SIZE;
} while ( ( pLOGDATA->dwRemainBufferSizeA < nRequiredSize ) );
char* pBuffer = new char[ pLOGDATA->dwBufferSizeA ];
if( pBuffer == NULL )
{
isSuccess = false;
break;
}
ZeroMemory( pBuffer, pLOGDATA->dwBufferSizeA * sizeof( char ) );
strcpy( pBuffer, pLOGDATA->szLogData );
ptrdiff_t nBetween = pLOGDATA->szNextMsgPtrA - pLOGDATA->szLogData;
delete [] pLOGDATA->szLogData;
pLOGDATA->szLogData = pBuffer;
pLOGDATA->szNextMsgPtrA = pLOGDATA->szLogData + nBetween;
} while (false);
return isSuccess;
}
bool CLog::getBufferW( UINT_PTR nRequiredSize, LOGDATA* pLOGDATA )
{
bool isSuccess = true;
do
{
if( pLOGDATA->dwRemainBufferSizeW > nRequiredSize )
break;
do
{
pLOGDATA->dwBufferSizeW += MSG_BUFFER_SIZE;
pLOGDATA->dwRemainBufferSizeW += MSG_BUFFER_SIZE;
} while ( ( pLOGDATA->dwRemainBufferSizeW < nRequiredSize ) );
wchar_t* pBuffer = new wchar_t[ pLOGDATA->dwBufferSizeW ];
if( pBuffer == NULL )
{
isSuccess = false;
break;
}
ZeroMemory( pBuffer, pLOGDATA->dwBufferSizeW * sizeof( wchar_t ) );
wcscpy( pBuffer, pLOGDATA->wszLogData );
ptrdiff_t nBetween = pLOGDATA->szNextMsgPtrW - pLOGDATA->wszLogData;
delete [] pLOGDATA->wszLogData;
pLOGDATA->wszLogData = pBuffer;
pLOGDATA->szNextMsgPtrW = pLOGDATA->wszLogData + nBetween;
} while (false);
return isSuccess;
}
const char* CLog::getLogLevelA()
{
switch( m_eCurrentLogLevel )
{
case LL_NONE:
return "LL_NONE";
break;
case LL_CRITICAL:
return "LL_CRITICAL";
break;
case LL_TRACE:
return "LL_TRACE";
break;
case LL_DEBUG:
return "LL_DEBUG";
break;
case LL_WARNING:
return "LL_WARNING";
break;
case LL_ERROR:
return "LL_ERROR";
break;
}
return "UNKNOWN LEVEL";
}
const wchar_t* CLog::getLogLevelW()
{
switch( m_eCurrentLogLevel )
{
case LL_NONE:
return L"LL_NONE";
break;
case LL_CRITICAL:
return L"LL_CRITICAL";
break;
case LL_TRACE:
return L"LL_TRACE";
break;
case LL_DEBUG:
return L"LL_DEBUG";
break;
case LL_WARNING:
return L"LL_WARNING";
break;
case LL_ERROR:
return L"LL_ERROR";
break;
}
return L"UNKNOWN LEVEL";
}
<file_sep>/UnArkWCX.cpp
// UnArkWCX.cpp : DLL 응용 프로그램을 위해 내보낸 함수를 정의합니다.
//
#include "stdafx.h"
#include "UnArkWCX.h"
#include <string>
#include <vector>
#include <CommCtrl.h>
#include <time.h>
#pragma warning( disable: 4996 )
EXTERN_C UNARKWCX_API HANDLE WINAPI OpenArchive( tOpenArchiveData *pArchiveData )
{
InitLogger();
LM_TRACE( L"Here" );
LM_TRACE( L"압축 파일 열기 시도" );
tOpenArchiveDataW pArchiveDataW;
pArchiveDataW.ArcName = _wcsdup( CA2U( pArchiveData->ArcName ).c_str() );
pArchiveDataW.CmtBuf = NULL;
pArchiveDataW.CmtBufSize = 0;
pArchiveDataW.CmtSize = 0;
pArchiveDataW.CmtState = 0;
pArchiveDataW.OpenMode = pArchiveData->OpenMode;
HANDLE hResult = OpenArchiveW( &pArchiveDataW );
pArchiveData->OpenResult = pArchiveDataW.OpenResult;
free( pArchiveDataW.ArcName );
return hResult;
}
EXTERN_C UNARKWCX_API HANDLE WINAPI OpenArchiveW( tOpenArchiveDataW *pArchiveDataW )
{
InitLogger();
LM_TRACE( L"Here" );
LM_TRACE( L"압축 파일 열기 시도" );
CArkInfo* pArkInfo = NULL;
do
{
pArchiveDataW->OpenResult = E_NOT_SUPPORTED;
if( ( pArchiveDataW->OpenMode != PK_OM_LIST ) &&
( pArchiveDataW->OpenMode != PK_OM_EXTRACT ) )
break;
LM_TRACE( L"압축 파일 이름 : %s", pArchiveDataW->ArcName );
pArkInfo = new CArkInfo;
if( pArkInfo == NULL )
{
pArchiveDataW->OpenResult = E_NO_MEMORY;
break;
}
if( pArkInfo->Open( pArchiveDataW->ArcName, NULL ) == FALSE )
break;
LM_TRACE( L"열기 결과 : %d", pArchiveDataW->OpenResult );
pArchiveDataW->OpenResult = 0;
} while (false);
return (HANDLE)pArkInfo;
}
EXTERN_C UNARKWCX_API int WINAPI ReadHeader( HANDLE hArcData, tHeaderData *pHeaderData )
{
LM_TRACE( L"Here" );
tHeaderDataExW headerDataW;
int nResult = ReadHeaderExW( hArcData, &headerDataW );
strncpy( pHeaderData->ArcName, strdup(CU2A( headerDataW.ArcName ).c_str()), 1024 );
strncpy( pHeaderData->FileName, strdup(CU2A( headerDataW.FileName ).c_str()), 1024 );
pHeaderData->FileAttr = headerDataW.FileAttr;
pHeaderData->FileCRC = headerDataW.FileCRC;
pHeaderData->FileTime = headerDataW.FileTime;
pHeaderData->PackSize = headerDataW.PackSize;
pHeaderData->UnpSize = headerDataW.UnpSize;
free( pHeaderData->ArcName );
free( pHeaderData->FileName );
return nResult;
}
EXTERN_C UNARKWCX_API int WINAPI ReadHeaderExW( HANDLE hArcData, tHeaderDataExW *pHeaderDataExW )
{
LM_TRACE( L"Here" );
CArkInfo* pArkInfo = reinterpret_cast< CArkInfo* >( hArcData );
int nResult = 0;
do
{
if( pArkInfo == INVALID_HANDLE_VALUE )
{
nResult = E_EOPEN;
break;
}
int currentFileIndex = pArkInfo->IncrementCurrentFileIndex();
if( currentFileIndex >= pArkInfo->GetArk()->GetFileItemCount() )
{
nResult = E_END_ARCHIVE;
break;
}
const SArkFileItem* pItem = pArkInfo->GetArk()->GetFileItem( currentFileIndex );
if( pItem == NULL )
{
nResult = E_EOPEN;
break;
}
LM_TRACE( L"Arc Name = %s", pArkInfo->GetArk()->GetFilePathName() );
LM_TRACE( L"File Name = %s", pItem->fileNameW );
LM_TRACE( L"File Time = %i64d", pItem->fileTime );
wcsncpy( pHeaderDataExW->ArcName, pArkInfo->GetArk()->GetFilePathName(), 1023 );
wcsncpy( pHeaderDataExW->FileName, pItem->fileNameW, 1023 );
pHeaderDataExW->FileAttr = pItem->attrib;
struct tm* tmCurrentTime = localtime( &pItem->fileTime );
if( tmCurrentTime != NULL )
{
pHeaderDataExW->FileTime = 0;
pHeaderDataExW->FileTime |= (tmCurrentTime->tm_year + 1900 - 1980) << 25;
pHeaderDataExW->FileTime |= (tmCurrentTime->tm_mon + 1) << 21;
pHeaderDataExW->FileTime |= (tmCurrentTime->tm_mday << 16 );
pHeaderDataExW->FileTime |= (tmCurrentTime->tm_hour << 11 );
pHeaderDataExW->FileTime |= (tmCurrentTime->tm_min << 5 );
pHeaderDataExW->FileTime |= (tmCurrentTime->tm_sec/2);
}
pHeaderDataExW->PackSize = pItem->compressedSize & 0xffffffff;
pHeaderDataExW->PackSizeHigh = pItem->compressedSize >> 32;
pHeaderDataExW->UnpSize = pItem->uncompressedSize & 0xffffffff;
pHeaderDataExW->UnpSizeHigh = pItem->uncompressedSize >> 32;
pHeaderDataExW->FileCRC = pItem->crc32;
pHeaderDataExW->HostOS = 0;
memset( pHeaderDataExW->Reserved, '\0', sizeof( char ) * 1024 );
} while (false);
return nResult;
}
EXTERN_C UNARKWCX_API int WINAPI ProcessFile( HANDLE hArcData, int Operation, char *DestPath, char *DestName)
{
LM_TRACE( L"Here" );
int nResult = 0;
WCHAR* wszDestPath = DestPath == NULL ? NULL : wcsdup( CA2U( DestPath ).c_str() );
WCHAR* wszDestName = DestName == NULL ? NULL : wcsdup( CA2U( DestName ).c_str() );
nResult = ProcessFileW(
hArcData,
Operation,
wszDestPath,
wszDestName );
free( wszDestName );
free( wszDestPath );
return nResult;
}
EXTERN_C UNARKWCX_API int WINAPI ProcessFileW( HANDLE hArcData, int Operation, WCHAR* pwszDestPath, WCHAR* pwszDestName )
{
LM_TRACE( L"Here" );
CArkInfo* pArkInfo = reinterpret_cast< CArkInfo* >( hArcData );
int nResult = 0;
do
{
if( pArkInfo == NULL )
{
nResult = E_EOPEN;
break;
}
switch( Operation )
{
case PK_SKIP:
break;
case PK_TEST:
break;
case PK_EXTRACT:
{
/*
pwszDestPath == NULL 이면 pwszDestName 에 경로명과 파일명이 모두 있음
pwszDestPath != NULL 이면 pwszDestPath 에는 경로가 pwszDestName 에는 파일명이 있음
*/
// /*
// Ark Library 의 ExtractOneAs 메소드에 오류가 있음.
// 우회책으로 pwszDestName 에 넘어온 경로명과 파일명을 분리해낸 후 경로명만 넘김
// 하지만 pwszDestName 에는 압축파일을 풀 대상경로와 압축파일 내부에서의 경로등이 모두 포함되어있음.
//
// 토탈 커맨더에서 압축을 풀면서 파일이름을 변경하거나 하는 일은 없다고 판단하여 위와 같이 작성함
// */
int ret = 0;
pArkInfo->GetArk()->SetEvent( &(pArkInfo->GetArkEvent()) );
if( ( pwszDestPath == NULL ) &&
( pwszDestName != NULL ) )
{
// LM_TRACE(( L"최초 전체 경로 : %s", pwszDestName ));
const SArkFileItem* pItem = pArkInfo->GetArk()->GetFileItem( pArkInfo->GetCurrentFileIndex() );
// LM_TRACE(( L"해당 색인의 파일이름 : %s", pItem->fileNameW ));
//
std::wstring wstrDestName( pwszDestName );
std::wstring::size_type nPos = wstrDestName.rfind( pItem->fileNameW );
if( nPos != std::wstring::npos )
{
// LM_TRACE(( L"대상 경로 : %s", wstrDestName.substr( 0, nPos ).c_str() ));
ret = pArkInfo->GetArk()->ExtractOneTo( pArkInfo->GetCurrentFileIndex(), wstrDestName.substr( 0, nPos ).c_str() );
}
else
{
// LM_ERROR(( L"색인과 대상경로가 겹치지 않음" ));
PathRemoveFileSpec( pwszDestName );
WCHAR* pwszBuffer = wcsdup( pItem->fileNameW );
PathRemoveFileSpec( pwszBuffer );
PathAddBackslash( pwszBuffer );
PathAddBackslash( pwszDestName );
// LM_TRACE(( L"%s\n%s", pwszDestName, pItem->fileNameW ));
pArkInfo->GetArk()->ClearExtractList();
pArkInfo->GetArk()->AddIndex2ExtractList( pArkInfo->GetCurrentFileIndex() );
ret = pArkInfo->GetArk()->ExtractMultiFileTo( pwszDestName, pwszBuffer );
free( pwszBuffer );
}
}
else if( ( pwszDestName != NULL ) &&
( pwszDestPath != NULL ) )
{
// LM_TRACE(( L"압축 풀기 시도 경로 : %s", pwszDestPath ));
// LM_TRACE(( L"압축 풀기 시도 이름 : %s", pwszDestName ));
ret = pArkInfo->GetArk()->ExtractOneTo( pArkInfo->GetCurrentFileIndex(), pwszDestPath );
}
pArkInfo->GetArk()->SetEvent( NULL );
// LM_TRACE(( L"압축 풀기 결과 : %d, %s", ret, GetArkLastErrorText( pArkInfo->getArk()->GetLastError() ).c_str() ));
if( ret == FALSE )
nResult = E_BAD_ARCHIVE;
}
break;
}
} while (false);
return nResult;
}
EXTERN_C UNARKWCX_API int WINAPI CloseArchive( HANDLE hArcData )
{
LM_TRACE( L"Here" );
if( hArcData != INVALID_HANDLE_VALUE )
delete (CArkInfo *)(hArcData);
else
{
gClsArkEvent.pfnProcessDataProc = NULL;
gClsArkEvent.pfnProcessDataProcW = NULL;
gClsArkEvent.pfnChangeVolProc = NULL;
gClsArkEvent.pfnChangeVolProcW = NULL;
}
return 0;
}
EXTERN_C UNARKWCX_API void WINAPI SetChangeVolProc( HANDLE hArcData, tChangeVolProc pfnChangeVolProc )
{
InitLogger();
LM_TRACE( L"Here" );
// CArkInfo* pArkInfo = reinterpret_cast< CArkInfo* >( hArcData );
// if( pArkInfo != NULL )
// pArkInfo->GetArkEvent().pfnChangeVolProc = pfnChangeVolProc;
}
EXTERN_C UNARKWCX_API void WINAPI SetChangeVolProcW( HANDLE hArcData, tChangeVolProcW pfnChangeVolProc )
{
InitLogger();
LM_TRACE( L"Here" );
// CArkInfo* pArkInfo = reinterpret_cast< CArkInfo* >( hArcData );
// if( pArkInfo != NULL )
// pArkInfo->GetArkEvent().pfnChangeVolProcW = pfnChangeVolProc;
}
EXTERN_C UNARKWCX_API void WINAPI SetProcessDataProc( HANDLE hArcData, tProcessDataProc pfnProcessDataProc )
{
InitLogger();
LM_TRACE( L"Here" );
CArkInfo* pArkInfo = reinterpret_cast< CArkInfo* >( hArcData );
if( pArkInfo != INVALID_HANDLE_VALUE )
pArkInfo->GetArkEvent().pfnProcessDataProc = pfnProcessDataProc;
else
gClsArkEvent.pfnProcessDataProc = pfnProcessDataProc;
}
EXTERN_C UNARKWCX_API void WINAPI SetProcessDataProcW( HANDLE hArcData, tProcessDataProcW pfnProcessDataProc )
{
InitLogger();
LM_TRACE( L"Here" );
CArkInfo* pArkInfo = reinterpret_cast< CArkInfo* >( hArcData );
if( pArkInfo != INVALID_HANDLE_VALUE )
pArkInfo->GetArkEvent().pfnProcessDataProcW = pfnProcessDataProc;
else
gClsArkEvent.pfnProcessDataProcW = pfnProcessDataProc;
}
EXTERN_C UNARKWCX_API int WINAPI GetPackerCaps()
{
InitLogger();
LM_TRACE( L"Here" );
return
PK_CAPS_NEW |
PK_CAPS_MODIFY |
PK_CAPS_MULTIPLE |
PK_CAPS_DELETE |
PK_CAPS_OPTIONS |
PK_CAPS_BY_CONTENT;
}
EXTERN_C UNARKWCX_API BOOL WINAPI CanYouHandleThisFile( char *FileName )
{
InitLogger();
LM_TRACE( L"Here" );
return CanYouHandleThisFileW( const_cast< WCHAR * >( CA2U( FileName ).c_str() ) );
}
EXTERN_C UNARKWCX_API BOOL WINAPI CanYouHandleThisFileW( WCHAR *FileName )
{
InitLogger();
LM_TRACE( L"Here" );
BOOL isCanHandle = FALSE;
do
{
CArkLib arkLib;
if( arkLib.Create( gArkDLLFullPathName ) != ARKERR_NOERR )
break;
ARK_FF fileFormat = arkLib.CheckFormat( FileName );
arkLib.Release();
arkLib.Destroy();
if( fileFormat == ARK_FF_UNKNOWN )
break;
if( ( fileFormat >= ARK_FF_UNSUPPORTED_FIRST ) &&
( fileFormat <= ARK_FF_UNSUPPORTED_LAST ) )
break;
if( ( fileFormat >= ARK_FF_NOTARCHIVE_FIRST ) &&
( fileFormat <= ARK_FF_NOTARCHIVE_LAST ) )
break;
isCanHandle = TRUE;
} while (false);
return isCanHandle;
}
EXTERN_C UNARKWCX_API int WINAPI PackFiles( char* PackedFile, char* SubPath, char* SrcPath, char* AddList, int Flags )
{
LM_TRACE( L"Here" );
LM_TRACE( "Packed Files = %s", PackedFile );
if( SubPath != NULL )
{
LM_TRACE( "Sub Path = %s", SubPath );
}
LM_TRACE( "Src Path = %s", SrcPath );
for( char* pszCurrent = AddList; *pszCurrent != 0; pszCurrent += strlen( pszCurrent ) + 1)
{
LM_TRACE( L"Add List = %s", pszCurrent );
}
LM_TRACE( "Flags = %d", Flags );
return 0;
}
EXTERN_C UNARKWCX_API int WINAPI PackFilesW( wchar_t* PackedFile, wchar_t* SubPath, wchar_t* SrcPath, wchar_t* AddList, int Flags )
{
int nRetValue = E_NOT_SUPPORTED; // 0 == SUCCESS
CArkLib arkLib;
IArkCompressor* pCompressor = NULL;
std::wstring strSrcPath, strDstPath;
std::vector< std::wstring > vecAddFile, vecSrcFile;
LM_TRACE( L"Parameter, Packed Files = %s||Sub Path = %s||Src Path = %s", PackedFile, SubPath, SrcPath );
for( wchar_t* pwszCurrent = AddList; *pwszCurrent != 0; pwszCurrent += wcslen( pwszCurrent ) + 1)
{
vecAddFile.push_back( pwszCurrent );
LM_TRACE( L"Parameter, Add List = %s", pwszCurrent );
}
LM_TRACE( L"Parameter, Flags = %d", Flags );
do
{
if( arkLib.Create( gArkDLLFullPathName ) != ARKERR_NOERR )
{
LM_ERROR( L"Ark Library Create Instance Failed = %d, %x, SYS ERROR = %E", arkLib.GetLastError(), arkLib.GetLastError(), arkLib.GetLastSystemError() );
nRetValue = E_NOT_SUPPORTED;
break;
}
pCompressor = arkLib.CreateCompressor();
if( pCompressor == NULL )
{
LM_ERROR( L"Ark Library Create Compressor Instance Failed" );
nRetValue = E_NOT_SUPPORTED;
break;
}
pCompressor->Init();
pCompressor->SetEvent( &gClsArkEvent );
if( pCompressor->SetOption( gArkCompressorOpt, NULL, 0 ) == FALSE )
{
LM_ERROR( L"Ark Library Set Option Failed = %d, %x, SYS ERROR = %E", arkLib.GetLastError(), arkLib.GetLastError(), arkLib.GetLastSystemError() );
nRetValue = E_NOT_SUPPORTED;
break;
}
for( size_t idx = 0; idx < vecAddFile.size(); ++idx )
{
strSrcPath = SrcPath;
if( *strSrcPath.rbegin() != L'\\' )
strSrcPath += L"\\" + vecAddFile[ idx ];
else
strSrcPath += vecAddFile[ idx ];
if( SubPath != NULL && SubPath[ wcslen( SubPath ) - 1 ] != L'\\' )
strDstPath = SubPath + vecAddFile[idx];
else if( SubPath != NULL && SubPath[ wcslen( SubPath ) - 1 ] == L'\\' )
strDstPath = SubPath + std::wstring( L"\\" ) + vecAddFile[idx];
else
strDstPath = vecAddFile[idx];
vecSrcFile.push_back( strSrcPath );
pCompressor->AddFileItem( strSrcPath.c_str(), strDstPath.c_str(), FALSE );
}
if( pCompressor->CreateArchive( PackedFile ) == FALSE )
{
LM_ERROR( L"ERROR = %d, %x", pCompressor->GetLastError(), pCompressor->GetLastError() );
nRetValue = E_ECREATE;
break;
}
else
{
if( Flags == PK_PACK_MOVE_FILES )
{
for( size_t idx = 0; idx < vecSrcFile.size(); ++idx )
DeleteFile( vecSrcFile[idx].c_str() );
}
}
nRetValue = 0;
} while (false);
if( pCompressor != NULL )
pCompressor->Release();
if( arkLib.IsCreated() != FALSE )
{
arkLib.Close();
arkLib.Destroy();
}
return nRetValue;
}
EXTERN_C UNARKWCX_API int WINAPI DeleteFiles( char *PackedFile, char *DeleteList )
{
LM_TRACE( L"Here" );
return 0;
}
EXTERN_C UNARKWCX_API int WINAPI DeleteFilesW( wchar_t *PackedFile, wchar_t *DeleteList )
{
LM_TRACE( L"Here" );
return 0;
}
EXTERN_C UNARKWCX_API void WINAPI ConfigurePacker( HWND Parent, HINSTANCE DllInstance )
{
InitLogger();
LM_TRACE( L"Here" );
DialogBox( DllInstance, MAKEINTRESOURCE(IDD_DLG_OPTIONS), Parent, ConfigurePackerDlgProc );
}
BOOL CALLBACK ConfigurePackerDlgProc( HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam )
{
switch (message)
{
case WM_INITDIALOG:
{
wchar_t szBuffer[ 128 ] = {0,};
GetPrivateProfileString( CONFIGURE_INI_SECNAME, CONFIGURE_SELECT_EXTENSION, L"ZIP", szBuffer, 128, gConfigureINIFullPath );
wcscpy( gCurrentArchiveExtension, szBuffer );
HWND hCBX_ARCHIVE_TYPE = GetDlgItem( hwndDlg, IDC_CBX_ARCHIVE_TYPE );
if( hCBX_ARCHIVE_TYPE != NULL )
{
SendMessage( hCBX_ARCHIVE_TYPE, CB_ADDSTRING, 0, (LPARAM)(LPCTSTR)(L"7Z") );
SendMessage( hCBX_ARCHIVE_TYPE, CB_ADDSTRING, 0, (LPARAM)(LPCTSTR)(L"ZIP") );
SendMessage( hCBX_ARCHIVE_TYPE, CB_ADDSTRING, 0, (LPARAM)(LPCTSTR)(L"ISO") );
SendMessage( hCBX_ARCHIVE_TYPE, CB_SELECTSTRING, (WPARAM)0, (LPARAM)(LPCTSTR)gCurrentArchiveExtension );
}
HWND hTab = GetDlgItem( hwndDlg, IDC_TAB );
if( hTab != NULL )
{
// TabCtrl_SetExtendedStyle( hTab, );
TCITEM tabItem;
tabItem.mask = TCIF_TEXT;
tabItem.iImage = -1;
tabItem.lParam = NULL;
tabItem.pszText = L"7Z";
tabItem.cchTextMax = wcslen( L"7Z" );
TabCtrl_InsertItem( hTab, 0, &tabItem );
tabItem.pszText = L"ZIP";
tabItem.cchTextMax = wcslen( L"ZIP" );
TabCtrl_InsertItem( hTab, 1, &tabItem );
tabItem.pszText = L"ISO";
tabItem.cchTextMax = wcslen( L"ISO" );
TabCtrl_InsertItem( hTab, 2, &tabItem );
}
}
return TRUE;
break;
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDOK:
WritePrivateProfileString( L"UnArkWCX", L"SelectArchiveExtension", gCurrentArchiveExtension, gConfigureINIFullPath );
// if (!GetDlgItemText(hwndDlg, ID_ITEMNAME, szItemName, 80))
// *szItemName=0;
// Fall through.
case IDCANCEL:
EndDialog(hwndDlg, wParam);
return TRUE;
}
}
}
return FALSE;
}
EXTERN_C UNARKWCX_API void WINAPI PackSetDefaultParams( PackDefaultParamStruct* dps )
{
InitLogger();
LM_TRACE( L"Here" );
wcscpy( gConfigureINIFullPath, CA2U( dps->DefaultIniName ).c_str() );
SetCompressorOptFromINI();
}
void SetCompressorOptFromINI()
{
gArkCompressorOpt.Init();
wchar_t szBuffer[ 128 ] = {0,};
ARK_COMPRESSION_METHOD defaultMethod;
// 압축 형식 설정
GetPrivateProfileString( CONFIGURE_INI_SECNAME, CONFIGURE_SELECT_EXTENSION, L"ZIP", szBuffer, 128, gConfigureINIFullPath );
wcscpy( gCurrentArchiveExtension, szBuffer );
if( wcsicmp( gCurrentArchiveExtension, L"ZIP" ) == 0 )
{
gArkCompressorOpt.ff = ARK_FF_ZIP;
defaultMethod = ARK_COMPRESSION_METHOD_DEFLATE;
}
else if( wcsicmp( gCurrentArchiveExtension, L"ISO" ) == 0 )
{
gArkCompressorOpt.ff = ARK_FF_ISO;
}
else if( wcsicmp( gCurrentArchiveExtension, L"7Z" ) == 0 )
{
gArkCompressorOpt.ff = ARK_FF_7Z;
defaultMethod = ARK_COMPRESSION_METHOD_LZMA2;
}
else if( wcsicmp( gCurrentArchiveExtension, L"LZH" ) == 0 )
{
gArkCompressorOpt.ff = ARK_FF_7Z;
defaultMethod = ARK_COMPRESSION_METHOD_LH6;
}
gArkCompressorOpt.saveNTFSTime = GetPrivateProfileInt( CONFIGURE_INI_SECNAME, CONFIGURE_SaveNTFSTimeForZIP, 0, gConfigureINIFullPath );
gArkCompressorOpt.streamOutput = FALSE;
gArkCompressorOpt.compressionMethod = (ARK_COMPRESSION_METHOD)GetPrivateProfileInt( CONFIGURE_INI_SECNAME, CONFIGURE_CompressionMerhod, defaultMethod, gConfigureINIFullPath );
gArkCompressorOpt.encryptionMethod = ARK_ENCRYPTION_METHOD_ZIP;
gArkCompressorOpt.compressionLevel = GetPrivateProfileInt( CONFIGURE_INI_SECNAME, CONFIGURE_CompressionLevel, -1, gConfigureINIFullPath );
if( gArkCompressorOpt.compressionLevel < -1 || gArkCompressorOpt.compressionLevel > 9 )
gArkCompressorOpt.compressionLevel = -1;
gArkCompressorOpt.splitSize = 0;
gArkCompressorOpt.forceZip64 = FALSE;
gArkCompressorOpt.useDosTime2PasswordCheck = FALSE;
gArkCompressorOpt.sfxPathName = NULL;
gArkCompressorOpt.forceUtf8FileName = TRUE;
gArkCompressorOpt.forceUtf8Comment = FALSE;
gArkCompressorOpt.utf8FileNameIfNeeded = TRUE;
gArkCompressorOpt.bypassWhenUncompressible = TRUE;
gArkCompressorOpt.lzmaEncodeThreadCount = 2;
gArkCompressorOpt.enableMultithreadDeflate = TRUE;
gArkCompressorOpt.deflateEncodeThreadCount = 0;
gArkCompressorOpt._7zCompressHeader = FALSE;
gArkCompressorOpt._7zEncryptHeader = FALSE;
gArkCompressorOpt.lzma2NumBlockThreads = 2;
gArkCompressorOpt.threadPriority = THREAD_PRIORITY_NORMAL;
}
//////////////////////////////////////////////////////////////////////////
BOOL32 CArkInfo::Open( LPCWSTR pwszFilePath, LPCWSTR password )
{
BOOL32 bSuccess = FALSE;
do
{
ARKERR err = arkLib.Create( gArkDLLFullPathName );
if( err != ARKERR_NOERR )
{
LM_TRACE( "ArkLib Create Failed = %d, %s", err, gArkDLLFullPathName );
break;
}
SArkGlobalOpt opt;
opt.bAzoSupport = TRUE;
opt.bPrintAssert = TRUE;
opt.bTreatTBZAsSolidArchive = FALSE;
opt.bTreatTGZAsSolidArchive = FALSE;
opt.bUseLongPathName = TRUE;
arkLib.SetGlobalOpt( opt );
bSuccess = arkLib.Open( pwszFilePath, password );
LM_TRACE( L"File Open Error Code = %d", arkLib.GetLastError() );
} while (false);
return bSuccess;
}
<file_sep>/Library/ConvertStr.h
#pragma once
#include <cassert>
#include <string>
#include "CommonUtil.h"
//////////////////////////////////////////////////////////////////////////
/// 문자열 변환을 위한 간편한 클래스 모음
/// 작성자 : 헬마
///
/// 2012-02-04 : CA2U8 클래스의 c_str() 함수에서 윈도 헤더를 사용하지 않을 때 컴파일되지 않는 문제 수정
/// 2012-02-04 : CU2U8 클래스의 c_str() 함수에서 윈도 헤더를 사용하지 않을 때 예외가 발생하는 문제 수정
/// 2012-02-04 : CU82A 클래스의 c_str() 함수에서 윈도 헤더를 사용하지 않을 때 코드 완성
//////////////////////////////////////////////////////////////////////////
#if defined(TEST_EXE_INCLUDE)
#define IMON_DLL_API
#else
#define IMON_DLL_API AFX_EXT_CLASS
#endif
// MBCS To Unicode
class IMON_DLL_API CA2U
{
public:
CA2U( const char* pszStr );
CA2U( const std::string& str );
~CA2U() { DeletePtrA< char* >( m_pszBuffer ); DeletePtrA< wchar_t* >( m_pwszBuffer ); }
operator const wchar_t* ();
#ifdef _AFX
operator const CStringW ();
#endif
CA2U& operator =( const char* pszStr );
CA2U& operator =( const std::string& str );
const wchar_t* c_str();
private:
char* m_pszBuffer;
wchar_t* m_pwszBuffer;
};
// Unicode To MBCS
class IMON_DLL_API CU2A
{
public:
CU2A( const wchar_t* pwszStr );
CU2A( const std::wstring& str );
#ifdef _AFX
CU2A( const CStringW& str );
#endif
~CU2A() { DeletePtrA< char* >( m_pszBuffer ); DeletePtrA< wchar_t* >( m_pwszBuffer ); }
operator const char* ();
CU2A& operator =( const wchar_t* pwszStr );
CU2A& operator =( const std::wstring& pwszStr );
const char* c_str();
private:
char* m_pszBuffer;
wchar_t* m_pwszBuffer;
};
// UTF-8 To Unicode
class IMON_DLL_API CU82U
{
public:
CU82U( const char* pszStr );
CU82U( const std::string& str );
~CU82U() { DeletePtrA< char* >( m_pszBuffer ); DeletePtrA< wchar_t* >( m_pwszBuffer ); }
// operator const wchar_t* ();
operator const std::wstring() { return c_str(); };
#ifdef _AFX
operator const CStringW ();
#endif
CU82U& operator =( const char* pszStr );
CU82U& operator =( const std::string& str );
const wchar_t* c_str();
private:
char* m_pszBuffer;
wchar_t* m_pwszBuffer;
};
// Unicode To UTF-8
class IMON_DLL_API CU2U8
{
public:
CU2U8( const wchar_t* pwszStr );
CU2U8( const std::wstring& str );
#ifdef _AFX
CU2U8( const CString& str );
#endif
~CU2U8() { DeletePtrA< char* >( m_pszBuffer ); DeletePtrA< wchar_t* >( m_pwszBuffer ); }
// operator const char* ();
operator const std::string() { return c_str(); };
CU2U8& operator =( const wchar_t* pwszStr );
CU2U8& operator =( const std::wstring& str );
const char* c_str();
private:
char* m_pszBuffer;
wchar_t* m_pwszBuffer;
};
// MBCS to UTF-8
class IMON_DLL_API CA2U8
{
public:
CA2U8( const char* pszStr );
CA2U8( const std::string& str );
~CA2U8() { DeletePtrA< char* >( m_pszBufferA ); DeletePtrA< char* >( m_pszBufferU8 ); }
// UTF-8 문자열을 반환함
operator const char* ();
CA2U8& operator =( const char* pszStr );
CA2U8& operator =( const std::string& str );
const char* c_str();
private:
char* m_pszBufferA;
char* m_pszBufferU8;
};
// UTF-8 to MBCS
class IMON_DLL_API CU82A
{
public:
CU82A( const char* pszStr );
CU82A( const std::string& str );
~CU82A() { DeletePtrA< char* >( m_pszBufferA ); DeletePtrA< char* >( m_pszBufferU8 ); }
// UTF-8 문자열을 반환함
operator const char* ();
CU82A& operator =( const char* pszStr );
CU82A& operator =( const std::string& str );
const char* c_str();
private:
char* m_pszBufferA;
char* m_pszBufferU8;
};
<file_sep>/Library/CommonUtil.h
#pragma once
#include <locale>
#include <string>
#include <cassert>
#include <stdarg.h>
#include <stdio.h>
#include <WinSock2.h>
#pragma comment( lib, "ws2_32.lib" )
//////////////////////////////////////////////////////////////////////////
/// 프로젝트에서 공통적으로 사용되는 유틸리티 클래스, 함수 모음
/// 작성자 : 헬마
//////////////////////////////////////////////////////////////////////////
#if defined(TEST_EXE_INCLUDE)
#define IMON_DLL_API
#else
#define IMON_DLL_API AFX_EXT_CLASS
#endif
IMON_DLL_API std::string format(const char *fmt, ...);
IMON_DLL_API std::string format_arg_list(const char *fmt, va_list args);
IMON_DLL_API std::wstring format(const wchar_t *fmt, ...);
IMON_DLL_API std::wstring format_arg_list(const wchar_t *fmt, va_list args);
IMON_DLL_API extern const std::locale locEnUs;
IMON_DLL_API bool IsAlphabet( const std::string& strString );
IMON_DLL_API bool IsAlphabet( const std::wstring& strString );
IMON_DLL_API bool IsNumber( const std::string& strString );
IMON_DLL_API bool IsNumber( const std::wstring& strString );
/*
전송받은 문자열이 날짜형식인지 점검
점검 문자열 형식 "%Y-%m-%d", "%Y%m%d"
*/
IMON_DLL_API bool IsDate( const std::wstring& strString );
// 초단위의 숫자를 넘겨서 경과시간을 %H %M %S 를 사용한 문자열로 서식화,
IMON_DLL_API std::wstring formatElapsedTime( unsigned int elapsedTimeSec, const std::wstring& fmt = L"%H 시간 %M 분 %S 초" );
template <typename T> inline
void DeletePtr( T& ptr )
{
if( ptr != NULL )
{
delete ptr;
ptr = NULL;
}
}
template <typename T> inline
void DeletePtrA( T& ptr )
{
if( ptr != NULL )
{
delete [] ptr;
ptr = NULL;
}
}
template <typename T> inline
void ReleasePtr( T& ptr )
{
if( ptr != nullptr )
{
ptr->Release();
delete ptr;
ptr = nullptr;
}
}
template< typename T > inline
void DeleteMapContainerPointerValue( T container )
{
for( typename T::iterator it = container.begin(); it != container.end(); ++it )
delete (*it).second;
}
IMON_DLL_API errno_t CopyAnsiString( char ** pszDest, const char * pszSrc, int srcLength = -1 );
IMON_DLL_API errno_t CopyWideString( wchar_t ** pszDest, const wchar_t * pszSrc, int srcLength = -1 );
IMON_DLL_API std::string string_replace_all( const std::string& src, const std::string& pattern, const std::string& replace );
IMON_DLL_API std::wstring string_replace_all( const std::wstring& src, const std::wstring& pattern, const std::wstring& replace );
IMON_DLL_API std::wstring GetFormattedDateTimeText( __time64_t tmTime, std::wstring fmt = L"%Y-%m-%d %H:%M:%S" );
IMON_DLL_API std::wstring GetFormattedDateText( __time64_t tmTime, std::wstring fmt = L"%Y년 %m월 %d일" );
IMON_DLL_API std::wstring GetFormattedTimeText( __time64_t tmTime, std::wstring fmt = L"%H시 %M분" );
IMON_DLL_API __time64_t GetTimeValueFromFormat( const std::wstring& dateTimeText, const std::wstring& fmt = L"%Y-%m-%d %H:%M:%S" );
// 문자열에서 공백으로 구분된 후 특정 delmiter 를 제거한 단어를 반환한다.
// /MessageText:"fsdfsdfds" /MessageCode:232
// delimiter = /MessageText: 라면 "fsdfsdfds" 반환
// delimiter = /MessageCode: 라면 "232" 반환
IMON_DLL_API std::wstring GetWordsUsingDelimiter( const std::wstring& strMessage, const std::wstring& delimiter );
IMON_DLL_API int _wcsicmp( const std::wstring& lhs, const std::wstring& rhs );
#ifdef _AFX
IMON_DLL_API int _wcsicmp( const CString& lhs, const CString& rhs );
#endif
IMON_DLL_API int _wtoi( const std::wstring& lhs );
IMON_DLL_API __int64 _wtoi64( const std::wstring& lhs );
IMON_DLL_API int u8sicmp( const std::string& lhs, const std::string& rhs );
IMON_DLL_API int u8toi( const std::string& lhs );
IMON_DLL_API __int64 u8toi64( const std::string& lhs );
// IP 주소로부터 해당하는 U_INT 숫자를 반환, 네트워크 바이트 순서로 반환됨
IMON_DLL_API unsigned long getULONGFromIPAddress( BYTE lsb, BYTE lsbBy1, BYTE lsbBy2, BYTE lsbBy3 );
// 네트워크 바이트 순서로 된 ULONG 을 받아 문자열된 IP 문자열 반환
IMON_DLL_API std::string getIPAddressFromULONG( unsigned long ulIPaddress );
IMON_DLL_API std::string getCPUBrandString();
// namespace boost
// {
// template<>
// inline int lexical_cast( const std::wstring& arg )
// {
// return _wtoi( arg.c_str() );
// }
//
// template<>
// inline double lexical_cast( const std::wstring& arg )
// {
// return _wtof( arg.c_str() );
// }
// }
IMON_DLL_API bool is64BitOS();
// 파일의 버전 정보 및 회사 정보를 구할수 있다.
// selectInfo 1 ~ 4 : Default : 2( ProductVersion )
// 1 : ProductVersion, 2 : FileVersion, 3 : Comments, 4 : CompanyName
IMON_DLL_API std::wstring GetFileInfomation( const std::wstring& filePath, const int selectInfo = 1 );<file_sep>/UnArkWCX.h
#pragma once
#include "UnArkWCX_Export.h"
#include "resource.h"
/*
토탈커맨더 플러그인인 WCX 의 수행에 있어서 필수적인 함수들 선언
*/
extern HINSTANCE g_hInst;
extern CArkLib gArkLib;
extern WCHAR gArkDLLFullPathName[ MAX_PATH ];
extern WCHAR gCurrentArchiveExtension[ 32 ];
extern WCHAR gConfigureINIFullPath[ MAX_PATH ];
extern BOOL isInitLogger;
extern SArkCompressorOpt gArkCompressorOpt;
BOOL CALLBACK ConfigurePackerDlgProc( HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam );
class CArkEvent : public IArkEvent
{
public:
CArkEvent() : pfnChangeVolProc( NULL ), pfnChangeVolProcW( NULL ), pfnProcessDataProc( NULL ), pfnProcessDataProcW( NULL ) {};
ARKMETHOD(void) OnOpening(const SArkFileItem* pFileItem, float progress, BOOL& bStop) {}
ARKMETHOD(void) OnStartFile(const SArkFileItem* pFileItem, BOOL& bStopCurrent, BOOL& bStopAll, int index ) {}
ARKMETHOD(void) OnProgressFile(const SArkProgressInfo* pProgressInfo, BOOL& bStopCurrent, BOOL& bStopAll)
{
int bContinue = TRUE;
if( pfnProcessDataProc != NULL )
{
bContinue = pfnProcessDataProc( NULL, pProgressInfo->_processed );
}
else if( pfnProcessDataProcW != NULL )
{
bContinue = pfnProcessDataProcW( NULL, pProgressInfo->_processed );
}
if( bContinue == FALSE )
{
bStopAll = TRUE;
bStopCurrent = TRUE;
}
}
ARKMETHOD(void) OnCompleteFile(const SArkProgressInfo* pProgressInfo, ARKERR nErr) {}
ARKMETHOD(void) OnError(ARKERR nErr, const SArkFileItem* pFileItem, BOOL bIsWarning, BOOL& bStopAll)
{
// LM_ERROR(( L"압축파일 작업 중 오류발생, %d", nErr ));
// LM_ERROR(( L"파일 이름 : %s", pFileItem->fileNameW ));
}
ARKMETHOD(void) OnMultiVolumeFileChanged(LPCWSTR szPathFileName)
{
// if( pfnChangeVolProc != NULL )
// {
// char* pFilePath = _strdup( CU2A(szPathFileName).c_str() );
//
// pfnChangeVolProc( pFilePath, PK_VOL_NOTIFY );
//
// free( pFilePath );
// }
// else if( pfnChangeVolProcW != NULL )
// {
// WCHAR* pFilePath = _wcsdup( szPathFileName );
//
// pfnChangeVolProcW( pFilePath, PK_VOL_NOTIFY );
//
// free( pFilePath );
// }
}
ARKMETHOD(void) OnAskOverwrite(const SArkFileItem* pFileItem, LPCWSTR szLocalPathName, ARK_OVERWRITE_MODE& overwrite, WCHAR pathName2Rename[ARK_MAX_PATH]) {}
ARKMETHOD(void) OnAskPassword(const SArkFileItem* pFileItem, ARK_PASSWORD_ASKTYPE askType, ARK_PASSWORD_RET& ret, WCHAR passwordW[ARK_MAX_PASS]) {}
tProcessDataProcW pfnProcessDataProcW;
tProcessDataProc pfnProcessDataProc;
tChangeVolProcW pfnChangeVolProcW;
tChangeVolProc pfnChangeVolProc;
};
extern CArkEvent gClsArkEvent;
class CArkInfo
{
public:
CArkInfo() : pArkLib( NULL ), currentFileIndex( -1 ) {} ;
~CArkInfo() { arkLib.Close(); arkLib.Destroy(); } ;
BOOL32 Open( LPCWSTR pwszFilePath, LPCWSTR password );
int IncrementCurrentFileIndex() { return ++currentFileIndex; };
int GetCurrentFileIndex() { return currentFileIndex; };
CArkLib* GetArk() { return &arkLib; };
CArkEvent& GetArkEvent() { return eEvent; };
private:
CArkLib arkLib;
IArk* pArkLib;
CArkEvent eEvent;
int currentFileIndex;
};
void InitLogger();
void SetCompressorOptFromINI();
| b87e85e47715f6c11a120861b99c9cfa2e8c6dfb | [
"C",
"C++",
"reStructuredText"
] | 17 | C++ | jgh0721/unarkwcx | daec4cd782d6375b85d60a456a699fc75511816a | a04927ebd82f227ef2e2523378361f9502b7c360 |
refs/heads/master | <repo_name>Olee625/Olee<file_sep>/src/main/java/com/olee/project/dto/RegisterRespDto.java
package com.olee.project.dto;
import lombok.Data;
@Data
public class RegisterRespDto {
private String userId;
private String createAt;
}
<file_sep>/src/main/java/com/olee/project/service/TokenManagementServiceImpl.java
package com.olee.project.service;
import com.olee.project.constant.Constant;
import com.olee.project.utils.ZsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class TokenManagementServiceImpl implements TokenManagementService {
@Value("${redis.expireOnValueIntegerSeconds}")
private double expiresIntegerSeconds;
private final ZsetUtil zsetUtil;
@Autowired
public TokenManagementServiceImpl(ZsetUtil zsetUtil) {
this.zsetUtil = zsetUtil;
}
@Override
public String generateToken(String email) {
log.debug("进入generateToken函数了,邮箱为:{}", email);
//生成token(格式为token:加密的邮箱-时间-六位随机数)
//加密的邮箱
return DigestUtils.md5DigestAsHex(email.getBytes()) + "-" +
//时间
//new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + "-" +
//六位随机字符串
(new Random().nextInt(999999 - 111111 + 1) + 111111);
}
@Override
//需要传入userid和email
public String generateAndStoreToken(String userId, String email) {
//根据email生成token值
String token = generateToken(email);
//生成创建时间的时间戳 score需要double类型
Instant instant = Instant.now();
//将token值,生成时间存放在对应的userId下
String redisKey = Constant.REDIS_KEY_PREFIX + userId;
zsetUtil.add(redisKey, token, instant.getEpochSecond());
//移除其余token(最多5个)
long num = zsetUtil.removeRange(redisKey, 0, -6);
log.debug("generateAndStoreToken方法删除了{}个token", num);
return token;
}
@Override
//传入userid和token值
public boolean checkToken(String userId, String token) {
//根据userid和token查询reids库
String redisKey = Constant.REDIS_KEY_PREFIX + userId;
Double tokenCreateTimestamp = zsetUtil.score(redisKey, token);
//判断token是否存在
if (tokenCreateTimestamp == null || tokenCreateTimestamp == 0.0) {
//不存在则验证失败
return false;
}
//存在
//验证失效时间
long nowTime = Instant.now().getEpochSecond();
return (tokenCreateTimestamp + expiresIntegerSeconds) >= nowTime;
}
@Override
//删除一条token记录,而不是userId下的所有token
public void deleteToken(String userId, String token) {
String redisKey = Constant.REDIS_KEY_PREFIX + userId;
long num = zsetUtil.remove(redisKey, token);
log.info("deleteToken方法,userId:{},token:{},{}条token已经删除", userId, token, num);
}
@Override
//用户修改密码后,删除所有该userId下的所有token
public void deleteAllTokens(String userId) {
String redisKey = Constant.REDIS_KEY_PREFIX + userId;
boolean result = zsetUtil.removeKey(redisKey);
log.info("用户:{}修改密码后,是否删除了key:{}", userId, result);
}
public void setExpireOnKey(String userId, long timeout, TimeUnit unit) {
String redisKey = Constant.REDIS_KEY_PREFIX + userId;
zsetUtil.setExpireOnKey(redisKey, timeout, unit);
}
}
<file_sep>/src/main/java/com/olee/project/config/GsonConfig.java
package com.olee.project.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
@Configuration
public class GsonConfig {
@Bean
public HttpMessageConverter customConverters() {
// 创建 convert 消息转换对象
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
// 通过构建器设置Gson的相关设置,生成Gson对象
Gson gson = new GsonBuilder()
.create();
//将设置好的Gson对象,传递给消息转化器
gsonHttpMessageConverter.setGson(gson);
return gsonHttpMessageConverter;
}
}
<file_sep>/src/main/java/com/olee/project/model/User.java
package com.olee.project.model;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class User {
private Long id;
private String userId;
private String email;
private String password;
private String nickname;
private String address;
//todo 时间类型
private LocalDateTime createAt;
private LocalDateTime updateAt;
}<file_sep>/src/test/java/com/olee/project/test/NormalTest.java
package com.olee.project.test;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NormalTest {
@Test
public void NewTest() throws IOException {
//获取文件内容到sb
File file = new File("my.log");
try {
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
StringBuilder contents = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
contents.append(line + '\n');
}
reader.close();
//正则表达
String contentsString = contents.toString().replace("\n", "");
Pattern pattern = Pattern.compile(".*Argument(# Time.*;)");
Matcher matcher = pattern.matcher(contentsString);
if (matcher.find())
System.out.println(matcher.group(1));
String[] logLists = matcher.group(1).split("# Time:");
System.out.println(logLists.length);
for (String log : logLists) {
System.out.println(log);
}
//System.out.println(contents.toString().replace("# administrator command: Ping;\n", ""));
} catch (IOException e) {
}
}
public void registTest() {
}
}
<file_sep>/src/main/java/com/olee/project/mapper/UserMapper.java
package com.olee.project.mapper;
import com.olee.project.model.User;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserMapper {
/**
* 通过邮箱查询用户
*/
@Select("SELECT userId,email,password,nickname,address,createAt,updateAt FROM olee_user WHERE email = #{email}")
User findByEmail(@Param("email") String email);
/**
* 通过userId查询用户
*/
@Select("SELECT userId,email,password,nickname,address,createAt,updateAt FROM olee_user WHERE userId = #{userId}")
User findByUserId(@Param("userId") String userId);
/**
* 通过userId查询用户
*/
@Select("SELECT userId FROM olee_user WHERE email = #{email}")
User judgingEmailExists(@Param("email") String email);
/**
* 通过userId查询用户
*/
@Select("SELECT password FROM olee_user WHERE userId = #{userId}")
User checkPassword(@Param("userId") String userId);
/**
* 插入新的用户
*/
@Insert("INSERT INTO olee_user(userId, email, password, createAt, updateAt, nickname, address) VALUES(#{userId}, #{email}, #{password}, #{createAt}, #{updateAt}, #{nickname}, #{address})")
void insert(User user);
/**
* 修改用户昵称和地址
*/
//@Update("UPDATE olee_user SET nickname=#{nickname},address=#{address} WHERE userId=#{userId}")
@UpdateProvider(type = SqlProvider.class, method = "update")
void updateNicknameAndAddress(User user);
/**
* 修改用户密码
*/
@Update("UPDATE olee_user SET password=#{password},updateAt=#{updateAt} WHERE userId=#{userId}")
void updatePassword(User user);
}
<file_sep>/src/main/java/com/olee/project/enums/ResponseCode.java
package com.olee.project.enums;
public enum ResponseCode {
//枚举常量
SUCCESS(0, "Success"),
SERVER_ERROR(-10001, "Server internal error"),
SERVER_BUSY(-10002, "Server is busy"),
SERVER_TIMEOUT(-10003, "Server timeout"),
EMAIL_MISTAKE(-20101, "Invalid email"),
PWD_MISTAKE(-20102, "Invalid password"),
EMAIL_ALREADY_EXISTS(-20111, "Email has been registered"),
PWD_NOT_CORRECT(-20112, "The password is incorrect"),
EMAIL_NOT_FOUND(-20113, "Email does not exist"),
TOKEN_INVALIDATION(-20201, "User‘s token have expired"),
TOKEN_MISTAKE(-20202, "User‘s token is incorrect"),
NICKNAME_MISTAKE(-20103, "Invalid nickname"),
ADDRESS_MISTAKE(-20104, "Invalid address"),
OLD_PWD_MISTAKE(-20105, "The old password is invalid"),
NEW_PWD_MISTAKE(-20106, "The new password is invalid"),
NICKNAME_AND_ADDRESS_ARE_EMPTY(-20107, "The nickname and address are empty at the same time"),
X_AUTHORIZATION_ERROR(-20108, "X-Authorization request header error"),
OLD_PWD_NOT_CORRECT(-20112, "Old password is incorrect");
private final Integer code;
private final String message;
ResponseCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer code() {
return this.code;
}
public String message() {
return this.message;
}
}
<file_sep>/src/main/java/com/olee/project/controller/UserController.java
package com.olee.project.controller;
import com.google.gson.JsonObject;
import com.olee.project.annotation.AuthToken;
import com.olee.project.dto.*;
import com.olee.project.model.User;
import com.olee.project.service.InfoManagementService;
import com.olee.project.service.RegisterLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
//由于主要的浏览器(例如Chrome)现在已符合规范并正确解释了UTF-8特殊字符 不需要charset = UTF-8参数。
@RequestMapping(value = "/api/v1/user",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {
private final RegisterLoginService registerLoginService;
private final InfoManagementService infoManagementService;
@Autowired
public UserController(RegisterLoginService registerLoginService, InfoManagementService infoManagementService) {
this.registerLoginService = registerLoginService;
this.infoManagementService = infoManagementService;
}
@PostMapping("/register")
public Response<RegisterRespDto> register(@RequestBody User user) {
//参数校验,邮箱和密码合法性,再对邮箱是否注册做判断,最后注册新用户,写入数据库
return registerLoginService.registerUser(user);
}
@PostMapping("/login")
public Response<UserRespDto> login(@RequestBody User user) {
//密码正确,可以登录并返回数据
return registerLoginService.checkUser(user);
}
@PostMapping("/logout")
@AuthToken
public Response<JsonObject> logout() {
String userId = AuthorizationThreadLocal.get().get("userId");
String token = AuthorizationThreadLocal.get().get("token");
log.info("userId为{},进入到logout的controller层", userId);
return registerLoginService.logout(userId, token);
}
@PostMapping("/getUserInfo")
@AuthToken
public Response<UserRespDto> getUserInfo() {
//拿到userId
String userId = AuthorizationThreadLocal.get().get("userId");
log.info("userId为{},进入到getUserInfo的controller层", userId);
return infoManagementService.getUserInfo(userId);
}
//更新用户信息
@PostMapping("/updateUserInfo")
@AuthToken
public Response<JsonObject> updateUserInfo(@RequestBody User user) {
//服务层更新操作
String userId = AuthorizationThreadLocal.get().get("userId");
log.info("userId为{},进入到updateUserInfo的controller层", userId);
return infoManagementService.changeInfo(user, userId);
}
@AuthToken
@PostMapping("/updatePassword")
public Response<JsonObject> updatePassword(@RequestBody PasswordReqDto passwordDto) {
//密码合法性校验和token校验通过后
String userId = AuthorizationThreadLocal.get().get("userId");
log.info("userId为{},进入到updatePassword的controller层", userId);
return infoManagementService.changePassword(passwordDto, userId);
}
}
| de747c77444a952721791913411fe2b6a27e17ef | [
"Java"
] | 8 | Java | Olee625/Olee | c022ef14fdb87d854e82b9d4dbd179b11a9017f9 | 1ccdb5251ba8e34ce6b840236dbe378b5155b737 |
refs/heads/master | <repo_name>MattSkrobis/proposed_groups<file_sep>/lib/from_file.rb
#!/usr/bin/env ruby
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'users_collection'
module FromFile
def self.call
user_collection_object.suggested_groups
end
private
def self.user_collection_object
UsersCollection.new(input_file.read)
end
def self.input_file
File.open(file_path, "r")
end
def self.file_path
ARGV[0]
end
end
puts FromFile.call<file_sep>/spec/users_collection_spec.rb
require 'users_collection'
describe UsersCollection do
let(:data_string) { "Isaura:Amira,Elliot,Lizzie,Margarito,Verla,Wilford:Juggling\nElliot:Isaura,Madalyn,Margarito,Shakira:Juggling,Mineral collecting\nMadalyn:Amira,Elliot,Margarito,Verla:Driving,Mineral collecting,Rugby\nLizzie:Amira,Isaura,Verla:Driving,Mineral collecting,Rugby" }
describe '#user_hash' do
let(:data_string) { "Isaura:Amira,Verla,Wilford:Sleeping\nElliot:Isaura,Madalyn,Margarito,Shakira:Juggling,Mineral collecting\nMadalyn:Amira,Elliot,Verla:Planking,Mineral collecting,Rugby\nLizzie:Amira,Isaura,Verla:Driving,Eating,Rugby" }
let(:user_hash) { {'Madalyn' => {friends: %w(Amira <NAME>), user_groups: ['Planking', 'Mineral collecting', 'Rugby']},
'Lizzie' => {friends: %w(Amira <NAME>), user_groups: ['Driving', 'Eating', 'Rugby']},
'Elliot' => {friends: %w(<NAME> Margarito Shakira), user_groups: ['Juggling', 'Mineral collecting']},
'Isaura' => {friends: %w(Amira <NAME>), user_groups: ['Sleeping']}} }
let(:users_collection) { UsersCollection.new(data_string) }
it { expect(users_collection.user_hash).to eq user_hash }
it 'should return a hash of one user friends and interests' do
expect(users_collection.user_hash[:friends]).to eq user_hash[:friends]
end
it 'should return user_groups' do
expect(users_collection.user_hash[:user_groups]).to eq user_hash[:user_groups]
end
end
context 'full data' do
let(:users_collection_2) { UsersCollection.new(data_string_2) }
let(:data_string_2) { "Amira:Isaura,Lizzie,Madalyn,Margarito,Shakira,Un:Driving,Mineral collecting\nElliot:Isaura,Madalyn,Margarito,Shakira:Juggling,Mineral collecting\nIsaura:Amira,Elliot,Lizzie,Margarito,Verla,Wilford:Juggling\nLizzie:Amira,Isaura,Verla:Driving,Mineral collecting,Rugby\nMadalyn:Amira,Elliot,Margarito,Verla:Driving,Mineral collecting,Rugby\nMargarito:Amira,Elliot,Isaura,Madalyn,Un,Verla:Mineral collecting\nShakira:Amira,Elliot,Verla,Wilford:Mineral collecting\nUn:Amira,Margarito,Wilford:\nVerla:Isaura,Lizzie,Madalyn,Margarito,Shakira:Driving,Juggling,Mineral collecting\nWilford:Isaura,Shakira,Un:Driving" }
describe '#suggested_groups_for' do
let(:suggestions) { ['Driving', 'Mineral collecting'] }
it { expect(users_collection_2.suggested_groups_for("Isaura")).to match_array suggestions }
end
describe '#suggested_groups' do
it { expect(users_collection_2.suggested_groups).to eq "Amira:\nElliot:\nIsaura:Driving,Mineral collecting\nLizzie:Juggling\nMadalyn:Juggling\nMargarito:Driving,Juggling\nShakira:Driving,Juggling\nUn:Driving,Mineral collecting\nVerla:Rugby\nWilford:Juggling,Mineral collecting\n" }
end
end
end
<file_sep>/lib/users_collection.rb
class UsersCollection
attr_reader :user_hash
LINE_PARSING_REGEXP = /(?<user_name>[^:]*):(?<friends>[^:]*):(?<interests>[^\n]*)/
def initialize(data_string)
@user_hash = data_string.each_line.inject({}) do |result, line|
line_match = LINE_PARSING_REGEXP.match(line)
result[line_match[:user_name]] = {friends: line_match[:friends].split(','), user_groups: line_match[:interests].split(',')}
result
end
end
def suggested_groups
group_hashes = user_hash.inject({}) do |result, (user_name)|
result[user_name] = suggested_groups_for(user_name)
result
end
formatting_output(group_hashes)
end
def suggested_groups_for(name)
histogram(data_for_histogram(name))
.reject {|interest| user_hash[name.to_s][:user_groups].include?(interest)}
.select { |_, value| value >= (user_hash[name.to_s][:friends].count / 2) }
.keys.sort
end
private
def formatting_output(group_hashes)
group_hashes.map do |name, interests|
"#{name}:#{interests.join(',')}"
end.join("\n") << "\n"
end
def reject_strangers(name)
user_hash.reject { |key| !user_hash[name.to_s][:friends].include?(key) }
end
def histogram(array)
Hash[*array.group_by { |value| value }.flat_map { |key, value| [key, value.size] }]
end
def data_for_histogram(name)
reject_strangers(name).flat_map do |_, details_hash|
details_hash[:user_groups]
end
end
end | 1eb3a920ad4324d579524fca4a6487e1315e1c4e | [
"Ruby"
] | 3 | Ruby | MattSkrobis/proposed_groups | 52c1ef777fd0c0358c870f281a3aa64dc9e02e41 | e1744e1f976f9cd0383de7ef1e6f8e81ebb26b23 |
refs/heads/master | <file_sep>package com.example.bkhutton.tipcalculator;
import android.icu.text.NumberFormat;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button calculate = (Button) findViewById(R.id.calculateButton);
calculate.setOnClickListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void onClick(View view) {
calculateTip();
}
private float getPercent() {
RadioButton ten = (RadioButton) findViewById(R.id.ten);
RadioButton fifteen = (RadioButton) findViewById(R.id.fifteen);
RadioButton twenty = (RadioButton) findViewById(R.id.twenty);
if (ten.isChecked()) {
return .1f;
}
if (fifteen.isChecked()) {
return .15f;
}
if (twenty.isChecked()) {
return .2f;
}
return 0;
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void calculateTip() {
EditText amountText = (EditText) findViewById(R.id.amount);
TextView output = (TextView) findViewById(R.id.outputText);
String amount = amountText.getText().toString();
NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
if (amount.matches("")) {
output.setText("Enter a bill amount");
return;
}
float bill = Float.valueOf(amount);
float tip = bill * getPercent();
output.setText("Your tip will be " + numberFormat.format(tip));
}
}
| 85cb3914055a472305446a665cd4a8d3d0d07c63 | [
"Java"
] | 1 | Java | Bkhutton/TipCalculator | d11ce99ab5dfb4d5b1b0e74bd0555b0c79fe550b | 25920c02722ce5dd243335befe467daea73f60d7 |
refs/heads/master | <file_sep>package server
import (
"net"
"strconv"
)
func StartServer(host string, port int64) {
address := host + ":" + strconv.FormatInt(port, 10)
ln, err := net.Listen("tcp", address)
if err != nil {
panic("Uhhhhhhhhhh")
}
for {
conn, err := ln.Accept()
if err != nil {
panic("Uhhhhhhhhhh")
}
statusLine := string("HTTP/1.1 200 Hello, HTTP Server!!\r\n")
headers := string("Content-Length: 0\r\n")
crlf := string("\r\n")
body := string("")
responseMessage := []byte(statusLine + headers + crlf + body)
conn.Write(responseMessage)
conn.Close()
}
}
<file_sep>module http-server
go 1.13
<file_sep>package main
import (
"http-server/server"
)
func main() {
server.StartServer("", 3000)
}
<file_sep>build: test
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ./bin/http-server -a -tags netgo -installsuffix netgo
test:
go test ./...
run:
go run main.go
| 704fcd94a989a38e9208f36f096d229c2d3d5abc | [
"Makefile",
"Go Module",
"Go"
] | 4 | Go | ayato-p/impl-http-server | d045a7359af64898291a42bbd39985001c79bbb4 | ea4685ceee222f77fc7331f66c015dc5d4aa5f3c |
refs/heads/master | <repo_name>MagpieShrike/Final-Project<file_sep>/Final Project/Assets/Scripts/DestroyByContact.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyByContact : MonoBehaviour
{
public GameObject explosion;
public GameObject playerExplosion;
public GameObject pickup;
public int scoreValue;
public int speed;
private GameController gameController;
private PlayerController player;
private Rigidbody rbPickup;
private int bossHealth;
private Vector3 direction = new Vector3(0, 0, 0);
private void Start()
{
bossHealth = 10;
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent < GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
GameObject playerObject = GameObject.FindWithTag("Player");
if (playerObject != null)
{
player = playerObject.GetComponent<PlayerController>();
}
if (player == null)
{
Debug.Log("Cannot find 'PlayerController' script");
}
GameObject pickupObject = GameObject.FindWithTag("Pickup");
if (pickupObject != null)
{
rbPickup = pickupObject.GetComponent<Rigidbody>();
}
if (rbPickup == null)
{
Debug.Log("Cannot find 'Rigidbody' script");
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Boundary") || other.CompareTag("Enemy") || other.CompareTag("Boss"))
{
return;
}
if (explosion != null)
{
Instantiate(explosion, transform.position, transform.rotation);
}
if (other.CompareTag("Boss"))
{
Debug.Log("damage");
bossHealth -= 1;
Debug.Log("damage");
Debug.Log(bossHealth);
Destroy(gameObject);
}
if (bossHealth <= 0)
{
gameController.AddScore(scoreValue);
Destroy(other.gameObject);
Destroy(gameObject);
}
if (other.CompareTag("Player"))
{
if (playerExplosion != null)
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
gameController.GameOver();
}
Debug.Log("Pickup");
player.Pickup();
}
if (playerExplosion != null)
{
gameController.AddScore(scoreValue);
Destroy(other.gameObject);
}
Destroy(gameObject);
Instantiate(pickup, transform.position, transform.rotation);
rbPickup.velocity = transform.forward * speed;
}
}
<file_sep>/Final Project/Assets/Scripts/GameController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public GameObject[] hazards;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public Text pointText;
public Text gameOverText;
public Text restartText;
public Text creditText;
public AudioClip bgMusic;
public AudioClip bossMusic;
public AudioClip winMusic;
public AudioClip loseMusic;
public AudioSource musicSource;
private int points;
private bool gameOver;
private bool restart;
GameObject boss;
// Start is called before the first frame update
void Start()
{
boss = GameObject.FindWithTag("Boss");
if (SceneManager.GetActiveScene().name == "Space Shooter")
{
musicSource.clip = bgMusic;
musicSource.Play();
}
else if (SceneManager.GetActiveScene().name == "Boss Battle")
{
musicSource.clip = bossMusic;
musicSource.Play();
}
points = 0;
UpdateScore();
gameOver = false;
restart = false;
restartText.text = "";
gameOverText.text = "";
creditText.text = "";
StartCoroutine (SpawnWaves());
}
void Update()
{
if (restart)
{
if (Input.GetKeyDown(KeyCode.X))
{
SceneManager.LoadScene("Space Shooter");
}
}
if (Input.GetKey("escape"))
Application.Quit();
bossState();
}
void bossState()
{
if (SceneManager.GetActiveScene().name == "Boss Battle" && musicSource.clip != winMusic)
{
if (!boss)
{
musicSource.clip = winMusic;
musicSource.Play();
gameOverText.text = "You Win!";
creditText.text = "Created by <NAME>";
gameOver = true;
}
}
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
GameObject hazard = hazards[Random.Range(0, hazards.Length)];
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
if (gameOver)
{
restartText.text = "Press 'X' to Restart";
restart = true;
break;
}
}
}
public void AddScore(int newPointValue)
{
points += newPointValue;
UpdateScore();
}
void UpdateScore()
{
pointText.text = "Points: " + points;
if(points >= 100 && SceneManager.GetActiveScene().name == "Space Shooter")
{
gameOverText.text = "You Win!";
creditText.text = "Created by <NAME>";
gameOver = true;
SceneManager.LoadScene("Boss Battle");
}
}
public void GameOver()
{
musicSource.clip = loseMusic;
musicSource.Play();
gameOverText.text = "Game Over";
creditText.text = "Created by <NAME>";
gameOver = true;
}
}
<file_sep>/README.md
# Final Project
Music & SFX by <NAME> www.soundimage.org :
* URBAN JUNGLE 2061
* LIGHT YEARS_V001
* STEAMTECH MAYHEM
* INFORMATION SHUTDOWN
* Air Lock 2
* Space Cannon
| 9c2331f7743c75aed7621861b73d724620a85af5 | [
"Markdown",
"C#"
] | 3 | C# | MagpieShrike/Final-Project | 0f1115c60c1b875b08e16d1006496b973d7f7c87 | 74233a796362796cb496db20116fa219aa1cc2b8 |
refs/heads/master | <file_sep>#include<reg51.h> //Header file inclusion for 8051
#include<intrins.h> // for using _nop_() function
void delay(unsigned int rtime);
void lcdcmd(unsigned char DATA);
void initialize(void);
void lcddat(unsigned char DATA);
void display_lcd(unsigned char location, unsigned char *d);
void send_pulse(void);
void lcd_number(int val);
void get_range(void);
#define LCDdata P1 //Declaring LCDdata
sbit trig=P3^5;//timer 1
sbit echo=P3^2;//INTR 0
sbit LCDrs = P2^0; //The Register select Pin
sbit LCDrw = P2^1; //The Read/Write Pin
sbit LCDen = P2^2; //The Enable Pin
void delay(unsigned int rtime)
{
unsigned int r,s;
for(r=0;r<rtime;r++)
for(s=0;s<1275;s++);
}
void lcdcmd(unsigned char DATA)
{
LCDrs=0;
LCDrw=0;
LCDen=1; //Strobe the enable pin
LCDdata = DATA; //Put the value on the pins
LCDrs=0;
LCDrw=0;
LCDen=0;
}
void initialize(void)
{
lcdcmd(0x30); //1 line and 5x7 matrix
delay(1);
lcdcmd(0x38); //2 line and 5x7 matrix
delay(1);
lcdcmd(0x0c); //Display on, cursor off
delay(1);
lcdcmd(0x01); //Clear display Screen
delay(1);
lcdcmd(0x06); //shift cursor to right
delay(1);
}
void lcddat(unsigned char DATA)
{
LCDrs = 1;
LCDrw = 0;
LCDen = 1; //Strobe the enable pin
LCDdata = DATA; //Put the value on the pins
LCDrs = 1;
LCDrw = 0;
LCDen = 0;
}
void display_lcd(unsigned char location, unsigned char *d)
{
lcdcmd(0x00 | location);
delay(1); //10mS delay generation
while(*d)
{
lcddat(*d++);
delay(1); //10mS delay generation
}
}
void send_pulse(void) //to generate 10 microseconds delay
{
TH0=0x00;
TL0=0x00;
trig=0;
trig=1;
_nop_();_nop_();_nop_();_nop_();_nop_(); //each _nop_() generates 1u sec of delay
_nop_();_nop_();_nop_();_nop_();_nop_();
trig=0;
}
void lcd_number(int val) // Function to display number
{
int i=3;
char str[7]={"0000 CM"};
while(val)
{
str[i]=0x30 | val%10;
val=val/10;
i--;
}
display_lcd(0xC5,str);
}
void get_range(void)
{
int range=0;
int timerval;
send_pulse();
while(INT0==0);
while(INT0==1);
timerval = TH0;
timerval = (timerval << 8) | TL0;
TH0=0xFF;
TL0=0xFF;
if(timerval<35000) //Makimum 38000us work at higher levels
range=timerval/59;
else
range = 0;
lcd_number(range);
}
void main(void)
{
//unsigned char string[]={"distance"};
initialize(); //initilaze LCD
display_lcd(0x80," OBSTACLE AT "); //Display character String from location specified
TMOD=0x09; //timer0 in 16 bit mode with gate enable
TR0=1; //timer run enabled
TH0=0x00;
TL0=0x00;
echo = 1; //setting pin P3.2 as input
while(1)
{
get_range();
delay(2);
}
}
<file_sep># Ultrasonic-distance-calculator
### AT89S52 interface with ultrasonic sensor HC-SR04 and 16X2 LCD to display distance
|  |
|:--:|
| *LCD and HC-SR04 interfacing with microcontroller* |
Circuit diagram for LCD and HC-SR04(ultrasonic senor) interfacing with AT89S52 microcontroller is shown in the above figure
### Project Requirements
1. 8051 or AT89S52 microcontroller
2. 16X2 LCD
3. HC-SR04 Ultrasonic Sensor
4. 10K POT
5. Few Jumper wires
6. Keil IDE
7. Basic microcontroller understanding
### How to setup
1. [Copy ultrasonic.c in project directory](https://github.com/naveen-nayan/ultrasonic-distance-calculator/blob/master/ultrasonic.c)
2. Open keil and setup to 8051 or AT89S52 microcontroller
3. Compile the file
4. Burn file to microcontroller
5. Enjoy
6. Can also generate a Hex code for proteus for simulation
| 6329f7c89c897c9c696634b1b7193dbf9027e208 | [
"Markdown",
"C"
] | 2 | C | althaf404/ultrasonic-distance-calculator | 41f1cf65be0c138b8574c442349f28865056e390 | 342e959d595fb3723856787034a268b259aa0ffa |
refs/heads/master | <file_sep>using UnityEngine;
using System.Collections;
[AddComponentMenu("Movement/MoveScript")]
public class MovementScript : MonoBehaviour
{
private Vector3 forward;
private Rigidbody rb;
private Transform Mcam;
//input Keys
private float moveHorizontal =0.0f,
moveVertical = 0.0f;
private bool jump;
private const float k_GroundRayLength = 1.5f;
private float m_JumpPower = .7f;
public float forwardSpeed = 10.0f;
Vector3 momentum;
Vector3 direction;
Vector3 originalPosition;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
Mcam = Camera.main.transform;
}
// Update is called once per frame
void FixedUpdate()
{
//Define local vectors based on where im facing
Vector3 forward = Mcam.TransformDirection(Vector3.forward);
Vector3 right = Mcam.TransformDirection(Vector3.right);
GetInput();
if (Physics.Raycast(transform.position, Vector3.down, k_GroundRayLength) && jump)
AddJumpForce();
AddMoveForce(forward, right);
UpdateCamera();
}
void GetInput()
{
moveHorizontal = Input.GetAxis("Horizontal");
moveVertical = Input.GetAxis("Vertical");
jump = Input.GetKey(KeyCode.Space);
}
void AddJumpForce()
{
rb.AddForce(Vector3.up * m_JumpPower, ForceMode.Impulse);
}
void AddMoveForce(Vector3 forward, Vector3 right)
{
rb.AddForce(new Vector3(forward.x, 0, forward.z) * moveVertical * forwardSpeed);
rb.AddForce(new Vector3(right.x, 0, right.z) * moveHorizontal * forwardSpeed);
}
void UpdateCamera()
{
Mcam.position = transform.position + new Vector3(0, 0.5f, 0);
}
}
| 3bbc43d353f8d5e7a9689242ddbdde51878d6083 | [
"C#"
] | 1 | C# | itsRaawwb/Swift | e75e462db9d943c549a401c5b97a568ae3f7d812 | d5fe2d54a823f87ab50eb4485486139fd6249a83 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#if 0
code that will not be executed, to hide code or long comment
some code that do not work
#endif
int main() {
unsigned char i = 'a';
printf("%I64ld\n", 28489298891);
//printf("divide: %d\n", 10 : 2);
short int k = 1;
while(k) {
printf("%d\n", k);
k--;
}
char a = 'A';
while(a--)
printf("value: %d\n", a);
printf("1 = %d\n", !'a');
int f = 0;
int arr[10] = {}; // trash, not 0
do printf("%d\n", arr[i]); while(f++ < 10);
exit(0);
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void input_output_a(void);
int main(int argc, char const *argv[]) {
input_output_a();
return 0;
}
void input_output_a() {
FILE *p_file = NULL;
char *test_str = "input_output_a";
size_t len = strlen(test_str);
p_file = fopen("text.txt", "a+");
fwrite(test_str, sizeof(char), len, p_file);
fflush(p_file);
int i = 2;
do fwrite(test_str, sizeof(char), len, p_file);
while(i-- > 0);
fclose(p_file);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#define h 25
#define w 80
char arr[h][w + 1];
void init() {
for (int i = 0; i < w; ++i) {
arr[0][i] = ' ';
}
arr[0][w] = '\0';
for (int i = 0; i < h; ++i) {
sprintf(arr[i], arr[0]);
}
}
void show() {
arr[h - 1][w - 1] = '\0';
for (int i = 0; i < h; ++i) {
printf(arr[i]);
}
}
void new_show() {
for (int i = 0; i < w; ++i) {
if (rand() % 12 == 1) {
arr[0][i] = '*';
}
}
}
void move_show() {
int dx;
for (int i = h - 1; i >= 0; --i) {
for (int s = 0; s < w; ++s) {
if (arr[i][s] == '*') {
arr[i][s] = ' ';
dx = 0;
if (rand() % 10 < 1) dx++;
if (rand() % 10 > 1) dx--;
dx = dx + s;
if ((dx >= 0) && (dx < w) && (i + 1) < h) {
arr[i + 1] = '*';
}
}
}
}
}
void set_cur(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_HANDLE), coord);
}
int main() {
init();
do {
set_cur(0, 0);
new_show();
move_show();
show();
Sleep(100);
} while(GetKeyState(VK_ESCAPE) >= 0);
return 0;
}
<file_sep>#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "binary_tree.h"
static BinTreeNode *pi_insert(BinTreeNode *, Leaf *);
static Leaf *pi_search(BinTreeNode *, int *);
static void pi_destroy(BinTreeNode *);
static BinTreeNode *pi_ll_rotation(BinTreeNode *);
static BinTreeNode *pi_rr_rotation(BinTreeNode *);
static BinTreeNode *pi_lr_rotation(BinTreeNode *);
static BinTreeNode *pi_rl_rotation(BinTreeNode *);
static void pi_print_in_order(BinTreeNode *);
static void pi_print_pre_order(BinTreeNode *);
static void pi_print_post_order(BinTreeNode *);
static char pi_height(BinTreeNode *);
static char pi_diff(BinTreeNode *);
<file_sep>#ifndef LIMITS_H
#define LIMITS_H
#include <stdio.h>
#include <limits.h>
#include <float.h>
void print_size_of_types(void);
#endif
<file_sep>#include "main.h"
#include "example.test.h"
#include "limits.h"
#include "different.h"
int main(int argc, char const *argv[]) {
char *s2 = "hello, world", s1[15];
strcopy_c(s1, s2);
puts(s1);
short int i = 0;
do {
print_size_of_types();
example_test();
} while(i == 0);
return 0;
}
<file_sep>#ifndef EXAMPLE_TEST_H
#define EXAMPLE_TEST_H
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "time-chrono.h"
float calculate(double i) {
return (((exp(i) / 0.789651) / exp(i * 12.21)) * 3.1931636689) /
(((exp(i / 2914.124) * i) / exp(i / 56.9137)) * exp(i * 139.91470));
}
float calc_optimize(char i) {
static unsigned char isCalc = 0;
static float calc_table[360] = { 0 };
if (!isCalc) {
int i = 0;
for (; i < 360; ++i) calc_table[i] = calculate(i);
isCalc = 1;
}
return calc_table[i];
}
void optimized_test(void) {
const unsigned int limit = 100000;
char i = 0;
double diff = 0.0;
do calc_optimize(rand() % 360);
while(i-- > limit);
diff = elapsed();
fprintf(stdout, "optimized: %.5f\n", diff);
}
void not_optimized_test(void) {
const unsigned int limit = 100000;
char i = 0;
double diff = 0.0;
start_chrono();
for (; i < limit; ++i)
calculate(rand() % 360);
diff = elapsed();
fprintf(stdout ,"not optimized: %.5f\n", diff);
}
void main_test1(void) {
char i = 2;
calc_optimize(1);
do {
not_optimized_test();
optimized_test();
}
while(i-- > 0);
}
#endif
<file_sep>#ifdef __linux__
#include <unistd.h>
#include <arpa/inet.h>
#elif __WIN32
#include <winsock2.h>
#else
#warning "net.h: platform is not supported"
#endif
#if defined(__linux__) || defined(__WIN32)
typedef enum error_t {
WINSOCK_ERR = -1,
SOCKET_ERR = -2,
SETOPT_ERR = -3,
PARSE_ERR = -4,
BIND_ERR = -5,
LISTEN_ERR = -6,
CONNECT_ERR = -7,
} error_t;
#include "net.h"
static int8_t _parse_address(char* address, char* ipv4, char* port);
// 127.0.0.1:8080
extern int listen_net(char* address) {
#ifdef __WIN32
WSDATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
return WINSOCK_ERR;
}
#endif
int listener = socket(AF_INET, SOCK_STREAM, 0);
if (listener < 0) {
return SOCKET_ERR;
}
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0) {
return SETOPT_ERR;
}
char ipv4[16];
char port[6];
if (_parse_address(address, ipv4, port) != 0) {
return PARSE_ERR;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(port));
addr.sin_addr.s_addr = inet_addr(ipv4);
if (bind(listener, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
return BIND_ERR;
}
if (listen(listener, SOMAXCONN) != 0) {
return LISTEN_ERR;
}
return listener;
}
extern int accept_net(int listener) {
return accept(listener, NULL, NULL);
}
extern int connect_net(char* address) {
#ifdef __WIN32
WSDATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
return WINSOCK_ERR;
}
#endif
int con = socket(AF_INET, SOCK_STREAM, 0);
if (con < 0) {
return SOCKET_ERR;
}
char ipv4[16];
char port[6];
if (_parse_address(address, ipv4, port) != 0) {
return PARSE_ERR;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(port));
addr.sin_addr.s_addr = inet_addr(ipv4);
if (connect(con, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
return CONNECT_ERR;
}
return con;
}
extern int close_net(int con) {
#ifdef __linux__
return close(con);
#elif __WIN32
return closesocket(con);
#endif
}
extern int send_net(int con, char* buffer, size_t size) {
return send(con, buffer, (int)size, 0);
}
extern int recv_net(int con, char* buffer, size_t size) {
return recv(con, buffer, (int)size, 0);
}
static int8_t _parse_address(char *address, char *ipv4, char *port) {
size_t i = 0, j = 0;
for (; address[i] != ':'; ++i) {
if (address[i] == '\0') {
return 1;
}
if (i >= 15) {
return 2;
}
ipv4[i] = address[i];
}
ipv4[i] = '\0';
for (i += 1; address[i] != '\0'; ++i, ++j) {
if (j >= 5) {
return 3;
}
port[j] = address[i];
}
port[j] = '\0';
return 0;
}
#endif /* defined(__linux__) || defined(__WIN32) */
<file_sep>#ifndef EXTCLIB_IO_H_
#define EXTCLIB_IO_H_
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
extern void inputs_io(char* buffer, size_t size);
#endif /* EXTCLIB_IO_H_ */
<file_sep>#include <stdio.h>
int main(argc, argv)
int argc;
char *argv[];
{
char symbol;
char* word_of_symbols;
char** sentence_of_words;
char* _sentence_of_words[1];
char*** paragraph_of_sentences;
char**** and_so_on;
}
<file_sep>#include "limits.h"
void print_size_of_types() {
printf("signed char min = %14d, signed char max = %14d\n", SCHAR_MIN, SCHAR_MAX);
printf("unsigned char min = %14u, unsigned char max = %14u\n", 0, UCHAR_MAX);
printf("signed short min = %14d, signed short max = %14d\n", SHRT_MIN, SHRT_MAX);
printf("unsigned short min = %14u, unsigned short max = %14u\n", 0, USHRT_MAX);
printf("signed int min = %14d, signed int max = %14d\n", INT_MIN, INT_MAX);
printf("unsigned int min = %14u, unsigned int max = %14u\n", 0, UINT_MAX);
printf("signed long min = %14ld, signed long max = %14ld\n", LONG_MIN, LONG_MAX);
printf("unsigned long min = %14u, unsigned long max = %14lu\n", 0, LONG_MAX);
printf("float min = %14e, float max = %14e\n", FLT_MIN, FLT_MAX);
printf("double min = %14e, double max = %14e\n", DBL_MIN, DBL_MAX);
}
<file_sep>#include <stdio.h>
#include "struct.h"
#pragma pack(push, 1)
typedef struct { char ch; int i; } Data;
#pragma pack(pop)
int main(int argc, char const *argv[]) {
Data data;
data.ch = 0x11;
data.i = 0x02030405;
char *p = (char *)&data;
p++;
*p = 90; // 5a
s_a_print_info();
return 0;
}
<file_sep>#include <stdio.h>
#include "struct.h"
void s_a_print_info(void) {
{
s_a_d s;
s.ch_a = 0;
s.ch_b = 1;
printf("size of s_a_d = %ld\n", sizeof(s_a_d));
printf("\t+------+------+\n");
printf("\t| ch_a | ch_b |\n");
printf("\t+------+------+\n\n");
printf("\t0x%p(ch_a): %x\n", &s.ch_a, *(char *)(&s.ch_a));
printf("\t0x%p(ch_b): %x\n", &s.ch_b, *(char *)(&s.ch_b));
printf("<----->\n");
}
{
s_a_p s;
s.ch_a = 0;
s.ch_b = 1;
printf("size of s_a_p = %ld\n", sizeof(s_a_p));
printf("\t+------+------+\n");
printf("\t| ch_a | ch_b |\n");
printf("\t+------+------+\n\n");
printf("\t0x%p(ch_a): %x\n", &s.ch_a, *(char *)(&s.ch_a));
printf("\t0x%p(ch_b): %x\n", &s.ch_b, *(char *)(&s.ch_b));
printf("<----->\n");
}
}
void s_b_print_info(void) {
{
s_b_p s;
unsigned char *p;
s.ch_a = 0xB0;
s.sh_a = 0xACDE;
s.sh_b = 0xF00E;
printf("size of s_b_p = %ld\n", sizeof(s_b_p));
printf("ch_a - 0x%p\n", &s.ch_a);
printf("sh_a - 0x%p\n", &s.sh_a);
printf("sh_b - 0x%p\n", &s.sh_b);
printf("\t+------+------+------+\n");
printf("\t| ch_a | sh_a | sh_b |\n");
printf("\t+------+------+------|\n\n");
printf("\t+------+------+------|\n");
p = (unsigned char *)(&s.ch_a);
printf("\t| %.2x |", *p);
p = (unsigned char *)(&s_sh_a);
printf("\t| %.2x | %.2x", *p, *(p + 1));
p = (unsigned char *)(&s.sh_b);
printf("\t| %.2x | %.2x\n", *p, *(p + 1));
printf("\t+------+------+------|\n\n");
}
{
s_b_d s;
unsigned char *p;
s.ch_a = 0xB0;
s.sh_a = 0xACDE;
s.sh_b = 0xF00E;
printf("size of s_b_d = %ld\n", sizeof(s_b_d));
printf("ch_a - 0x%p\n", &s.ch_a);
printf("sh_a - 0x%p\n", &s.sh_a);
printf("sh_b - 0x%p\n", &s.sh_b);
printf("\t+------+------+------+\n");
printf("\t| ch_a | sh_a | sh_b |\n");
printf("\t+------+------+------|\n\n");
printf("\t+------+------+------|\n");
p = (unsigned char *)(&s.ch_a);
printf("\t| %.2x |", *p);
p = (unsigned char *)(&s_sh_a);
printf("\t| %.2x | %.2x", *p, *(p + 1));
p = (unsigned char *)(&s.sh_b);
printf("\t| %.2x | %.2x\n", *p, *(p + 1));
printf("\t+------+------+------|\n\n");
}
}
void s_c_print_info(void) {
{
s_c_p s;
unsigned char *p;
s.ch_a[0] = 0x01;
s.ch_a[1] = 0x10;
s.ch_a[2] = 0x11
s.i_a = 0x00000002;
s.sh_a = 0x3333;
s.sh_b = 0x44;
printf("size of s_c_p = %ld\n", sizeof(s_c_p));
printf("ch_a[0] - 0x%p\n", &s.ch_a[0]);
printf("ch_a[1] - 0x%p\n", &s.ch_a[1]);
printf("ch_a[2] - 0x%p\n", &s.ch_a[2]);
printf("i_a - 0x%p\n", &s.i_a);
printf("sh_a - 0x%p\n", &s.sh_a);
printf("ch_b - 0x%p\n", &s.ch_b);
printf("\t+------+------+------+------+------+------+------+------+------+------+\n");
printf("\t| ch_a | ch_a | ch_a | i_a | sh_a | ch_b |\n");
printf("\t+------+------+------+------+------+------+------+------+------+------+\n\n");
printf("\t+------+------+------+------+------+------+------+------+------+------+\n");
printf("\t+------+------+------+------+------+------+------+------+------+------+\n");
p = (unsigned char*)(&s.ch_a[0]);
printf("\t| %.2x | %.2x | %.2x |", *p, *(p + 1), *(p + 2));
p = (unsigned char*)(&s.i_a);
printf(" | %.2x | %.2x | %.2x | %.2x |", *p, *(p + 1), *(p + 2), *(p + 3));
p = (unsigned char*)(&s.sh_a);
printf(" | %.2x | %.2x |", *p, *(p + 1));
p = (unsigned char*)(&s.ch_b);
printf(" | %.2x |\n", *p);
printf("\t+------+------+------+------+------+------+------+------+------+------+\n\n");
printf("<----------> <----------> <---------->\n\n");
}
{
s_c_d s;
unsigned char *p;
s.ch_a[0] = 0x01;
s.ch_a[1] = 0x10;
s.ch_a[2] = 0x11;
s.i_a = 0x00000002;
s.sh_a = 0x3333;
s.ch_b = 0x44;
printf("size of s_c_d = %li\n\n", sizeof(s_c_d));
printf("ch_a[0] - 0x%p\n", &s.ch_a[0]);
printf("ch_a[1] - 0x%p\n", &s.ch_a[1]);
printf("ch_a[2] - 0x%p\n", &s.ch_a[2]);
printf("i_a - 0x%p\n", &s.i_a);
printf("sh_a - 0x%p\n", &s.sh_a);
printf("ch_b - 0x%p\n", &s.ch_b);
printf("\t+------+------+------+------+\n");
printf("\t| ch_a | ch_a | ch_a | |\n");
printf("\t+------+------+------+------+\n");
printf("\t| i_a |\n");
printf("\t+------+------+------+------+\n");
printf("\t| sh_a | ch_b | |\n");
printf("\t+------+------+------+------+\n\n");
printf("\t+------+------+------+------+\n");
p = (unsigned char*)(&s.ch_a[0]);
printf("\t| %.2x | %.2x | %.2x | %.2x |\n", *p, *(p + 1), *(p + 2), *(p + 3));
printf("\t+------+------+------+------+\n");
p = (unsigned char*)(&s.i_a);
printf("\t| %.2x | %.2x | %.2x | %.2x |\n", *p, *(p + 1), *(p + 2), *(p + 3));
printf("\t+------+------+------+------+\n");
p = (unsigned char*)(&s.sh_a);
printf("\t| %.2x | %.2x |", *p, *(p + 1));
p = (unsigned char*)(&s.ch_b);
printf(" | %.2x | %.2x |\n", *p, *(p + 1));
printf("\t+------+------+------+------+\n\n");
}
}
void test_data(char *p_data) {
s_problem_d d;
d = *((s_problem_d*)(p_data));
printf("ch = %c\n", d.ch);
printf("sh = %i\n", d.sh);
}
void problem_example(void) {
s_problem_d data;
char *send_buffer;
data.ch = 'a';
data.sh = 0x200;
send_buffer = (char*)&(data);
test_data(send_buffer);
}
<file_sep>#include <stdio.h>
#include <string.h>
struct Test {
char name[20];
};
struct Test fn(void);
int main(int argc, char const *argv[]) {
struct Test test_struct = fn();
return 0;
}
struct Test fn() {
struct Test test;
strcpy(test.name, "hello");
return test;
}
<file_sep>#include "example.test.h"
void example_test() {
char c = 0, i = 0, str[SIZE];
int *string = calloc(LIM - 1, sizeof(int));
for (short int i = 0; i < LIM - 1 && (c = getchar()) != EOF && c != '\n'; ++i, string++)
str[i] = c, *string = c;
for (short int i = 0; i < LIM - 1; i++, printf("%d\n", *string++));
do; while(printf("%d,\n", *string++), i-- > 0);
free(string);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
typedef int listDate;
typedef unsigned lengthData;
struct singleList {
listDate p_data;
struct singleList *p_next;
};
/* 0x400000 0x400004
+--------+ +--------+ +--------+
| p_data | | 1 | | 2 |
+--------+ +--------+ .->+--------+
| p_next | |0x400004| --. | NULL |
+--------+ +--------+ +--------+
for 5 int elements = (4 + 4) * 5 = 40 bytes
*/
struct DoubleList {
listDate p_data;
struct DoubleList *p_prev;
struct DoubleList *p_next;
};
/* 0x400000
+--------+ +--------+
| p_data | | 1 |
+--------+ +--------+
| p_next | | NULL |
+--------+ +--------+
| p_prev | | NULL |
+--------+ +--------+
for 5 int elements = (4 + 4 + 4) * 5 = 60 bytes
*/
struct unrolledLinkedList {
listDate *p_data_array;
lengthData length;
struct unrolledLinkedList *p_next;
};
/* 0x400000
+----------+ +-----------+
| p_data[] | | 1,2,3,4,5 |
+----------+ +-----------+
| length | | 5 |
+----------+ +-----------+
| p_next | | NULL |
+----------+ +-----------+
for 5 int elements = ((4 * 5) + 4 + 4) = 28 bytes
*/
int main(int argc, char const *argv[]) {
struct singleList *p_head;
struct singleList *p_tail;
p_head = NULL;
// append
char data = 1;
if (p_head == NULL) {
p_head = malloc(sizeof(struct singleList));
p_head->p_data = data;
p_head = NULL;
} else {
struct singleList *tmp;
tmp = p_head;
while(tmp->p_next)
tmp = tmp->p_next;
tmp->p_next = malloc(sizeof(struct singleList));
tmp->p_next->p_data = data;
tmp->p_next->p_next = NULL;
}
struct singleList *p_next;
p_next = p_head;
while(p_next->p_next) {
printf("%i, ", p_next->p_data);
p_next = p_next->p_next;
}
printf("%i\n", p_next->p_data);
return 0;
}
<file_sep>#include <stdio.h>
int main(void) {
char arr[3] = { 1, 2, 3 };
//arr[3] = 4; aborted (core dump)
printf("arr[3] = %d\n\n", arr[3]);
int array[10];
char i = 10; // random 40 bytes in memory (every time is different values in elements)
do printf("array[%d] = %d\n", i, array[i]);
while(i-- > 0);
char *str = "he\0llo";
// char str[] = "he\0llo"; (also is used)
printf("string will be trimmed to 'he': %s\n", str);
char *string = "hello world";
//string[2] = 0; (programm is crash)
/*while(*string != 0) {
if (*string == ' ') *string = 0;
if (*string == 0) break;
printf("%c", *string++);
}*/
/*int j = 0;
while(string[j] != 0)
printf("%c", string[j++]);
printf("\n");*/
char s[] = "hello!\0";
s[6] = 'e';
int k = 0;
while(s[k] != 0)
printf("%c", s[k]++);
printf("\n\n");
char st[] = "hello!\0";
st[6] = 'e';
printf("%s\n", st);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(const unsigned int argc, const char *argv[]) {
if (argc < 3) goto less_args;
if (argc > 3) goto more_args;
less_args: {
fprintf(stdout, "%s\n", "not specified code listing extention .c and .out");
exit(1);
}
more_args: {
fprintf(stdout, "%s\n", "there must be one file with the extention .c and .out");
exit(1);
}
char output[100] = "gcc -g -o ";
const char *file_out = argv[2];
const char *file_name = argv[1];
strcat(output, file_out);
strcat(output, " ");
strcat(output, file_name);
system(output);
fprintf(stdout, "%s\n", "press enter to start program");
getchar();
const char point[3] = "./";
const char *start = strcat(point, file_out);
system(start);
fprintf(stdout, "%m\n");
return 0;
}
<file_sep>#include <stdio.h>
void one_dimensional_array_example_a() {
int arr_a[3] = { 1, 2, 3 };
int arr_c[] = { 1, 2, 3 };
int arr_b[] = { [0] = 10, [2] = 3 };
void print(int *p_array, int length) {
for (int i = 0; i < length; i++)
printf("%i", *(p_array + i));
printf("\n");
}
int get_value(const int *p_array, int index) {
return *(p_array + index);
}
void set_value(int *p_array, int index, int value) {
*(p_array + index) = value;
}
int change_element_of_storing(int *p_array, int index) {
return *((char *)p_array + index);
}
print(arr_a, 3);
printf("before: [1] = %d\n", get_value(arr_a, 3));
set_value(arr_a, 4, 0);
printf("change_element_of_storing: %d\n", change_element_of_storing(arr_a, 3));
print(arr_c, 3);
printf("before: [1] = %d\n", get_value(arr_c, 19));
set_value(arr_c, 0, 0);
printf("change_element_of_storing: %d\n", change_element_of_storing(arr_c, 2));
}
void one_dimensional_array_example_b() {
int arr_a[3] = { 1, 2, 3 };
int arr_c[] = { 1, 2, 3 };
int arr_b[] = { [0] = 10, [2] = 3 };
void print(int p_array[], int length) {
for (int i = 0; i < length; i++)
printf("%i", p_array[i]);
printf("\n");
}
int get_value(const int p_array[], int index) {
return p_array[i];
}
void set_value(int p_array[], int index, int value) {
p_array[index] = value;
}
print(arr_a, 3);
printf("before: [1] = %d\n", get_value(arr_a, 3));
set_value(arr_a, 0, 1);
printf("change_element_of_storing: %d\n", change_element_of_storing(&arr_a[0], 3));
print(arr_c, 3);
printf("before: [1] = %d\n", get_value(arr_c, 19));
set_value(arr_c, 0, 1);
printf("change_element_of_storing: %d\n", change_element_of_storing(arr_c, 2));
}
void one_dimensional_array_example_c() {
int arr_a[3] = { 1, 2, 3 };
int arr_c[] = { 1, 2, 3 };
int arr_b[] = { [0] = 10, [2] = 3 };
void print(int (*p_array)[], int length) {
for (int i = 0; i < length; i++)
printf("%i", *(*p_array + i));
printf("\n");
}
int get_value(const int (*p_array)[], int index) {
return *(*p_array + index);
}
void set_value(int (*p_array)[], int index, int value) {
*(*p_array + index) = value;
}
int change_element_of_storing(int *p_array, int index) {
return *((char *)*p_array + index);
}
print(&arr_a, 3);
printf("before: [1] = %d\n", get_value(&arr_a, 3));
set_value(&arr_a, 0, 4);
printf("change_element_of_storing: %d\n", change_element_of_storing(&arr_a, 3));
print(&arr_c, 3);
printf("before: [1] = %d\n", get_value(&arr_c, 19));
set_value(&arr_c, 0, 6);
printf("change_element_of_storing: %d\n", change_element_of_storing(&arr_c, 2));
}
void one_dimensional_array_example_d() {
#define AR1_SIZE 3
int arr_a[AR1_SIZE + 1] = { AR1_SIZE };
#define AR2_SIZE 7
int arr_b[AR2_SIZE + 1] = { AR2_SIZE, 1, 2, 3, 4, 5, 6, 7 };
#define AR3_SIZE 1
int arr_c[AR3_SIZE + 1] = {AR3_SIZE, 1};
void print(int array[]) {
const int end = array[0] + 1;
for (int i = 0; i < end; i++)
printf("%d", array[i]);
printf("\n");
}
int get_value(const int array[], int index) {
if (index > array[0]) return 0;
return array[index + 1];
}
void set_value(const int array[], int index, int value) {
if (index > array[0]) return 0;
array[index + 1] = value;
}
set_value(arr_a, 2, 4);
print(arr_a);
set_value(arr_b, 5, 6);
print(arr_b);
set_value(arr_c, 0, 3);
print(arr_c);
}
int main(int argc, char const *argv[]) {
one_dimensional_array_example_a();
one_dimensional_array_example_b();
one_dimensional_array_example_c();
int tmp = 0;
int *a1 = 0; /* poiner to int or array */
int *a2[1] = { 0 }; /* array of pointers to int */
int (*a3)[]; /* poiner to array of int */
int a4[2] = { 1, 2 }; /* arrays of int */
// a1 = 1; /* warrning - incompatible type*/
a1 = &tmp;
// a2[0] = 1; /* warrning - incompatible type*/
a2[0] = &tmp;
a3 = &a4;
tmp = a4[0];
*(*a3) = 2;
// *(*a3) = &tmp; /* warrning - incompatible type*/
tmp = *(*a3);
tmp = a4[0];
a = 0; /* -> array[] */
a = NULL; /* -> *array*/
}
<file_sep>#ifndef TIME_CHRONO_H
#define TIME_CHRONO_H
#include <time.h>
struct timespec tstart = { 0, 0 };
struct timespec tend = { 0, 0 };
void start_chrono(void) {
clock_gettime(CLOCK_MONOTONIC, &tstart);
}
double elapsed() {
static double res = 0.0;
clock_gettime(CLOCK_MONOTONIC, &tend);
res = ((double)tend.tv_sec + 1.0e-9 * tend.tv_nsec) -
((double)tstart.tv_sec + 1.0e-9 * tstart.tv_nsec);
return res;
}
#endif
<file_sep>#include <stdio.h>
void two_dimensional_array_example_a() {
int arr_a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; // 0x?? 1 2 3 4 5 6
int arr_b[][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; // 0x?? 1 2 3 4 5 6
//int arr_a[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; // error
void print(int *p_array, int lines, int columns) {
for (int l = 0; l < lines; l++) {
for (int c = 0; c < columns; c++)
printf("%d", p_array[l * columns + c]);
printf("\n");
}
}
int get_value(const int *p_array, int lines, int columns) {
return p_array[lines * columns + columns];
}
void set_value(const int *p_array, int lines, int columns, int value) {
p_array[lines * columns + columns] = value;
}
printf("%p\n", &arr_a); /* the same address */
printf("%p\n", &arr_a[0]);
printf("%p\n", &arr_a[0][0]);
// print(arr_a, 1, 2); /* warning */
// print(&arr_a[0], 1, 2); /* warning */
print(&arr_a[0][0], 1, 2);
printf("%i\n", get_value(&arr_a[0][0], 3, 1));
set_value(&arr_a[0][0], 3, 1, 100);
printf("%i\n", get_value(&arr_a[0][0], 3, 1));
}
void two_dimensional_array_example_b() {
int arr_a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; // 0x?? 1 2 3 4 5 6
int arr_b[][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; // 0x?? 1 2 3 4 5 6
void print_a23(int p_array[2][3]) {
for (int l = 0; l < 2; l++) {
for (int c = 0; c < 3; c++)
printf("%d", p_array[l][c]);
printf("\n");
}
}
int get_value_a23(const int p_array[2][3], int lines, int columns) {
return p_array[lines][columns];
}
void set_value_a23(const int p_array[2][3], int lines, int columns, int value) {
p_array[lines][columns] = value;
}
print_a23(arr_a);
print_a23(arr_b);
printf("%i\n", get_value_a23(arr_a, 1, 1));
set_value_a23(arr_a, 1, 1, 100);
printf("%i\n", get_value_a23(arr_a, 1, 1));
}
void two_dimensional_array_example_c() {
int arr_a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; // 0x?? 1 2 3 4 5 6
int arr_b[][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; // 0x?? 1 2 3 4 5 6
void print_al3(int p_array[][3]) {
for (int l = 0; l < lines; l++) {
for (int c = 0; c < 3; c++)
printf("%d", p_array[l][c]);
printf("\n");
}
}
int get_value_al3(const int p_array[][3], int lines, int columns) {
return p_array[lines][columns];
}
void set_value_al3(const int p_array[][3], int lines, int columns, int value) {
p_array[lines][columns] = value;
}
print_al3(arr_a);
print_al3(arr_b);
printf("%i\n", get_value_al3(arr_a, 1, 1));
set_value_al3(arr_a, 1, 1, 100);
printf("%i\n", get_value_al3(arr_a, 1, 1));
}
int main(int argc, char const *argv[]) {
two_dimensional_array_example_a();
two_dimensional_array_example_b();
two_dimensional_array_example_c();
return 0;
}
<file_sep>#include "routes.h"
void index_page(int con, HTTPreq* req) {
printf("%s - %s - %s\n", req->method, req->path, req->proto);
if (strcmp(req->path, "/") != 0) {
parsehtml_http(con, "static/page404.html");
return;
}
parsehtml_http(con, "static/index.html");
}
void about_page(int con, HTTPreq* req) {
if (strcmp(req->path, "/about") != 0) {
parsehtml_http(con, "static/page404.html");
return;
}
parsehtml_http(con, "static/about.html");
}
<file_sep>CC = gcc
APP = test.test
define build-obj-different
$(CC) -o0 -g3 -Wall -c different.c -o different.o
$(CC) -masm=intel -g3 -Wall -c different.c -S
endef
test.out: main.o different.o example.test.o limits.o
$(CC) -Wall main.o different.o example.test.o limits.o -o $(APP)
main.o: main.c main.h different.h example.test.h limits.h
$(CC) -o0 -g3 -Wall -c main.c -o main.o
$(CC) -masm=intel -g3 -Wall -c main.c -S
different.o: different.c different.h
$(call build-obj-different)
example.test.o: example.test.c example.test.h
$(CC) -o0 -g3 -Wall -c example.test.c -o example.test.o
$(CC) -masm=intel -g3 -Wall -c example.test.c -S
limits.o: limits.c limits.h
$(CC) -o0 -g3 -Wall -c limits.c -o limits.o
$(CC) -masm=intel -g3 -Wall -c limits.c -S
clean:
rm -rf *.s *.o *.test
<file_sep>#!/bin/bash
gcc -Wall -E main.c -o main.i && gcc -E different.c -o different.i && gcc -E example.test.c -o example.test.i && gcc -E limits.c -o limits.i
gcc -Wall -S main.i -o main.s && gcc -S different.i -o different.s && gcc -S example.test.i -o example.test.s && gcc -S limits.i -o limits.s
gcc -Wall -c main.c -o main.o && gcc -c different.c -o different.o && gcc -c example.test.c -o example.test.o && gcc -c limits.c -o limits.o
gcc -Wall main.o different.o example.test.o limits.o -o res.out
<file_sep>#ifndef EXTCLIB_HTTP_H_
#define EXTCLIB_HTTP_H_
#include <stdint.h>
typedef struct HTTPreq {
char method[16]; // GET
char path[2048]; // /books
char proto[16]; // HTTP/1.1
uint8_t state;
size_t index;
} HTTPreq;
typedef struct HTTP HTTP;
extern HTTP *new_http(char *address);
extern void free_http(HTTP *http);
extern void handle_http(HTTP *http, char *path, void(*)(int, HTTPreq*));
extern int8_t listen_http(HTTP *http);
extern void parsehtml_http(int conn, char *filename);
#endif /* EXTCLIB_HTTP_H_ */
<file_sep>#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
printf("args count: %d\n", argc);
printf("%p\n%p\n", argv, *argv);
if (argc < 3 || strlen(argv[1]) > 2 ||\
(argv[1][1] != 'p' && argv[1][1] != 'a' && argv[1][1] != 'c') ||\
atoi(argv[2]) == 0) {
printf("-p -> search for position number\n-c -> search for course number\n-a -> search for age");
return 0;
}
for (int i = 0; i < argc; i++)
printf("%d: %s\n", i, argv[i]);
return 0;
}
<file_sep>#ifndef EXAMPLE_TEST_H
#define EXAMPLE_TEST_H
#include <stdio.h>
#include <stdlib.h>
#define LIM 10
#define SIZE 20
void example_test(void);
#endif
<file_sep>#include "main.h"
#include "test.h"
int main(int argc, char const *argv[]) {
sum();
printf("test divide files\n");
return 0;
}
<file_sep>#include <stdio.h>
void *pointer_test_a(void const *, long int const **);
void ***d_pointer_test_a(char const **);
unsigned short int const **a_d_p_a(void *[]);
int main(int argc, char const **argv) {
int num = 123, *pr2, **pr1;
pr2 = # pr1 = &pr2;
printf("Value of num is: \t%d\n", num);
printf("Value of *pr2 is: \t%d\n", *pr2);
printf("Value of **pr1 is: \t%d\n\n", **pr1);
printf("address of num is: \t%p\n", &num);
printf("address of *pr2 is: \t%p\n", pr2);
printf("address of **pr1 is: \t%p\n\n", *pr1);
printf("value of pointer pr2: \t\t%p\n", pr2);
printf("value of pointer pr2 using pr1: \t%p\n\n", *pr1);
printf("address of pointer pr2: \t\t%p\n", &pr2);
printf("address of pointer pr2 using pr1: \t%p\n\n", pr1);
printf("Value of Pointer pr1 is: %p\n", pr1);
printf("Address of Pointer pr1 is: %p\n\n", &pr1);
if (num == *pr2 == **pr1) printf("%s\n", "ok");
//if (&num == pr2 == *pr1) printf("%s\n", "ok");
if (&pr2 == pr1) printf("%s\n", "ok");
short int i_a = 10;
long int *p_i_a = (long int *)(void *)(&i_a);
short int **d_p_i_a = (short int **)(void **)(&p_i_a);
printf("address1: %p\n", &i_a);
printf("address2: %p\n", p_i_a);
printf("address3: %p\n\n", *d_p_i_a);
pointer_test_a((void const *)(p_i_a), (long int const **)(d_p_i_a));
d_pointer_test_a((char const **)(p_i_a));
a_d_p_a((void **)(p_i_a));
}
void *pointer_test_a(void const *p_a, long int const **d_p_a) {
char const ***t_p_a = (char const ***)(&d_p_a);
printf("address -1: %p\n", d_p_a);
printf("address 0: %p\n", *t_p_a);
unsigned short int const **p_pointer = (unsigned short int const **)(&p_a);
printf("address 1: %p\n", p_a);
printf("address 2: %p\n", *p_pointer);
printf("value 0: %d\n", ***t_p_a);
return (void *)(*p_pointer);
}
void ***d_pointer_test_a(char const **d_poiter) {
return (void ***)(&d_poiter);
}
unsigned short int const **a_d_p_a(void *a[]) {
printf("address1: %p\n", a);
printf("address2: %p\n", *a);
return (unsigned short int const **)(&a);
}
<file_sep>CC=gcc
LN=ld
CFLAGS=-Wall -std=c99
HEADERS=routes.h
SOURCES=routes.c
OBJECTS=routes.o
.PHONY: default
default: build link
build: $(HEADERS) $(SOURCES)
$(CC) $(CFLAGS) -c $(SOURCES)
link: $(OBJECTS)
$(LN) -r $(OBJECTS) -o another.o
clean:
rm -f *.o *.i *.s
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N_LINES 13
#define FIELD_SIZE 10
#define PLAYER_1 0
#define PLAYER_2 ~PLAYER_1
#define ARROW_KEY_PRESSED 0xE0
#define KEY_ENTER 13
#define KEY_UP 72
#define KEY_RIGHT 77
#define KEY_LEFT 75
#define KEY_DOWN 80
#define TARGET '+'
typedef enum { EMPTY = 0, SHOT, STRIKE, KILL, SHIP, FIELD_INFO_END } fiedInfo;
typedef enum { INIT = 0, DRAW, PROGRESSING, EXIT } gameState;
char draw_symbol[FIELD_INFO_END] = { ' ', '*', 'x', '#', '&' };
char *field[] = {
" ABCDEFGHIJ ABCDEFGHIJ ",
" *----------* *----------*",
"0 | | 0 | |",
"1 | | 1 | |",
"2 | | 2 | |",
"3 | | 3 | |",
"4 | | 4 | |",
"5 | | 5 | |",
"6 | | 6 | |",
"7 | | 7 | |",
"8 | | 8 | |",
"9 | | 9 | |",
" *----------* *----------*"
};
void draw_field(fiedInfo *, unsigned short);
void ship_generate(fiedInfo *);
unsigned char get_target_position(unsigned char *, unsigned char *);
int main() {
gameState game_state = INIT;
unsigned char isRun = 1;
int player = PLAYER_1;
fiedInfo p1_data[FIELD_SIZE * FIELD_SIZE] = { EMPTY };
fiedInfo p2_data[FIELD_SIZE * FIELD_SIZE] = { EMPTY };
fiedInfo *tmp;
unsigned char target_x = 0, target_y = 0;
unsigned short shot_position = 0;
while(isRun) {
if (game_state == INIT) {
ship_generate(p1_data);
ship_generate(p2_data);
p1_data[0] = KILL;
game_state = DRAW;
}
if (game_state == DRAW) {
system("clear");
tmp = player == PLAYER_1 ? p1_data : p2_data;
draw_field(tmp, shot_position);
if (get_target_position(&target_x, &target_y)) game_state = PROGRESSING;
shot_position = (target_y << 8) | target_x;
}
if (game_state == PROGRESSING) {
player = ~player;
game_state = DRAW;
}
if (game_state == EXIT) {}
}
return 0;
}
void draw_field(fiedInfo *p_data, unsigned short a_target) {
int i = 0;
do fprintf(stdout, "%s\n", field[i]);
while(i++ < 1);
unsigned char target_x = 0, target_y = 0;
target_x = a_target; // 1 10
target_y = a_target >> 8;
for (int i = 0; i < 10; i++) {
fprintf(stdout, "%c%c", field[i + 2][0], field[i + 2][2]);
for (int j = 0; j < FIELD_SIZE; j++) fprintf(stdout, "%c", draw_symbol[p_data[i * FIELD_SIZE + j]]);
for (int j = 12; j < 20; j++) fprintf(stdout, "%c", field[i + 2][j]);
for (int j = 0; j < FIELD_SIZE; j++) {
if (i == target_y && j == target_x) printf("%c", TARGET);
else fprintf(stdout, " ");
}
fprintf(stdout, "%c\n", field[i + 2][30]);
}
fprintf(stdout, "%s\n", field[N_LINES - 1]);
}
void ship_generate(fiedInfo *p_data) {
srand(time(NULL)); /*i * n + j*/
for (int i = 0; i < FIELD_SIZE; i++)
p_data[i + FIELD_SIZE + (rand() % 10) + 1] = SHIP;
}
unsigned char get_target_position(unsigned char *ap_x, unsigned char *ap_y) {
int key = 0;
key = getchar();
if (key == ARROW_KEY_PRESSED) {
key = getchar();
if (key == KEY_DOWN) {
if (*ap_y < FIELD_SIZE -1) *ap_y++;
return 0;
}
if (key == KEY_UP) {
if (*ap_y > 0) *ap_y--;
return 0;
}
if (key == KEY_LEFT) {
if (*ap_x < FIELD_SIZE -1) *ap_x++;
return 0;
}
if (key == KEY_RIGHT) {
if (*ap_x > 0) *ap_x--;
return 0;
}
}
if (key == KEY_ENTER) return 1;
return 0;
}
<file_sep>#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct Car {
int weight;
char name[50];
int length;
};
struct Bad {
int width, height;
};
int calculateBad(struct Bad bad);
int calculateGood(struct Bad *good);
int calculateBad(struct Bad bad) {
return bad.width * bad.height;
}
int calculateGood(struct Bad *good) {
printf("address for struct: %p\n", good);
printf("value for struct.field: %d\n", good->width);
return good->width * good->height;
}
int main(void) {
char line[255];
FILE *file = fopen("draft.txt", "a");
fprintf(file, "%s\n", "hello world");
do fprintf(stdout, "line: %s\n", line);
while (fgets(line, 10, file));
fclose(file);
struct Bad object = { 20, 40 };
int result = calculateBad(object);
int res = calculateGood(&object);
printf("value1: %d and value2: %d\n", result, res);
int ch = &10;
int *pointer = &ch;
int number = 10; // address in memory is the same
int *pointer = &number;
// the same as above and no need to declare variable 'number'
// we can not do like that !
int *pointer2 = 10;
printf("& value: %p and pointer: %p\n", &number, pointer);
int *scan_pointer;
printf("%s\n", "start");
scanf("%d\n", scan_pointer);
printf("value: %d\n", *scan_pointer);
struct Car bmw;
bmw.weight = 10000; //bmw.name = "bmw m5";
strcpy(bmw.name, "bmw m5");
// the same result of declaration of object from structs
struct Car audi = { 20000, "<NAME>" };
int i = 4;
do {
if (i == 2) goto here;
printf("%s and count: %d\n", "hello world", i);
}
while (i-- > 0);
here: {
printf("%s\n", "goto to is used");
printf("%s\n", "and here");
exit(1);
}
printf("%s\n", "not enter here");
int a = 3;
float b = 2.12;
int res = a / b;
fprintf(stdout, "res: %d\n", res);
const float x = 1.2344, y = 5.2345;
float res;
printf("%f\n", res);
printf("result: %.3f\n", x / y);
const bool flag = true;
const unsigned short val = 20;
for (int i; i < 2; i++) {
if (i != 10) { // trash !
printf("value for uninitialized variable: %d\n", i);
break;
}
}
printf("%d + %d = %d\n", 1, 2, 3);
short number = 10;
while (number > 0)
fprintf(stdout, "number: %d\n", number--);
printf("\n");
short number2 = 10;
while (number2-- > 0)
fprintf(stdout, "number: %d\n", number2);
printf("\n%m\n");
const time_t tm = time(NULL);
fprintf(stdout, "time: %s\n", ctime(&tm));
}
<file_sep>#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int my_pow(int val, int deg) {
int res = 1;
while(deg != 0) {
res *= val;
deg--;
}
return res;
}
char* repeat_str(unsigned int count, const char* str) {
int len = 0;
while(*str++)
len++;
printf("length: %d\n", len);
char* dest = (char*)malloc(sizeof(char) * count * len);
for(int i = 0; i < count; i++)
strcpy(dest + i * len, str);
return dest;
}
char* repeat_str_while(unsigned int count, const char* str) {
int length = strlen(str);
char* dest = (char*)malloc(sizeof(char) * count * length);
while(count--) {
printf("count: %d\n", count);
strcat(dest, str);
}
return dest;
}
int main() {
/*const char* base = "hello";
char* repeated = repeat_str_while(3, base);
while(*repeated)
printf("%c", *repeated++);
printf("\n");
const int length = strlen(base), count = 2;
char* test = (char*)malloc(sizeof(char) * length * count);
strcat(test, base);
strcat(test, base);
strcat(test, base);
while(*test)
printf("%c", *test++);
printf("\n");*/
/*const char* source = "source";
const char len = strlen(source);
const char count = 3;
char* res = (char*)malloc(len * count + 1);
int i = 0; char* p;
for (i = 0, p = res; i < count; ++i, p += len)
memcpy(p, source, len);
*p = '\0';
while(*res)
printf("%c", *res++);
printf("\n");*/
int res = round(2.8 / 2);
printf("res: %d\n", res);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "hashtab.h"
#include "net.h"
#include "http.h"
#define METHOD_SIZE 16
#define PATH_SIZE 2048
#define PROTO_SIZE 16
typedef struct HTTP {
char *host;
int32_t len;
int32_t cap;
void(**funcs)(int, HTTPreq*);
HashTab *tab;
} HTTP;
static HTTPreq _new_request(void);
static void _parse_request(HTTPreq *request, char *buffer, size_t size);
static void _null_request(HTTPreq *request);
static int8_t _switch_http(HTTP *http, int conn, HTTPreq *request);
static void _page404_http(int conn);
extern HTTP *new_http(char *address) {
HTTP *http = (HTTP*)malloc(sizeof(HTTP));
http->cap = 1000;
http->len = 0;
http->host = (char*)malloc(sizeof(char)*strlen(address)+1);
strcpy(http->host, address);
http->tab = new_hashtab(http->cap, STRING_TYPE, DECIMAL_TYPE);
http->funcs = (void(**)(int, HTTPreq*))malloc(http->cap * (sizeof (void(*)(int, HTTPreq*))));
return http;
}
extern void free_http(HTTP *http) {
free_hashtab(http->tab);
free(http->host);
free(http->funcs);
free(http);
}
extern void handle_http(HTTP *http, char *path, void(*handle)(int, HTTPreq*)) {
set_hashtab(http->tab, string(path), decimal(http->len));
http->funcs[http->len] = handle;
http->len += 1;
if (http->len == http->cap) {
http->cap <<= 1;
http->funcs = (void(**)(int, HTTPreq*))realloc(http->funcs,
http->cap * (sizeof (void(*)(int, HTTPreq*))));
}
}
extern int8_t listen_http(HTTP *http) {
int listener = listen_net(http->host);
if (listener < 0) {
return 1;
}
while(1) {
int conn = accept_net(listener);
if (conn < 0) {
continue;
}
HTTPreq req = _new_request();
while(1) {
char buffer[BUFSIZ] = {0};
int n = recv_net(conn, buffer, BUFSIZ);
if (n < 0) {
break;
}
_parse_request(&req, buffer, n);
if (n != BUFSIZ) {
break;
}
}
_switch_http(http, conn, &req);
close_net(conn);
}
close_net(listener);
return 0;
}
extern void parsehtml_http(int conn, char *filename) {
char buffer[BUFSIZ] = "HTTP/1.1 200 OK\nContent-type: text/html\n\n";
size_t readsize = strlen(buffer);
send_net(conn, buffer, readsize);
FILE *file = fopen(filename, "r");
if (file == NULL) {
return;
}
while((readsize = fread(buffer, sizeof(char), BUFSIZ, file)) != 0) {
send_net(conn, buffer, readsize);
}
fclose(file);
}
static HTTPreq _new_request(void) {
return (HTTPreq){
.method = {0},
.path = {0},
.proto = {0},
.state = 0,
.index = 0,
};
}
/*
GET /books HTTP/1.1
*/
static void _parse_request(HTTPreq *request, char *buffer, size_t size) {
printf("%s\n", buffer);
for (size_t i = 0; i < size; ++i) {
switch(request->state) {
case 0:
if (buffer[i] == ' ' || request->index == METHOD_SIZE-1) {
request->method[request->index] = '\0';
_null_request(request);
continue;
}
request->method[request->index] = buffer[i];
break;
case 1:
if (buffer[i] == ' ' || request->index == PATH_SIZE-1) {
request->path[request->index] = '\0';
_null_request(request);
continue;
}
request->path[request->index] = buffer[i];
break;
case 2:
if (buffer[i] == '\n' || request->index == PROTO_SIZE-1) {
request->proto[request->index] = '\0';
_null_request(request);
continue;
}
request->proto[request->index] = buffer[i];
break;
default: return;
}
request->index += 1;
}
}
static void _null_request(HTTPreq *request) {
request->state += 1;
request->index = 0;
}
static int8_t _switch_http(HTTP *http, int conn, HTTPreq *request) {
if (!in_hashtab(http->tab, string(request->path))) {
char buffer[PATH_SIZE];
memcpy(buffer, request->path, PATH_SIZE);
int32_t index = strlen(request->path);
if (index == 0) {
_page404_http(conn);
return 1;
}
index -= 1;
// buffer[index] = '\0';
for (; index > 0 && buffer[index] != '/'; --index) {
buffer[index] = '\0';
}
if(!in_hashtab(http->tab, string(buffer))) {
_page404_http(conn);
return 2;
}
index = get_hashtab(http->tab, string(buffer)).decimal;
http->funcs[index](conn, request);
return 0;
}
int32_t index = get_hashtab(http->tab, string(request->path)).decimal;
http->funcs[index](conn, request);
return 0;
}
static void _page404_http(int conn) {
char *header = "HTTP/1.1 404 Not Found\n\nnot found";
size_t headsize = strlen(header);
send_net(conn, header, headsize);
}
<file_sep>#include <stdio.h>
#include <string.h>
#define MINE_FOOD_COST_OIL 100
#define MINE_FOOD_COST_FOOD 200
#define MINE_FOOD_COST_GOLD 80
#define MINE_OIL_COST_OIL 100
#define MINE_OIL_COST_FOOD 200
#define MINE_OIL_COST_GOLD 80
#define MINE_GOLD_COST_OIL 300
#define MINE_GOLD_COST_FOOD 600
#define MINE_GOLD_COST_GOLD 200
#define FOOD_K 2.8f
#define OIL_K 2.8f
#define GOLD_K 2.8f
typedef enum { FOOD = 0, OIL, GOLD, MINE_END } eMine;
typedef struct {
char id;
char level;
short growth;
float k;
} Mine;
typedef struct {
Mine mines[30];
int mine_count;
int warehouse[MINE_END];
} Resources;
void init_resources(Resources *);
void resource_processing(Resources *);
void print_res_info(Resources *);
void increase_level_mine(Resources *, int);
int main() {
Resources resources;
init_resources(&resources);
int in_val = 0;
do {
resource_processing(&resources);
system("clear");
print_res_info(&resources);
char key = getchar();
if (key == '0') increase_level_mine(&resources, 0);
if (key == '1') increase_level_mine(&resources, 1);
if (key == '2') increase_level_mine(&resources, 2);
if (key == '3') increase_level_mine(&resources, 3);
} while(1);
return 0;
}
void init_resources(Resources *resources) {
char i = 0;
resources->mine_count = 0;
resources->warehouse[OIL] = 0;
resources->warehouse[FOOD] = 1;
resources->warehouse[GOLD] = 2;
resources->mines[i].level = 1;
Mine resources->mines[i] = { i, FOOD, FOOD_K * resources->mines[i].level, FOOD_K };
resources->mine_count = ++i;
resources->mines[i].level = 1;
Mine resources->mines[i] = { i, OIL, OIL_K * resources->mines[i].level, OIL_K };
resources->mine_count = ++i;
resources->mines[i].level = 1;
Mine resources->mines[i] = { i, GOLD, GOLD_K * resources->mines[i].level, GOLD_K };
resources->mine_count = ++i;
}
void resource_processing(Resources * resources) {
eMine type;
for (int i = 0; i < resources->mine_count; i++) {
type = resources->mines[i][FOOD]++;
resources->warehouse[type] += resources->mines[i].growth;
}
}
void print_res_info(Resources *resources) {
printf("+------+-----+------+\n");
printf("| food | oil | gold |\n");
printf("+------+-----+------+\n");
printf("|%10i|%10i|%10i|\n", resources->warehouse[FOOD], resources->warehouse[OIL], resources->warehouse[GOLD]);
printf("+------+-----+------+\n");
eMine type;
for (int i = 0; i < resources->mine_count; i++) {
type = resources->mines[i].type;
if (type == FOOD) printf("food - ");
if (type == OIL) printf("oil - ");
if (type == GOLD) printf("gold - ");
printf("[id]:%2i;", i);
printf("[level]:%3i", resources->mines[i].level);
printf("[growth]:%3i\n", resources->mines[i].growth);
}
}
void increase_level_mine(Resources *resources, int id) {
int food = resources->warehouse[FOOD];
int oil = resources->warehouse[OIL];
int gold = resources->warehouse[GOLD];
int needs_food = 0;
int needs_oil = 0;
int needs_gold = 0;
int isIncreased = 0;
if (id < resources->mine_count) {
int type = resources->mines[id][FOOD]++;
if (type == FOOD) {
needs_food = (resources->mines[id].level + 1) * MINE_FOOD_COST_FOOD;
needs_oil = (resources->mines[id].level + 1) * MINE_FOOD_COST_OIL;
needs_gold = (resources->mines[id].level + 1) * MINE_FOOD_COST_GOLD;
if (food >= needs_food && oil >= needs_oil && gold >= needs_gold) isIncreased = 1;
}
if (type == OIL) {
needs_food = (resources->mines[id].level + 1) * MINE_OIL_COST_FOOD;
needs_oil = (resources->mines[id].level + 1) * MINE_OIL_COST_OIL;
needs_gold = (resources->mines[id].level + 1) * MINE_OIL_COST_GOLD;
if (food >= needs_food && oil >= needs_oil && gold >= needs_gold) isIncreased = 1;
}
if (type == GOLD) {
needs_food = (resources->mines[id].level + 1) * MINE_GOLD_COST_FOOD;
needs_oil = (resources->mines[id].level + 1) * MINE_GOLD_COST_OIL;
needs_gold = (resources->mines[id].level + 1) * MINE_GOLD_COST_GOLD;
if (food >= needs_food && oil >= needs_oil && gold >= needs_gold) isIncreased = 1;
}
if (isIncreased) {
resources->mines[id].level++;
resources->mines[id].growth = resources->mines[id].level * resources->mines[id].k;
resources->warehouse[FOOD] -= needs_food;
resources->warehouse[OIL] -= needs_oil;
resources->warehouse[GOLD] -= needs_gold;
}
}
}
<file_sep>#include "transaction.h"
struct Line {
Line(const char* name, const char* lastname, int year): name(name), lastname(lastname), year(year) {}
int year;
const char* name;
const char* lastname;
};
void start(void) {
vector<Line> db;
db.push_back(Line("Nikola", "Tesla", 1856));
db.push_back(Line("Albert", "Einstein", 1879));
db.push_back(Line("Bill", "Gates", 1955));
db.push_back(Line("Stive", "Jobs", 1955));
db.push_back(Line("Mark", "Zuckerberg", 1984));
mutex mtx;
thread tr1(change, ref(db), ref(mtx));
thread tr2(rollback, ref(db), ref(mtx));
thread tr3(view, ref(db), ref(mtx));
tr1.join();
tr2.detach();
tr3.join();
}
void change(vector<Line>& db, mutex& mtx) {
int i = 0;
usleep(10000);
while("mutex& mtx and & vector<Line>& db") {
mtx.lock();
int j = 0;
while("records is changing") {
cout << "value k is: " << j << endl;
db.at(j).year = 2000;
if (j++ == 4) break;
}
cout << "value i is: " << i << endl;
if (i++ == 4) return;
mtx.unlock();
}
return;
}
void rollback(vector<Line>& db, mutex& mtx) {
int i = 0;
usleep(10000);
while("mutex& mtx and & vector<Line>& db") {
mtx.lock();
//db.at(i).year = 1900 + i;
db.at(0).year = 1856;
db.at(1).year = 1879;
db.at(2).year = 1955;
db.at(3).year = 1955;
db.at(4).year = 1984;
if (i++ == 4) return;
mtx.unlock();
}
return;
}
void view(vector<Line>& db, mutex& mtx) {
while("mutex& mtx and & vector<Line>& db") {
lock_guard<mutex> lock(mtx);
cout << "view: " << endl;
for (auto& row : db) cout << row.year << ", ";
cout << endl;
usleep(100000);
}
return;
}
int main(int, const char**) {
start();
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define width 65
#define height 25
typedef struct {
int x, y;
int w;
} racket;
typedef struct {
float x, y;
} ball;
char arr[height][width + 1];
racket r;
ball b;
int lvl = 1;
void init_ball() {
b.x = 2;
b.y = 2;
}
void put_ball() {
arr[(int)round(b.y)][(int)round(b.x)] = '*';
}
void move_ball(int x, int y) {
b.x = x;
b.y = y;
}
void init_racket() {
r.w = 7;
r.x = (width - r.w) / 2;
r.y = height - 1;
}
void put_racket() {
for (int i = r.x; i < r.x + r.w; ++i) {
arr[r.y][i] = '@';
}
}
void init() {
for (int i = 0; i < width; ++i) {
arr[0][i] = '#';
}
arr[0][width] = '\0';
for (int i = 1; i < width - 1; ++i) {
arr[1][i] = ' ';
}
for (int i = 1; i < width; ++i) {
strncpy(arr[i], arr[1], width + 1);
}
}
void move_racket(int x) {
r.x = x;
if (r.x < 1) {
r.x = 1;
}
if (r.x + r.w >= width) {
r.x = width - 1 - r.w;
}
}
void show() {
for (int i = 0; i < height; ++i) {
printf("%s\n", arr[i]);
}
}
void set_cur(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_HANDLE), coord);
}
void show_preview() {
system("clear");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \t\t\t\t\t\t LEVEL %d", lvl);
Sleep(1000);
system("clear");
}
int main(void) {
char c;
init_racket();
init_ball();
move_racket(2);
show_preview();
do {
set_cur(0, 0);
init();
put_racket();
put_ball();
show();
scanf("%c", &c);
if (c == 'a') move_racket(r.x - 1);
if (c == 'd') move_racket(r.x + 1);
move_ball(r.x + r.w / 2, r.y - 1);
Sleep(10);
} while(c != 'q');
return 0;
}
<file_sep>#include <stdio.h>
int main(void) {
int arr[10] = { [0 ... 4] = 5, [6 ... 9] = 7 };
int i = 0;
for (; i < 10; ++i)
printf("value: %d, index -> %d\n", arr[i], i);
}
<file_sep>#ifndef TEST_H
#define TEST_H
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#define PARAMS_COUNT 4
#define POWER 0
#define ARMOR 1
#define INTELLEGENCE 2
#define POWER_2 3
#define COUNT_FOOD_FARM 5
#define COUNT_OIL_FARM 5
#define FARM_K 1.2
unsigned short food_farm[COUNT_FOOD_FARM] = { 1 };
unsigned short oil_farm[COUNT_OIL_FARM] = { 1 };
unsigned short oil_warehouse = 0;
unsigned short food_warehouse = 0;
unsigned char player_params[PARAMS_COUNT] = { 0 };
void resource_processing(void) {
float food_produce = 0.0f, oil_produce = 0.0f;
char i = 0;
for (; i < COUNT_FOOD_FARM; ++i)
if ((rand() % 30) == 5) food_farm[i]++;
i = 0;
for (; i < COUNT_OIL_FARM; ++i)
if ((rand() % 30) == 5) oil_farm[i]++;
for (i = 0; i < COUNT_FOOD_FARM; ++i)
food_produce += food_farm[i] * FARM_K;
for (i = 0; i < COUNT_OIL_FARM; ++i)
oil_produce += oil_farm[i] * FARM_K;
food_warehouse += food_produce;
oil_warehouse += oil_produce;
system("clear");
fprintf(stdout, "food produce (h) -> %0.f\n", food_produce * 3600.f);
fprintf(stdout, "oil produce (h) -> %0.f\n", oil_produce * 3600.f);
fprintf(stdout, "food warehouse: %d\n", food_warehouse);
fprintf(stdout, "oil warehouse: %d\n", oil_warehouse);
}
void print_common_power(void) {
char i = PARAMS_COUNT, result = 0;
do result += player_params[i];
while(i-- > 0);
printf("common: %d\n", result);
}
void print_params(void) {
unsigned char i = 0;
for (; i < PARAMS_COUNT; ++i) {
if (i == POWER) fprintf(stdout, "power: %i\n", player_params[POWER]);
if (i == ARMOR) fprintf(stdout, "armor: %i\n", player_params[ARMOR]);
if (i == POWER_2) fprintf(stdout, "power_2: %i\n", player_params[POWER_2]);
if (i == INTELLEGENCE) fprintf(stdout, "intellegence: %i\n", player_params[INTELLEGENCE]);
}
}
void init_param_values(void) {
char i = PARAMS_COUNT;
do player_params[i] = rand() % 40;
while(i-- > 0);
}
void main_test2(void) {
do {
resource_processing();
sleep(1);
}
while(1);
}
#endif
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void input_output_a() {
FILE *p_file = NULL;
char *test_str = "input_output_a";
size_t len = strlen(test_str);
p_file = fopen("text.txt", "a+");
fwrite(test_str, sizeof(char), len, p_file);
fflush(p_file);
int i = 2;
do fwrite(test_str, sizeof(char), len, p_file);
while(i-- > 0);
fclose(p_file);
}
void input_output_b() {
FILE *p_file = NULL;
char *test_str = "input_output_b";
size_t len = strlen(test_str);
p_file = fopen("file.txt", "a+";
setbuf(p_file, NULL);
int i = 0;
for (; i < 4; ++i)
fwrite(test_str, sizeof(char), len, p_file);
fclose(p_file);
}
void input_output_a_error() {
FILE *p_file = NULL;
char *test_str = "input_output_a_error, small buffer";
char buffer[10] = { 0 };
size_t len = strlen(test_str);
p_file = fopen("file.txt", "a+");
setbuf(p_file, buffer);
char g = 5;
do {
fwrite(test_str, sizeof(char), len, p_file);
fflush(p_file);
} while(g-- > 0);
fclose(p_file);
}
void input_output_b_error() {
FILE *p_file = NULL;
char *test_str = "input_output_b_error, small buffer";
char buffer[20] = { 0 };
size_t len = strlen(test_str);
p_file = fopen("file.txt", "a+");
setbuf(p_file, buffer);
char g = 5;
do fwrite(test_str, sizeof(char), len, p_file);
while(g-- > 0);
g = 5;
do {
fwrite(test_str, sizeof(char), len, p_file);
fflush(p_file);
} while(g-- > 0);
fclose(p_file);
}
void input_output_e() {
FILE *p_file = NULL;
char *test_str = "input_output_e";
char buffer[BUF_SIZE] = { 0 };
size_t len = strlen(test_str);
p_file = fopen("file.txt", "a+");
setvbuf(p_file, buffer, _IOFBF, BUF_SIZE);
char h = 3;
do fwrite(test_str, sizeof(char), len, p_file);
while(h-- > 0);
h = 5;
do {
fwrite(test_str, sizeof(char), len, p_file);
fflush(p_file);
} while(h-- > 0);
fclose(p_file);
}
void input_output_struct_a() {
Test1 data_write;
Test1 data_read;
data_write.id = 123;
data_write.value = 3018;
FILE *pf_write = NULL, *pf_read = NULL;
pf_write = fopen("save_data_1.txt", "w");
fwrite(&data_write, sizeof(Test1), 1, pf_write);
fclose(pf_write);
pf_read = fopen("save_data_1.txt", "r");
fread(&data_read, sizeof(Test1), 1, pf_write);
fclose(pf_read);
}
void input_output_struct_b() {
Test1 data_write;
Test1 data_read;
data_write.id = 123;
data_write.value = 3018;
FILE *pf_write = NULL, *pf_read = NULL;
pf_write = fopen("save_data_2.txt", "w");
fpintf(data_write, "%d\n%d", data_write.id, data_write.value);
fclose(pf_write);
pf_read = fopen("save_data_2.txt", "r");
fscanf(pf_read, "%d\n%d", &data_read.id, &data_read.value;
fclose(pf_read);
}
<file_sep>#ifndef BINARY_TREE_H
#define BINARY_TREE_H
typedef struct { int data; } BinTreeData;
typedef struct {
int key;
BinTreeData value;
} Leaf;
typedef struct {
struct BinTreeNode *p_left;
struct BinTreeNode *p_right;
Leaf data;
} BinTreeNode;
typedef struct {
BinTreeNode *p_root;
} BinTree;
void bt_init(BinTree *);
void bt_destroy(BinTree *);
void bt_insert(BinTree *, Leaf *);
Leaf *bt_search(BinTree *);
void bt_in_order_print(BinTree *);
void bt_pre_order_print(BinTree *);
void bt_post_order_print(BinTree *);
#endif
<file_sep>#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
int sort_numbers(const void *a, const void *b);
int sort_strings(const void *a, const void *b);
int main(void) {
const unsigned char nums_size = 51;
const unsigned char buf_size = 6;
const unsigned char values_count = 7;
short nums[nums_size];
char buf[buf_size];
char str[nums_size * 2] = "your 6 numbers: ";
int r, temp;
char *strings[] = { "o", "s", "d" };
srand(time(NULL));
for (unsigned char i = 0; i < sizeof(nums - 1) / sizeof(int); i += 1)
nums[i] = i;
for (unsigned char i = 0; i < sizeof(nums - 1) / sizeof(int); i += 1) {
r = (rand() % sizeof(nums)) + 1;
temp = nums[i];
nums[i] = nums[r];
nums[r] = temp;
}
qsort(nums, nums_size, sizeof(int), sort_numbers);
for (unsigned char i = 0; i < nums_size; i += 1)
fprintf(stdout, "%i", nums[i]);
qsort(strings, sizeof(strings), sizeof(char), sort_strings);
for (unsigned char i = 0; i < sizeof(strings); i += 1)
fprintf(stdout, "%s\n", strings[i]);
for (unsigned char i = 0; i < values_count; i += 1) {
sprintf(buf, "%d", nums[i]);
strcat(buf, " ");
strcat(str, buf);
}
fprintf(stdout, "\n%s\n", str);
return 0;
}
int sort_numbers(const void *a, const void *b) {
const int x = *(int *)a;
const int y = *(int *)b;
return x - y;
}
int sort_strings(const void *a, const void *b) {
char **x = (char**)a;
char **y = (char**)b;
return strcmp(*x, *y);
}
<file_sep>#include <stdio.h>
#include <stdarg.h> /* va_list, va_start, va_arg, va_end */
void f_a(int, ...);
void f_b(char *, ...);
void example_a(void);
void example_a() {
char a = 4;
do f_a(a, a + 1, a * 2, a - 2);
while(a-- > 0);
}
void f_b(char *p_format, ...) {
va_list(p_array);
va_start(p_array, p_format);
for (char *p = p_format; *p; p++) {
if (*p != '%') {
putchar(*p);
continue;
}
p++;
if (*p == 'd') {
int i_val = 0;
i_val = va_arg(p_array, int);
printf("%d", i_val);
}
if (*p == 'f') {
double d_val = 0.;
d_val = va_arg(p_array, double);
printf("%f", d_val);
}
if (*p == 's') {
for (char *s_val = va_arg(p_array, char *); *s_val; s_val++)
putchar(*s_val);
}
else putchar(*p);
va_end(p_array);
}
}
void example_b() {
f_b("%d %f %s %i\n", 11, 12.12f, "Hello", 200);
}
void f_a(int count, ...) {
int value = 0;
va_list(vl); /* init variable */
va_start(vl, count); /* enable access to the variable argument */
char g = count;
do {
value = va_arg(vl, int); /* get next value from list */
printf("%d\n", value);
} while(g-- > 0);
va_end(vl); /* clear off what was needed */
printf("\n");
}
typedef struct { int health; int armor; } Unit;
typedef struct { int value_a; int value_b; int value_c; } Data;
void f_c(Type args[], ...) {
int index = 0;
va_list(p_args);
va_start(p_args, args);
while(args[index] != END) {
int value = args[index]
if (value == UNIT) {
Unit unit = va_arg(p_args, Unit);
printf("Unit info:\nArmor: %d\nHealth: %d", unit.armor, unit.health);
}
if (value == DATA) {
Data data = va_arg(p_args, Data);
printf("Data info:\nvalue_a: %d, value_a: %d\nvalue_c: %d", data.value_a, data.value_b, data.value_c);
}
index++;
va_list(p_args);
}
}
int main(int argc, char const *argv[]) {
example_b();
return 0;
}
<file_sep>#ifndef INPUT_OUTPUT_H
#define INPUT_OUTPUT_H
#define TEST_1
void input_output_a(void);
void input_output_b(void);
#elif defined(TEST_2)
void input_output_a_error(void);
void input_output_b_error(void);
#elif defined(TEST_3)
#define BUF_SIZE 19
void input_output_e(void);
void input_output_f(void);
#elif defined(TEST_4)
typedef struct { int id; int value; } Test1;
typedef struct { int id; char *str; } Test2;
void input_output_struct_a(void);
void input_output_struct_b(void);
#endif
<file_sep>#ifndef EXTCLIB_HASHTAB_H_
#define EXTCLIB_HASHTAB_H_
#include <stddef.h>
#include <stdint.h>
#include "type.h"
typedef struct HashTab HashTab;
extern HashTab *new_hashtab(size_t size, vtype_t key, vtype_t value);
extern void free_hashtab(HashTab *hashtab);
extern value_t get_hashtab(HashTab *hashtab, void *key);
extern int8_t set_hashtab(HashTab *hashtab, void *key, void *value);
extern void del_hashtab(HashTab *hashtab, void *key);
extern _Bool in_hashtab(HashTab *hashtab, void *key);
extern _Bool eq_hashtab(HashTab *x, HashTab *y);
extern size_t size_hashtab(HashTab *hashtab);
extern size_t sizeof_hashtab(void);
extern void print_hashtab(HashTab *hashtab);
extern void println_hashtab(HashTab *hashtab);
extern void print_hashtab_format(HashTab *hashtab);
extern void println_hashtab_format(HashTab *hashtab);
#endif /* EXTCLIB_HASHTAB_H_ */
<file_sep>#include <stdio.h>
/* correct .h file */ /*
#ifndef WHILE_LOOP_H
#define WHILE_LOOP_H
void do_while_example(void);
#endif // WHILE_LOOP_H
*/
int main() {
printf("%c\n", 7);
int i = 0;
do printf("ascii value: #%d -> %c\n", i, i);
while(i++ < 256);
printf("line: %d\nfunction: %s\nfile: %s\n", __LINE__, __FUNCTION__, __FILE__);
// /*(cpp lesson6.c)*/ __LINE__, __FUNCTION__, __FILE__;
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
#define CONST 50
#undef CONST
#define G 20
#define H 30
#define SUM(a, b) (a + b) * 2
#ifdef (if defined)
#ifndef (if not defined)
#endif
static int number = 500;
outer int n = 20;
void print_hello();
short add_number();
short test(const short number);
void recur(int number);
void fn1(int *pointer);
void fn2(int *pointer);
void fn1(int *pointer) {
*pointer = *pointer + *pointer;
};
void fn2(int *pointer) {
*pointer = *pointer / *pointer;
};
void string(char *pointer) {
while (*pointer) {
*pointer = *pointer ^ 31;
pointer++;
}
};
struct coords { int x; int y; };
struct coords Top;
typedef struct { int value1; int value2; } Pointer2;
typedef struct { Pointer2 a; Pointer2 b; } Coordinators;
Pointer2 bottom = { 10, 10 };
Coordinators var;
typedef struct { char str[4]; } Bad;
typedef struct { char *str; } Good;
typedef struct { char *name; char *population; } City;
int main(void) {
City first, second, third, *fourth;
first.name = "first city";
first.population = "123";
fprintf(stdout, "first struct: city = %s, population = %s\n", first.name, first.population);
fourth = &second;
fourth->name = "second city";
fourth->population = "128";
fprintf(stdout, "second struct: city = %s, population = %s\n", second.name, second.population);
fourth = &third;
fourth -> name = "third city";
fourth -> population = "981";
fprintf(stdout, "address: %p and value: %d\n", fourth, *fourth);
fprintf(stdout, "third struct: city = %s, population = %s\n", fourth -> name, fourth -> population);
int numbers[] = { 1, 2, 3 };
fprintf(stdout, "first value: %d\n", *numbers);
Bad bad = { 'b', 'a', 'd', '\0' };
Good good = { "good" };
/* GOOD EXAMPLE */
fprintf(stdout, "value in struct: %s\n", bad.str);
char *pointer = "ok";
for (short i = 0; i < sizeof(bad.str); i += 1)
bad.str[i] = *pointer++;
fprintf(stdout, "changed value in struct: %s\n", bad.str);
fprintf(stdout, "value = %d and address = %p\n", *good.str, good.str);
var.a = bottom; var.b = bottom;
Pointer.x = 10; Pointer.y = 20;
Top.x = 30; Top.y = 40;
fprintf(stdout, "top: %d %d\n", Top.x, Top.y);
fprintf(stdout, "pointer: %d %d\n", Pointer.x, Pointer.y);
printf("char size = %ld\n", sizeof(char));
printf("int size = %ld\n", sizeof(int));
printf("short size = %ld\n", sizeof(short));
printf("long size = %ld\n", sizeof(long));
printf("short float = %ld\n", sizeof(float));
printf("long double = %ld\n", sizeof(double));
printf("void = %ld\n", sizeof(void));*/
int SIZE = 100;
char str1[100] = "string 1";
char str2[] = " string 2\n";
char str3[100] = "string 3";
char str4[] = " string 4\n";
const int size = sizeof str2;
printf("size of str2 = %d\n", size);
strcat(str1, str2);
fputs(str1, stdout);
printf("%c", '\n');
const int size = 50;
char string[size + 1];
const int s = 50;
char arr[s + 1];
fscanf(stdin, "%s\n", string);
fscanf(stdin, "%[^\n]", arr);
gets(arr); not use
fprintf(stdout, "string: %s\n", string);
fprintf(stdout, "arr: %s\n", arr);
fgets(string, 50, stdin);
fputs(string, stdout);
int number;
fscanf(stdin, "%d", &number);
printf("%d\n", number);
char *p_arr_string[3] = { "item1", "item2", "item3" };
fprintf(stdout, "pointer p_arr_string: %p\n", p_arr_string);
fprintf(stdout, "first value: %s\n", p_arr_string[0]);
fprintf(stdout, "first value pointer: %d\n", *p_arr_string[0]);
int numbers[] = { 1, 2, 3 };
int *pointer = &numbers[0];
fprintf(stdout, "numbers value: %d\n", *numbers);
fprintf(stdout, "numbers pointer: %p, pointer: %p\n", numbers, pointer);
int *arr_pointers[2] = { pointer, numbers };
for (int i = 0; i < 2; i++)
fprintf(stdout, "%p\n", arr_pointers[i]);
const int SIZE = 100;
char str[SIZE];
char *p_string = str;
fprintf(stdout, "%s", "enter your string ");
scanf("%s", str);
string(str);
fprintf(stdout, "%s\n", str);
string(str);
fprintf(stdout, "%s\n", str);
int number = 100;
int *pointer = &number;
fprintf(stdout, "number: %d, value on pointer: %d, address: %p\n", number, *pointer, pointer);
fn1(pointer);
fprintf(stdout, "change value via pointer: %d, number: %d, address: %p\n", *pointer, number, pointer);
fn2(pointer);
fprintf(stdout, "change value via pointer: %d, number: %d, address: %p\n", *pointer, number, pointer);
const int a = 10, b = 20;
int c = a + b * 2;
int d = SUM(a, b);
int s = SUM(G, H);
printf("%d\n", s);
extern int number;
printf("%d\n", number);
int number = 10;
short num = 1;
long numberoc = 100;
char letter = 'a';
float fl = 1.234;
double decimal = 1.234;
long long n = 19398318931;
printf("number = %i, short = %d\n", number, num);
printf("numberoc = %d, letter = %c, float = %f, double = %g\n", number, letter, fl, decimal);
int age, weight;
char name[50];
printf("enter your name ");
scanf("%s", name);
printf("enter your age ");
scanf("%d", &age);
printf("enter your weight ");
scanf("%d", &weight);
printf("weight: %d, age: %i, name: %s\n", weight, age, name);
printf("address in computer for variable 'name' %p\n", &name);
short n = 1;
short hello;
printf("%p\n", &n);
scanf("%hd", &hello);
int a = 100, b = 20;
int sum = a + b;
printf("%d\n", sum);
printf("%i\n", a - b);
int number = 10;
float c = (double) number;
int b = (int) c;
printf("%f\n", c);
printf("%d\n", b);
printf("%i\n", (int) 2.2);
int numbers[3] = { 1, 2, 3, 4 };
char arr[4] = { 'a', 'b', 'c', '\0' };
char str[] = { "abc" };
printf("arr = %s and str = %s\n", arr, str);
for (int i = 0; i < 4; i++)
printf("str[i] = %c\n", str[i]);*/
char name[] = { "name" };
char s = name[10];
char arr[2][3] = { { 'a', 'b', '\0' }, { 'c', 'd', '\0' } };
#define STR_VALUE "value of this string"
#define NUMBER 100.01
#define STRING { "hello world" }
const int VALUE = 10;
const char string[] = { "hello world" };
enum days { monday = 'A', tuesday = 2 };
printf("%d\n", monday);
printf("%i\n", tuesday);
typedef int myType;
myType value = 10;
typedef char string[10];
string str[] = { "abc" };
int const a = 10, b = 20;
#if a < b
printf("%s\n", "hello world");
#endif
printf("%s\n", "what is wrong");*/
int number = 6 % 2 == 0 ? printf("%s\n", "even") : printf("%s\n", "odd");
printf("%i because length of world 'even\\n' is 5\n", number);
const int number = 10;
if (number == 10) printf("%s\n", "true");
else printf("%s\n", "not equals");
const char letter = 'A';
if (letter == 'A') printf("%s\n", "letters are not odd");
else if (letter == 'V') printf("%s\n", "letter else if");
else printf("%s\n", "not defined");
const short result = strcmp("hello", "world");
printf("%i\n", result);
short number = 0;
fprintf(stdout, "%s\n", "fprintf function");
fscanf(stdin, "%hd", &number);
switch(number) {
case 1: fprintf(stdout, "%s\n", "test");
break;
}
const char string[4] = { 's', 't', 'r', '\0' };
for (short i = 0; i < strlen(string); i+=1)
fprintf(stdout, "%s%d\n", "current value is ", string[i]);
const short numbers[] = { 1, 2, 3 };
for (short i = 0; i < 3; i+=1)
fprintf(stdout ,"number[%d] = %d\n", i, numbers[i]);
short i = 0;
while (i != 5) {
printf("%d\n", i);
i++;
}
for (short i = 0; i < 5; i+=1) {
if (i == 2) goto mark;
printf("%d\n", i);
}
mark:
printf("%s\n", "operator 'go to'");
print_hello();
const short number = add_number();
printf("%d\n", number);
fprintf(stdout, "%d\n", add_number());
printf("%d\n", test(10));
short number;
fprintf(stdout, "%s\n", "enter value ");
fscanf(stdin, "%hd", &number);
recur(number);
fprintf(stdout, "%s\n", "done");
const int number = 10;
const int *p_number;
p_number = &number;
const int num = 15;
const int *p_num = #
printf("Value: %i, address: %p\n", *p_num, p_num);
printf("Value: %d, address: %p\n", *p_number, p_number);
const int *p_arr_number;
int arr[] = { 1, 2, 3, 4 };
p_arr_number = arr;
for (short i = 0; i < 4; i++) {
printf("Index[%d] = value: %d, address: %p\n", i, *p_arr_number, p_arr_number);
*p_arr_number++;
}
char *p_arr_char;
char string[] = { "test" };
p_arr_char = string;
for (short i = 0; i < strlen(string); i++) {
if (*p_arr_char == 's') *p_arr_char = 'x';
fprintf(stdout, "value: %c\n", *p_arr_char++);
}
int *p_number;
int number = 10;
p_number = &number;
printf("%d\n", *p_number);
*p_number = 20;
printf("%d\n", *p_number);
int number1 = 30;
int *p_number1 = &number1;
printf("%d\n", *p_number1);
int numbers[] = { 1, 2, 3 };
int *p_arr_number = numbers;
for (int i = 0; i < 3; i+=1) {
fprintf(stdout, "%d\n", *(p_arr_number + i));
}
int numbers[] = { 1, 2 };
int *p_numbers = numbers;
for (int i = 0; i < 2; i+=1) {
fprintf(stdout, "value: %d\n", numbers[i]);
p_numbers++;
}
}
void recur(int number) {
fprintf(stdout, "%d\n", number);
if (--number < 0) return;
else recur(number);
}
short test(const short number) {
return number;
}
short add_number() {
const short a = 10, b = 20;
return a + b;
}
void print_hello(void) {
fprintf(stdout, "%s\n", "hello Function");
}
<file_sep>#define MAX(a, b) a > b
#define MIN(a, b) a < b
#define STR(s1, s2) s1 < s2
#define COMBINE(a, b) MIN(a, b) == MAX(a,b)
int main() {
const char max = MAX(10, 20);
const char min = MIN(10, 20);
const char str = STR("hello", "world");
const char combine = COMBINE(max, min);
}
<file_sep>#!/bin/bash
gcc -Wall -E main.c -o main.i && gcc -E test.c -o test.i
gcc -Wall -S main.i -o main.s && gcc -S test.i -o test.s
gcc -Wall -c main.c -o main.o && gcc -c test.c -o test.o
gcc -Wall main.o test.o -o res.out
<file_sep>#ifndef EXTCLIB_TREE_H_
#define EXTCLIB_TREE_H_
#include <stddef.h>
#include <stdint.h>
#include "type.h"
typedef struct Tree Tree;
extern Tree *new_tree(vtype_t key, vtype_t value);
extern void free_tree(Tree *tree);
extern value_t get_tree(Tree *tree, void *key);
extern int8_t set_tree(Tree *tree, void *key, void *value);
extern void del_tree(Tree *tree, void *key);
extern _Bool in_tree(Tree *tree, void *key);
extern _Bool eq_tree(Tree *x, Tree *y);
extern size_t size_tree(Tree *tree);
extern size_t sizeof_tree(void);
extern void print_tree(Tree *tree);
extern void println_tree(Tree *tree);
extern void print_tree_branches(Tree *tree);
extern void println_tree_branches(Tree *tree);
#endif /* EXTCLIB_TREE_H_ */
<file_sep>#ifndef _ROUTES_H_
#define _ROUTES_H_
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "../extclib/http.h"
void index_page(int con, HTTPreq* req);
void about_page(int con, HTTPreq* req);
#endif /* _ROUTES_H_ */
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <time.h>
#include <Windows.h>
#include <winuser.h>
#include <conio.h>
int main(void) {
char arr[10][21];
int i, x, y;
int ox, oy;
int ax, ay;
int apples;
char key;
i = apples = 0, x = 10, y = 5;
ax = ay = 5;
srand(time(NULL));
do {
sprintf(*(arr + 0), "####################");
for (i = 1; i < 9; ++i)
sprintf(*(arr + i), "# #");
sprintf(*(arr + 9), "####################");
*(*(arr + y) + x) = '@';
*(*(arr + ax) + ay) = '&';
system("clear");
i = 0;
for (; i < 10; ++i)
printf("%s\n", *(arr + i));
printf("apples: %d\n", apples);
scanf("%c", &key);
ox = x;
oy = y;
if (key == 'w') y--;
else if (key == 's') y++;
else if (key == 'a') x--;
else if (key == 'd') x++;
printf("%d\n", *(*(arr + x) + y));
if (*(*(arr + x) + y) == '#')
x = ox; y = oy;
if (x == ax && y == ay)
ax = rand() * 1.0 / RAND_MAX * 18 + 1, ay = rand() * 1.0 / RAND_MAX * 8 + 1, ++apples;
} while(key != 'e');
return 0;
}
<file_sep>#include <stdio.h>
#include "example.test.h"
#include "array.test.h"
int main(int argc, char *argv[]) {
main_test2();
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#define TEST_3
void print_struct_info(void);
#ifdef TEST_1
typedef struct { char a; char b; } s_a;
typedef struct { char a; short b; } s_b;
typedef struct { char a; int b; } s_c;
typedef struct { char a; double b; } s_d;
typedef struct { long a; char b; } s_e;
typedef struct { float a; long double b; } s_f;
#pragma pack(push, 4)
typedef struct { char a; long long b; } s_e_p;
typedef struct { short a; long double b; } s_f_p;
#pragma pack(pop)
void print_struct_info() {
printf("size of s_a { char; char } = %li\n", sizeof(s_a));
printf("size of s_b { char; short } = %li\n", sizeof(s_b));
printf("size of s_c { char;int } = %li\n", sizeof(s_c));
printf("size of s_d { char; double } = %li\n", sizeof(s_d));
printf("size of s_c { long; char } = %li\n", sizeof(s_e));
printf("size of s_d { float; long double } = %li\n", sizeof(s_f));
printf("size of s_c { char; long long } = %li\n", sizeof(s_e_p));
printf("size of s_d { short; long double } = %li\n", sizeof(s_f_p));
}
#elif defined(TEST_2)
typedef struct { char a : 1; char b : 1; } s_a; // 6 unused
typedef struct { char a : 5; char b : 3; } s_b; // 0
typedef struct { char a : 5; char b : 4; } s_c; // 7 unused -> 2 bytes
typedef struct { char a : 2; char : 0; char b : 4; } s_d; // takes rest of 8 -> 8 -2 = 6
typedef struct { char a : 4; char : 0; char b : 4; } s_e; // takes rest of 8 -> 8 -4 = 4 // 28 unused -> char extended to int (32b)
void print_struct_info() {
printf("size of s_a { char a: 1; char b: 1 } = %li\n", sizeof(s_a));
printf("size of s_b { char a: 5; char b: 3 } = %li\n", sizeof(s_b));
printf("size of s_c { char a: 5; char b: 4 } = %li\n", sizeof(s_c));
printf("size of s_d { char a: 4; char : 0; char b: 4 } = %li\n", sizeof(s_d));
printf("size of s_e { char a: 4; int : 0; char b: 4 } = %li\n", sizeof(s_e));
}
#elif defined(TEST_3)
typedef struct { char a : 1; char : 0; } s_a;
typedef struct { char a : 5; short : 0; } s_b;
typedef struct { char a : 5; int : 0; } s_c;
typedef struct { char a : 4; long long : 0; } s_d;
void print_struct_info() {
printf("size of s_a { char a: 1; char : 0 } = %ld\n", sizeof(s_a));
printf("size of s_b { char a: 5; short : 0 } = %ld\n", sizeof(s_b));
printf("size of s_c { char a: 5; int : 0 } = %ld\n", sizeof(s_c));
printf("size of s_d { char a: 4; char : 0; long long : 0 } = %ld\n", sizeof(s_d));
}
#elif defined(TEST_4)
typedef struct { char a : 1; char : 0; char b; } s_a;
typedef struct { char a : 5; short : 0; char b } s_b;
typedef struct { char a : 5; int : 0; char b } s_c;
typedef struct {
char a : 1; // 1
char : 0 // 7 unused
char b : 2 // 2
char : 4 // 4 unused
char c : 2 // 2
} s_d;
typedef struct {
char a : 1; // 1
short : 0; // 15 unused
char b : 2; // 2
char : 4; // 4 unused
char c : 2; // 2
} s_e;
typedef struct {
char a : 1; // 1
int : 0; // 31 unused
char b : 2; // 2
char : 4; // 4 unused
char c : 2; // 2
} s_f;
void print_struct_info() {
printf("size of s_a = %li\n", sizeof(s_a));
printf("size of s_b = %li\n", sizeof(s_b));
printf("size of s_c = %li\n", sizeof(s_c));
printf("size of s_d = %li\n", sizeof(s_d));
printf("size of s_e = %li\n", sizeof(s_e));
printf("size of s_f = %li\n", sizeof(s_f));
}
#endif
typedef struct { char b1: 1; char b2: 1; char b3: 1; char b4: 1; char b5: 1; char b6: 1; char b7: 1; char b8: 1; } sByte;
/*
(C99, 6.7.2.1p4)
"A bit-field shall have a type that is a qualified or
unqualified version of _Bool, signed int, unsigned int, or some other
implementation-defined type."
(C99, 6.7.2.1p10)
"If enough space remains, a bit-field that immediately follows another bit-field
in a structure shall be packed into adjacent bits of the same unit"
(C99, 6.7.2.1p11)
"A bit-field declaration with no declarator, but only a colon and a width, indicates an
unnamed bit-field.As a special case, a bit-field structure member with a width of 0
indicates that no further bit-field is to be packed into the unit in which the previous bitfield,if any, was placed."
The special unnamed bit field of width zero breaks up padding:
it specifies that the next bit field begins at the beginning of the next
allocation unit.
*/
int main(int argc, char const *argv[]) {
print_struct_info();
return 0;
}
<file_sep>#include "test.h"
void sum() {
return;
}
<file_sep>#ifdef STRUCT_H
#define STRUCT_H
typedef struct { char ch_a; char ch_b } s_a_d;
typedef struct { char ch_a; short sh_a; short sh_b } s_b_d;
typedef struct { char ch_a[3]; int i_a; short sh_a; char ch_b } s_c_d;
#pragma pack(push, 1)
typedef struct { char ch_a; char ch_b } s_a_p;
#pragma pack(pop)
#pragma pack(push, 1)
typedef struct { char ch_a; short sh_a; short sh_b } s_b_p;
#pragma pack(pop)
#pragma pack(push, 1)
typedef struct { char ch_a[3]; int i_a; short sh_a; char ch_b } s_c_p;
#pragma pack(pop)
typedef struct { char ch; short sh } s_problem_d;
#pragma pack(push, 1)
typedef struct { char ch; short sh } s_problem_p;
#pragma pack(pop)
void s_a_print_info(void);
void s_b_print_info(void);
void s_c_print_info(void);
void test_data(char *);
void problem_example(void);
#endif
<file_sep>CC=gcc
CFLAGS=-Wall -std=c99
FILES=main.c extclib/extclib.o routes/another.o
.PHONY: default build run
default: build run
routes.o:
$(CC) $(CFLAGS)
build: $(FILES)
$(CC) $(CFLAGS) $(FILES) -o main
run: main
./main
delete:
rm -rf main
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <time.h>
#include <math.h>
//#include <Windows.h>
//#include <winuser.h>
//#include <conio.h>
#define cnt 5
#define _celoe int
#define show_i printf("%d\n", cnt);
typedef int celoe;
typedef struct {} _point;
typedef int (*f)(int, int, void(*)(void));
typedef int (*fa[4])(int, int);
typedef struct _o {} o_, *_o_;
enum {BOLD = 0b0001, ITALIC = 0b0010, UNDERLINE = 0b0100};
union {
struct {
unsigned char is_bold: 1;
unsigned char is_italic: 1;
unsigned char is_underline: 1;
unsigned char: 2;
unsigned char l: 4;
};
unsigned char flags;
};
void free_and_null(void** p) {
free(*p);
*p = NULL;
}
BOOL check_in(int x, int y) {
return (() && () && () && ());
}
int main(int argc, const char* argv[]) {
/*setlocale(LC_ALL, "Ukraine");
srand(time(NULL));
if (int a = 4, celoe x, i = 0, arr[10], m[9], char v[10]; !a) {
printf("%s\n", "enter"), scanf("%d", &x), printf("x = %g\n", (float)x), sprintf(&v[0], "hello\0");
while(i <= 10) printf("i = %d\n", i++), printf("%s\n%d\n", v, *(arr + i));;
do a += ++x++ + ++a;; while(a-- != -1);
for (;;) for (; i < 9; i++, *(m + i) = i + 1); if (a--) return -1;
}/
celoe i = cnt;
OemToChar(s, s);*/
int i = 0;
for (; i < argc; ++i) {
char* c;
float f = strtof(argv[i], &c);
printf("%s -- %s --\n", *c == 0 ? "digit" : "string", argv[i]);
}
while(*argv)
printf("%s\n", *argv++);
struct _text t;
t.is_bold = t.is_italic = 1;
t.is_underline = 0;
char text = BOLD | UNDERLINE;
if (text & BOLD) {
printf("%s\n", "Text is in bold");
}
int i = 2;
char c[2];
sprintf(&c[0], "%i", i);
itoa(i, c, 10);
printf("string = %s\n", c);
float f;
char s[40] = "567";
i = atoi(s);
f = atof(s);
char _s[21];
_s[20] = '\0';
for (int i = 0; i < 20; ++i) {
_s[i] = rand() % ('z' - 'a' + 1) + 'a';
}
void* p;
*p = 0;
int* ptr;
ptr = &i;
if (ptr != NULL) {
*ptr = 4;
}
int* ai = NULL;
ai = (int*)malloc(sizeof(int) * 2);
*ai = 0;
ai = (int*)realloc(ai, sizeof(int) * 5);
free(ai);
ai = (int*)malloc(sizeof(int) * 3);
free(ai);
ai = NULL;
int l = 4;
for (int i = 0; i < l; ++i) {
printf("address = %d\n", &*(arr + i));
printf("address = %d\n", arr + i);
}
void* o = NULL;
o = malloc(8);
if (o != NULL) {
*(int*)o = 8;
*(double*)o = 0.23;
free_and_null(&o);
printf("%d\n", *(int*)o);
}
free(o);
o = NULL;
printf("%s\n", _s);
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
struct Test {
unsigned int age;
unsigned char name[10];
};
void add_test(struct Test *, unsigned char *, char *, unsigned char *);
void print_struct_data(void *);
int main(int argc, char const *argv[]) {
unsigned int a = 0xFE340056;
printf("value a is: \t\t0x%08X\n", a);
unsigned int *p_a = &a;
printf("value p_a is: \t\t0x%08d\n", (unsigned int)p_a);
printf("value *p_a is: \t\t0x%08d\n", *p_a);
*p_a = 0xEF222222;
unsigned char uch[10] = { 0x33, 0x64, 0x65, 0x88, 0x32 };
printf("value uch is: \t\t0x%08d\n", (unsigned int)uch);
unsigned int **p_p_a;
p_a = &a;
p_p_a = &p_a;
printf("p_p_a: \t\t%p\n", p_p_a);
printf("p_a: \t\t%p\n", p_a);
printf("*p_a: \t\t%d\n", *p_a);
printf("**p_p_a: \t\t%d\n", **p_p_a);
**p_p_a = 0xB2182490;
printf("%d\n", a);
struct Test test;
test.age = 20;
strcpy(test.name, "test");
print_struct_data((void *)&test);
unsigned char counter = 0, age = 20;
add_test(&test, &counter, "test for name", &age);
printf("counter value: %d\n", counter);
return 0;
}
void add_test(struct Test *test, unsigned char *test_counter, char *ch, unsigned char *age) {
strcpy(test->name, ch);
test->age = *age;
(*test_counter)++;
}
void print_struct_data(void *p_str) {
printf("struct age: \t%d\nstruct name: \t%s\n", (*(struct Test *)p_str).age, (*(struct Test *)p_str).name);
}
<file_sep>#ifndef VA_PARAMS_H
#define VA_PARAMS_H
typedef enum { UNIT = 0, DATA, END } Type;
typedef struct { int health; int armor; } Unit;
typedef struct { int value_a; int value_b; int value_c; } Data;
void f_a(int, ...);
void f_b(char *, ...);
void f_c(Type, ...);
void example_a(void);
void example_a(void);
void example_a(void);
#endif
<file_sep>#include "different.h"
void strcopy_a(char *s1, char *s2) {
short int i = 0;
while((s1[i] = s2[i]) != '\0')
i++;
}
void strcopy_b(char *s1, char *s2) {
int i = 0;
while((s1[i++] = s2[i]) != '\0');
}
void strcopy_c(char *s1, char *s2) {
while(*s1++ = *s2++);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
void foo_a(void);
void foo_b(void);
void foo_c(void);
unsigned int test_a(unsigned int, int);
unsigned int test_b(unsigned int, int);
typedef int *pint;
typedef void (*pfn_v)(void);
typedef unsigned int (*pfn_s_i)(unsigned int, int);
int main(int argc, char const *argv[]) {
pint pa, pb, pc;
pfn_v pf_arr[3];
pfn_s_i pf_s_i_arr[2];
pf_s_i_arr[0] = &test_a;
pf_s_i_arr[1] = &test_b;
char i = sizeof(pf_s_i_arr) / sizeof(pfn_s_i);
do printf("%d\n", (*pf_s_i_arr[i])(i, argc));
while(i-- > 0);
pf_arr[0] = &foo_a;
pf_arr[1] = &foo_b;
pf_arr[2] = &foo_c;
char g = sizeof(pf_arr) / sizeof(pfn_v);
do
printf("pointer to an each element in arr: %p\n", (*pf_arr)++);
while(g-- > 0);
printf("%p-%p-%p\n", &pa, &pb, &pc);
pfn_v a, b, c;
a = &foo_a, b = &foo_b, c = &foo_c;
(*a)(), (*b)(), (*c)();
void (*ps)() = &foo_a;
ps();
void (*pf)();
pf = &foo_a;
(*pf)();
pf = &foo_b;
(*pf)();
pf = &foo_c;
(*pf)();
return 0;
}
void foo_a(void) {
printf("%s\n", __FUNCTION__);
}
void foo_b(void) {
printf("%s\n", __FUNCTION__);
}
void foo_c(void) {
printf("%s\n", __FUNCTION__);
}
unsigned int test_a(unsigned int a, int argc) {
return a + argc;
}
unsigned int test_b(unsigned int b, int argc) {
return b + argc;
}
<file_sep>CC=gcc
LN=ld
CFLAGS=-Wall -std=c99
HEADERS=http.h net.h io.h hashtab.h tree.h type.h
SOURCES=http.c net.c io.c hashtab.c tree.c type.c
OBJECTS=http.o net.o io.o hashtab.o tree.o type.o
.PHONY: default
default: build link
build: $(HEADERS) $(SOURCES)
$(CC) $(CFLAGS) -c $(SOURCES)
link: $(OBJECTS)
$(LN) -r $(OBJECTS) -o extclib.o
clean:
rm -f *.o *.i *.s
<file_sep>#include <stdio.h>
#include <string.h>
void print_str(const char *);
void print_chars(const char *);
void print_uint32_arr(const unsigned int *, unsigned int len);
void sum_f(float, float, float *);
void div_f(float, float, float *);
struct Student {
char name[20];
unsigned char age;
unsigned char course;
};
struct Student_list {
struct Student *st;
void (*add_course)(struct Student *);
void (*add_age)(struct Student *);
void (*modify_name)(struct Student *, char *);
void (*delete_pos)(struct Student *, unsigned int, unsigned int *);
};
void add_student(struct Student *, unsigned int *, char *, unsigned char, unsigned char);
void add_course(struct Student *);
void add_age(struct Student *);
void modify_name(struct Student*, char *);
void delete_pos(struct Student *, unsigned int, unsigned int *);
void print_student(struct Student *);
int main(int argc, char const *argv[]) {
unsigned int *print_str_addr;
print_str_addr = (unsigned int *)(&print_str);
printf("%p\n", (unsigned int *)(&print_str_addr));
void (*print_str_new)(const char *c_str);
print_str_new = (void *)print_str_addr;
print_str_new("hello world");
void (*print_str_next)(const char *);
print_str_next = (void *)(&print_str);
(*print_str_next)("hello world");
void (*print_str_next_test)(const char *) = (void *)(&print_str);
void (*fns_arr[4])(float, float, float *) = { sum_f, div_f };
float i = 2, a = 2., b = 3., res = 0.;
do {
(*fns_arr)(a, b, &res);
fns_arr++;
} while((int)i-- > 0);
struct Student st[20];
unsigned int st_count = 0, g = 20;
do {
add_student(st + st_count, &st_count, "name", 2 + g, 18 + g);
if (g == 1) break;
} while(g--> 0);
for (int i = 0; i < st_count; i++) print_student(st + i);
printf("student counter: %d\n\n", st_count);
struct Student_list st_list = { st, add_course, add_age, modify_name, delete_pos };
st_list.add_course(st + 5);
st_list.add_age(st + 1);
st_list.modify_name(st + 2, "hello world");
for (int i = 0; i < st_count; i++) print_student(st + i);
st_list.delete_pos(st, 4, &st_count);
for (int i = 0; i < st_count; i++) print_student(st + i);
return 0;
}
void print_str_next(const char *c_str) {}
void print_str_new(const char *c_str) {}
void print_str_next_test(const char *c_str) {}
void print_str(const char *c_str) {
printf("%s\n", c_str);
}
void print_chars(const char *a) {}
void print_uint32_arr(const unsigned int *a, unsigned int len) {}
void sum_f(float a_f, float b_f, float *sum_f) {
*sum_f = a_f + b_f;
}
void div_f(float a_f, float b_f, float *div_f) {
*div_f = a_f / b_f;
}
void add_student(struct Student *res_st, unsigned int *student_counter, char *ch, unsigned char cr, unsigned char age) {
strcpy(res_st->name, ch);
res_st->course = cr;
res_st->age = age;
(*student_counter)++;
}
void delete_pos(struct Student *st_list, unsigned int pos, unsigned int *student_counter) {
for (unsigned int i = pos; i < *student_counter; i++) {
strcpy(st_list[i].name, st_list[i + 1].name);
st_list[i].age = st_list[i].age;
st_list[i].course = st_list[i + 1].course;
}
(*student_counter)--;
}
void add_course(struct Student *st) {
st->course++;
}
void add_age(struct Student *st) {
st->age++;
}
void modify_name(struct Student *st, char *ch) {
strcpy(st->name, ch);
}
void print_student(struct Student *st) {
printf("name: %s, age: %d, course: %d\n", st->name, st->age, st->course);
}
<file_sep>#ifndef SORT_TOOL_H
#define SORT_TOOL_H
#include <stdbool.h>
#define TEST_1
#ifdef TEST_0
typedef struct { int data; } Test;
typedef bool (*pf_compare)(struct Test, struct Test);
void ia_bubble_sort(struct Test *, struct Test *, pf_compare);
#ifdef TEST_1
typedef /*int*/ bool (*pf_compare)(unsigned, unsigned); // pointer to compare function
void ia_bubble_sort(int *, unsigned, pf_compare);
#elif defined(TEST_2)
typedef enum { ASCENDING = 0; DESCENDING; END_OF_COMPARISON; } Compare;
void ia_bubble_sort(int *, unsigned, Compare);
#elif defined(TEST_3)
void ia_bubble_sort_ascending(int *, unsigned);
void ia_bubble_sort_descending(int *, unsigned);
#elif defined(BOOL_1)
typedef int bool;
#define TRUE 1
#define FALSE !TRUE
#elif defined(BOOL_2)
typedef enum { FALSE = 0, TRUE } bool;
#elif defined(BOOL_3)
typedef enum { false = 1 == 0, true = !false } bool;
#elif defined(BOOL_4)
#include <stdbool.h>
#endif
void ia_print(int *, unsigned);
<file_sep>#include <stdio.h>
void test(int *a, int *b) {
*a = 100;
*b = 200;
}
int main(void) {
int a = 10;
int b = 20;
test(&a, &b);
printf("%d - %d\n", a, b);
short arr[3];
printf("%p\n", &arr[0]);
printf("%p\n", &arr[1]);
printf("%p\n\n", &arr[2]);
int number = 0x10203040;
char *pointer = (char *)&number;
pointer = pointer + 3;
*pointer = 0x21;
printf("%#x\n\n", number);
short num = 102;
char *point = (char *)#
int i = 4;
do printf("%p\n", point++);
while(i-- > 0);
}
<file_sep>#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include "extclib/net.h"
#define BUFFER 256
int main(void) {
int listener = listen_net("0.0.0.0:8080");
if (listener < 0) {
fprintf(stderr, "%d\n", listener);
return 1;
}
fprintf(stdout, "%s\n", "server is listening");
char buffer[BUFFER];
while(1) {
int con = accept_net(listener);
if (con < 0) {
fprintf(stderr, "%s\n", "error: accept");
return 3;
}
while(1) {
int length = recv_net(con, buffer, BUFFER);
if (length < 0) {
break;
}
for (char* p = buffer; *p != '\0'; ++p) {
*p = toupper(*p);
}
send_net(con, buffer, BUFFER);
}
close_net(con);
}
close_net(listener);
return 0;
}
<file_sep>#include <stdio.h>
static void my_counter(void);
static void print_result(char str[]);
int main(int argc, char const *argv[]) {
auto char ch = 10;
auto float const f_a = 8.;
auto float const f_b = 3.;
if (f_a > f_b) {
static unsigned char const n = 5;
printf("char value: %d\n", n);
} else {
auto unsigned char const n = 6;
printf("char value in another block: %d\n", n);
}
for (char i = 0; i < 3; i++) {
for (char j = 0; j < 4; j++) {
static int n = 0;
auto int m = 0;
printf("value n: %d, m: %d\n", n++, m++);
}
}
static char i = 0;
do {
register char j = 0;
do {
printf("value i: %d, j: %d\n", i, j);
} while(j++ < 4);
} while(i++ < 3);
for (auto char i = 0; i < 10; i++)
my_counter();
return 0;
}
static void my_counter() {
auto char i = 0;
static char g = 0;
printf("i = %d, g = %d\n", i++, g++);
}
static void print_result(char str[]) {
printf("%s %.5f\n", str, res);
}
<file_sep>#include <stdio.h>
#include <stdint.h>
#include "extclib/net.h"
#include "extclib/io.h"
#define BUFFER_SIZE 256
extern void inputs_io(char* buffer, size_t size);
int main(void) {
int con = connect_net("127.0.0.1:8080");
if (con < 0) {
fprintf(stderr, "%d\n", con);
return 1;
}
char buffer[BUFFER_SIZE];
inputs_io(buffer, BUFFER_SIZE);
send_net(con, buffer, BUFFER_SIZE);
recv_net(con, buffer, BUFFER_SIZE);
fprintf(stdout, "%s\n", buffer);
close_net(con);
return 0;
}
<file_sep>#include <string.h>
#include <stdio.h>
#include "routes/routes.h"
int main(void) {
HTTP* serve = new_http("127.0.0.1:7545");
handle_http(serve, "/", index_page);
handle_http(serve, "/about", about_page);
listen_http(serve);
free_http(serve);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdarg.h>
int main(int argc, char const *argv[]) {
example_a();
example_b();
example_c();
return 0;
}
<file_sep>#ifndef EXTCLIB_NET_H_
#define EXTCLIB_NET_H_
#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
extern int listen_net(char* address);
extern int accept_net(int listener);
extern int connect_net(char* address);
extern int close_net(int con);
extern int send_net(int con, char* buffer, size_t size);
extern int recv_net(int con, char* buffer, size_t size);
#endif /* EXTCLIB_NET_H_ */
<file_sep>#ifndef _TRANSACTION_H
#define _TRANSACTION_H
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <unistd.h>
using namespace std;
struct Line;
void change(vector<Line>&, mutex&);
void rollback(vector<Line>&, mutex&);
void view(vector<Line>&, mutex&);
void start(void);
#endif /* _TRANSACTION_H */
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "tree.h"
#include "type.h"
typedef struct tree_node {
struct {
value_t key;
value_t value;
} data;
_Bool exist;
struct tree_node *left;
struct tree_node *right;
struct tree_node *parent;
} tree_node;
typedef struct Tree {
struct {
vtype_t key;
vtype_t value;
} type;
size_t size;
struct tree_node *node;
} Tree;
static tree_node *_new_node(vtype_t tkey, vtype_t tvalue, void *key, void *value);
static void _set_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue, void *key, void *value);
static void _set_key(tree_node *node, vtype_t tkey, void *key);
static void _set_value(tree_node *node, vtype_t tvalue, void *value);
static void _free_tree(Tree *tree, tree_node *node);
static void _free_key_tree(vtype_t type, tree_node *node);
static void _free_value_tree(vtype_t type, tree_node *node);
static void _print_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue);
static void _print_branches_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue);
static void _print_node_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue);
static tree_node *_get_tree(tree_node *node, vtype_t tkey, void *key);
static int8_t _cmp_tkey_tree(tree_node *node, vtype_t tkey, void *key);
static int8_t _cmp_int32(int32_t x, int32_t y);
static tree_node *_del1_tree(Tree *tree, vtype_t tkey, void *key);
static void _del2_tree(Tree *tree, tree_node *node);
static void _del3_tree(Tree *tree, tree_node *node);
static _Bool _eq_tree(vtype_t tkey, vtype_t tvalue, tree_node *x, tree_node *y);
extern Tree *new_tree(vtype_t key, vtype_t value) {
switch(key) {
case DECIMAL_TYPE:
case STRING_TYPE:
break;
default:
fprintf(stderr, "%s\n", "key type not supported");
return NULL;
}
switch(value) {
case DECIMAL_TYPE:
case REAL_TYPE:
case STRING_TYPE:
break;
default:
fprintf(stderr, "%s\n", "value type not supported");
return NULL;
}
Tree *tree = (Tree*)malloc(sizeof(Tree));
tree->type.key = key;
tree->type.value = value;
tree->node = NULL;
tree->size = 0;
return tree;
}
extern void free_tree(Tree *tree) {
_free_tree(tree, tree->node);
free(tree);
}
extern _Bool in_tree(Tree *tree, void *key) {
return _get_tree(tree->node, tree->type.key, key) != NULL;
}
extern value_t get_tree(Tree *tree, void *key) {
tree_node *node = _get_tree(tree->node, tree->type.key, key);
if (node == NULL) {
fprintf(stderr, "%s\n", "value undefined");
value_t none = {
.decimal = 0,
};
return none;
}
return node->data.value;
}
extern int8_t set_tree(Tree *tree, void *key, void *value) {
if (tree->node == NULL) {
tree->node = _new_node(tree->type.key, tree->type.value, key, value);
tree->size += 1;
return 0;
}
_set_tree(tree, tree->node, tree->type.key, tree->type.value, key, value);
return 0;
}
extern void del_tree(Tree *tree, void *key) {
tree_node *node = _del1_tree(tree, tree->type.key, key);
if (node == NULL) {
return;
}
if (node->left != NULL && node->right != NULL) {
_del3_tree(tree, node);
return;
}
_del2_tree(tree, node);
return;
}
extern _Bool eq_tree(Tree *x, Tree *y) {
if (x->type.key != y->type.key) {
return 0;
}
if (x->type.value != y->type.value) {
return 0;
}
if (x->size != y->size) {
return 0;
}
return _eq_tree(x->type.key, x->type.value, x->node, y->node);
}
static _Bool _eq_tree(vtype_t tkey, vtype_t tvalue, tree_node *x, tree_node *y) {
if (x == NULL && y == NULL) {
return 1;
}
if (x != NULL && y != NULL) {
_Bool fkey = 0;
_Bool fval = 0;
switch(tkey) {
case DECIMAL_TYPE:
fkey = x->data.key.decimal == y->data.key.decimal;
break;
case STRING_TYPE:
fkey = strcmp((char*)x->data.key.string, (char*)y->data.key.string) == 0;
break;
default: ;
}
switch(tvalue) {
case DECIMAL_TYPE:
fval = x->data.value.decimal == y->data.value.decimal;
break;
case REAL_TYPE:
fval = x->data.value.real == y->data.value.real;
break;
case STRING_TYPE:
fval = strcmp((char*)x->data.value.string, (char*)y->data.value.string) == 0;
break;
default: ;
}
return fkey && fval && _eq_tree(tkey, tvalue, x->left, y->left) && _eq_tree(tkey, tvalue, x->right, y->right);
}
return 0;
}
extern size_t size_tree(Tree *tree) {
return tree->size;
}
extern size_t sizeof_tree(void) {
return sizeof(Tree);
}
extern void print_tree(Tree *tree) {
printf("#T[ ");
_print_tree(tree, tree->node, tree->type.key, tree->type.value);
putchar(']');
}
extern void println_tree(Tree *tree) {
print_tree(tree);
putchar('\n');
}
extern void print_tree_branches(Tree *tree) {
_print_branches_tree(tree, tree->node, tree->type.key, tree->type.value);
}
extern void println_tree_branches(Tree *tree) {
_print_branches_tree(tree, tree->node, tree->type.key, tree->type.value);
putchar('\n');
}
static tree_node *_new_node(vtype_t tkey, vtype_t tvalue, void *key, void *value) {
tree_node *node = (tree_node*)malloc(sizeof(tree_node));
node->exist = 0;
_set_key(node, tkey, key);
_set_value(node, tvalue, value);
node->left = NULL;
node->right = NULL;
node->parent = NULL;
return node;
}
static void _set_key(tree_node *node, vtype_t tkey, void *key) {
if (node->exist) {
_free_key_tree(tkey, node);
}
switch(tkey) {
case DECIMAL_TYPE:
node->data.key.decimal = (int32_t)(intptr_t)key;
break;
case STRING_TYPE: {
size_t size = strlen((char*)key);
node->data.key.string = (char*)malloc(sizeof(char)*size+1);
strcpy(node->data.key.string, (char*)key);
}
break;
default: ;
}
}
static void _set_value(tree_node *node, vtype_t tvalue, void *value) {
if (node->exist) {
_free_value_tree(tvalue, node);
}
switch(tvalue) {
case DECIMAL_TYPE:
node->data.value.decimal = (int32_t)(intptr_t)value;
break;
case REAL_TYPE:
node->data.value.real = *(double*)value;
free((double*)value);
break;
case STRING_TYPE: {
size_t size = strlen((char*)value);
node->data.value.string = (char*)malloc(sizeof(char)*size+1);
strcpy(node->data.value.string, (char*)value);
}
break;
default: ;
}
node->exist = 1;
}
static void _set_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue, void *key, void *value) {
int8_t cond = _cmp_tkey_tree(node, tkey, key);
if (cond > 0) {
if (node->right == NULL) {
node->right = _new_node(tkey, tvalue, key, value);
node->right->parent = node;
tree->size += 1;
} else {
_set_tree(tree, node->right, tkey, tvalue, key, value);
}
} else if (cond < 0) {
if (node->left == NULL) {
node->left = _new_node(tkey, tvalue, key, value);
node->left->parent = node;
tree->size += 1;
} else {
_set_tree(tree, node->left, tkey, tvalue, key, value);
}
} else {
_set_key(node, tkey, key);
_set_value(node, tvalue, value);
}
}
static tree_node *_get_tree(tree_node *node, vtype_t tkey, void *key) {
if (node == NULL) {
return NULL;
}
int8_t cond = _cmp_tkey_tree(node, tkey, key);
if (cond > 0) {
return _get_tree(node->right, tkey, key);
} else if (cond < 0) {
return _get_tree(node->left, tkey, key);
}
return node;
}
static int8_t _cmp_tkey_tree(tree_node *node, vtype_t tkey, void *key) {
int8_t cond = 0;
switch(tkey) {
case DECIMAL_TYPE:
cond = _cmp_int32((int32_t)(intptr_t)key, node->data.key.decimal);
break;
case STRING_TYPE:
cond = strcmp((char*)key, node->data.key.string);
break;
default: ;
}
return cond;
}
static int8_t _cmp_int32(int32_t x, int32_t y) {
if (x > y) {
return 1;
} else if (x < y) {
return -1;
}
return 0;
}
static tree_node *_del1_tree(Tree *tree, vtype_t tkey, void *key) {
tree_node *node = tree->node;
node = _get_tree(node, tkey, key);
if (node == NULL) {
return NULL;
}
if (node->left != NULL || node->right != NULL) {
return node;
}
tree_node *parent = node->parent;
if (parent == NULL) {
tree->node = NULL;
} else if (parent->left == node) {
parent->left = NULL;
} else {
parent->right = NULL;
}
tree->size -= 1;
_free_key_tree(tree->type.key, node);
_free_value_tree(tree->type.value, node);
free(node);
return NULL;
}
static void _del2_tree(Tree *tree, tree_node *node) {
tree_node *parent = node->parent;
tree_node *temp;
if (node->right != NULL) {
temp = node->right;
} else {
temp = node->left;
}
if (parent == NULL) {
tree->node = temp;
} else if (parent->left == node) {
parent->left = temp;
} else {
parent->right = temp;
}
tree->size -= 1;
temp->parent = parent;
_free_key_tree(tree->type.key, node);
_free_value_tree(tree->type.value, node);
free(node);
}
static void _del3_tree(Tree *tree, tree_node *node) {
tree_node *ptr = node->right;
while (ptr->left != NULL) {
ptr = ptr->left;
}
node->data.key = ptr->data.key;
node->data.value = ptr->data.value;
tree_node *parent = ptr->parent;
if (parent->left == ptr) {
parent->left = NULL;
} else {
parent->right = NULL;
}
tree->size -= 1;
// _free_key_tree(tree->type.key, node);
// _free_value_tree(tree->type.value, ptr);
free(ptr);
}
static void _print_node_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue) {
putchar('{');
switch(tkey) {
case DECIMAL_TYPE:
printf("%d", node->data.key.decimal);
break;
case STRING_TYPE:
printf("'%s'", node->data.key.string);
break;
default: ;
}
printf(" => ");
switch(tvalue) {
case DECIMAL_TYPE:
printf("%d", node->data.value.decimal);
break;
case REAL_TYPE:
printf("%lf", node->data.value.real);
break;
case STRING_TYPE:
printf("'%s'", node->data.value.string);
break;
default: ;
}
printf("} ");
}
static void _print_branches_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue) {
if (node == NULL) {
printf("null");
return;
}
putchar('(');
_print_branches_tree(tree, node->left, tkey, tvalue);
putchar(' ');
_print_node_tree(tree, node, tkey, tvalue);
_print_branches_tree(tree, node->right, tkey, tvalue);
putchar(')');
}
static void _print_tree(Tree *tree, tree_node *node, vtype_t tkey, vtype_t tvalue) {
if (node == NULL) {
return;
}
_print_tree(tree, node->left, tkey, tvalue);
_print_node_tree(tree, node, tkey, tvalue);
_print_tree(tree, node->right, tkey, tvalue);
}
static void _free_tree(Tree *tree, tree_node *node) {
if (node == NULL) {
return;
}
_free_tree(tree, node->left);
_free_tree(tree, node->right);
_free_key_tree(tree->type.key, node);
_free_value_tree(tree->type.value, node);
free(node);
}
static void _free_key_tree(vtype_t type, tree_node *node) {
switch(type) {
case STRING_TYPE:
free(node->data.key.string);
break;
default: ;
}
}
static void _free_value_tree(vtype_t type, tree_node *node) {
switch(type) {
case STRING_TYPE:
free(node->data.value.string);
break;
default: ;
}
}
<file_sep>#include <stdio.h>
// this value 'MAX_STRING_LENGTH' will be thrown away because of no usage by preprocessor
#define MAX_STRING_LENGTH 100
#define SIZE_OF_MEMORY
#define IS_64_BYTES_PER_TAKT
#define OS_WINDOWS
#define MAX(a, b) a > b
#define MIN(a, b) a < b
#define STR(s1, s2) s1 < s2
#define COMBINE(a, b) MIN(a, b) == MAX(a,b)
int sum(int, int);
int main(void) {
#ifdef defined(OS_WINDOWS)
printf("%s\n", "it will be printed, but value to OS_WINDOWS was not assigned");
//win_print()
#else //lin_print()
#ifdef IS_64_BYTES_PER_TAKT
// loadin config fot this operation system
#else //...
#ifdef SIZE_OF_MEMORY == 32
//...
#else //...
#endif
bool flag = false;
if (flag = true)
printf("%s\n", "it will be executed");
double val1 = 10.2f;
double test1 = 9139.3131;
float test2 = test1;
float val2 = val1;
{
const char value = 10;
printf("%s\n", "internal scope");
}
printf("result: %d\n", sum(10, 20));
const char max = MAX(10, 20);
const char min = MIN(10, 20);
const char str = STR("hello", "world");
const char combine = COMBINE(max, min);
int arr[10] = { [0 ... 4] = 5, [6 ... 9] = 7 };
int i = 0;
for (; i < 10; ++i)
printf("value: %d, index -> %d\n", arr[i], i);
char ch = 25;
char ich = 6;
printf("we want to understand 'inch' as char: %c\n", ich);
do {
printf("value in char: %i\n", ch);
} while(ch -= 5);
printf("char: %d\n", ch);
printf("%c\n", 7);
int i = 0;
do printf("ascii value: #%d -> %c\n", i, i);
while(i++ < 256);
printf("line: %d\nfunction: %s\nfile: %s\n", __LINE__, __FUNCTION__, __FILE__);
char arr[3] = { 1, 2, 3 };
arr[3] = 4;
printf("arr[3] = %d\n\n", arr[3]);
int array[10];
char i = 10;
do printf("array[%d] = %d\n", i, array[i]);
while(i-- > 0);
char *str = "he\0llo";
char str[] = "he\0llo"; (also is used)
printf("string will be trimmed to 'he': %s\n", str);
char *string = "hello world";
string[2] = 0; (programm is crash)
while(*string != 0) {
if (*string == ' ') *string = 0;
if (*string == 0) break;
printf("%c", *string++);
}
int j = 0;
while(string[j] != 0)
printf("%c", string[j++]);
printf("\n");
char s[] = "hello!\0";
s[6] = 'e';
int k = 0;
while(s[k] != 0)
printf("%c", s[k]++);
printf("\n\n");
char st[] = "hello!\0";
st[6] = 'e';
printf("%s\n", st);
int a = 10;
int b = 20;
test(&a, &b);
printf("%d - %d\n", a, b);
short arr[3];
printf("%p\n", &arr[0]);
printf("%p\n", &arr[1]);
printf("%p\n\n", &arr[2]);
int number = 0x10203040;
char *pointer = (char *)&number;
pointer = pointer + 3;
*pointer = 0x21;
printf("%#x\n\n", number);
short num = 102;
char *point = (char *)#
int i = 4;
do printf("%p\n", point++);
while(i-- > 0);
}
void test(int *a, int *b) {
*a = 100;
*b = 200;
}
int sum(int a, int b) {
return a + b;
}
<file_sep>#include <stdio.h>
#include <stdbool.h>
// this value 'MAX_STRING_LENGTH' will be thrown away because of no usage by preprocessor
#define MAX_STRING_LENGTH 100
#define SIZE_OF_MEMORY
#define IS_64_BYTES_PER_TAKT
#define OS_WINDOWS
int sum(int, int);
int main(void) {
#ifdef defined(OS_WINDOWS)
printf("%s\n", "it will be printed, but value to OS_WINDOWS was not assigned");
//win_print()
#else //lin_print()
#ifdef IS_64_BYTES_PER_TAKT
// loadin config fot this operation system
#else //...
#ifdef SIZE_OF_MEMORY == 32
//...
#else //...
#endif
bool flag = false;
if (flag = true)
printf("%s\n", "it will be executed");
double val1 = 10.2f;
double test1 = 9139.3131;
float test2 = test1;
float val2 = val1;
{
const char value = 10;
printf("%s\n", "internal scope");
}
printf("result: %d\n", sum(10, 20));
}
int sum(int a, int b) {
return a + b;
}
<file_sep>#include <stdio.h>
#include <string.h>
int main(void) {
const void *a;
const void *b;
int x = *(int *)a;
fprintf(stdout, "%d\n", x);
for (short i = 0; i < 50; i += 1)
fprintf(stdout, "error: %d, value: %s\n", i, strerror(i));
FILE *no_pointer = fopen("no_file.txt", "r");
if (no_pointer != NULL) fprintf(stdout, "%s\n", "success");
else perror("error while opening file");
const short size = 100;
char arr[1000];
FILE *original_pointer = fopen("text.txt", "r");
FILE *copy_pointer = fopen("copy.txt", "w");
if (copy_pointer != NULL && original_pointer != NULL) {
const int lettersR = fread(arr, 1, size, original_pointer);
const int lettersW = fwrite(arr, 1, lettersR, copy_pointer);
fprintf(stdout, "file: 'text.txt was read total chars: '%d\n", lettersR);
fprintf(stdout, "file: 'copy.txt was written total chars: '%d\n", lettersW);
fclose(original_pointer);
fclose(copy_pointer);
} else {
fprintf(stdout, "file was opened with failure: %s\n", "text.txt");
fprintf(stdout, "file was opened with failure: %s\n", "copy.txt");
return 1;
}
const int size = 100;
char str[size];
char name[100] = { "from lamer to programmer" };
char value[100];
FILE *file_pointer;
file_pointer = fopen("text.txt", "r+a");
// r, w, a, r+, w+, a+, rb, wb
if (file_pointer != NULL) {
fprintf(stdout, "opened file for writing\n");
fprintf(stdout, "reading data from file\n\n");
while (fgets(str, size, file_pointer))
fprintf(stdout, "read file: %s", str);
fprintf(stdout, "\nreading was stopped\n");
fputs(name, file_pointer);
fprintf(stdout, "\n");
do {
fprintf(stdout, "value is: %s\n", value);
}
while(fgets(value, 100, file_pointer));
fprintf(stdout, "file will be closed: %s\n", "file.txt");
fclose(file_pointer);
}
else {
fprintf(stderr, "failed to open file or create file\n");
return 1;
}
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "sort_tool.h"
#define ARRAY_SIZE 30
typedef enum { E_SO_ASCENDING = 0, E_SO_DESCENDING, E_SO_CUSTOM, E_SO_END } SortOrder;
bool pred_ascending(unsigned, unsigned);
bool pred_descending(unsigned, unsigned);
bool pred_custom(unsigned, unsigned);
bool pred_ascending_s(struct Test, struct Test);
bool pred_descending(struct Test, struct Test);
bool pred_custom(struct Test, struct Test);
int main(int argc, char const *argv[]) {
int iarray[ARRAY_SIZE] = { 0 };
for (int i = 0; i < ARRAY_SIZE; ++i)
iarray[i] = rand() % 1000;
ia_print(&iarray[0], ARRAY_SIZE);
ia_bubble_sort(&iarray[0], ARRAY_SIZE, &pred_ascending);
printf("\n\n");
ia_print(&iarray[0], ARRAY_SIZE);
ia_bubble_sort(&iarray[0], ARRAY_SIZE, &pred_descending);
printf("\n\n");
ia_print(&iarray[0], ARRAY_SIZE);
pf_compare pfa[E_SO_END];
pfa[E_SO_ASCENDING] = &pred_ascending;
pfa[E_SO_DESCENDING] = &pred_descending;
pfa[E_SO_CUSTOM] = &pred_custom;
for (char i = 0; i < E_SO_END, i++) {
ia_bubble_sort(&iarray[0], ARRAY_SIZE, pfa[i]);
printf("\n");
ia_print(&iarray[0], ARRAY_SIZE);
}
return 0;
}
void ia_print_s(struct Test *apArray, unsigned aSize) {
for (unsigned i = 0; i < aSize; i++)
printf("%d", apArray[i].data);
printf("%\n");
}
bool pred_ascending(unsigned int a, unsigned int b) {
return a >= b;
}
bool pred_descending(unsigned int a, unsigned int b) {
return a < b;
}
bool pred_custom(unsigned int a, unsigned int b) {
return a + b > 400;
}
<file_sep>#include <stdio.h>
#define BUFFER_SIZE 5
typedef struct {
int read_index;
int write_index;
int is_empty;
int is_full;
int data[BUFFER_SIZE];
} CircularBuffer;
void init(CircularBuffer *);
int put(CircularBuffer *, int);
int get(CircularBuffer *);
void clear(CircularBuffer *);
int is_empty(CircularBuffer *);
int is_full(CircularBuffer *);
/*
in = 0
out = 0
[] [] [] []
put(1)
[1] [] [] []
in++
put(2)
[1] [2] [] []
in++
put(3)
[1] [2] [3] []
in++
put(4)
[1] [2] [3] [4]
in++
put(5)
[1] [2] [3] [4]
get() = 1
out++
[] [2] [3] [4]
*/
void init(CircularBuffer *p_buffer) {
p_buffer->read_index = 0;
p_buffer->write_index = 0;
p_buffer->is_empty = 1;
p_buffer->is_full = 0;
}
int put(CircularBuffer *p_buffer, int const value) {
if (p_buffer->is_full) return -1;
if (p_buffer->write_index >= BUFFER_SIZE) p_buffer->write_index = p_buffer->read_index;
if (p_buffer->is_empty) {
p_buffer->is_empty = 0;
p_buffer->data[p_buffer->write_index++] = value;
if (p_buffer->write_index == p_buffer->read_index) p_buffer->is_full = 1;
return 1;
}
p_buffer->data[p_buffer->write_index++] = value;
if (p_buffer->write_index == p_buffer->read_index) p_buffer->is_full = 1;
return 1;
}
int get(CircularBuffer *p_buffer) {
if (p_buffer->is_empty) return -1;
p_buffer->is_full = 0;
if (p_buffer->read_index >= BUFFER_SIZE) p_buffer->read_index = 0;
int const res = p_buffer->data[p_buffer->read_index++];
if (p_buffer->read_index == p_buffer->write_index) p_buffer->is_empty = 1;
return res;
}
void clear(CircularBuffer *p_buffer) {
p_buffer->is_empty = 1;
p_buffer->is_full = 0;
p_buffer->write_index = 0;
p_buffer->read_index = 0;
}
int is_empty(CircularBuffer *p_buffer) {
return p_buffer->is_empty;
}
int is_full(CircularBuffer *p_buffer) {
return p_buffer->is_full;
}
int main(int argc, char const *argv[]) {
CircularBuffer buffer;
init(&buffer);
char i = 5, g = 4;
do {
put(&buffer, i);
get(&buffer);
if (i == 5) clear(&buffer);
} while(i-- > 0);
i = 3;
do {
put(&buffer, i);
get(&buffer);
} while(i-- > 0);
i = 6;
do get(&buffer); while(i-- > 0);
do put(&buffer, i + g); while(i-- > 0);
i = 6;
do get(&buffer); while(i-- > 0);
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
typedef union { char ch; short sh; int i; long l; } Example_a;
/* ch: #, sh: ##, i: ####, l: ######## */
typedef union { char ch; short sh; int i; char buffer[9]; } Example_b;
/* ch: #, sh: ##, i: ####, buffer: ######## #??????? */
typedef union { char buffer[9]; char ch; short sh; int i; } Example_c;
/* buffer: ######## #??????? ,ch: #, sh: ##, i: #### */
typedef enum { KEY_PRESSED = 0, MOUSE_PRESSED } InputType;
typedef struct {
InputType input_type;
union {
int key_code;
struct { int x; int y; int key_code; } mouse_info;
} union;
} InputEvent_a;
typedef struct {
InputType input_type;
union {
int key_code;
struct { int x; int y; int key_mouse_codel; };
};
} InputEvent_b;
typedef enum { CHAR = 0, INTEGER, FLOAT, DOUBLE } Type;
typedef struct {
Type type;
union { char ch; int i; float f; double d; };
} Variant_a;
int main(int argc, char const *argv[]) {
printf("size of union example_a: %ld\n", sizeof(Example_a));
printf("size of union example_b: %ld\n", sizeof(Example_b));
printf("size of union example_c: %ld\n", sizeof(Example_c));
{
InputEvent_a event;
event.input_type = MOUSE_PRESSED;
event.union.mouse_info.x = 10;
event.union.mouse_info.y = 10;
event.union.key_code = 1;
event.input_type = KEY_PRESSED;
event.key_code = 27;
}
{
InputEvent_b event;
event.input_type = MOUSE_PRESSED;
event.x = 10;
event.y = 10;
event.key_mouse_codel = 1;
event.input_type = KEY_PRESSED;
event.key_code = 27;
}
Variant_a var;
var.type = CHAR;
var.ch = 'A';
if (var.type == CHAR)
if (var.ch == 'A') {
var.type = FLOAT;
var.f = 1.234f;
}
var.type = DOUBLE;
var.d = 1.412;
var.type = INTEGER;
var.i = 1.1;
return 0;
}
<file_sep>#ifndef TEST_H
#define TEST_H
void sum(void);
#endif
<file_sep>#include <stdio.h>
#include <stdbool.h>
void fnWithoutVoid() {}
void fnWithVoid(void) {}
int main(void) {
fnWithVoid(/*no value shoud be passed in here*/);
//fnWithVoid(false); error here
const char letter = 'A';
printf("value of letter A is: %d\n", letter);
// this is true (because of data types -> приведение к одному типа данных)
if (65 == 'A') printf("ascii value and char representation are equal\n");
fnWithoutVoid(1, 2, "3");
fnWithoutVoid(true);
fnWithoutVoid();
/*
char a = 0, b = 0;
a && b && {
printf("%s\n", "from bash I used this");
}
*/
return 0;
}
<file_sep>#ifndef DIFFERENT_H
#define DIFFERENT_H
#define STR_COPY
#ifdef STR_COPY
void strcopy_a(char *, char *);
void strcopy_b(char *, char *);
void strcopy_c(char *, char *);
#endif
#elif defined(TEST_1)
#endif
<file_sep>#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define CONST 100lu
typedef enum { ONE = 0, TWO, THREE, END } Test;
void strcopy(char *, char *);
typedef struct {
char value;
char test;
} TestStruct;
typedef struct {
char ch;
short sh;
} s_problem_default;
#pragma pack(push, 1)
typedef struct {
char ch; short sh;
} s_problem_packaged;
#pragma pack(pop)
void test_data(char *p_data) {
s_problem_default defaul;
defaul = *((s_problem_default *)(p_data));
printf("ch = %c\n", defaul.ch);
printf("sh = %i\n", defaul.sh);
}
void problem_example(void) {
s_problem_default data;
char *send_buffer;
data.ch = 'a';
data.sh = 0x200;
printf("%p\n", &data);
send_buffer = (char*)&(data);
test_data(send_buffer);
}
bool fn(unsigned, unsigned);
bool fn(unsigned int a, unsigned int b) {
return a > b;
}
typedef struct {
int data;
} NodeData;
int main() {
NodeData node;
node.data = 10;
printf("%p\n%p\n", fn, &fn);
problem_example();
TestStruct st;
st.value = 0x01;
st.test = 0x0A;
printf("size of struct is: %ld\n", sizeof(st));
printf("\t+------+------+\n");
printf("\t| ch_a | ch_b |\n");
printf("\t+------+------+\n\n");
printf("\t%p(value): %x\n", &st.value, *(int *)(&st.value/**(char *)(&st.value)*/));
printf("\t%p(test): %x\n", &st.test, *(char *)(&st.test));
printf("<----->\n");
int i = 10;
printf("%7i\n", i);
Test test = 20;
Test array[END] = { ONE };
// test is one of accepted values in 'Test'
printf("%d - %d\n", END, test);
int g = END;
do printf("%d\n", (*array)++);
while(g-- > 0);
printf("\n");
unsigned short target = 1;
unsigned char x = 0, y = 0;
x = target;
y = target >> 8;
printf("%d-%d-%d\n", target, x, y);
int x = 0;
int y;
if((y = x) == 0)
printf("%s\n", "this is working");
for (int i = (x = y++); i < 4, y++;)
printf("current value: i = %d, x = %d, y = %d\n", i, x, y);
for (int i = 0; i < 4; i++, printf("%d\n", i));
int i = 2;
do; while(printf("i = %d\n", i), i-- > 0);
unsigned short int a = 4;
unsigned long int b = 5;
short char g = 'a';
short c = 4;
long d = 5;
char f = 'a';
printf("short char: %ld\n", sizeof(short char));
printf("char: %ld\n", sizeof(char));
printf("short: %ld\n", sizeof(short));
printf("long: %ld\n", sizeof(long));
printf("short int: %ld\n", sizeof(unsigned short int));
printf("long int: %ld\n", sizeof(unsigned long int));
printf("unsigned long number: %ld\n", CONST);
printf("5 / 10 = %d\n", 5 / 10);
printf("5 / 10.0 = %.2f\n\n", 5 / 10.);
printf("%d\n", __BOOL);
int j = (int)getchar();
putchar(j);
printf("int: %d\n", j);
char ch;
printf("A symbol: %c\n", ch - 32);
putchar(42); putchar('*' + '0');
printf("\n");
putchar('*' + '\0');
printf("\n");
int *p_array = calloc(3, sizeof(short int));
putchar((*p_array = 41) + '\0');
printf("\n");
free(p_array);
char *s2 = "hello, world", s1[15];
strcopy(s1, s2);
puts(s1);
}
void strcopy(char *s1, char *s2) {
int i = 0;
while((s1[i] = s2[i]) != '\0')
i++;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]) {
char *m_pointer = NULL;
unsigned char m_l = 20;
unsigned char n_s = 0;
m_pointer = malloc((sizeof(char) * m_l) +1);
memset(m_pointer, 0, (sizeof(char) * m_l) +1);
char i = 0;
for (; i < m_l; ++i)
printf("%d -> %c\n", i, *m_pointer++);
char *c_pointer = NULL;
unsigned char c_l = 5;
c_pointer = calloc(c_l + 1, sizeof(char));
char g = c_l;
do printf("%d -> %c\n", g, *c_pointer++);
while(g-- > 0);
strcpy(c_pointer, "Hello");
printf("%s\n", c_pointer);
n_s = c_l + strlen(" world") + 1;
printf("%p -- \n", c_pointer);
c_pointer = realloc(c_pointer, n_s);
printf("%p -- \n", c_pointer);
strcat(c_pointer, " world");
c_pointer[n_s] = '\0';
printf("%s\n", c_pointer);
if (c_pointer != NULL) free(c_pointer);
if (m_pointer != NULL) free(m_pointer);
c_pointer = NULL;
m_pointer = NULL;
return 0;
}
<file_sep>#include "io.h"
#define INDEX(ptr, init) (ptr-init)
extern void inputs_io(char* buffer, size_t size) {
if (size == 0) {
return;
}
char* ptr = buffer;
while((*ptr = getchar()) != '\n' && INDEX(ptr, buffer) < size - 1) {
++ptr;
}
*ptr = '\n';
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void my_strcpy(char* str1, const char* str2) {
while(*(str1++) = *(str2++));
}
char my_toupper(char c) {
return c >= 'a' && c <= 'z' ? c - 32 : c - 0;
}
char my_tolower(char c) {
return c += c >= 'A' && c <= 'Z' ? +32 : 0;
}
char* hello(const char* name) {
char* res = (char*)malloc(20 * sizeof(char) + 1);
strcpy(res, "Hello, ");
if (name == NULL) return strcat(res, " World!");
char i = 7;
char len = strlen(name);
*(res + i) = my_toupper(*(name + 0));
for (i = 1; i < len; i++)
*(res + 7) = my_tolower(*(name + i))
*(res + len + 7) = '!';
*(res + len + 8) = '\0';
return res;
}
int main() {
const char* name = "hog";
hello(name);
printf("size: %ld\n", sizeof("hello"));
char* input = "hello";
char str[80];
char* str_d = NULL;
str_d = (char*)malloc(sizeof(char) * 5 + 1);
my_strcpy(str, input);
my_strcpy(str_d, input);
char i = 0;
while(*(str + i))
printf("%c\n", *(str + i++));
i = 0;
while(*(str_d++))
printf("%c\n", *(str_d++));
char s1[10] = "test";
char s2[10] = "string";
int i = 0;
strcat(s1, s2);
for(char i = 0; i < sizeof(s1)/sizeof(char); ++i)
printf("%d", s1[i]);
printf("\n");
}
<file_sep>#include <stdio.h>
enum { ONE = 0, TWO, THREE, END };
int main(int argc, char const *argv[]) {
static unsigned int i_a[END] = { 0xfe34, 0xab34, 0xac57 };
unsigned int *i_a0 = &i_a[ONE];
unsigned int *i_a2 = &i_a[TWO];
unsigned int m, n = i_a2 - i_a0;
printf("value: %lu\n", sizeof(unsigned int) * n);
n = *++i_a0;
printf("pre increment *++: \t0x%x\n", n);
m = ++*i_a0;
printf("++*: increment: \t0x%x\n", m);
m = *(i_a0)++;
printf("post increment (*)++: \t0x%x\n", m);
m = *i_a0++;
printf("post increment ++*: \t0x%x\n", m);
printf("value: 0x%x\n", *(unsigned char *)i_a2++);
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
typedef int my_int;
typedef struct { char name[10]; char surname[10]; } give_name_to_combined_type;
struct Point {
int a;
int b;
};
union un { int a; int b; };
enum n { A = 0, B, END };
typedef enum { a = 0, b, c, end } en;
int main(int argc, char const *argv[]) {
struct Point x, y, z;
// un n; (error)
union un u;
u.a = 10;
my_int n = 3;
give_name_to_combined_type struct_test;
strcpy(struct_test.name, "name");
strcpy(struct_test.surname, "surname");
en num[end] = { 1, 2, 3 };
// n = 9; ?
return 0;
}
<file_sep>#!/bin/bash
gcc -Wall -E lesson1.c -o main.i
gcc -Wall -S main.i main.s
gcc -Wall -c lesson1.c -o main.o
gcc -Wall main.o -o res.out
<file_sep>#include "sort_tool.h"
void ia_bubble_sort(int *apArray, unsigned aSize, /*enum*/ pf_compare pf) {
for (unsigned i = 1; i < aSize; ++i)
for (unsigned j = 0; j < aSize - i; ++j)
if ((*pf)(apArray[i], apArray[j + 1])) { // if
int tmp = apArray[i];
apArray[j] = apArray[j + 1];
apArray[j + 1] = tmp;
}
}
void ia_print(int *apArray, unsigned aSize) {
for (int i = 0; i < aSize; i++)
printf("%i", *apArray++);
printf("\n");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "hashtab.h"
#include "tree.h"
#include "type.h"
typedef struct HashTab {
struct {
vtype_t key;
vtype_t value;
} type;
size_t size;
Tree **table;
} HashTab;
static uint32_t _get_hash(HashTab *hashtab, void *key);
static uint32_t _strhash(char *s, size_t size);
extern HashTab *new_hashtab(size_t size, vtype_t key, vtype_t value) {
switch(key) {
case DECIMAL_TYPE:
case STRING_TYPE:
break;
default:
fprintf(stderr, "%s\n", "key type not supported");
return NULL;
}
switch(value) {
case DECIMAL_TYPE:
case REAL_TYPE:
case STRING_TYPE:
break;
default:
fprintf(stderr, "%s\n", "value type not supported");
return NULL;
}
HashTab *hashtab = (HashTab*)malloc(sizeof(HashTab));
hashtab->table = (Tree**)malloc(size * sizeof(Tree*));
for (size_t i = 0; i < size; ++i) {
hashtab->table[i] = new_tree(key, value);
}
hashtab->size = size;
hashtab->type.key = key;
hashtab->type.value = value;
return hashtab;
}
extern void del_hashtab(HashTab *hashtab, void *key) {
uint32_t hash = _get_hash(hashtab, key);
del_tree(hashtab->table[hash], key);
}
extern _Bool in_hashtab(HashTab *hashtab, void *key) {
uint32_t hash = _get_hash(hashtab, key);
return in_tree(hashtab->table[hash], key);
}
extern value_t get_hashtab(HashTab *hashtab, void *key) {
uint32_t hash = _get_hash(hashtab, key);
return get_tree(hashtab->table[hash], key);
}
extern int8_t set_hashtab(HashTab *hashtab, void *key, void *value) {
uint32_t hash = _get_hash(hashtab, key);
set_tree(hashtab->table[hash], key, value);
return 0;
}
extern _Bool eq_hashtab(HashTab *x, HashTab *y) {
if (x->type.key != y->type.key) {
return 0;
}
if (x->type.value != y->type.value) {
return 0;
}
if (x->size != y->size) {
return 0;
}
for (size_t i = 0; i < x->size; ++i) {
if (size_tree(x->table[i]) != size_tree(y->table[i])) {
return 0;
}
if (eq_tree(x->table[i], y->table[i]) != 0) {
return 0;
}
}
return 1;
}
extern size_t size_hashtab(HashTab *hashtab) {
return hashtab->size;
}
extern size_t sizeof_hashtab(void) {
return sizeof(HashTab);
}
extern void free_hashtab(HashTab *hashtab) {
for (size_t i = 0; i < hashtab->size; ++i) {
free_tree(hashtab->table[i]);
}
free(hashtab->table);
free(hashtab);
}
extern void print_hashtab(HashTab *hashtab) {
printf("#H[ ");
for (size_t i = 0; i < hashtab->size; ++i) {
if (size_tree(hashtab->table[i]) == 0) {
continue;
}
printf("(%u :: ", (uint32_t)i);
print_tree(hashtab->table[i]);
printf(") ");
}
putchar(']');
}
extern void println_hashtab(HashTab *hashtab) {
print_hashtab(hashtab);
putchar('\n');
}
extern void print_hashtab_format(HashTab *hashtab) {
printf("#H[\n");
for (size_t i = 0; i < hashtab->size; ++i) {
if (size_tree(hashtab->table[i]) == 0) {
continue;
}
printf("\t(%u :: ", (uint32_t)i);
print_tree(hashtab->table[i]);
printf(")\n");
}
putchar(']');
}
extern void println_hashtab_format(HashTab *hashtab) {
print_hashtab_format(hashtab);
putchar('\n');
}
static uint32_t _get_hash(HashTab *hashtab, void *key) {
uint32_t hash = 0;
switch(hashtab->type.key) {
case DECIMAL_TYPE:
hash = (uint32_t)(intptr_t)key % hashtab->size;
break;
case STRING_TYPE:
hash = _strhash((char*)key, hashtab->size);
break;
default: ;
}
return hash;
}
static uint32_t _strhash(char *s, size_t size) {
uint32_t hashval;
for (hashval = 0; *s != '\0'; ++s) {
hashval = *s + 31 * hashval;
}
return hashval % size;
}
| acf35fbc046e1c3c94c1d568b1e88b5e227f48e5 | [
"C",
"Makefile",
"C++",
"Shell"
] | 92 | C | RV8V/code-c | 7ac1edbb5b8255a8221bd92a65725106be37e24f | 94c63984f153861806b7c04b5cf86cbc444e60c4 |
refs/heads/master | <repo_name>rdarleyDP/node-course-2-chat-app<file_sep>/server/server.js
// Load in built in modules
const http = require('http');
const path = require('path');
// Load in other modules
const express = require('express');
const socketIO = require('socket.io');
const {generateMessage, generateLocationMessage} = require('./utils/message');
const {isRealString} = require('./utils/validation');
const {Users} = require('./utils/users');
// Set up path for Express
const publicPath = path.join(__dirname, '../public');
// Setup port for heroku and local
const port = process.env.PORT || 3000;
// Initiate express app
var app = express();
// Configure web sockets server
var server = http.createServer(app);
var io = socketIO(server);
var users = new Users();
app.use(express.static(publicPath));
io.on('connection', (socket) => {
console.log('New user connected');
// Listen for join
socket.on('join', (params, callback) => {
if (!isRealString(params.name) || !isRealString(params.room)) {
return callback('Name and room name are required');
}
socket.join(params.room);
// Check for unique user name
if (!users.checkUniqueUser(socket.id, params.name, params.room)) {
return callback('That is not a unique name');
}
// Add a user to the user list
users.removeUser(socket.id);
users.addUser(socket.id, params.name, params.room);
io.to(params.room).emit('updateUserList', users.getUserList(params.room));
// Emit Admin welcome message
socket.emit('newMessage', generateMessage('Admin', `Welcome to the ${params.room} chat room!`));
// Alert everyone that a new user joined the room
socket.broadcast.to(params.room).emit('newMessage', generateMessage('Admin', `${params.name} has joined the chat.`));
callback();
});
// Listen for createMessage from client
socket.on('createMessage', (message, callback) => {
var user = users.getUser(socket.id);
if (user && isRealString(message.text)) {
io.to(user.room).emit('newMessage', generateMessage(user.name, message.text));
}
callback();
});
// Listen for createLocationMessage
socket.on('createLocationMessage', (coords) => {
var user = users.getUser(socket.id);
if (user) {
io.to(user.room).emit('newLocationMessage', generateLocationMessage(user.name, coords.latitude, coords.longitude));
}
});
socket.on('disconnect', () => {
var user = users.removeUser(socket.id);
if (user) {
io.to(user.room).emit('updateUserList', users.getUserList(user.room));
io.to(user.room).emit('newMessage', generateMessage('Admin', `${user.name} has left the room.`));
}
});
});
// Tell express to listen on the chosen port
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});<file_sep>/server/utils/message.test.js
const expect = require('expect');
const {generateMessage, generateLocationMessage} = require('./message');
describe('generateMessage', () => {
it('should generate the correct message object', () => {
var from = 'Izzy';
var text = 'Give me second dinner';
var message = generateMessage(from, text);
expect(message.from).toBe(from);
expect(message.text).toBe(text);
expect(typeof message.createdAt).toBe('number');
});
});
describe('generateLocationMessage', () => {
it('should generate correct location object', () => {
var from = 'Admin';
var lat = 21;
var long = 30;
var message = generateLocationMessage(from, lat, long);
expect(message.from).toBe(from);
expect(message.url).toBe(`https://www.google.com/maps?q=${lat},${long}`);
expect(typeof message.createdAt).toBe('number');
});
});<file_sep>/server/utils/users.test.js
const expect = require('expect');
const {Users} = require('./users');
describe('Users', () => {
var users;
beforeEach(() => {
users = new Users();
users.users = [{
id: '1',
name: 'Robin',
room: 'a'
},
{
id: '2',
name: 'Ryan',
room: 'b'
},
{
id: '3',
name: 'Izzy',
room: 'a'
}];
});
it('should add new user', () => {
var users = new Users();
var user = {
id: '123',
name: 'Robin',
room: 'Test room'
};
var resUser = users.addUser(user.id, user.name, user.room);
expect(users.users).toEqual([{"id": "123", "name": "Robin", "room": "test room"}]);
});
it('should add a unique user', () => {
var uniqueUser = {
id: '555',
name: 'Violet',
room: 'A'
};
var thisUser = users.checkUniqueUser(uniqueUser.id, uniqueUser.name, uniqueUser.room);
console.log(thisUser);
expect(thisUser).toBeTruthy();
expect(users.users.length).toBe(3);
});
it('should reject a duplicate name', () => {
var dupeUser = {
id: '777',
name: 'Robin',
room: 'A'
};
var thisUser = users.checkUniqueUser(dupeUser.id, dupeUser.name, dupeUser.room);
expect(thisUser).toBeFalsy();
expect(users.users.length).toBe(3);
});
it('should return names for room A', () => {
var thisUser = users.addUser('555', 'Violet', 'A');
var people = users.getUserList('A');
expect(people).toEqual(['Robin', 'Izzy', 'Violet']);
});
it('should return names for room B', () => {
var people = users.getUserList('B');
expect(people).toEqual(['Ryan']);
});
it('should remove a user', () => {
// take id, remove
var user = users.removeUser('1');
expect(user.id).toBe('1');
expect(users.users.length).toBe(2);
});
it('should not remove user', () => {
// pass in invalid id, array should not change
var user = users.removeUser('7');
expect(user).toBeUndefined();
expect(users.users.length).toBe(3);
});
it('should get a user', () => {
// pass in valid id and get user back
var user = users.getUser('1');
expect(user.id).toBe('1');
});
it('should not find user', () => {
// pass in invalid id and not get a user back
var user = users.getUser('4');
expect(user).toBeUndefined();
});
}); | fffd38f8aa53cd72b1df427bebff69df37a1d470 | [
"JavaScript"
] | 3 | JavaScript | rdarleyDP/node-course-2-chat-app | 43a76466e5c4491867efdfb6d063419ee24b33df | b81d393e9bc374c27b70b29bb116543024e9fb6b |
refs/heads/master | <repo_name>diverse-project/varylatex<file_sep>/vary/static/js/colors.js
function gradient(perc, start_color, end_color) {
let [r1,g1,b1] = start_color.slice(-6).match(/(..)/g).map(x => parseInt(x, 16));
let [r2,g2,b2] = end_color.slice(-6).match(/(..)/g).map(x => parseInt(x, 16));
color =
Math.round(r1 + (r2-r1) * perc / 100) * 256 * 256 +
Math.round(g1 + (g2-g1) * perc / 100) * 256 +
Math.round(b1 + (b2-b1) * perc / 100);
return '#' + ('000000' + color.toString(16)).slice(-6);
}<file_sep>/vary/model/generation/compile.py
import os
import subprocess
from vary.model.generation.subcall import run_command
def generate_bbl(filepath):
"""
Loads the bibliography file
"""
working_directory, texfile = os.path.split(filepath)
try:
# Precompile the main file to get the .aux file
run_command(["pdflatex", "-draftmode", "-interaction=batchmode", texfile + ".tex"], working_directory)
# Load the bibtex references from the .aux
run_command(["bibtex", texfile + ".aux"], working_directory)
except subprocess.TimeoutExpired:
print("The bibliography compilation process timed out")
def compile_latex(filename):
"""
Compile the document with pdftex.
After the generation of the bibliography we may need two runs to link all the references.
"""
working_directory, texfile = os.path.split(filename)
try:
run_command(["pdflatex", "-draftmode", "-interaction=batchmode", texfile], working_directory)
run_command(["pdflatex", "-interaction=batchmode", texfile], working_directory)
return True
except subprocess.TimeoutExpired:
return False
<file_sep>/vary/model/decision_trees/analysisCT.r
# Adapted from https://github.com/FAMILIAR-project/varylatex/blob/master/output-FSE/analysisCT.R
library(rpart)
library(rpart.plot)
library(caret)
library(readr)
library(dplyr)
mystats <- read_csv("../varylatex/result_example.csv",
col_types = cols(
ACK = col_factor(levels = c("True","False")),
BOLD_ACK = col_factor(levels = c("True","False")),
EMAIL = col_factor(levels = c("True","False")),
LONG_ACK = col_factor(levels = c("True","False")),
LONG_AFFILIATION = col_factor(levels = c("True","False")),
PARAGRAPH_ACK = col_factor(levels = c("True","False")),
PL_FOOTNOTE = col_factor(levels = c("True","False")),
js_style = col_factor(levels = c("\\footnotesize", "\\scriptsize", "\\tiny")),
nbPages = col_factor(levels = c("4","5"))
)
)
evalCT <- function (stats, perc) {
# View(stats)
summary(stats$nbPages)
stats <- na.omit(stats)
#print(summary(stats$nbPages))
sample <- sample.int(n = nrow(stats), size = floor(perc*nrow(stats)), replace = F)
test <- stats[-sample, ]
train <- stats[sample, ]
fit <- rpart(nbPages~.-idConfiguration-space,data=train,method="class")
rpart.plot(fit,type=4, extra=0, box.palette=c("palegreen3", "red"))
pred = predict(fit, test, type="class")
cm <- confusionMatrix(pred, test$nbPages)
return (cm$overall['Accuracy'])
}
evalCT(stats=mystats, perc = (7/10))<file_sep>/vary/static/js/index.js
function closeTabs(tabId) {
let tabs = document.getElementsByClassName("tab-content");
for (tab of tabs) {
tab.style["display"] = "none";
}
}
function toggleButtonsOff() {
let buttons = document.getElementsByClassName("tab-button");
for (button of buttons) {
button.classList.remove("active")
}
}
function openTab(event, tabId) {
closeTabs();
document.getElementById(tabId).style["display"] = "flex";
event.currentTarget.classList.add("active");
}<file_sep>/Dockerfile
FROM python:3
RUN apt-get update -y\
&& apt-get install texlive-full -y\
&& apt-get install graphviz -y\
&& rm -rf /var/lib/apt/lists/*
COPY . /varylatex
WORKDIR /varylatex
RUN pip install -r requirements.txt
VOLUME /varylatex/build
CMD /bin/bash
<file_sep>/vary/views/project_files.py
import os
import json
import re
from flask import request, redirect, url_for, render_template, session, send_from_directory
from vary import app
from vary.model.files.tex_injection import add_graphics_variables, add_include_macros_variables, add_itemsep_variable
VARIABLE_FILE_NAME = "variables.json"
@app.route('/selectfile', methods=["GET", "POST"])
def selectfile():
if request.method == "POST":
main_filename = request.form.get('filename')
session['main_file_name'] = main_filename
upload_folder = app.config['UPLOAD_FOLDER']
add_include_macros_variables(os.path.join(upload_folder, main_filename))
return redirect(url_for('auto_variables'))
else:
return render_template('selectfile.html')
@app.route('/filenames')
def get_filenames():
"""
Gets the potential main tex file names based on the content of the source folder and
the fact that it contains or not a \documentclass{} declaration
"""
filenames = []
dc_pattern = re.compile(r"\\documentclass(\[[^\]]*\])*{[^}]*}")
texfile_pattern = re.compile(r".*\.tex")
for root, _, files in os.walk(app.config['UPLOAD_FOLDER']):
for filename in files:
if texfile_pattern.match(filename):
path = os.path.join(root, filename)
with open(path) as file:
data = file.read()
if any(li for li in data.splitlines() if dc_pattern.match(li)):
filenames.append(os.path.relpath(path, "vary/source"))
return json.dumps(filenames)
@app.route('/config_src')
def config_src():
"""
Gets the config JSON file of the project, which defines the domain of the variables.
"""
return send_from_directory("source", VARIABLE_FILE_NAME)
@app.route('/auto_variables', methods=["GET", "POST"])
def auto_variables():
if request.method == "POST":
project_folder = app.config['UPLOAD_FOLDER']
main_file_path = os.path.join(project_folder, session['main_file_name'])
form = request.form
if form.get('generateImageSizes'):
add_graphics_variables(main_file_path)
if form.get("generateItemsep"):
add_itemsep_variable(main_file_path)
return redirect(url_for('mode'))
else:
return render_template("auto_variables.html")
<file_sep>/docs/about.md
# Motivation
With this implementation of VaryLaTeX we want to give the user a way to add variability to a LaTeX document, to help them either customize a document, or tweak it to match some requirements. For instance, one may want a document that fits on a maximum of 10 pages.
# Adding variability
## Choice between a templating framework and native LaTeX
[The first version of VaryLaTeX](https://github.com/FAMILIAR-project/varylatex) used a templating framework to inject variability into the document. The upside of doing this is that it is not limited to LaTeX documents and can be used for other formats without much teawking.
The downsides of it is that the user has to learn the template syntax and, most importantly, the annotated document would no longer compile whereas a native LaTex solution can make functionnal documents outside of the tool.
Still being able to render the document while writing it being judged as important, we chose to go with the native solution instead of the template one.
## Values and conditionals
There are two ways we want to express variability in our LaTeX documents :
- **Values**, which may be numbers (size of an image, of the margin...) or a choice between values (like different display styles, colors).
- **Booleans**, that can be used to make togglable parts of a document based on whether a variable is true or false.
## Values
In the original implementation of [latex-optimizer](https://gitlab.com/martisak/latex-optimizer/), variables are defined using a file (`macros.tex`) where for each value there is a line like this :
```tex
\def\varname{value}
```
Here, to prevent conflicts with already defined values and offer more naming options, we hide the variables behind the prefix `vary@`.
The syntax for defining a value is :
```tex
\defVal{name}{value}
```
Which behind the scenes creates a command (because `\newcommand` seems recommended over `\def`) like this
```tex
\vary@name
```
The created command expands to `value`
As writing the prefix every time can be tedious and the `@` prevents direct access to the variable, the value can be retrieved using
```tex
\getVal{name}
```
## Conditionals
The other aspect of variability that we need is the ability to toggle parts of the document, using `if` statements and booleans.
The condition that is used here is whether a variable exists or not. A value of `true` will be declared like this :
```tex
\defVal{name}{}
```
A value of `false` will not be defined.
To check if a variable is defined, we use the `\ifcsname` macro that displays its content only if a command with a certain name is defined. As this is an `if` command that is defined in LaTeX, the content ends on `\fi` and it is possible to add an `else` block with `\else`.
The first idea was just to provide an alias of `ifcsname` that would take the name of the variable as a parameter and put it inside `\ifcsname`. This would have allowed the user to use the condition like a normal one, with `\else` and `\fi
The issue with this solution concerns nested `if` conditions like this :
```tex
\ifVal{bool1}
\ifVal{bool2}
\fi
\fi
```
In this case, if `bool1` is not defined, the content of the first condition will not be expanded. The block will end at the first `fi` met, which is the one directly after `\ifVal{bool2}`. That means that the part after that `fi` will be executed and an error will be thrown because of the extra `\fi` at the end.
To solve this problem, we use a syntax that is more similar to programming languages, with the conditional block delimited by brackets :
```tex
% Syntax without else block
\ifVal{val}{
This will only be displayed if val has been defined.
}
% Syntax with else block
\ifValElse{val}{
This will only be displayed if val has been defined.
}{
This will only be displsyed if val has not been defined.
}
```
## Summary / How to use the syntax :
To declare a value :
```tex
\defVal{name}{value}
% Example :
\defVal{img_ratio}{0.75}
```
To declare a boolean set to true :
```tex
\defVal{name}{}
```
To get the value of a defined variable :
```tex
% If the value has not been defined, this will throw an error
\getVal{name}
```
Conditionals :
```tex
\defVal{defined}{}
\ifVal{defined}{This is displayed}
\ifVal{not_defined}{This is not}
\ifValElse{defined}{This is displayed}{And this is not}
```
## Representing the domain of definition of the variables
If we want to generate possible values for our variavles, we need to specify their name and definition domain. To do this, we add a file to the project, called ``variables.json. It can define 4 types of variables :
- `booleans` : either defined or not.
- `enums` : defined to one of the possible values
- `choices` : groups of booleans where only one is defined
- `numbers` : floating point numbers, with min, max and decimal precision.
The structure of the file is as follows (order is not important) :
```json
{
"booleans": ["bool_name_1", ..., "bool_name_n"],
"enums": {
"enum_name_1" : ["enum_1_a", ..., "enum_1_z"],
"enum_name_2" : ...
}
"choices": [
["choice_1_a", ..., "choice_1_z"],
...
["choice_n_a", ...]
],
"numbers": {
"num_name_1": [min, max, precision],
...
"num_name_n": [min, max, precision]
}
}
```
An example can be seen [there](../vary/example/fse/variables.json).
The JSON file is then used by the proram to either generate random configurations or to show the possible choices to the user.
# The application
## Timeline
The application started from a `python` script, which itself was inspired by the [latex-optimizer project by <NAME>](https://gitlab.com/martisak/latex-optimizer/).
The first goal was to generate documents with random configurations based on the `variables.json` file.
Then, with those documents, we observe the page counts and how they changed based on the variables. These records are stored in a CSV file that is then used by `scikit-learn` to create a **decision tree** that guesses if a document following a given configuration is going to match the requirements.
All of this was done with a command-line tool but as the number of options was increasing and as it was not very user-friendly, so we decided to create a web-app based on the same concept, which would make the use of the tool easier.
With the app, we finally decided to propose 2 options, one that generates documents to create an estimator and guide the user while setting the variables, and the other that is just here to provide a configurator for the document without trying to check its page count.
We also added a way to generate automatically new variables, for the size when using `\includegraphics` and for the space between elements in a list. These variables can be automatically added to a document without the need for the user to write anything.
## Command-line app
The first idea of the project was to create a tool that we could call from the terminal and that would generate random configurations of a document and then output a CSV file of the results and an image of the decision tree corresponding to the results.
We realized that it was not user-friendly as we needed to specify may options every time, so we decided to create a web application so the user could gain more control through a web interface.
## Server side
As the project was initially written in `python`, we chose a to use `python` framework for making our webapp. We decided to use `Flask` for that.
The functionalities that were used in the command-line app were turned into functions and extracted to common source files, used by both the command-line and the server app.
There are two ways to select a project in the app : the first one is to place everything in a `.zip` file and upload it to the server with the import button. The second one is to have the project on [Overleaf](http://overleaf.com), create a **read-only** link to it and copy and paste the key that links to the project (the key is the part after `https://www.overleaf.com/read/` in the link). The program then gets access to the project and is able to download the `.zip` of the project directly.
## Client side
The client side is a basic interface with HTML, CSS and JavaScript, and bootstrap to simplify the layout.
# Automatically generated variables
Apart from using previously-defined variation points, we wanted to be able to add new variables to a document, and thus have a way to tweak a document that was not intended for VaryLaTeX.
For now, there are two types of variables that can be infered this way. The first one is a variable for each element included via `\includegraphics` : instead of using the specified `height`, `width` or `scale`, we generate a variable whose domain is centered on the original value.
The second one is a variable that changes the space between 2 items in a list, to reduce its size.
The user can choose whether they want to use the variables or to stick with the original document.
<file_sep>/vary/__init__.py
from flask import Flask
from vary.model.files.directory import create_dir, get_secret_key
import os
# Constants
SERVER_SOURCE_FOLDER = "source"
UPLOAD_FOLDER = os.path.join("vary", SERVER_SOURCE_FOLDER)
SERVER_RESULTS_FOLDER = "results"
RESULT_FOLDER = os.path.join("vary", SERVER_RESULTS_FOLDER)
ALLOWED_EXTENSIONS = {"zip"}
# App
app = Flask(__name__)
# Config
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024
app.secret_key = get_secret_key(os.path.join("vary", "key"))
# Creates the result folder as an empty folder is not saved by GIT
create_dir(RESULT_FOLDER)
import vary.views
<file_sep>/docs/howto_variability.md
# Add Variability elements in a LaTeX document
## Definitions
Variability can be added to your LaTeX document by two manners :
- Togglable blocks, based on a boolean condition
- Values, that can be either number or strings (that can contain LaTeX macros).
## Apply Variability
To use the variables, you may want to add those two lines in your source document :
```tex
\include{macros}
\include{values}
```
If you don't, the app will do it for you but your document won't be able to compile with another tool (overleaf, `latexmk`...).
You can get the value of a variable with
```tex
\getVal{valName} % Expands to the value
```
Conditionals blocks can be created with `if` and `if-else` commands, the content of the `if` is displayed only if the value with the corresponding name is defined.
```tex
\ifVal{valName} {
% This part is rendered only if the
% value is defined
}
\ifValElse{valName} {
% This part is rendered only if the
% value is defined
}{
% This part is rendered only if the
% value is not defined
}
```
## Defining variables' domain
For the program to generate variations of the document, you need to specify the domain of the variables. It is done by adding a file called `variables.json` in the source folder.
In this file you can declare four types of variable domains :
- `"booleans"` : An array of variables names that can correspond to either `true` or `false`, to be used with `\ifVal` only.
- `"numbers"` : A JSON object mapping the name of the variable with an array of length 3, containing the minimum, the maximum, and the precision of the value.
- `"enums"` : A JSON object mapping the name of a variable with an array of all the possible values it can take.
- `"choices"` : An array of arrays (groups) of booleans, where exactly one boolean is set to `true` for each group.
An example of a `variables.json` file can be found [there](../vary/example/fse/variables.json)
## Manually setting variables
If you want to still be able to work with a preview of your document, you need to add the [macros.tex](../vary/model/macros.tex) file in the source folder, and add definitions of the variables' values in a file called `values.tex`, in the same folder.
To define the variables you need to use the provided `defVal` command :
```tex
\defVal{valName}{} % Used for booleans set to true
\defVal{valName}{value} % For variables that store a value
```
Note : to represent a boolean set to false, you just need to not define it.<file_sep>/vary/views/free_config.py
from flask import render_template
from vary import app
@app.route('/config')
def config():
return render_template("free_config.html")<file_sep>/vary/model/generation/inject.py
import os
def get_variable_def(k, v):
"""
\\defVal{name}{value}
"""
if v == False or v == "False":
return ""
if v == True:
return fr"\defVal{{{k}}}{{}}"
return fr"\defVal{{{k}}}{{{v}}}"
def write_variables(config, temp_path):
""" Write variables to file """
with open(os.path.join(temp_path, "values.tex"), "w") as f:
for k, v in config.items():
macro = get_variable_def(k, v)
if macro != "":
f.write(f"{macro}\n")
<file_sep>/vary/model/files/directory.py
import os
import shutil
import time
from pathlib import Path
def clear_directory(path):
"""
Removes the content of a directory without removing the directory itself
"""
for root, dirs, files in os.walk(path):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
def remove_directory(path):
"""
Removes a directory and its content
"""
shutil.rmtree(path)
def create_temporary_copy(path):
"""
Creates a working directory with a copy of the project files, that can be altered by the program
and used for the compilations.
"""
timestamp = str(time.time())
tmp_path = os.path.join(os.getcwd(), "vary/build", timestamp)
try:
shutil.copytree(path, tmp_path)
macro_path = os.path.join(os.path.split(os.path.realpath(__file__))[0], "../macros.tex")
macro_copy_path = os.path.join(tmp_path, "macros.tex")
shutil.copyfile(macro_path, macro_copy_path)
except shutil.Error:
print("Error creating the temporary copy")
return tmp_path
def create_dir(path):
"""
Creates a directory with the specified path if it does not already exists
"""
Path(path).mkdir(parents=True, exist_ok=True)
def get_secret_key(path):
if os.path.isfile(path):
with open(path, 'rb') as f:
return f.read()
else:
key = os.urandom(16)
with open(path, 'ab') as f:
f.write(key)
return key<file_sep>/vary/model/__init__.py
from pathlib import Path
# Create the required folders if they do not exist
Path("vary/build").mkdir(parents=True, exist_ok=True)
Path("vary/source").mkdir(parents=True, exist_ok=True)
Path("vary/results").mkdir(parents=True, exist_ok=True)
<file_sep>/vary/static/js/custom_select.js
class CustomOption {
/* ---- Fields
- this.div : HTML div element containing the representation of the option
- this._name : Displayed name of the option (use this.name to update the div)
- this.value : The value corresponding to the option
- this._color : Background color of the div (use this.color to update it)
- this.parent : The CustomSelect element containing this option.
------------ */
// Accessors
get name() {return this._name;}
set name(new_name) {
this._name = new_name;
this.div.innerText = new_name;
}
get color() {return this._color; }
set color(new_color) {
this._color = new_color;
set_background(this.div, new_color);
}
// If color is omitted, the option has the default background of the "custom-option" class in the stylesheet
constructor(name, value, color) {
this.div = document.createElement("div");
this.value = value;
this.parent = null;
this.name = name;
this.color = color;
this.div.classList.add("custom-option");
let that = this;
this.div.addEventListener('click', function(event) {
that.parent.select_option(that);
});
}
// Sets the parent select of this option and appends the div to its option list.
bind_to_select(select) {
this.parent = select;
select.option_div.appendChild(this.div);
}
show() {
this.div.classList.remove("option-collapsed");
}
hide() {
this.div.classList.add("option-collapsed");
}
}
/**
* Represents an object similar to the html <select>, made of divs, that can handle background color.
*
*/
class CustomSelect {
constructor(name, value, color) {
this.div = document.createElement("div");
this.div.classList.add("custom-select");
this.options = [];
this.selection_listeners = [];
this.name = "";
this.selection_div = document.createElement("div");
this.selection_div.classList.add("custom-selected-option");
this.option_div = document.createElement("div");
this.option_div.classList.add("custom-select-options")
this.div.appendChild(this.selection_div);
this.div.appendChild(this.option_div);
this.expanded = false;
if (name) {
let default_option = this.add_option(name, value, color);
this.select_option(default_option);
}
let that = this;
// Expand / collapse on click listener
window.addEventListener("click", function(event) {
let clicked_on_selection = that.selection_div.contains(event.target);
(!clicked_on_selection || that.expanded)? that.collapse() : that.expand();
});
}
add_option(name, value, color) {
let customOption = new CustomOption(name, value, color);
customOption.bind_to_select(this);
this.options.push(customOption);
return customOption;
}
add_selection_listener(listener) {
this.selection_listeners.push(listener);
}
remove_selection_listener(listener) {
let index = this.selection_listeners.indexOf(listener);
if (index > -1) {
this.selection_listeners.splice(index, 1);
}
}
select_option(option) {
let prev_option = this.selected_option;
if (this.selected_option == option) return;
if (prev_option) prev_option.show();
option.hide();
this.selected_option = option;
this.selection_div.innerText = this.selected_option.name;
set_background(this.selection_div, this.selected_option.color);
for (let listener of this.selection_listeners) {
listener(option, prev_option);
}
}
add_to_parent(parent) {
parent.appendChild(this.div);
this.collapse();
}
expand() {
/*
for (let option of this.options) {
if (option == this.selected_option) continue;
option.show();
}*/
this.option_div.style["visibility"] = "visible";
this.expanded = true;
}
collapse() {
/*
for (let option of this.options) {
option.hide();
}*/
this.option_div.style["visibility"] = "collapse";
this.expanded = false;
}
}
function set_background(element, color) {
if (color)
element.style["background-color"] = color;
else
element.style.removeProperty("background-color");
}<file_sep>/vary/static/js/constraints.js
const CONFIG = {};
let PROBAS = {};
let has_data = false;
let filter_generation = false;
let nb_variables = 0;
let max_pages = 5;
const RED = "#ff2020";
const GREEN = "#20ff20";
const enum_selects = [];
const bool_selects = [];
const choice_selects = [];
$('document').ready(function(){
document.getElementById("maxPages").addEventListener("input", function() {
if (this.value !== "") {
if (this.value > 0) {
max_pages = this.value;
}
}
})
let pdf_viewer = document.getElementById("pdf_viewer");
pdf_viewer.data="";
fetch_congig_src();
});
function compile(reset) {
let label = document.getElementById("msg");
let table = document.getElementById("results");
let qtyInput = document.getElementById("qtyInput");
let amount = parseInt(qtyInput.value)
if (isNaN(amount)) {
label.innerText = "Invalid input : please enter a number";
return;
}
if (amount < 1 || amount > 100) {
label.innerText = "Invalid input : please enter a number of documents between 1 and 100";
return;
}
// else
label.innerText = (reset ? "Generating" : "Adding" ) + " " + amount + " documents";
route = (reset ? '/generate_pdfs/' : '/add_pdfs/') + amount;
if (reset) {
document.getElementsByClassName("table-container")[0].style["visibility"] = "hidden";
table.getElementsByTagName("thead")[0].innerHTML = "";
table.getElementsByTagName("tbody")[0].innerHTML = "";
}
let data = filter_generation ? JSON.stringify(CONFIG) : "{}"
$.ajax({
type: "POST",
contentType: "application/json",
url: route,
data: data,
success: csv => fill_table(csv, reset),
}).then(() => {
label.innerHTML = "<a href='/tree_img' target='_blank'>See decision tree</a>";
refresh_probas();
})
}
function fill_table(csv, reset) {
has_data = true;
let parsedCSV = d3.csv.parseRows(csv);
let table = d3.select("#results");
if (reset)
table.select("thead")
.selectAll("th")
.data(parsedCSV[0]).enter()
.append("th")
.text(d => d)
let new_rows = table.select("tbody")
.selectAll("tr")
.data(d3.csv.parse(csv))
.enter()
.append("tr")
new_rows.selectAll("td")
.data(function(d) { return Object.values(d); }).enter()
.append("td")
.text(function(d) { return d; });
new_rows.append("td")
.append("button")
.text("PDF")
.on("click", build_pdf);
document.getElementsByClassName("table-container")[0].style["visibility"] = "visible";
document.getElementById("addBtn").disabled = false;
}
function build_pdf(data) {
delete data[""]
let pdf_viewer = document.getElementById("pdf_viewer");
pdf_viewer.data = "";
$.ajax({
url: "/build_pdf",
dataType: "json",
contentType: "application/json",
type: "POST",
data: JSON.stringify(data),
success: result => {
pdf_viewer.data = "/build_pdf";
}
})
}
function fetch_congig_src() {
$.ajax({
url: "/config_src",
type: 'GET',
dataType: 'json',
cache: false,
success: load_config_src
});
}
function load_config_src(config) {
let config_div = document.getElementById("configurator");
let booleans = config["booleans"];
if (booleans) load_booleans(booleans);
let enums = config["enums"];
if(enums) load_enums(enums);
let choices = config["choices"];
if (choices) load_choices(choices);
let numbers = config["numbers"];
if (numbers) load_numbers(numbers);
}
function load_booleans(booleans) {
nb_variables += booleans.length;
let bool_div = document.getElementById("boolDiv");
for (let name of booleans) {
let bool_option = new BooleanOption(name);
bool_option.addSelectionChangeListener((newValue, oldValue) => select_enum_bool_callback(name, newValue, oldValue));
bool_div.appendChild(bool_option.div);
bool_selects.push(bool_option);
}
}
function load_enums(enums) {
nb_variables += Object.keys(enums).length;
let enum_div = document.getElementById("enumDiv");
for (let name in enums) {
let enum_option = new EnumOption(name);
enum_option.addSelectionChangeListener((newValue, oldValue) => select_enum_bool_callback(name, newValue, oldValue));
for (let option of enums[name]) {
enum_option.addOption(option, option);
}
enum_div.appendChild(enum_option.div);
enum_selects.push(enum_option);
}
}
function load_choices(choices) {
nb_variables += choices.length;
CHOICES = choices
let choice_div = document.getElementById("choiceDiv");
for (let group of choices) {
let group_option = new GroupOption();
group_option.addSelectionChangeListener(select_choice_callback);
for (option of group) {
group_option.addOption(option, option);
}
choice_div.appendChild(group_option.div);
choice_selects.push(group_option);
}
}
function load_numbers(numbers) {
nb_variables += Object.keys(numbers).length;
let number_div = document.getElementById("numberDiv");
for(let name in numbers) {
let number_option = new NumberOption(
name,
numbers[name][0],
numbers[name][1],
(0.1 ** numbers[name][2]).toFixed(numbers[name][2])
);
number_option.addChangeListener((newValue, oldValue) => select_number_callback(name, newValue, oldValue));
number_option.addToggleListener((enabled) => toggle_number_callback(name, enabled));
number_div.appendChild(number_option.div);
}
}
function select_enum_bool_callback(name, newValue, oldValue) {
if (newValue == null) {
delete CONFIG[name];
} else {
CONFIG[name] = newValue;
}
refresh_probas();
}
function select_choice_callback(newValue, oldValue) {
delete CONFIG[oldValue];
if (newValue != null) {
CONFIG[newValue] = true;
}
refresh_probas();
}
function select_number_callback(name, newValue, oldValue) {
CONFIG[name] = newValue;
refresh_probas();
}
function toggle_number_callback(name, enabled) {
if (!enabled) {
delete CONFIG[name];
refresh_probas();
}
}
function update_selector() {
for (select of enum_selects) {
update_background_enum(select);
}
for (select of bool_selects) {
update_background_bool(select);
}
for (group of choice_selects) {
update_background_choice(group);
}
}
function update_background_enum(select) {
for (option in select.options) {
let value = select.options[option];
let proba;
if (value == null)
proba = PROBAS["enums"][select.name]["default"];
else
proba = PROBAS["enums"][select.name]["values"][value];
select.setColor(option, gradient(proba * 100, RED, GREEN));
}
//set_background(select.selection_div, select.selected_option.color);
}
function update_background_bool(select) {
for (option in select.options) {
let value = select.options[option];
let proba;
if (value == null)
proba = PROBAS["booleans"][select.name]["default"];
else
proba = PROBAS["booleans"][select.name][value ? "true" : "false"];
select.setColor(option, gradient(proba * 100, RED, GREEN));
}
//set_background(select.selection_div, select.selected_option.color);
}
function update_background_choice(select) {
for (option in select.options) {
let value = select.options[option];
let proba = PROBAS["choices"][option];
select.setColor(option, gradient(proba * 100, RED, GREEN));
}
// TODO set background (need to compute the probability for any of them)
}
function refresh_probas() {
if (!has_data) return;
let url = "/predict/" + max_pages;
$.ajax({
url: url,
dataType: "json",
contentType: "application/json",
type: "POST",
data: JSON.stringify(CONFIG),
success: result => {
PROBAS = result;
update_selector();
}
})
}
function filter_pressed() {
let filterBtn = document.getElementById('filterBtn');
if (filter_generation) {
filterBtn.classList.add("active");
} else {
filterBtn.classList.remove("active");
}
filter_generation = ! filter_generation;
filterBtn.innerText = `Generate documents using these constraints : ${filter_generation? "enabled" : "disabled"}`;
}<file_sep>/vary/static/js/config_element.js
class EnumOption {
get name() {
return this._name;
}
set name(n) {
this._name = n;
this.refreshNameLabel(n);
}
get div() {
return this.mainDiv;
}
constructor(name) {
this._name = name;
// The div containing the element, a row using bootstrap classes for the layout
this.mainDiv = document.createElement("div");
this.mainDiv.classList.add("row", "w-100");
// Left part with the label
this.nameLabel = document.createElement('label');
this.nameLabel.classList.add("col");
// Right part with the options
let right_col_div = document.createElement("div");
right_col_div.classList.add("col-auto");
this.selectionDiv = document.createElement('div');
this.selectionDiv.classList.add("btn-group", "btn-group-sm", "btn-group-toggle");
this.selectionDiv.setAttribute("role", "group");
this.selectionDiv.setAttribute("data-toggle", "buttons");
right_col_div.appendChild(this.selectionDiv);
this.options = {};
this.selectedOption = null;
this.selectionChangeListeners = [];
this.mainDiv.appendChild(this.nameLabel);
this.mainDiv.appendChild(right_col_div);
this.addOption("Any", null);
this.selectOption(null);
this.refreshNameLabel();
}
refreshNameLabel(name) {
this.nameLabel.innerHTML = `${this.name} :`.bold();
}
addOption(name, value) {
if(this.options[name] == null) {
let label = document.createElement('label');
label.textContent = name || "Any";
label.classList.add("btn", "btn-secondary");
let radio = document.createElement('input');
radio.type = "radio";
radio.name = this.name;
label.appendChild(radio);
let nb_options = this.selectionDiv.children.length;
if (nb_options == 0) {
label.classList.add("active");
radio.checked = true;
this.selectionDiv.appendChild(label);
} else {
this.selectionDiv.insertBefore(label, this.selectionDiv.children[nb_options-1]);
}
label.addEventListener('click', (event) => {
this.selectOption(name);
});
this.options[name] = value;
}
}
addSelectionChangeListener(listener) {
this.selectionChangeListeners.push(listener);
}
callSelectionChangeListeners(newVal, oldVal) {
for (let listener of this.selectionChangeListeners) {
listener(newVal, oldVal);
}
}
selectOption(name) {
let value = this.options[name];
if (this.selectedOption == value) {
return;
}
let old = this.selectedOption;
this.selectedOption = value;
this.callSelectionChangeListeners(value, old);
}
setColor(name, color) {
for (let c of this.selectionDiv.children) {
if(c.textContent == name) {
c.style["background-color"] = color;
}
}
}
}
class BooleanOption extends EnumOption {
constructor(name) {
super(name);
this.addOption("True", true);
this.addOption("False", false);
}
}
class GroupOption extends EnumOption {
get name() {
return null;
}
set name(n) {}
constructor() {
super("");
this.mainDiv.removeChild(this.nameLabel);
this.selectionDiv.parentNode.classList.add("mx-auto");
}
}
class NumberOption {
get div() {
return this.mainDiv;
}
get name() {
return this._name;
}
set name(n) {
this._name = n;
this.refreshNameLabel();
}
get min() {
return this._min;
}
set min(m) {
this._min = m;
this.refreshRangeInput();
}
get max() {
return this._max;
}
set max(m) {
this.max = m;
this.refreshRangeInput();
}
get step() {
return this._step;
}
set step(s) {
this._step;
this.refreshRangeInput();
}
constructor(name, min, max, step) {
this._min = min;
this._max = max;
this._step = step;
this._name = name;
let mainDiv = document.createElement('div');
mainDiv.classList.add("row", "w-100");
let selectionDiv = document.createElement('div');
selectionDiv.classList.add("col-auto");
let nameLabel = document.createElement("label");
nameLabel.classList.add("col");
let valueLabel = document.createElement("label");
valueLabel.style["visibility"] = "hidden";
let rangeInput = document.createElement("input");
rangeInput.type = "range";
rangeInput.disabled = true;
rangeInput.classList.add("mx-2");
rangeInput.addEventListener("input", (e) => {
valueLabel.textContent = rangeInput.value;
});
rangeInput.addEventListener("change", () => this.updateValue());
let disableCheckBox = document.createElement('input');
disableCheckBox.type = "checkbox";
disableCheckBox.addEventListener("change", () => {
this.rangeInput.disabled = !disableCheckBox.checked;
this.valueLabel.style["visibility"] = disableCheckBox.checked ? "visible" : "hidden";
this.updateValue();
this.callToggleListeners(disableCheckBox.checked);
})
this.mainDiv = mainDiv;
this.nameLabel = nameLabel;
this.rangeInput = rangeInput;
this.valueLabel = valueLabel;
this.disableCheckBox = disableCheckBox;
this.changeListeners = [];
this.toggleListeners = [];
this.value = 0;
this.mainDiv.appendChild(nameLabel);
selectionDiv.appendChild(valueLabel);
selectionDiv.appendChild(rangeInput);
selectionDiv.appendChild(disableCheckBox);
this.mainDiv.appendChild(selectionDiv);
this.value = this.rangeInput.value;
this.refreshRangeInput();
this.refreshNameLabel();
}
updateValue() {
let oldVal = this.value;
this.value = this.rangeInput.value;
this.callChangeListeners(this.value, oldVal);
}
addChangeListener(listener) {
this.changeListeners.push(listener);
}
callChangeListeners(newVal, oldVal) {
for (let listener of this.changeListeners) {
listener(newVal, oldVal);
}
}
addToggleListener(listener) {
this.toggleListeners.push(listener);
}
callToggleListeners(enabled) {
for (let listener of this.toggleListeners) {
listener(enabled);
}
}
refreshNameLabel() {
this.nameLabel.innerHTML = `${this.name} :`.bold();
}
refreshRangeInput() {
this.rangeInput.min = this.min;
this.rangeInput.max = this.max;
this.rangeInput.step = this.step;
this.rangeInput.value = this.min;
this.valueLabel.textContent = this.min;
}
}
<file_sep>/main_optimizer.py
import argparse
import os
import json
import shutil
import pandas as pd
from pandas.core.common import flatten
from vary.model.overleaf_util import fetch_overleaf
from vary.model.files.directory import clear_directory, create_temporary_copy, create_dir
from vary.model.files.tex_injection import inject_space_indicator
from vary.model.generation.generate import generate_random, generate_pdf
from vary.model.generation.compile import generate_bbl
from vary.model.decision_trees.analysis import decision_tree
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="Name of the file you want to compile")
parser.add_argument("-s", "--source", default=os.path.join(os.getcwd(),"vary/source"),
help="Path of the LaTeX source folder")
parser.add_argument("-v", "--verbose", action="store_true", help="Notifies when a PDF is generated")
parser.add_argument("-o", "--output", default=os.path.join(os.getcwd(), "vary/results"),
help="The path of the output folder")
parser.add_argument("-g", "--generations", default=10, type=int,
help="Amount of randomly generated configs used to generate the tree")
parser.add_argument("-ts", "--trainsize", default=100, type=int,
help="Percentage of the generations used to train the tree (the rest is used to calculate the \
accuracy)")
parser.add_argument("-ol", "--overleaf",
help="Key of the readonly link of the project on Overleaf (the letters avter '/read/'). \
It needs to have a 'values.json' file and the document must include 'macros' and 'values'")
parser.add_argument("-c", "--config", help="Generate a specific PDF from a config JSON string")
parser.add_argument("-p", "--maxpages", type=int, help="The maximum amount of pages accepted for the document")
args = parser.parse_args()
document_path = args.source
filename = args.filename.replace(".tex","")
if args.overleaf:
clear_directory(document_path)
fetch_overleaf(args.overleaf, document_path)
temp_path = create_temporary_copy(document_path)
conf_source_path = os.path.join(document_path, "variables.json")
with open(conf_source_path) as f:
conf_source = json.load(f)
# DataFrame initialisation
cols = conf_source["booleans"] + \
list(conf_source["numbers"].keys()) + \
list(conf_source["enums"].keys()) + \
list(flatten(conf_source["choices"])) + \
["nbPages", "space"]
df = pd.DataFrame(columns=cols)
file_path = os.path.join(temp_path, filename)
inject_space_indicator(file_path)
# LaTeX bbl pregeneration
generate_bbl(file_path)
# ----------------------------------------
# PDF generation
# ----------------------------------------
if args.config:
row = generate_pdf(json.loads(args.config), filename, temp_path)
pdf_name = filename+".pdf"
shutil.copyfile(os.path.join(temp_path, pdf_name), os.path.join(args.output, pdf_name))
else:
for i in range(args.generations):
row = generate_random(conf_source, filename, temp_path)
df = df.append(row, ignore_index=True)
if args.verbose:
print(f"Doc {i} generated")
# Clean working directory
shutil.rmtree(temp_path)
# Create the output directory
create_dir(args.output)
# Export results to CSV
result_path = os.path.join(args.output, "result.csv")
df.to_csv(result_path)
# ----------------------------------------
# Decision Tree Analysis
# ----------------------------------------
if args.config:
exit() # Not useful for single generation
# Percentage of the sample used to create the tree
# When using the tool we could use 100% of the data as we want the tree to be as precise as possible
perc = args.trainsize
if args.maxpages:
decision_tree(result_path, args.maxpages, perc, args.output)
<file_sep>/vary/views/__init__.py
import vary.views.compile
import vary.views.index
import vary.views.constraints
import vary.views.project_files
import vary.views.select_mode
import vary.views.free_config<file_sep>/vary/model/overleaf_util.py
# from bs4 import BeautifulSoup # Useful if we use an account or retrieve the CSRF token from the login page
import requests
import re
import json
import zipfile
import os
def fetch_overleaf(invite_key, output_folder):
"""
Gets the content of a LaTeX project on Overleaf, from a READ-ONLY invite link and exports it to the output folder
"""
if not re.match("[a-z]+", invite_key):
os.write(2, b"This is not a valid invite key. The invite key is the group of letters " +
b"after the '/read/' in the read-only link\n")
exit()
invite_url = "https://www.overleaf.com/read/" + invite_key
grant_url = invite_url + "/grant"
session = requests.Session()
# Login
# Not necessary unless you want to import a project with a read / write link
#
# email = INSERT EMAIL
# password = <PASSWORD>
# login_url = "https://www.overleaf.com/login"
# r = session.get(login_url)
# csrf = BeautifulSoup(r.text, 'html.parser').find('input', { 'name' : '_csrf' })['value']
# r = session.post(login_url, { '_csrf' : csrf , 'email' : email , 'password' : <PASSWORD> })
# Loads the invite page on the website to get the cookies
r = session.get(invite_url)
# Headers of the post request
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Content-Type": "application/json;charset=utf-8",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0",
"Host": "www.overleaf.com",
"Origin": "https://www.overleaf.com",
"TE": "Trailers",
"Content-Length": "48"
}
# CSRF token used to validate the POST request
csrf = re.search('window.csrfToken = "([^"]*)";', r.content.decode("utf-8")).group(1)
# Solution without having to search for the csrf token in the javascript page
# It seems to be possible to use the csrf token found on the login page to do the post
#
# r = session.get(login_url)
# csrf = BeautifulSoup(r.text, 'html.parser').find('input', { 'name' : '_csrf' })['value']
data = '{"_csrf":"%s"}' % csrf
# POST request that allows the user to access the document
r = session.post(
grant_url,
data=data,
cookies=session.cookies,
headers=headers
)
# Real path of the project
project_path = json.loads(r.content)['redirect']
zip_name = "sources.zip"
download_url = "https://www.overleaf.com%s/download/zip" % project_path
# Download the project
r = session.get(download_url, stream=True)
# Write the response to a zip file
with open(zip_name, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
# Extract the file to the specified folder
with zipfile.ZipFile("sources.zip", "r") as zip_ref:
zip_ref.extractall(output_folder)
# Clean the archive
os.remove(zip_name)
<file_sep>/vary/example/fse/lemonde.js
if ( navigator.userAgent.toLowerCase().indexOf('google') === -1 &&
navigator.userAgent.toLowerCase().indexOf('msnbot') === -1 &&
navigator.userAgent.toLowerCase().indexOf('yahoo!') === -1 &&
document.referrer.toLowerCase().indexOf('google') === -1 &&
document.referrer.toLowerCase().indexOf('bing.com') === -1 &&
document.referrer.toLowerCase().indexOf('search.yahoo') === -1 ) {
document.getElementById('articleBody').innerHTML = document.getElementById('articleBodyRestreint').innerHTML;
document.getElementById('teaser_article').style.display = 'block'; }<file_sep>/vary/model/files/tex_injection.py
import os
import re
import math
from vary.model.files.dictionnaries import merge_dicts, merge_configs
def inject_space_indicator(file_path):
"""
Adds a command to the main .tex file to write the remaining space on the PDF at the end of the document.
The result of the LaTeX command is an output in a file called "space.txt" with the space left.
The "space.txt" file is created during the PDF generation.
"""
file_path_tex = file_path + ".tex"
to_inject = \
"\\newwrite\\writeRemSpace\n"+\
"\\immediate\\openout\\writeRemSpace=space.txt\n"+\
"\\immediate\\write\\writeRemSpace{\\the\\dimexpr\\pagegoal-\\pagetotal-\\baselineskip\\relax}\n"+\
"\\immediate\\closeout\\writeRemSpace\n"
pattern = re.compile(r"^[^%]*\\end{document}")
with open(file_path_tex, 'r+') as file:
lines = file.readlines()
doc_end_line = 0
for line in reversed(lines):
doc_end_line -= 1
if pattern.match(line):
break
lines.insert(doc_end_line, to_inject)
file.seek(0) # Go back to the beginning of the file
file.writelines(lines)
def get_remaining_space(path):
"""
Retrieves the remaining space calculated during the PDF build by the space indicator command.
It does it by reading the "space.txt" log file where it was written.
"""
space_file_path = os.path.join(path, "space.txt")
with open(space_file_path) as f:
content = f.read()
return float(content[:-3])
def get_sub_files(main_file_path):
"""
Gets the list of the tex files included in the document
"""
pattern = re.compile(r"^[^%]*\\(?:input|include)\{([^}]*)}") # the "in" prefix is not excluded for readability
sub_files = []
with open(main_file_path, 'r') as f:
for line in f.readlines():
match = pattern.match(line)
if match:
sub_files.append(match.group(1))
return sub_files
def add_graphics_variables_to_file(file_path):
"""
Looks for all the 'includegraphics' commands in the file and extracts a variation point on the height/width/size.
Returns a dictionary with the name of the variables as the keys and their initial values as the values.
"""
dir_path, filename = os.path.split(file_path)
if not filename.endswith(".tex"):
filename += ".tex"
file_path = os.path.join(dir_path, filename)
if not os.path.isfile(file_path):
return {}
graphics_pattern = re.compile(r"^[^%]*(\\includegraphics\[([^\]]*)\]\{([^}]*)}).*")
param_pattern = re.compile(r"(\w+)\s*=\s*([\d.]+)(.*)")
variables = {}
with open(file_path, "r+") as f:
lines = f.readlines()
for i, line in enumerate(lines):
match = graphics_pattern.match(line)
if match:
param = match.group(2)
graphics_filename = match.group(3)
param_match = param_pattern.match(param)
if param_match:
param_name = param_match.group(1)
param_default_val = param_match.group(2)
param_unit = param_match.group(3)
var_name = param_name+"_"+graphics_filename
variables[var_name] = float(param_default_val)
newline = line.replace(
match.group(1),
fr"\includegraphics[{param_name}=\getVal{{{var_name}}}{param_unit}]{{{graphics_filename}}}"
)
lines[i] = newline
f.seek(0)
f.writelines(lines)
return variables
def float_variable_to_range(variable):
"""
Creates a range of values based on a central float value.
The result is an array with the minimum being 70% of the original value and the maximum being 130%.
The last element of the array is the digit precision, so the step is around
one 100th of the magnitude of the original value
"""
precision = round(2-math.log10(variable))
min_val = round(variable*0.7, precision)
max_val = round(variable*1.3, precision)
return [min_val, max_val, precision]
def add_graphics_variables(main_file_path):
base_path = os.path.dirname(main_file_path)
subfiles = [os.path.join(base_path, name) for name in get_sub_files(main_file_path)]
subfiles.append(main_file_path)
variables = {}
for file_path in subfiles:
set_values = add_graphics_variables_to_file(file_path)
variables = merge_dicts(variables, {k: float_variable_to_range(v) for k, v in set_values.items()})
config_path = os.path.join(base_path, "variables.json")
merge_configs(config_path, {"numbers": variables})
def add_include_macros_variables(main_file_path):
to_inject = ""
with open(main_file_path) as f:
content = f.read()
try:
content.index(r"\include{macros}")
except ValueError:
to_inject += "\\include{macros}\n"
try:
content.index(r"\include{values}")
except ValueError:
to_inject += "\\include{values}\n"
if to_inject:
documentclass_pattern = re.compile(r"\\documentclass(\[[^\]]*\])*{[^}]*}")
with open(main_file_path, "r+") as f:
lines = f.readlines()
for index, line in enumerate(lines):
match = documentclass_pattern.search(line)
if match:
break
if match:
lines.insert(index + 1, to_inject)
f.seek(0)
f.writelines(lines)
def add_itemsep_variable(main_file_path):
include_values_pattern = re.compile(r"\\include{values}")
with open(main_file_path, "r+") as f:
lines = f.readlines()
for index, line in enumerate(lines):
match = include_values_pattern.search(line)
if match:
break
if match:
lines.insert(index + 1, r"\setlength\itemsep{\getVal{itemsep}pt}")
f.seek(0)
f.writelines(lines)
itemsep_dict = {"numbers": {"itemsep": [-5, 5, 1]}}
base_path = os.path.dirname(main_file_path)
config_path = os.path.join(base_path, "variables.json")
merge_configs(config_path, itemsep_dict)
<file_sep>/vary/model/generation/subcall.py
import subprocess
TIMEOUT = 15
def run_command(command, working_directory):
"""
Calls a subprocess with the specified command.
Throws subprocess.TimeoutExpired if the program takes more than TIMEOUT seconds.
"""
process = subprocess.Popen(
command, cwd=working_directory,
stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
close_fds=True
)
process.wait(timeout=TIMEOUT)
if process is not None:
process.kill()
<file_sep>/vary/static/js/selectfile.js
let selection = '';
let selected = false;
$('document').ready(function(){
$.get('/filenames', function(res) {
let names = JSON.parse(res);
let select = $("#file_select");
console.log(names);
for(filename of names) {
let opt = document.createElement('option');
opt.value = filename;
opt.text = filename;
select.append(opt);
}
})
});
function selection_changed() {
let select = document.getElementById("file_select");
let option = select.options[select.selectedIndex];
selected = true;
selection = option.value;
}<file_sep>/vary/views/index.py
import os
import zipfile
from flask import flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from vary import app, ALLOWED_EXTENSIONS
from vary.model.overleaf_util import fetch_overleaf
from vary.model.files.directory import clear_directory
from vary.model.files.dictionnaries import init_variables_json
@app.route('/', methods=["GET", "POST"])
def index():
"""
First page, which gives a choice between two methods for selecting a project.
"""
return render_template('index.html')
@app.route('/upload_project', methods=['POST'])
def upload_project():
if 'file' not in request.files:
flash('No file part in the request')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if check_filename(file.filename):
upload_folder = app.config['UPLOAD_FOLDER']
clear_directory(upload_folder) # Delete potential previous project
filename = secure_filename(file.filename)
filepath = os.path.join(upload_folder, filename)
file.save(filepath)
flash('Project uploaded !')
with zipfile.ZipFile(filepath, "r") as zip_ref:
zip_ref.extractall(upload_folder)
os.remove(filepath)
init_variables_json(upload_folder)
return redirect(url_for('selectfile'))
@app.route('/import_overleaf', methods=['POST'])
def import_overleaf():
upload_folder = app.config['UPLOAD_FOLDER']
key = request.form.get('key')
clear_directory(upload_folder) # Delete potential previous project
fetch_overleaf(key, upload_folder)
return redirect(url_for('selectfile'))
def check_filename(filename):
"""
Checks the name of an uploaded file to make sure it has the right format
"""
return "." in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS<file_sep>/README.md
# VaryLaTeX
How to submit a research paper, a technical report, a grant proposal , or a curriculum vitae that respect imposed constraints such as formatting instructions and page limits? It is a [challenging](https://twitter.com/mark_riedl/status/1219800144188772354) [task](https://twitter.com/zacharylipton/status/1282700969386684422), especially when coping with time pressure, isn't it?
**With VaryLaTeX, simply drop your archive into your Web browser! VaryLaTeX makes automatically vary your PDF to fit the pages limit... and if you're unhappy, you can still control different aspects of your document with a configurator.**

http://phdcomics.com/comics.php?f=1971
VaryLaTeX is a solution based on variability, constraint programming , and machine learning techniques for documents written in LaTeX to meet constraints and deliver on time. VaryLaTeX allows users annotating LaTeX source files with variability information, e.g., (de)activating portions of text, tuning figures' sizes, or tweaking line spacing. Then, a fully automated procedure learns constraints among Boolean and numerical values for avoiding non-acceptable paper variants, and finally, users can further configure their papers (e.g., aesthetic considerations) or pick a (random) paper variant that meets constraints, e.g., page limits.
*Feel free to contribute, suggest features, provide feedbacks, use cases*
There is a short demonstration: https://www.youtube.com/watch?v=u1ralqbHCyM&list=PLcDsXHkK7hJ3n9v7VAMbZCIV6egreI8OL and some technical explanations in this Youtube playlist
## How to run VaryLaTeX?
To run it, you need have `texlive` and `python` (3) installed, then
```
pip install -r requirements.txt
python main_server.py
```
If it does not work, you may want to use `python3` and `pip3` instead of `python` and `pip`.
The app can then be accessed in a browser at [0.0.0.0:5000](http://0.0.0.0:5000/).
You can also run the app within a `Docker` container : to do this, install docker then, in the project folder
```bash
# Create the image
sudo docker build -t varylatex .
# Create the container
sudo docker run -it --rm -p 5000:5000 varylatex
```
And inside the container you can run
```bash
python main_server.py
```
To learn about the implementation and the choices that were made for the project, see [about.md](docs/about.md).
## Contributors
It's a complete rewrite/extension of https://github.com/FAMILIAR-project/varylatex (originally written in Java, Bash scripts, and some R code).
To re-initiate the work, we build upon the implementation described on this blog post [LaTeX writing as a constrained non-convex optimization problem](https://blog.martisak.se/2020/06/06/latex-optimizer/) and available on gitlab: https://gitlab.com/martisak/latex-optimizer/
(note: "fork" of gitlab as described here: http://ruby.zigzo.com/2015/03/23/moving-from-gitlab-to-github/)
<NAME> realized the whole implementation during an internship at [DiverSE](https://www.diverse-team.fr/)
## Publications
More details can be found in the following paper, published/presented at 12th International Workshop on Variability Modelling of Software-Intensive Systems https://vamos2018.wordpress.com/:
"VaryLaTeX: Learning Paper Variants That Meet Constraints" by <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>: https://hal.inria.fr/hal-01659161/
<file_sep>/vary/model/files/dictionnaries.py
import os
import json
def merge_configs(json_config_path, config):
"""
Adds the variables contained in config to the json config file
"""
with open(json_config_path) as f:
conf_source = json.load(f)
res_conf = merge_dicts(conf_source, config)
with open(json_config_path, 'w') as f:
json.dump(res_conf, f, indent=4)
def merge_dicts(base_dict, second_dict):
"""
Recursively creates a dictionary with the contents of two dicts.
In case of a key conflicts, the dicts are merged, the arrays are concatenated and the values are replaced by
the ones of the second dict.
"""
output_dict = base_dict.copy()
for key, value in second_dict.items():
if key in base_dict:
if type(value) == list:
output_dict[key] += value
elif type(value) == dict:
output_dict[key] = merge_dicts(output_dict[key], value)
else:
output_dict[key] = value
else:
output_dict[key] = value
return output_dict
def init_variables_json(path):
"""
Sets up the "variables.json" file if it is empty or incomplete.
"""
json_path = os.path.join(path, "variables.json")
open(json_path, 'a').close() # Creates the file if it is missing
with open(json_path, 'r+') as f:
if not f.read(): # If the file is empty (or has just been created)
f.write("{}")
template = {
"booleans": [],
"numbers": {},
"enums": {},
"choices": []
}
merge_configs(json_path, template)
<file_sep>/vary/model/decision_trees/analysis.py
# Based on this example on DecisionTrees with scikit learn :
# http://chrisstrelioff.ws/sandbox/2015/06/08/decision_trees_in_python_with_scikit_learn_and_pandas.html
# Basic imports
import os
import subprocess
# Data manipulation imports
from sklearn.tree import DecisionTreeClassifier, export_graphviz
import pandas as pd
def visualize_tree(tree, feature_names, output_path):
"""
Creates a PNG image of a decision tree and exports it in the folder specified bu output_path.
The name of the image is dt.png.
"""
dot_path = os.path.join(output_path, "dt.dot")
img_path = os.path.join(output_path, "dt.png")
with open(dot_path, 'w') as f:
export_graphviz(tree, out_file=f,
feature_names=feature_names,
filled=True,
special_characters=True,
rounded=True,
class_names=list(map(str, tree.classes_)))
command = ["dot", "-Tpng", dot_path, "-o", img_path]
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
exit("Could not run dot, ie graphviz, to "
"produce visualization")
def load_csv(csv_path):
"""
Creates a dataframe based on the CSV path
"""
return pd.read_csv(csv_path, index_col=0)
def refine_csv(df):
"""
Transforms the categorical values (typically strings) of the sets into integers that could
be exploited by the DecisionTree. It uses the One-hot method.
"""
# Set of categorical values
cat_vals = set()
# Change string (seen as objects) values to booleans
for col_name, col_type in dict(df.dtypes).items():
if col_type == 'O': # If this is a column of objects (true for strings)
df = pd.concat([df, pd.get_dummies(df[col_name], prefix=col_name)], axis=1)
cat_vals.add(col_name)
# Get all the features except the class (nbPages), the remaining space, and initial categorical features
features = list(set(df.columns) - set(["nbPages", "space"]) - cat_vals)
return df, features
def get_sample_size(df, perc):
"""
The size of the training set based on a percentage of the total dataframe
"""
return int(len(df)*float(perc)/100)
def split_frame(df, features, sample_size, max_pages):
"""
Separates the dataframe into training and testing set and gives the results for every entry
"""
y = (df["nbPages"] <= max_pages) & (df["space"] >= 0)
train = df[features][:sample_size]
test = df[features][sample_size:]
return train, test, y
def create_dt(train, y, sample, min_samples_split=10, random_state=99):
dt = DecisionTreeClassifier(min_samples_split=min_samples_split, random_state=random_state)
dt.fit(train, y[:sample])
return dt
def decision_tree(csv_path, max_pages, perc=100, output_path=None):
"""
Returns the classifier and the array of the feature names
"""
df = load_csv(csv_path)
# Replace string values by booleans with one-hot method
df, features = refine_csv(df)
sample_size = get_sample_size(df, perc)
train, test, y = split_frame(df, features, sample_size, max_pages)
classifier = create_dt(train, y, sample_size, min_samples_split=4)
# Only useful for testing, but we may use 100% of the data for training, and skip the computing of the accuracy
if perc < 100:
print("Accuracy :", classifier.score(test, y[sample_size:]))
# Generate a .dot and a .png file of the tree if there is an output path
if output_path:
visualize_tree(classifier, features, output_path)
return classifier, features
def predict(classifier, config, config_src, features):
"""
Uses tre decision tree to estimate the probability of a config (which can have incomplete data)
to match the target class
"""
internal_tree = classifier.tree_
# Modify the config to adapt categorical values
newconfig = config.copy()
for name in config_src["enums"]:
val = config.get(name)
if val:
del newconfig[name]
for possible_value in config_src["enums"][name]:
temp_name = pd.get_dummies(possible_value, prefix=name).columns[0]
newconfig[temp_name] = 0
newname = pd.get_dummies(val, prefix=name).columns[0]
newconfig[newname] = 1
# Go through the nodes and store the population for each class in the accumulator
def recurse(node_id, acc):
# End condition : leaf node
if internal_tree.children_right[node_id] == internal_tree.children_left[node_id]:
# Add the populations of the leaf to the accumulator
res = list(map(sum, zip(acc, list(internal_tree.value[node_id][0]))))
return res
# The feature used in this node
ft = features[internal_tree.feature[node_id]]
value = newconfig.get(ft)
# If the value is defined then follow the corresponding path, otherwise work on the populations
# on the two branches
if value is not None:
if value == "true":
value = 1
if value == "false":
value = 0
if float(value) > internal_tree.threshold[node_id]:
return recurse(internal_tree.children_right[node_id], acc)
else:
return recurse(internal_tree.children_left[node_id], acc)
else:
new_acc = recurse(internal_tree.children_right[node_id], acc)
return recurse(internal_tree.children_left[node_id], new_acc)
pop = recurse(0, [0]*internal_tree.n_classes[0])
total = sum(pop)
classes = list(classifier.classes_)
if True not in classes:
return 0
target_index = classes.index(True)
return pop[target_index] / total
def eval_options(classifier, config, config_src, features):
"""
For a given config, evaluates the probability for a config one change away to match the target class.
Returns a dictionary similar to a configuration source but with probabilities.
Structure :
{
"enums" : {
<e_name1> : {
"default" : <proba_default>,
"values" : {
<val1_1> : <e_prob1_1>,
...
<val1_n> : <e_prob1_n>
}
},
<e_name2> : { ... },
...
},
"booleans" : {
<b_name1> : {
"default" : <b_prob1>
"false" : <b_prob1_false>,
"true" : <b_prob1_true>,
},
<b_name2> : { ... }
},
"choices" : {
<c_name1> : <c_prob1>,
<c_name2> : <c_prob2>,
...
},
"numbers" : {
<n_name1> : {
"default" : <n_prob1>,
"limits" [
{"lower" : <lower_1_1>, "upper" : <upper_1_1>, "prob" : <n_prob1_1>},
{"lower" : <lower_1_2>, "upper" : <upper_1_2>, "prob" : <n_prob1_2>},
{ ... },
...
]
}
}
}
"""
prob_dict = {}
temp_cfg = config.copy()
# enums
enums = {}
for name, values in config_src["enums"].items():
enums[name] = {}
probas = {}
for val in values:
temp_cfg[name] = val
probas[val] = predict(classifier, temp_cfg, config_src, features)
del temp_cfg[name]
enums[name]["default"] = predict(classifier, temp_cfg, config_src, features)
if name in config:
temp_cfg[name] = config[name]
enums[name]["values"] = probas
prob_dict["enums"] = enums
# booleans
booleans = {}
for name in config_src["booleans"]:
probas = {}
for val in [True, False]:
temp_cfg[name] = val
probas[val] = predict(classifier, temp_cfg, config_src, features)
del temp_cfg[name]
probas["default"] = predict(classifier, temp_cfg, config_src, features)
if name in config:
temp_cfg[name] = config[name]
booleans[name] = probas
prob_dict["booleans"] = booleans
# choices
choices = {}
for group in config_src["choices"]:
selected_value = None
for name in group:
if name in temp_cfg:
del temp_cfg[name]
if name in config:
selected_value = name
for name in group:
temp_cfg[name] = True
choices[name] = predict(classifier, temp_cfg, config_src, features)
del temp_cfg[name]
if selected_value:
temp_cfg[selected_value] = config[selected_value]
prob_dict["choices"] = choices
# numbers
numbers = {}
for name, domain in config_src["numbers"].items():
numbers[name] = {}
min_bound, max_bound, _ = domain
numbers[name]["limits"] = []
internal_tree = classifier.tree_
thresholds = \
[min_bound] + \
[internal_tree.threshold[i] for i, n in enumerate(internal_tree.feature) if n >= 0 and features[n] == name] + \
[max_bound]
thresholds.sort()
for lower, upper in (zip(thresholds[:-1], thresholds[1:])):
average = (lower + upper) / 2
temp_cfg[name] = average
numbers[name]["limits"].append({
"lower": lower,
"upper": upper,
"prob": predict(classifier, temp_cfg, config_src, features)
})
del temp_cfg[name]
numbers[name]["default"] = predict(classifier, temp_cfg, config_src, features)
if name in config:
temp_cfg[name] = config[name]
prob_dict["numbers"] = numbers
return prob_dict
<file_sep>/vary/views/constraints.py
import os
import json
from flask import render_template, send_from_directory, request
from vary import app, RESULT_FOLDER
from vary.model.decision_trees.analysis import eval_options, decision_tree, visualize_tree
@app.route('/constraints')
def constraints():
return render_template("constraints.html")
@app.route('/tree_img')
def get_tree():
response = send_from_directory("results", 'dt.png')
response.headers['Cache-Control'] = 'no-store'
return response
@app.route("/predict/<int:max_pages>", methods=["POST"])
def predict(max_pages):
config = request.json
conf_source_path = os.path.join(app.config["UPLOAD_FOLDER"], "variables.json")
with open(conf_source_path) as f:
conf_source = json.load(f)
csv_path = os.path.join(RESULT_FOLDER, "result.csv")
classifier, features = decision_tree(csv_path, max_pages)
tree_path = os.path.join(RESULT_FOLDER, "dt.png")
visualize_tree(classifier, features, RESULT_FOLDER)
probas = eval_options(classifier, config, conf_source, features)
return json.dumps(probas)
<file_sep>/vary/model/generation/analyze_pdf.py
import fitz
from intervaltree import IntervalTree, Interval
def page_count(pdf_path):
"""
Counts the number of pages in a PDF file
"""
document = fitz.open(pdf_path)
return int(document.pageCount)
<file_sep>/vary/model/generation/generate.py
import os
import random
import json
import pandas as pd
from pandas.core.common import flatten
from pathlib import Path
from vary.model.files.directory import create_temporary_copy, remove_directory
from vary.model.files.tex_injection import inject_space_indicator, get_remaining_space
from vary.model.generation.compile import generate_bbl
from vary.model.generation.inject import write_variables
from vary.model.generation.compile import compile_latex
from vary.model.generation.analyze_pdf import page_count
def random_config(conf_source, fixed_values={}):
"""
Generates a config dictionnary based on the range of values provided from a dictionnary containing the following keys :
"booleans", "numbers", "enums" and "choices".
Booleans are either true or false and only their names need to be specified.
Numbers are represented with the variable name as the key, and a tuple (min_val, max_val, precision) as the value.
Enums are variables that can have one value from a list provided as the value in the dictionnary.
Choices are groups of booleans where exactly one can be true at a time. They are provided as a list of lists.
"""
config = {}
if "booleans" in conf_source:
for boolean in conf_source["booleans"]:
config[boolean] = fixed_values[boolean] if boolean in fixed_values else random.choice([True, False])
if "numbers" in conf_source:
for var_name, params in conf_source["numbers"].items():
if var_name in fixed_values:
config[var_name] = fixed_values[var_name]
else:
min_bound, max_bound, precision = params
config[var_name] = round(random.uniform(min_bound, max_bound), precision)
if "enums" in conf_source:
for var_name, options in conf_source["enums"].items():
config[var_name] = fixed_values[var_name] if var_name in fixed_values else random.choice(options)
if "choices" in conf_source:
for options in conf_source["choices"]:
selection = random.choice(options)
for o in options:
if o in fixed_values and fixed_values[o]:
selection = o
for o in options:
config[o] = o == selection
return config
def generate_pdf(config, filename, temp_path):
"""
Builds a PDF with the values defined in config. The bibliography should already be loaded.
Returns a dictionnary with the config and the calculated values of the PDF (number of pages, space left).
"""
filename_tex = filename + ".tex"
filename_pdf = filename + ".pdf"
tex_path = os.path.join(temp_path, filename_tex)
pdf_path = os.path.join(temp_path, filename_pdf)
write_variables(config, temp_path)
compile_latex(tex_path)
row = config.copy()
row["nbPages"] = page_count(pdf_path)
row["space"] = get_remaining_space(temp_path)
return row
def generate_random(conf_source, filename, temp_path, fixes_values={}):
"""
Builds a PDF from a random config based on conf_source.
Returns a dictionary with the config and the calculated values of the PDF (number of pages, space left).
"""
config = random_config(conf_source, fixes_values)
return generate_pdf(config, filename, temp_path)
def generate_pdfs(filename, source, output, nb_gens, reset=True, fixed_values = {}):
"""
Creates as many PDFs as specified with nb_gens, from a random config based on conf_source, and calculate
their values. The config and values are stored in a "result.csv" file in the output directory.
If reset is set to False and there is already a result file, the results are appended to the previous ones.
"""
temp_path = create_temporary_copy(source) # Create the temporary working directory
file_path = os.path.join(temp_path, filename)
inject_space_indicator(file_path)
generate_bbl(file_path) # LaTeX bbl pregeneration
# Load the variables
conf_source_path = os.path.join(source, "variables.json")
with open(conf_source_path) as f:
conf_source = json.load(f)
# DataFrame initialisation
csv_result_path = os.path.join(output, "result.csv")
df = _create_df(conf_source) if reset else pd.read_csv(csv_result_path, index_col=0)
for _ in range(nb_gens):
row = generate_random(conf_source, filename, temp_path, fixed_values)
df = df.append(row, ignore_index=True)
# Clean working directory
remove_directory(temp_path)
# Create the output directory
Path(output).mkdir(parents=True, exist_ok=True)
# Export results to CSV
df.to_csv(csv_result_path)
def _create_df(conf_source):
cols = conf_source["booleans"] \
+ list(conf_source["numbers"].keys()) \
+ list(conf_source["enums"].keys()) \
+ list(flatten(conf_source["choices"])) \
+ ["nbPages", "space"]
return pd.DataFrame(columns=cols)
<file_sep>/vary/views/compile.py
import os
import json
from flask import session, send_from_directory, request, g
from shutil import copyfile
from vary import app
from vary.model.generation.compile import generate_bbl
from vary.model.generation.generate import generate_random, generate_pdfs
from vary.model.files.directory import create_temporary_copy, remove_directory
from vary.model.files.tex_injection import inject_space_indicator
@app.route('/generate_pdfs/<int:generations>', methods=["POST"])
def compile_pdfs(generations, reset=True):
"""
Builds the specified amount of documents. If reset is set to True,
discards the data about the previouslly generated documents.
"""
output = "vary/results"
fixed_values = request.json or {}
filename = session['main_file_name'].replace(".tex", "") # main file name without extension
source = app.config['UPLOAD_FOLDER'] # The project is located in the "source" folder
generate_pdfs(filename, source, output, generations, reset, fixed_values)
return send_from_directory("results", "result.csv")
@app.route('/add_pdfs/<int:generations>', methods=["POST"])
def add_pdfs(generations):
"""
Builds the specified amount of documents and append them to the previously generated ones.
"""
return compile_pdfs(generations, reset=False)
@app.route('/build_pdf', methods=['GET', 'POST'])
def build_pdf():
"""
Creates and returns a PDF that follows the specified configuration.
If some variables are not specified, a random value is chosen for it.
"""
filename = session['main_file_name'].replace(".tex", "")
if request.method == "GET":
resp = send_from_directory("results", filename + ".pdf")
resp.headers['Cache-Control'] = 'max-age=0, no-cache, must-revalidate'
return resp
config = request.json
output = "vary/results"
source = os.path.join(app.config['UPLOAD_FOLDER'])
temp_path = create_temporary_copy(source)
file_path = os.path.join(temp_path, filename)
inject_space_indicator(file_path)
generate_bbl(file_path)
conf_source_path = os.path.join(source, "variables.json")
with open(conf_source_path) as f:
conf_source = json.load(f)
generate_random(conf_source, filename, temp_path, config)
outpath = os.path.join(output, filename + ".pdf")
if os.path.exists(outpath):
os.remove(outpath)
copyfile(
os.path.join(temp_path, filename + ".pdf"),
os.path.join(outpath)
)
remove_directory(temp_path)
return '{"success":true}', 200, {'ContentType': 'application/json'}
<file_sep>/requirements.txt
Flask==1.1.2
intervaltree==3.0.2
PyMuPDF==1.17.1
pandas==1.0.5
requests==2.22.0
scikit-learn==0.23.1<file_sep>/vary/views/select_mode.py
from flask import render_template
from vary import app
@app.route("/mode")
def mode():
return render_template("select_mode.html")
| d1b4afee1e329160409f8a4d24900cceb1f17716 | [
"JavaScript",
"Markdown",
"Python",
"Text",
"R",
"Dockerfile"
] | 33 | JavaScript | diverse-project/varylatex | 71186926f3c182720fe3859401a25462a1e4c824 | 648c19660cee625c36814ea393e02c8431b611af |
refs/heads/master | <file_sep>package ness.tomerbu.edu.cam;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private int REQUEST_CAMERA = 10;
ImageView ivImageCapture;
private File imageFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ivImageCapture = (ImageView) findViewById(R.id.ivImageCapture);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
takePicture();
}
});
}
//OnClick On Fab...
private void takePicture() {
if (checkCallingOrSelfPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
PackageManager.PERMISSION_GRANTED){
requestPermissions(
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CAMERA);
return;
}
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
File folder = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
imageFile = File.createTempFile("temp", "jpg", folder);
//String path = imageFile.getAbsolutePath();
Uri uri = FileProvider.getUriForFile(this,
"ness.tomerbu.edu.cam.fileprovider",
imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CAMERA);
} catch (IOException e) {
e.printStackTrace();
}
}
//Response of permission
onRequestPermissionResult(){
if (requestCode == REQUEST_CAMERA &&
granted[0]==PackageManager.PERMISSION_GRANTED){
takePicture();
}
else {
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show()
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) {
super.onActivityResult(requestCode, resultCode, resultIntent);
//Get the thumbnail:
//Bitmap thumbnail = resultIntent.getParcelableExtra("data");
//ivImageCapture.setImageBitmap(thumbnail);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ivImageCapture.setImageBitmap(bitmap);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 728ebf8ca801a8833453e304bfe8d0ae9be299b3 | [
"Java"
] | 1 | Java | nesscollege2016/Cam | 7c8b0a105f4faa1f8ed65de4c704393711e99fb1 | 1057dda4ac22473fbc537a9340088f5391dc5555 |
refs/heads/master | <repo_name>mortonfox/ft-starter<file_sep>/server/models/person.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, createdModifiedPlugin = require('mongoose-createdmodified').createdModifiedPlugin;
/**
* Getters
*/
var getNicknames = function (nicknames) {
return nicknames.join(',');
};
/**
* Setters
*/
var setNicknames = function (nicknames) {
return nicknames.split(',');
};
/**
* Person Schema
*/
var PersonSchema = new Schema({
name: {
type : String,
default : '',
trim : true
},
age: Number,
gender: {
type: String,
default : 'unspecified',
enum: ['male', 'female', 'unspecified'],
},
nicknames: {
type: [],
get: getNicknames,
set: setNicknames
},
friends: [{
type: Schema.Types.ObjectId,
ref: 'Person'
}]
});
/**
* Virtuals
*/
PersonSchema.virtual('friendCount').get(function(){
return this.friends.length;
});
// Ensure virtuals are serialised.
PersonSchema.set('toJSON', {virtuals: true});
PersonSchema.set('toObject', {virtuals: true});
/**
* Plugins
*/
PersonSchema.plugin(createdModifiedPlugin, {index: true});
/**
* Validations
*/
PersonSchema.path('name').required(true, 'Person name cannot be blank');
/**
* Hooks
*/
PersonSchema.pre('remove', function (next) {
console.log('Goodbye, ' + this.name);
next();
});
/**
* Methods
*/
Schema.methods = {
giveTitle: function (title, cb) {
this.name = title + " " + this.name;
this.save(cb);
}
};
/**
* Statics
*/
PersonSchema.statics = {
load: function (options, cb) {
var criteria = options.criteria || {};
var populate = options.populate || [];
var select = options.select || '';
this.findOne(criteria)
.select(select)
.populate(populate)
.exec(cb);
},
// use to create custom statics (like 'retired/deleted')
list: function (options, cb) {
var criteria = options.criteria || {};
var sort = options.sort || { createdAt: -1 };
var limit = options.limit === 0 ? 0 : (options.limit || 10);
var page = options.page || 0;
var populate = options.populate || [];
var select = options.select || '';
this.find(criteria)
.select(select)
.populate(populate)
.sort(sort)
.limit(limit)
.skip(limit * page)
.exec(cb);
}
};
exports = module.exports = mongoose.model('Person', PersonSchema);
<file_sep>/app/router.js
var Router = Ember.Router.extend(); // ensure we don't share routes between all Router instances
Router.map(function() {
this.route('login');
this.route('logout');
this.route('signup');
this.route('people');
this.route('protected');
this.resource('person', { path: '/people/:person_id' });
this.route('edit-person', { path: '/people/:person_id/edit' });
this.route('new-person', { path: '/people/new' });
});
export default Router;
<file_sep>/server/controllers/people.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
, Person = mongoose.model('Person');
/**
* Middleware
*/
// attach objects from params, etc
/**
* Request handlers
*/
/**
* Find all people.
*
* @returns {object} person
*/
// app.get('/api/people/', people.index);
exports.index = function(req, res, next) {
Person.list({}, function(err, people) {
if (err) return next(err);
res.send({ person: people });
});
};
/**
* Find person by id.
*
* @returns {object} person
*/
// app.get('/api/people/:id', people.load);
exports.load = function(req, res, next) {
Person.findById(req.params.id, function (err, person) {
if (err) return next(err);
if (!person) return next(new Error('not found'));
res.send({ person: person });
});
};
/**
* Create new person.
*
* @param {object} person
* @returns {object} person
*/
// app.post('/api/people', people.create);
exports.create = function(req, res, next) {
Person.create(req.body.person, function (err, person) {
if (err) return next(err);
res.send({ person: person });
});
};
/**
* Update person by id.
*
* @param {string} id
* @returns {object} person
*/
// app.put('/people/:id', people.update);
exports.update = function(req, res, next) {
Person.findByIdAndUpdate(req.params.id, req.body.person, function(err, person) {
if (err) return next(err);
res.send({ person: person });
});
};
/**
* Delete person by id.
*
* @param {string} id
* @returns 200 OK
*/
// app.del('/people/:id', people.destroy);
exports.destroy = function(req, res, next) {
Person.findById(req.params.id).remove(function(err) {
if (err) return next(err);
res.send(200);
});
};
<file_sep>/app/models/person.js
export default DS.Model.extend({
name: DS.attr('string'),
age: DS.attr('number')
});
<file_sep>/server/config/fixtures.js
/**
* Fixture data.
*/
var mongoose = require('mongoose');
// Load fixture data
var Person = mongoose.connection.model('Person');
Person.collection.remove(function(err) {
if (err) throw err;
//Convert object to array
var data = [
{
name: 'Bianca',
age: 15,
gender: 'female',
nicknames: 'Cruella',
},
{
name: 'Desmond',
age: 20,
gender: 'male',
nicknames: 'Des',
},
{
name: 'Cosby',
age: 11,
gender: 'male',
nicknames: 'Oz',
}
];
data.forEach(function(item) {
var doc = new Person(item);
Person.findOne({}, function (err, friend) {
if (!err && friend) {
doc.friends.push(friend);
}
doc.save();
});
});
});
<file_sep>/server/config/config.js
var path = require('path')
, rootPath = path.normalize(__dirname + '/..');
module.exports = {
development: {
db: 'mongodb://localhost/cygnus_db',
root: rootPath,
app: {
name: 'FT Example App'
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
}
},
production: {}
};
<file_sep>/README.md
# ft-starter
Starter template for future projects.
## Build Process
- Framekwork: [Ember App Kit], [eak-update](https://github.com/gevious/eak-update)
- Task Runner: [Grunt]
- Package Managers: [NPM], [Bower]
- Testing: [QUnit], [Mocha], [Karma]
## Backend
- Db: [MongoDb]
- ORM: [Mongoose]
- Server: [Express]
## Frontend
- Client: [Ember] + [Ember Data]
- Templates: [Handlebars]
- Styles: [Bootstrap]
## Build
```
> npm install
> bower install
> grunt server
```
### Future Goals
- [OAuth2](http://goo.gl/LK5U0J): [authorization](https://github.com/jaredhanson/oauth2orize)/[authentication](https://github.com/jaredhanson/passport-http-bearer), client creation,
- Client side authentication, client creation: [Ember-Simple-Auth](https://github.com/simplabs/ember-simple-auth), [Ember-Auth](https://github.com/heartsentwined/ember-auth)
### Inspiration
- [Ember App Kit](https://github.com/stefanpenner/ember-app-kit)
- [Node Express Mongoose Demo](https://github.com/madhums/node-express-mongoose-demo)
- [Eber Sass Express Starter](https://github.com/sahat/ember-sass-express-starter)
- [MEAN](https://github.com/Xorcode/mean)
- [NodeAPI](https://github.com/ealeksandrov/NodeAPI)
- [Ember AMD Starter](https://github.com/b3nj4m/ember-amd-starter)
[Ember App Kit]: https://github.com/stefanpenner/ember-app-kit
[QUnit]: https://qunitjs.com/
[Mocha]: http://visionmedia.github.io/mocha/
[Karma]: http://karma-runner.github.io/
[Grunt]: http://gruntjs.com/
[NPM]: https://npmjs.org/
[Bower]: http://bower.io/
[MongoDb]: http://docs.mongodb.org/
[Express]: http://expressjs.com/
[Mongoose]: http://mongoosejs.com/
[Ember]: http://emberjs.com/
[Ember Data]: https://github.com/emberjs/data
[Handlebars]: http://handlebarsjs.com/
[Bootstrap]: http://twitter.github.io/bootstrap/
<file_sep>/server/models/user.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, crypto = require('crypto')
, oAuthTypes = ['twitter'];
/**
* User Schema
*/
var UserSchema = new Schema({
name: { type: String, default: '' },
email: { type: String, default: '' },
username: { type: String, default: '' },
provider: { type: String, default: '' },
hashed_password: { type: String, default: '' },
salt: { type: String, default: '' },
authToken: { type: String, default: '' },
twitter: {}
});
/**
* Virtuals
*/
UserSchema
.virtual('password')
.set(function(password) {
this._password = <PASSWORD>;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() { return this._password; });
/**
* Pre-save hook
*/
UserSchema.pre('save', function(next) {
if (this.isNew) {
if (!validatePresenceOf(this.password) && !this.doesNotRequireValidation()) {
next(new Error('Invalid password'));
}
// Fake OAuth 2.0 for ember-simple-auth
var hashContent = this.username + this.password + Date.now() + Math.random();
this.authToken = crypto.createHash('sha1').update(hashContent).digest('hex');
next();
}
else {
next();
}
});
/**
* Validations
*/
var validatePresenceOf = function (value) {
return value && value.length;
};
// the below 5 validations only apply if you are signing up traditionally
// UserSchema.path('name').validate(function (name) {
// if (this.doesNotRequireValidation()) return true;
// return name.length;
// }, 'Name cannot be blank');
UserSchema.path('email').validate(function (email) {
if (this.doesNotRequireValidation()) return true;
return email.length;
}, 'Email cannot be blank');
UserSchema.path('email').validate(function (email, fn) {
if (this.doesNotRequireValidation()) fn(true);
var User = mongoose.model('User');
// Check only when it is a new user or when email field is modified
if (this.isNew || this.isModified('email')) {
User.find({ email: email }).exec(function (err, users) {
fn(!err && users.length === 0);
});
} else fn(true);
}, 'Email already exists');
UserSchema.path('username').validate(function (username) {
if (this.doesNotRequireValidation()) return true;
return username.length;
}, 'Username cannot be blank');
UserSchema.path('hashed_password').validate(function (hashed_password) {
if (this.doesNotRequireValidation()) return true;
return hashed_password.length;
}, 'Password cannot be blank');
/**
* Methods
*/
UserSchema.methods = {
/**
* Authenticate - check if the passwords are the same
*
* @param {String} plainText
* @return {Boolean}
* @api public
*/
authenticate: function (plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
},
/**
* Make salt
*
* @return {String}
* @api public
*/
makeSalt: function () {
return Math.round((new Date().valueOf() * Math.random())) + '';
},
/**
* Encrypt password
*
* @param {String} password
* @return {String}
* @api public
*/
encryptPassword: function (password) {
if (!password) return '';
var encrypted;
try {
encrypted = crypto.createHmac('sha1', this.salt).update(password).digest('hex');
return encrypted;
} catch (err) {
return '';
}
},
/**
* Validation is not required if using OAuth
*/
doesNotRequireValidation: function() {
return ~oAuthTypes.indexOf(this.provider);
}
};
/**
* Statics
*/
UserSchema.statics = {
load: function (options, cb) {
var criteria = options.criteria || {};
var populate = options.populate || [];
var select = options.select | '';
this.findOne(criteria)
.select(select)
.populate(populate)
.exec(cb);
},
list: function (options, cb) {
var criteria = options.criteria || {};
var sort = options.sort || { createdAt: -1 };
var limit = options.limit === 0 ? 0 : (options.limit || 10);
var page = options.page || 0;
var populate = options.populate || [];
var select = options.select || '';
this.find(criteria)
.select(select)
.populate(populate)
.sort(sort)
.limit(limit)
.skip(limit * page)
.exec(cb);
}
};
exports = module.exports = mongoose.model('User', UserSchema);
<file_sep>/server/config/routes.js
var users = require('../controllers/users')
, people = require('../controllers/people')
, _ = require('underscore')
, auth = require('./middlewares/authorization');
/* Expose routes */
module.exports = function (app, passport) {
/* Passport Local */
app.post('/token', passport.authenticate('local', { failureRedirect: '#/login' }), users.authCallback);
app.post('/signup', users.signup);
app.get('/logout', users.logout);
/* Passport Twitter */
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '#/login' }), users.authCallback);
/* API */
// People
app.get('/api/people', people.index);
app.get('/api/people/:id', people.load);
app.post('/api/people', people.create);
app.put('/api/people/:id', people.update);
app.del('/api/people/:id', people.destroy);
};
<file_sep>/server/config/express.js
/* Module dependencies */
var express = require('express')
, mongoStore = require('connect-mongo')(express)
, winston = require('winston')
, lockFile = require('lockfile')
, fs = require('fs')
, path = require('path');
var env = process.env.NODE_ENV || 'development';
module.exports = function (app, config, passport) {
/* Debugging */
app.set('showStackError', true);
app.configure('development', function () {
app.use(lock);
app.use(require("connect-livereload")());
});
/* Logging */
var log;
if (env !== 'development') { // Use winston on production
log = {
stream: {
write: function (message, encoding) {
winston.info(message);
}
}
};
} else {
log = 'dev';
}
app.use(express.logger(log));
/* Static assets */
app.use(express.compress());
app.use(express.favicon());
// `expressServer:debug`
if (config.gruntTarget === 'debug') {
// Simulate `copy:assemble` task
app.use(static({ urlRoot: '/config', directory: 'config' }));
app.use(static({ urlRoot: '/vendor', directory: 'vendor' }));
app.use(static({ directory: 'public' }));
app.use(static({ urlRoot: '/tests', directory: 'tests' })); // For test-helper.js and test-loader.js
app.use(static({ directory: 'tmp/result' }));
} else {
// `expressServer:dist`, production
app.use(static({ directory: 'dist' }));
}
/* Session storage */
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
// Express/Mongo session storage
app.use(express.session({
secret: 'SECRET',
store: new mongoStore({
url: config.db,
collection : 'sessions'
})
}));
// Use passport session
app.use(passport.initialize());
app.use(passport.session());
/* Routes */
app.use(app.router);
/* Error handling */
app.use(function(err, req, res, next){
// Treats "not found" in the error msg as 404.
if (err.message
&& (~err.message.indexOf('not found')
|| (~err.message.indexOf('Cast to ObjectId failed')))) {
return next();
}
console.error(err.stack);
res.send(500, { error: 'Something blew up!' });
});
// assume 404 since no middleware responded
app.use(function(req, res, next){
res.send(404, { error: 'Resource not found.' });
});
app.configure('development', function () {
app.locals.pretty = true;
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
};
// Works with grunt tasks/locking.js
function lock(req, res, next) {
(function retry() {
if (lockFile.checkSync('tmp/connect.lock')) {
setTimeout(retry, 30);
} else { next(); }
})();
}
// Gotta catch 'em all (and serve index.html)
function static(options) {
return function(req, res, next) {
var filePath = "";
if (options.directory) {
var regex = new RegExp('^' + (options.urlRoot || ''));
// URL must begin with urlRoot's value
if (!req.path.match(regex)) { next(); return; }
filePath = options.directory + req.path.replace(regex, '');
}
else if (options.file) {
filePath = options.file;
}
else {
throw new Error('static() isn\'t properly configured!');
}
fs.stat(filePath, function(err, stats) {
if (err) { next(); return; } // Not a file, not a folder => can't handle it
if (options.ignoredFileExtensions) {
if (options.ignoredFileExtensions.test(req.path)) {
res.send(404, {error: 'Resource not found'});
return; // Do not serve index.html
}
}
// Is it a directory? If so, search for an index.html in it.
if (stats.isDirectory()) { filePath = path.join(filePath, 'index.html'); }
// Serve the file
res.sendfile(filePath, function(err) {
if (err) { next(); return; }
});
});
};
}
<file_sep>/app/app.js
import Resolver from 'ember/resolver';
Ember.Application.initializer({
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.setup(container, application);
}
});
var App = Ember.Application.extend({
LOG_ACTIVE_GENERATION: true,
LOG_MODULE_RESOLVER: true,
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
LOG_VIEW_LOOKUPS: true,
modulePrefix: 'appkit',
Resolver: Resolver['default']
});
export default App;
| 574b381fb582113ec5f93a9f844c46cd612118a2 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | mortonfox/ft-starter | 35aad37e8fc8bea4fca6ccdce2288b4a43bc9f5b | d5ba09e2274b90cd323e10e4dabd71594178391a |
refs/heads/master | <repo_name>sevenjames/MinecraftServerBuild<file_sep>/mc-server-start
#!/bin/bash
# launch a minecraft server, but not if it's already running
cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
lockfile="./server.running.lock"
if [ -e "$lockfile" ]; then
echo "Launch Abort. Server is already running."
exit 1
else
touch "$lockfile"
echo "Server Launch..."
java -Xms1G -Xmx1G -jar paper.jar
echo "Server Stopped."
rm "$lockfile"
echo "Press RETURN to continue."; read
exit 0
fi
<file_sep>/mc-session-start
#!/bin/bash
# launch a tmux session for a server, but not if the server is already running
# requires the additional start script specified at $startscr
cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
lockfile="./server.running.lock"
startscr="./mc-server-start"
successprint() {
echo "SERVER STARTED IN A DETACHED TMUX SESSION."
echo " Use tmux commands to attach the session:"
echo " from outside tmux: tmux attach -t mcserver"
echo " from inside tmux: C-b s"
}
if [ -e "$lockfile" ]; then
echo "Launch Abort. Server is already running."
exit 1
else
if [ -e "$startscr" ]; then
tmux new -d -s mcserver "$startscr" && successprint
# tmux provides an additional check; it wont create
# a session by name if it already exists.
exit 0
else
echo "Launch Abort. Launch script missing."
exit 1
fi
fi
| 9ed4ac0bd75f082848241e7325f4534514221db8 | [
"Shell"
] | 2 | Shell | sevenjames/MinecraftServerBuild | 431608099a37614c7add3c092165ef4f605de728 | 4f2713717d6f5377bc784f4e5c1efbb1a9056bc0 |
refs/heads/master | <file_sep>import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import page.MainPage;
import page.SearchPage;
import java.util.ArrayList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by wwl on 2019/2/12.
*
* @author wwl
*/
@TestMethodOrder(OrderAnnotation.class)
public class SearchTest {
static MainPage mainPage;
static SearchPage searchPage;
@BeforeAll
static void beforeAll() {
mainPage = MainPage.start();
searchPage = mainPage.gotoSearch();
}
@Order(1)
@ParameterizedTest
@CsvFileSource(resources = "/data/SearchTest.csv", numLinesToSkip = 1)
void 搜索测试(String keyword, String exp) {
String name = searchPage.search(keyword).getAll().get(0);
assertThat(name, equalTo(exp));
}
@Order(2)
@ParameterizedTest
@CsvFileSource(resources = "/data/SearchTest.csv", numLinesToSkip = 1)
void 股票搜索测试(String keyword, String exp) {
String name = searchPage.search(keyword).getByStock().getAll().get(0);
assertThat(name, equalTo(exp));
}
@Order(3)
@ParameterizedTest
@CsvFileSource(resources = "/data/SearchTest.csv", numLinesToSkip = 1)
void 选择(String keyword) {
ArrayList<String> arrayList = searchPage.search(keyword).addSelected();
assertThat(arrayList, hasItems("com.xueqiu.android:id/followed_btn", "com.xueqiu.android:id/follow_btn"));
}
}
<file_sep>"# XueqiuTesting"
<file_sep>package common;
import config.XueqiuConfig;
import org.junit.jupiter.params.provider.Arguments;
import java.util.*;
import java.util.stream.Stream;
import static org.junit.jupiter.params.provider.Arguments.arguments;
public class FindData {
static XueqiuConfig data = new XueqiuConfig();
private static Stream<Arguments> getData(String casename) {
data.load("/data/testData.yaml");
ArrayList<HashMap<String, Object>> cases = data.getCase(casename);
int len = cases.size();
Arguments[] arg = new Arguments[len];
for (int i = 0; i < len; i++) {
HashMap<String, Object> d = cases.get(i);
Object[] o = d.values().toArray();
arg[i] = arguments(o);
}
return Arrays.stream(arg);
}
static Stream<Arguments> 添加删除自选股票() {
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
return getData(method);
}
static Stream<Arguments> 密码登录() {
return getData("密码登录");
}
}
<file_sep>package page;
import driver.Driver;
import io.appium.java_client.TouchAction;
import io.appium.java_client.touch.LongPressOptions;
import io.appium.java_client.touch.offset.PointOption;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import javax.swing.*;
import java.util.ArrayList;
/**
* Created by wwl on 2019/2/12.
*
* @author wwl
*/
public class OptionalPage extends BasePage {
public SearchPage gotoSearch() {
find(By.id("action_create_cube")).click();
return new SearchPage();
}
public OptionalPage delStock(String stockName) {
WebElement e1 = find(By.id("listview")).findElement(text(stockName));
TouchAction ta = new TouchAction(Driver.getCurrentDriver());
PointOption op = new PointOption();
op.withCoordinates(e1.getLocation().getX(),e1.getLocation().getY());
try {
ta.longPress(op).release().perform();
} catch (Exception e) {
e.printStackTrace();
}
find(text("删除")).click();
return this;
}
public ArrayList<String> getAll() {
ArrayList<String> array = new ArrayList<String>();
for (WebElement e : finds(By.id("portfolio_stockName"))) {
array.add(e.getText());
}
return array;
}
}
<file_sep>import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import org.junit.jupiter.params.provider.MethodSource;
import page.MainPage;
import page.OptionalPage;
import java.util.ArrayList;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by wwl on 2019/2/12.
*/
public class OptionalTest {
static MainPage mainPage;
static OptionalPage optionalPage;
@BeforeAll
static void beforeAll() {
mainPage = MainPage.start();
optionalPage = mainPage.gotoOptional();
}
@ParameterizedTest
@CsvFileSource(resources = "/data/OptionalTest.csv")
void 添加删除自选股票(String keyword, String stockName) {
ArrayList<String> array = optionalPage.gotoSearch().search(keyword).addOptional().cancelOnOptionPage().getAll();
assertThat(array, hasItems(stockName));
ArrayList<String> array2 = optionalPage.delStock(stockName).getAll();
assertThat(array.size() - array2.size(), is(1));
}
@ParameterizedTest
@MethodSource("common.FindData#添加删除自选股票")
void 添加删除自选股票2(String keyword, String stockName) {
ArrayList<String> array = optionalPage.gotoSearch().search(keyword).addOptional().cancelOnOptionPage().getAll();
assertThat(array, hasItems(stockName));
ArrayList<String> array2 = optionalPage.delStock(stockName).getAll();
assertThat(array.size() - array2.size(), is(1));
}
}
<file_sep>package page;
import driver.Driver;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import java.util.List;
/**
* Created by wwl on 2019/2/2.
* @author wwl
*/
public class BasePage {
static WebElement find(By locator) {
try {
return Driver.getCurrentDriver().findElement(locator);
} catch (NoSuchElementException e) {
Driver.getCurrentDriver().findElement(text("下次再说")).click();
return Driver.getCurrentDriver().findElement(locator);
}
}
static List<WebElement> finds(By locator) {
List<WebElement> array;
try {
array = Driver.getCurrentDriver().findElements(locator);
return array;
} catch (NoSuchElementException e) {
Driver.getCurrentDriver().findElement(text("下次再说")).click();
array = Driver.getCurrentDriver().findElements(locator);
return array;
}
}
static By locate(String locator) {
if (locator.matches("/.*")) {
return By.xpath(locator);
} else {
return By.id(locator);
}
}
static By text(String content) {
return By.xpath("//*[@text='" + content + "']");
}
}
<file_sep>import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import page.LoginPage;
import page.MainPage;
import page.ProfilePage;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by wwl on 2019/2/2.
*
* @author wwl
*/
public class LoginTest {
static MainPage mainPage;
static ProfilePage profilePage;
@BeforeAll
static void beforeAll() {
mainPage = MainPage.start();
profilePage = mainPage.gotoProfile();
}
@ParameterizedTest
@CsvSource({
"18606535376,XXXXXXXX,用户名或密码错误",
"1860653536,XXXXXXXX,手机号码填写错误"
})
void 密码登录(String username, String password, String exp) {
LoginPage loginPage = profilePage.gotoLogin();
loginPage.passwordFail(username, password);
assertThat(loginPage.getMessage(), equalTo(exp));
profilePage=loginPage.gotoProfile();
}
@ParameterizedTest
@MethodSource("common.FindData#密码登录")
void 密码登录2(String username, String password, String exp) {
LoginPage loginPage = profilePage.gotoLogin();
loginPage.passwordFail(username, password);
assertThat(loginPage.getMessage(), equalTo(exp));
profilePage=loginPage.gotoProfile();
}
}
<file_sep>package config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by wwl on 2019/2/15.
*/
public class GlobalConfig {
public XueqiuConfig xueqiu = new XueqiuConfig();
public AppiumConfig appium = new AppiumConfig();
public static GlobalConfig load(String path) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
GlobalConfig config = mapper.readValue(GlobalConfig.class.getResource(path), GlobalConfig.class);
return config;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void write(String path) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
mapper.writeValue(new File(path), new GlobalConfig());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| ce9f5908019d4aedaab0e60eb10dadbc111a8992 | [
"Markdown",
"Java"
] | 8 | Java | wl99/XueqiuTesting | ba83c19767d3ead9806f4bb20c8b8fbfc321c4ca | d6454cb9c1aca19f7810f82faf41f755be65f6e0 |
refs/heads/main | <file_sep>package com.example.superandroidproject.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import com.example.superandroidproject.QuanLi.QuanLiHDCTActivity;
import com.example.superandroidproject.R;
import com.example.superandroidproject.dao.HoaDonCT_DAO;
import com.example.superandroidproject.dao.HoaDonDAO;
import com.example.superandroidproject.model.HoaDonChiTietModel;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class HoaDonCTAdapter extends RecyclerView.Adapter<HoaDonCTAdapter.CTViewHolder> {
Context context;
ArrayList<HoaDonChiTietModel> list;
public static double thanhTien2 = 0;
public HoaDonCTAdapter(Context context, ArrayList<HoaDonChiTietModel> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public HoaDonCTAdapter.CTViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View view = inflater.inflate(R.layout.item_hdct, parent, false);
return new HoaDonCTAdapter.CTViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CTViewHolder holder, final int position) {
holder.tvMaHDCT.setText(String.valueOf(list.get(position).getMaHoaDonCT()));
holder.tvMaSachCT.setText(list.get(position).getTieuDe());
holder.tvSoLuongCT.setText(String.valueOf(list.get(position).getSoLuong()));
int sl = Integer.parseInt(holder.tvSoLuongCT.getText().toString());
holder.tvThanhTien.setText(String.valueOf(list.get(position).getGia1Sach()*sl));
holder.ivXoaHDCT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
XoaHDCT(position, list.get(position).getMaHD());
}
});
}
@Override
public int getItemCount() {
return list.size();
}
void XoaHDCT(final int position, final int maHD){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Xóa Hóa đơn Chi tiết");
builder.setMessage("Suy nghĩ kĩ đi!! Có chắc muốn xóa?")
.setPositiveButton("Xóa", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (HoaDonCT_DAO.XoaHoaDonCT(list.get(position).getMaHoaDonCT(), context)){
Toast.makeText(context, "Đã xóa! Uống tí nước đi.", Toast.LENGTH_SHORT).show();
list.remove(position);
list.clear();
list.addAll(HoaDonCT_DAO.GetHDCT(context, maHD));
for (int j = 0; j < list.size(); j++) {
thanhTien2 = thanhTien2 + list.get(j).getGia1Sach() * list.get(j).getSoLuong();
}
Log.i("tt2", thanhTien2 + " adapter");
Intent intent = new Intent(context, QuanLiHDCTActivity.class);
intent.putExtra("t2", thanhTien2);
// context.startActivity(intent);
// Bundle bundle = new Bundle();
// bundle.putDouble("tt2", thanhTien2);
// QuanLiHDCTActivity hdctActivity = new QuanLiHDCTActivity();
// hdctActivity.setIntent(intent);
notifyDataSetChanged();
dialog.dismiss();
}
}
})
.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context, "OK Fine", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public class CTViewHolder extends RecyclerView.ViewHolder {
TextView tvMaHDCT, tvMaSachCT, tvSoLuongCT, tvThanhTien, tvThoiGian;
ImageView ivXoaHDCT;
public CTViewHolder(@NonNull View itemView) {
super(itemView);
tvMaHDCT = itemView.findViewById(R.id.tvMaHDCT);
tvMaSachCT = itemView.findViewById(R.id.tvMaSachCT);
tvSoLuongCT = itemView.findViewById(R.id.tvSoLuongCT);
tvThanhTien = itemView.findViewById(R.id.tvThanhTien);
tvThoiGian = itemView.findViewById(R.id.tvThoiGianMua);
ivXoaHDCT = itemView.findViewById(R.id.ivXoaHDCT);
}
}
}
<file_sep>package com.example.superandroidproject.QuanLi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.superandroidproject.R;
import com.example.superandroidproject.adapter.LoaiSachAdapter;
import com.example.superandroidproject.dao.LoaiSachDao;
import com.example.superandroidproject.model.LoaiSachModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class QuanLiLoaiSachActivity extends AppCompatActivity {
RecyclerView rcvLoaiSach;
FloatingActionButton fabThemLoaiSach;
ArrayList<LoaiSachModel> list_LoaiSach = new ArrayList<>();
LoaiSachAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quan_li_loai_sach);
fabThemLoaiSach = findViewById(R.id.fab_ThemLoaiSach);
rcvLoaiSach = findViewById(R.id.rcvLoaiSach);
rcvLoaiSach.setHasFixedSize(true);
// ADD Recycler Riew vào giao diện
RecyclerView.LayoutManager manager = new LinearLayoutManager(QuanLiLoaiSachActivity.this);
rcvLoaiSach.setLayoutManager(manager);
list_LoaiSach = LoaiSachDao.GetAll(QuanLiLoaiSachActivity.this);
adapter = new LoaiSachAdapter(QuanLiLoaiSachActivity.this, list_LoaiSach);
rcvLoaiSach.setAdapter(adapter);
fabThemLoaiSach.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogThem(QuanLiLoaiSachActivity.this);
}
});
}
// DIALOG THÊM LOẠI SÁCH
private void DialogThem(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(QuanLiLoaiSachActivity.this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_them_loai_sach, null);
builder.setView(view);
final Dialog dialog = builder.create();
dialog.show();
// ========================================
Button btnThemLoaiSach = view.findViewById(R.id.btnThemLoaiSach);
final EditText edtTenTheLoai = view.findViewById(R.id.edtThemTenTheLoai);
final EditText edtViTri = view.findViewById(R.id.edtThemViTri);
final EditText edtThemMoTa = view.findViewById(R.id.edtThemMoTa);
final Button btnHuy = view.findViewById(R.id.btnHuyThemLoaiSach);
btnThemLoaiSach.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tenTheLoaiMoi = edtTenTheLoai.getText().toString();
int viTriMoi = Integer.parseInt(edtViTri.getText().toString());
String moTaMoi = edtThemMoTa.getText().toString();
LoaiSachModel loaiSachMoi = new LoaiSachModel(tenTheLoaiMoi,moTaMoi,viTriMoi);
if (LoaiSachDao.ThemLoaiSach(loaiSachMoi, context)) {
Toast.makeText(context, "Thêm hoàn tất. Cày view Sếp thôi", Toast.LENGTH_SHORT).show();
list_LoaiSach.clear();
list_LoaiSach.addAll(LoaiSachDao.GetAll(context));
adapter.notifyDataSetChanged();
dialog.dismiss();
} else {
Toast.makeText(context, "Oi zoi oi!! Lỗi kìa", Toast.LENGTH_SHORT).show();
}
}
});
btnHuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}<file_sep>package com.example.superandroidproject.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.superandroidproject.database.DbHelper;
import com.example.superandroidproject.model.HoaDonModel;
import java.util.ArrayList;
public class HoaDonDAO {
// LOAD DỮ LIỆU TỪ BẢNG
public static ArrayList<HoaDonModel> GetAll(Context context){
ArrayList<HoaDonModel> list = new ArrayList<>();
DbHelper helper = new DbHelper(context);
// TẠO CSDL SQLITE
SQLiteDatabase db = helper.getReadableDatabase();
// Câu lệnh truy vấn toàn bộ dữ liệu từ bảng TABLE_HOA_DON
String sql = "select * from TABLE_HOA_DON";
// Tạo con trỏ, trả về result set
Cursor cs = db.rawQuery(sql, null);
cs.moveToFirst();
while (!cs.isAfterLast()) {
int maHoaDon = Integer.parseInt(cs.getString(0));
String tenKhachHang = cs.getString(1);
String ngayMua = cs.getString(2);
HoaDonModel hoaDon = new HoaDonModel(maHoaDon, tenKhachHang, ngayMua);
list.add(hoaDon);
cs.moveToNext();
}
cs.close();
db.close();
return list;
}
// THÊM HÓA ĐƠN
public static boolean ThemHoaDon(HoaDonModel hd, Context context) {
DbHelper helper = new DbHelper(context);
// TẠO CSDL SQLITE
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("tenKhachHang", hd.getKhachHang());
values.put("ngayMua", hd.getNgayMua());
return db.insert("TABLE_HOA_DON", null, values) > 0;
}
public static boolean CapNhatHoaDon(HoaDonModel hd,String tenMoi,String date, Context context){
DbHelper helper = new DbHelper(context);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("tenKhachHang", tenMoi);
values.put("ngayMua", date);
return db.update("TABLE_HOA_DON", values, "maHoaDon=? ", new String[]{String.valueOf(hd.getMaHoaDon())}) > 0;
}
public static boolean XoaHoaDon(int hd, Context context){
DbHelper helper = new DbHelper(context);
SQLiteDatabase db = helper.getWritableDatabase();
int row = db.delete("TABLE_HOA_DON","maHoaDon=?",new String[]{String.valueOf(hd)});
return row>0;
}
}
<file_sep>package com.example.superandroidproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class WelcomeActivity extends AppCompatActivity {
private static int SPLASH_SCREEN_TIME_OUT=2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i=new Intent(WelcomeActivity.this,
LoginActivity.class);
//Intent is used to switch from one activity to another.
startActivity(i);
//invoke the SecondActivity.
finish();
//the current activity will get finished.
}
}, SPLASH_SCREEN_TIME_OUT);
}
}<file_sep>package com.example.superandroidproject;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.superandroidproject.dao.NguoiDungDao;
import com.example.superandroidproject.model.NguoiDungModel;
public class DoiMatKhauActivity extends AppCompatActivity {
EditText edtMatKhauCu, edtMatKhauMoi, edtMatKhauMoi2;
Button btnDoiMatKhau;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doi_mat_khau);
edtMatKhauCu = findViewById(R.id.editTextOldPassword);
edtMatKhauMoi= findViewById(R.id.editTextNewPassword);
edtMatKhauMoi2 = findViewById(R.id.editTextReNewPassword);
btnDoiMatKhau = findViewById(R.id.buttonChange);
btnDoiMatKhau.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DoiMatKhau();
}
});
}
public void DoiMatKhau(){
String passCu = edtMatKhauCu.getText().toString();
String passMoi = edtMatKhauMoi.getText().toString();
String passMoi2 = edtMatKhauMoi2.getText().toString();
String username = LoginActivity.USER.getUserName();
if (!NguoiDungDao.CheckPassCu(passCu)){
Toast.makeText(this, "Mật khẩu cũ ko đúng", Toast.LENGTH_SHORT).show();
} else if (passMoi.isEmpty()){
Toast.makeText(this, "Vui lòng nhập mật khẩu mới", Toast.LENGTH_SHORT).show();
}
else {
if (!passMoi.equals(passMoi2)){
Toast.makeText(this, "Mật khẩu mới ko trùng khớp", Toast.LENGTH_SHORT).show();
} else {
if (NguoiDungDao.ChangePassword(new NguoiDungModel(username, passMoi), DoiMatKhauActivity.this)){
// Toast.makeText(this, "Đổi mật khẩu thành công", Toast.LENGTH_SHORT).show();
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(DoiMatKhauActivity.this);
// Add the buttons
builder.setPositiveButton("Đăng xuất", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(DoiMatKhauActivity.this, LoginActivity.class);
startActivity(i);
}
});
builder.setNegativeButton("Về trang chủ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(DoiMatKhauActivity.this, MainActivity.class);
startActivity(i);
}
});
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("Đổi mật khẩu thành công. Bạn muốn đăng xuất?")
.setTitle("Đổi mật khẩu");
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
} else {
Toast.makeText(this, "Đã xảy ra sự cố. Vui lòng thử lại", Toast.LENGTH_SHORT).show();
}
}
}
}
}<file_sep>package com.example.superandroidproject.QuanLi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.example.superandroidproject.R;
import com.example.superandroidproject.adapter.HoaDonAdapter;
import com.example.superandroidproject.dao.HoaDonDAO;
import com.example.superandroidproject.model.HoaDonModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class QuanLiHoaDonActivity extends AppCompatActivity {
RecyclerView rcvHoaDon;
FloatingActionButton fabThemHoaDon;
HoaDonAdapter adapter;
ArrayList<HoaDonModel> list_HoaDon = new ArrayList<>();
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quan_li_hoa_don);
rcvHoaDon = findViewById(R.id.rcvHoaDon);
// rcvHoaDon.setHasFixedSize(true);
fabThemHoaDon = findViewById(R.id.fab_ThemHoaDon);
// GÁN DỮ LIỆU VÀO RECYCLERVIEW
RecyclerView.LayoutManager manager = new LinearLayoutManager(QuanLiHoaDonActivity.this);
rcvHoaDon.setLayoutManager(manager);
list_HoaDon = HoaDonDAO.GetAll(QuanLiHoaDonActivity.this);
adapter = new HoaDonAdapter(QuanLiHoaDonActivity.this, list_HoaDon);
rcvHoaDon.setAdapter(adapter);
// BUTTON THÊM HÓA ĐƠN
fabThemHoaDon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogThem(QuanLiHoaDonActivity.this);
}
});
}
public void DialogThem(final Context context) {
// todo: hiện dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_them_hoa_don, null);
builder.setView(view);
final Dialog dialog = builder.create();
dialog.show();
// ========================================
Button btnThemHoaDon = view.findViewById(R.id.btnThemHoaDon);
final EditText edtTenKhachHang = view.findViewById(R.id.edtThemTenKhachHang);
final Button btnHuy = view.findViewById(R.id.btnHuyThemHoaDon);
// < ========== NHẬP NGÀY ==============
final EditText edtNgayMua = view.findViewById(R.id.edtThemNgayMua);
final Calendar myCalendar = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
edtNgayMua.setText(format.format(myCalendar.getTime()));
}
};
edtNgayMua.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(QuanLiHoaDonActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
// ========== HẾT ĐOẠN NHẬP NGÀY ============== />
btnThemHoaDon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tenKhachHang = edtTenKhachHang.getText().toString();
String date = edtNgayMua.getText().toString();
HoaDonModel hoaDon = new HoaDonModel(tenKhachHang, date);
if (edtTenKhachHang.getText().toString().equals("") || edtNgayMua.getText().toString().equals("")) {
Toast.makeText(context, "Điền đầy đủ nào ", Toast.LENGTH_SHORT).show();
} else {
if (HoaDonDAO.ThemHoaDon(hoaDon, context)) {
Toast.makeText(context, "Thêm hoàn tất. Cày view Sếp thôi", Toast.LENGTH_SHORT).show();
list_HoaDon.clear();
list_HoaDon.addAll(HoaDonDAO.GetAll(context));
adapter.notifyDataSetChanged();
dialog.dismiss();
} else {
Toast.makeText(context, "Oi zoi oi!! Lỗi kìa", Toast.LENGTH_SHORT).show();
}
}
}
});
btnHuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}<file_sep>package com.example.superandroidproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.superandroidproject.QuanLi.QuanLiHoaDonActivity;
import com.example.superandroidproject.QuanLi.QuanLiLoaiSachActivity;
import com.example.superandroidproject.QuanLi.QuanLiNguoiDungActivity;
import com.example.superandroidproject.QuanLi.QuanLiSachActivity;
public class MainActivity extends AppCompatActivity {
TextView tvNguoiDung, tvLoaiSach, tvSach, tvHoaDon, tvThongKe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvNguoiDung = findViewById(R.id.tvNguoiDung);
tvLoaiSach = findViewById(R.id.tvTheLoai);
tvSach = findViewById(R.id.tvSach);
tvHoaDon = findViewById(R.id.tvHoaDon);
tvThongKe = findViewById(R.id.tvThongKe);
tvNguoiDung.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, QuanLiNguoiDungActivity.class);
startActivity(intent);
}
});
tvLoaiSach.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, QuanLiLoaiSachActivity.class);
startActivity(intent);
}
});
tvSach.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, QuanLiSachActivity.class);
startActivity(intent);
}
});
tvHoaDon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, QuanLiHoaDonActivity.class);
startActivity(intent);
}
});
tvThongKe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThongKeActivity.class);
startActivity(intent);
}
});
}
// HIỆN DIALOG OPTION MENU
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.buttonDoiMatKhau) {
Intent intent = new Intent(MainActivity.this, DoiMatKhauActivity.class);
startActivity(intent);
} else if (item.getItemId() == R.id.buttonDangXuat) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(item);
}
}<file_sep>package com.example.superandroidproject.adapter;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.superandroidproject.R;
import com.example.superandroidproject.dao.LoaiSachDao;
import com.example.superandroidproject.model.LoaiSachModel;
import java.util.ArrayList;
public class LoaiSachAdapter extends RecyclerView.Adapter<LoaiSachAdapter.LoaiSachViewHolder> {
private Context context;
private ArrayList<LoaiSachModel> list_LoaiSach;
public LoaiSachAdapter(Context context, ArrayList<LoaiSachModel> list_LoaiSach) {
this.context = context;
this.list_LoaiSach = list_LoaiSach;
}
@NonNull
@Override
public LoaiSachAdapter.LoaiSachViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View view = inflater.inflate(R.layout.item_loai_sach, parent, false);
return new LoaiSachViewHolder(view);
}
// HÀM SỬA LOẠI SÁCH
private void DialogSua(final LoaiSachModel ls){
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_sua_loai_sach, null);
builder.setView(view);
final EditText tenLoaiSach = view.findViewById(R.id.edtSuaTenLoaiSach);
final EditText moTa = view.findViewById(R.id.edtSuaMoTa);
final EditText viTri = view.findViewById(R.id.edtSuaViTri);
Button btnHuy = view.findViewById(R.id.btnHuySuaLoaiSach);
Button btnThem = view.findViewById(R.id.btnSuaLoaiSach);
tenLoaiSach.setText(ls.getTenTheLoai());
moTa.setText(ls.getMoTa());
viTri.setText(String.valueOf(ls.getViTri()));
final Dialog dialog = builder.create();
dialog.show();
// BUTTON SỬA
btnThem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tenLoaiSachMoi = tenLoaiSach.getText().toString();
String moTaMoi = moTa.getText().toString();
int viTriMoi = Integer.parseInt(viTri.getText().toString());
if(LoaiSachDao.updateLoaiSach(ls, tenLoaiSachMoi, moTaMoi, viTriMoi, context)){
Toast.makeText(context, "Sửa thành công", Toast.LENGTH_SHORT).show();
list_LoaiSach.clear();
list_LoaiSach.addAll(LoaiSachDao.GetAll(context));
notifyDataSetChanged();
dialog.dismiss();
} else {
Toast.makeText(context, "Sửa thất bại", Toast.LENGTH_SHORT).show();
}
}
});
// TẮT DIALOG THÊM
btnHuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
@Override
public void onBindViewHolder(@NonNull LoaiSachAdapter.LoaiSachViewHolder holder, final int position) {
holder.tvViTri.setText(String.valueOf(list_LoaiSach.get(position).getViTri()));
holder.tvTenLoaiSach.setText(list_LoaiSach.get(position).getTenTheLoai());
holder.tvMaTheLoai.setText(String.valueOf(list_LoaiSach.get(position).getMaTheLoai()));
holder.tvMoTa.setText(list_LoaiSach.get(position).getMoTa());
holder.ivAvatarLoaiSach.setImageResource(R.drawable.skull);
holder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogSua(list_LoaiSach.get(position));
}
});
holder.ivXoaLoaiSach.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Xóa Loại Sách");
builder.setMessage("Suy nghĩ kĩ đi!! Có chắc muốn xóa?")
.setPositiveButton("Xóa", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (LoaiSachDao.XoaLoaiSach(list_LoaiSach.get(position).getMaTheLoai(), context)){
Toast.makeText(context, "Đã xóa! Tối ngủ cẩn thận.", Toast.LENGTH_SHORT).show();
list_LoaiSach.remove(position);
list_LoaiSach.clear();
list_LoaiSach.addAll(LoaiSachDao.GetAll(context));
notifyDataSetChanged();
dialog.dismiss();
}
}
})
.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context, "Nước đi hay đấy", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
@Override
public int getItemCount() {
return list_LoaiSach.size();
}
public static class LoaiSachViewHolder extends RecyclerView.ViewHolder {
CardView item;
ImageView ivAvatarLoaiSach, ivXoaLoaiSach;
TextView tvTenLoaiSach, tvViTri, tvMaTheLoai, tvMoTa;
public LoaiSachViewHolder(@NonNull View itemView) {
super(itemView);
item = itemView.findViewById(R.id.cardView_LoaiSach);
ivAvatarLoaiSach = itemView.findViewById(R.id.ivAvatarLoaiSach);
ivXoaLoaiSach = itemView.findViewById(R.id.ivXoaLoaiSach);
tvTenLoaiSach = itemView.findViewById(R.id.tvTenLoaiSach);
tvMoTa = itemView.findViewById(R.id.tvMoTa);
tvMaTheLoai = itemView.findViewById(R.id.tvMaTheLoai);
tvViTri = itemView.findViewById(R.id.tvViTri);
}
}
}
<file_sep>package com.example.superandroidproject.adapter;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.superandroidproject.R;
import com.example.superandroidproject.dao.LoaiSachDao;
import com.example.superandroidproject.dao.SachDao;
import com.example.superandroidproject.model.LoaiSachModel;
import com.example.superandroidproject.model.SachModel;
import java.util.ArrayList;
public class SachAdapter extends RecyclerView.Adapter<SachAdapter.SachViewHolder> {
private Context context;
private ArrayList<SachModel> list_Sach;
public SachAdapter(Context context, ArrayList<SachModel> list_Sach) {
this.context = context;
this.list_Sach = list_Sach;
}
@NonNull
@Override
public SachViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View view = inflater.inflate(R.layout.item_sach, parent, false);
return new SachViewHolder(view);
}
// HÀM SỬA SÁCH
private void DialogSua(final SachModel sach){
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_sua_sach, null);
builder.setView(view);
final Spinner spnThemMaTheLoaiSach = view.findViewById(R.id.spnSuaMaTheLoai);
final EditText tenSach = view.findViewById(R.id.edtSuaTenSach);
final EditText tacGia = view.findViewById(R.id.edtSuaTacGia);
final EditText nxb = view.findViewById(R.id.edtSuaNXB);
final EditText giaBan = view.findViewById(R.id.edtSuaGiaBan);
final EditText soLuong = view.findViewById(R.id.edtSuaSoLuong);
Button btnHuy = view.findViewById(R.id.btnHuySuaSach);
Button btnSuaSach = view.findViewById(R.id.btnSuaSach);
// Hiện dữ liệu có sẵn lên dialog
tenSach.setText(sach.getTieuDe());
tacGia.setText(sach.getTacGia());
nxb.setText(String.valueOf(sach.getNxb()));
giaBan.setText(String.valueOf(sach.getGiaBan()));
soLuong.setText(String.valueOf(sach.getSoLuong()));
final Dialog dialog = builder.create();
dialog.show();
ArrayList<LoaiSachModel> theLoaiSach = LoaiSachDao.GetAll(context);
ArrayAdapter spnAdapter = new ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, theLoaiSach);
spnThemMaTheLoaiSach.setAdapter(spnAdapter);
spnThemMaTheLoaiSach.setSelection(sach.getMaTheLoai() - 1);
// BUTTON SỬA SACH
btnSuaSach.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tenSachMoi = tenSach.getText().toString();
String tacGiaMoi = tacGia.getText().toString();
String nxbMoi = nxb.getText().toString();
int giaBanMoi = Integer.parseInt(giaBan.getText().toString());
int soLuongMoi = Integer.parseInt(soLuong.getText().toString());
LoaiSachModel loaiSachModel = (LoaiSachModel) spnThemMaTheLoaiSach.getSelectedItem();
int maTheLoai = loaiSachModel.getMaTheLoai();
SachModel sachUpdate = new SachModel(tenSachMoi, maTheLoai, tacGiaMoi, nxbMoi, giaBanMoi, soLuongMoi);
if(SachDao.updateSach(sachUpdate, context)){
Toast.makeText(context, "Sửa thành công", Toast.LENGTH_SHORT).show();
list_Sach.clear();
list_Sach.addAll(SachDao.GetAll(context));
notifyDataSetChanged();
dialog.dismiss();
} else {
Toast.makeText(context, "Sửa thất bại", Toast.LENGTH_SHORT).show();
}
}
});
// TẮT DIALOG THÊM
btnHuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
@Override
public void onBindViewHolder(@NonNull SachViewHolder holder, final int position) {
holder.tvTenSach.setText(list_Sach.get(position).getTieuDe());
holder.tvTacGia.setText(list_Sach.get(position).getTacGia());
holder.tvNXB.setText(list_Sach.get(position).getNxb());
holder.tvSoLuong.setText(String.valueOf(list_Sach.get(position).getSoLuong()));
holder.tvGiaBan.setText(String.valueOf(list_Sach.get(position).getGiaBan()));
holder.ivAvatarSach.setImageResource(R.drawable.inspiration);
holder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogSua(list_Sach.get(position));
}
});
holder.ivXoaSach.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Xóa Sách");
builder.setMessage("Suy nghĩ kĩ đi!! Có chắc muốn xóa?")
.setPositiveButton("Xóa", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (SachDao.XoaSach(list_Sach.get(position).getMaSach(), context)){
Toast.makeText(context, "Đã xóa! Tối ngủ tốt.", Toast.LENGTH_SHORT).show();
list_Sach.remove(position);
list_Sach.clear();
list_Sach.addAll(SachDao.GetAll(context));
notifyDataSetChanged();
dialog.dismiss();
}
}
})
.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context, "Nước đi hay đấy", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
@Override
public int getItemCount() {
return list_Sach.size();
}
public static class SachViewHolder extends RecyclerView.ViewHolder {
CardView item;
ImageView ivAvatarSach, ivXoaSach;
TextView tvTenSach, tvTacGia, tvNXB, tvGiaBan, tvSoLuong;
public SachViewHolder(@NonNull View itemView) {
super(itemView);
item = itemView.findViewById(R.id.itemSach);
ivAvatarSach = itemView.findViewById(R.id.ivAvatarSach);
ivXoaSach = itemView.findViewById(R.id.ivXoaSach);
tvTenSach = itemView.findViewById(R.id.tvTenSach);
tvTacGia = itemView.findViewById(R.id.tvTacGia);
tvGiaBan = itemView.findViewById(R.id.tvGiaSach);
tvSoLuong = itemView.findViewById(R.id.tvSoLuong);
tvNXB = itemView.findViewById(R.id.tvNXB);
}
}
}
// TODO: mã thể loại sách tự tăng ko thay thế
// TODO: load mã thể loại của sách lên spinner để sửa sách
<file_sep>include ':app'
rootProject.name = "SuperAndroidProject"<file_sep>package com.example.superandroidproject.QuanLi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.superandroidproject.DoiMatKhauActivity;
import com.example.superandroidproject.LoginActivity;
import com.example.superandroidproject.R;
import com.example.superandroidproject.adapter.NguoiDungAdapter;
import com.example.superandroidproject.dao.NguoiDungDao;
import com.example.superandroidproject.model.NguoiDungModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class QuanLiNguoiDungActivity extends AppCompatActivity {
RecyclerView rcvNguoiDung;
FloatingActionButton fabThemNguoiDung;
NguoiDungAdapter adapter;
ArrayList<NguoiDungModel> list_NguoiDung = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quan_li_nguoi_dung);
rcvNguoiDung = findViewById(R.id.rcvNguoiDung);
rcvNguoiDung.setHasFixedSize(true);
fabThemNguoiDung = findViewById(R.id.fab_ThemNguoiDung);
// ADD Recycler View vào giao diện
RecyclerView.LayoutManager manager = new LinearLayoutManager(QuanLiNguoiDungActivity.this);
rcvNguoiDung.setLayoutManager(manager);
list_NguoiDung = NguoiDungDao.GetAll(QuanLiNguoiDungActivity.this);
adapter = new NguoiDungAdapter(QuanLiNguoiDungActivity.this, list_NguoiDung);
rcvNguoiDung.setAdapter(adapter);
// HIỆN DIALOG THÊM NGƯỜI DÙNG
fabThemNguoiDung.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogThem(QuanLiNguoiDungActivity.this);
}
});
}
// DIALOG THÊM NGƯỜI DÙNG
public void DialogThem(final Context context) {
// todo: hiện dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_them_nguoi_dung, null);
builder.setView(view);
final Dialog dialog = builder.create();
dialog.show();
// ========================================
Button btnThemNguoiDung = view.findViewById(R.id.btnThemNguoiDung);
final EditText edtTenDangNhap = view.findViewById(R.id.edtThemTenDangNhap);
final EditText edtMatKhau = view.findViewById(R.id.edtThemMatKhau);
final EditText edtMatKhau2 = view.findViewById(R.id.edtThemLaiMatKhau);
final EditText edtHoTen = view.findViewById(R.id.edtThemHoTen);
final EditText edtSoDienThoai = view.findViewById(R.id.edtThemSoDienThoai);
final Button btnHuy = view.findViewById(R.id.btnHuyThemNguoiDung);
btnThemNguoiDung.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String usernameMoi = edtTenDangNhap.getText().toString();
String matkhauMoi = edtMatKhau.getText().toString();
String matKhauMoi2 = edtMatKhau2.getText().toString();
String hoTenMoi = edtHoTen.getText().toString();
String soDienThoaiMoi = edtSoDienThoai.getText().toString();
NguoiDungModel nguoiDungMoi = new NguoiDungModel(usernameMoi, matkhauMoi, hoTenMoi, soDienThoaiMoi);
if (edtTenDangNhap.getText().toString().equals("") || edtMatKhau.getText().toString().equals("") || edtHoTen.getText().toString().equals("")) {
Toast.makeText(context, "Điền đầy đủ nào ", Toast.LENGTH_SHORT).show();
} else if (!matkhauMoi.equals(matKhauMoi2)) {
Toast.makeText(context, "Xác nhận mật khẩu không trùng khớp", Toast.LENGTH_SHORT).show();
} else {
if (NguoiDungDao.ThemNguoiDung(nguoiDungMoi, context)) {
Toast.makeText(context, "Thêm hoàn tất. Cày view Sếp thôi", Toast.LENGTH_SHORT).show();
list_NguoiDung.clear();
list_NguoiDung.addAll(NguoiDungDao.GetAll(context));
adapter.notifyDataSetChanged();
dialog.dismiss();
} else {
Toast.makeText(context, "Oi zoi oi!! Lỗi kìa", Toast.LENGTH_SHORT).show();
}
}
}
});
btnHuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}<file_sep>package com.example.superandroidproject.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.superandroidproject.database.DbHelper;
import com.example.superandroidproject.model.LoaiSachModel;
import com.example.superandroidproject.model.NguoiDungModel;
import java.util.ArrayList;
public class LoaiSachDao {
// TODO: UPDATE THÔNG TIN LOẠI SÁCH
public static boolean updateLoaiSach(LoaiSachModel ls, String tenLoaiSachMoi, String moTaMoi, int viTriMoi, Context context){
DbHelper helper = new DbHelper(context);
// TẠO CSDL SQLITE
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("tenTheLoai", tenLoaiSachMoi);
values.put("moTa", moTaMoi);
values.put("viTri", viTriMoi);
int row = db.update("TABLE_LOAI_SACH",values,"maTheLoai=? ", new String[]{String.valueOf(ls.getMaTheLoai())});
return row>0;
}
public static ArrayList<LoaiSachModel> GetAll(Context context){
ArrayList<LoaiSachModel> listLoaiSach = new ArrayList<>();
DbHelper helper = new DbHelper(context);
// TẠO CƠ SỞ DL SQL
SQLiteDatabase db = helper.getReadableDatabase();
// Câu lệnh truy vấn toàn bộ dữ liệu từ bảng TABLE_LOAI_SACH
String sql = "select * from TABLE_LOAI_SACH";
// Tạo con trỏ, trả về result set
Cursor cs = db.rawQuery(sql, null);
cs.moveToFirst();
while (!cs.isAfterLast()){
int maTheLoai = cs.getInt(0);
String tenTheLoai = cs.getString(1);
String moTa = cs.getString(2);
int viTri = cs.getInt(3);
LoaiSachModel ls = new LoaiSachModel(maTheLoai, tenTheLoai, moTa, viTri);
listLoaiSach.add(ls);
cs.moveToNext();
}
cs.close();
return listLoaiSach;
}
// THÊM LOẠI SÁCH
public static boolean ThemLoaiSach(LoaiSachModel ls, Context context){
DbHelper helper = new DbHelper(context);
// TẠO CSDL SQLITE
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("tenTheLoai", ls.getTenTheLoai());
values.put("moTa", ls.getMoTa());
values.put("viTri", ls.getViTri());
return db.insert("TABLE_LOAI_SACH", null, values) > 0;
}
// XÓA LOẠI SÁCH
public static boolean XoaLoaiSach(int maTheLoai, Context context){
DbHelper helper = new DbHelper(context);
SQLiteDatabase db = helper.getWritableDatabase();
int row = db.delete("TABLE_LOAI_SACH","maTheLoai=?",new String[]{String.valueOf(maTheLoai)});
return row>0;
}
}
<file_sep># LibraryApp
My other assignment.
| 65e1a6ed973feb2e21992b4ce8a06a9ac20d0b5f | [
"Markdown",
"Java",
"Gradle"
] | 13 | Java | huyhq01/LibraryApp | f536d4f7eb11a944d74f05d3ad1a342183d6f09e | 080b9870f5500b7bd402eedd7606899d1e3f5ad8 |
refs/heads/master | <repo_name>flashboyka/CRM<file_sep>/lots/models.py
'''
package: lots
description: models
'''
from uuid import uuid4
from django.db import models
from django.utils.translation import ugettext_lazy as _
from stocks.models import Stock
from goods.models import Good
class Currency(models.Model):
'''
model for currencies
'''
name = models.CharField(max_length=50, verbose_name=_('Currency'))
def __str__(self):
'''
overlapping str method for currency
:return:
'''
return self.name
class Meta: #pylint: disable=too-few-public-methods
'''
meta class for currency
'''
verbose_name = _('currency')
verbose_name_plural = _('currencies')
class Lot(models.Model):
'''
Model for lots
'''
lot_number = models.CharField(max_length=50,
blank=True,
editable=False,
verbose_name=_('lot number'))
good = models.ForeignKey(Good, on_delete=models.CASCADE, verbose_name=_('Product'))
base_price = models.DecimalField(max_digits=20, decimal_places=2, verbose_name=_('base price'))
series = models.CharField(max_length=20, verbose_name=_('series'))
currency = models.ForeignKey(Currency, on_delete=models.CASCADE, verbose_name=_('currency'))
shelf_life = models.DateField(verbose_name=_('shelf life'))
created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_('date of creation'))
edited = models.DateTimeField(auto_now=True, editable=False, verbose_name=_('date of edition'))
quantity = models.PositiveIntegerField(verbose_name=_('quantity'))
stock = models.ForeignKey(Stock, on_delete=models.CASCADE, null=True, verbose_name=_('Stock'))
def save(self, *args, **kwargs): #pylint: disable=arguments-differ
'''
overlapped save method for Lot method
:param args:
:param kwargs:
:return:
'''
self.lot_number = f'Партия {str(uuid4())[:8]}'
super(Lot, self).save(*args, **kwargs)
def total_amount(self):
return self.base_price * self.quantity
def __str__(self):
'''
overlapped str method for Lot model
:return:
'''
return self.lot_number
class Meta: #pylint: disable=too-few-public-methods
'''
meta class for lots
'''
verbose_name = _('Lot')
verbose_name_plural = _('Lots')
<file_sep>/revaluation/tests.py
from django.test import TestCase
from . import models
class PricingModelTestCase(TestCase):
fixtures = ['fixture_reval.json']
def setUp(self):
self.pricing = models.Pricing.objects.last()
def test_pricing_str(self):
self.assertEqual(self.pricing.__str__(), 'обычная')<file_sep>/contragents/admin.py
from django.contrib import admin
from contragents import models
class ContactInline(admin.TabularInline):
model = models.Contact
@admin.register(models.Contragent)
class ContragentAdmin(admin.ModelAdmin):
inlines = [ContactInline, ]
list_display = ['name', 'inn', 'address_ur']
@admin.register(models.Contact)
class ContactAdmin(admin.ModelAdmin):
list_display = ['last_name', 'first_name', 'middle_name', 'contragent']
<file_sep>/lots/tests.py
from decimal import Decimal
from django.test import TestCase
from . import models
class LotsModelsTestCase(TestCase):
fixtures = ['fixture_lots.json']
def setUp(self) -> None:
self.currency = models.Currency.objects.last()
self.lot = models.Lot.objects.last()
def test_lot_str(self):
self.assertEqual(self.lot.__str__(), 'Партия 875f551f')
def test_lot_save(self):
self.assertEqual(self.lot.lot_number, 'Партия 875f551f')
def test_total_amount(self):
self.lot.save()
self.assertEqual(self.lot.total_amount(), Decimal('500000.00'))
def test_currency_str(self):
self.assertEqual(self.currency.__str__(), 'сум')
<file_sep>/lots/__init__.py
default_app_config = 'lots.apps.LotsConfig'<file_sep>/crm/admin.py
from django.contrib import admin
from crm.models import AgreementTask, TaskStatus, Agreement
@admin.register(TaskStatus)
class TaskStatusAdmin(admin.ModelAdmin):
list_display = ['name', 'created', 'edited']
@admin.register(AgreementTask)
class AgreementTaskAdmin(admin.ModelAdmin):
list_display = ['status', 'created', 'edited']
@admin.register(Agreement)
class AgreementAdmin(admin.ModelAdmin):
list_display = ['code', 'result', 'created', 'edited']
list_filter = ['code', ]
<file_sep>/requirements.txt
Django==2.2.3
django-mptt>=0.10.0
django-suit==0.2.26
django-sekizai==1.0.0
pytils>=0.3
Pillow>=7.0.0
<file_sep>/lots/admin.py
from django.contrib import admin
from . import models
@admin.register(models.Lot)
class LotAdmin(admin.ModelAdmin):
list_display = ['lot_number']
@admin.register(models.Currency)
class CurrencyAdmin(admin.ModelAdmin):
list_display = ['name']<file_sep>/revaluation/apps.py
from django.apps import AppConfig
class RevaluationConfig(AppConfig):
name = 'revaluation'
<file_sep>/revaluation/admin.py
from django.contrib import admin
from . import models
@admin.register(models.Pricing)
class PricingModelAdmin(admin.ModelAdmin):
list_display = ['name']
<file_sep>/stocks/tests.py
from decimal import Decimal
from django.test import TestCase
from . import models
class StocksModelsTestCase(TestCase):
fixtures = ['fixture_stock.json']
def setUp(self) -> None:
self.stock = models.Stock.objects.last()
def test_stock_str(self):
self.assertEqual(self.stock.__str__(), 'Склад 1')
def test_stock_total_amount_base(self):
self.assertEqual(self.stock.total_amount_base(), Decimal('55.00'))
<file_sep>/requirements_test.txt
-r requirements.txt
codecov>=2.0.15
coverage>=4.5.3
Sphinx==2.3.1
rst2pdf==0.96
sphinx-rtd-theme==0.4.3
<file_sep>/stocks/models.py
'''
package: stocks
description: models
'''
from decimal import Decimal
from django.db import models
from django.utils.translation import ugettext_lazy as _
from contragents.models import Contragent
from addresses import models as addresses_models
class Stock(models.Model):
'''
Model for stocks
'''
name = models.CharField(max_length=100, verbose_name=_('Name'))
country = models.ForeignKey(addresses_models.Country, on_delete=models.CASCADE, blank=True, null=True,
verbose_name=_("Country"))
city = models.ForeignKey(addresses_models.City, on_delete=models.CASCADE, blank=True, null=True,
verbose_name=_("City"))
region = models.ForeignKey(addresses_models.Region, on_delete=models.CASCADE, blank=True, null=True,
verbose_name=_("Region"))
district = models.ForeignKey(addresses_models.District, on_delete=models.CASCADE, blank=True, null=True,
verbose_name=_("District"))
street = models.ForeignKey(addresses_models.Street, verbose_name=_("Street"), on_delete=models.CASCADE)
house = models.CharField(max_length=50, blank=True, null=True, verbose_name=_("House"))
created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_('date of creation'))
edited = models.DateTimeField(auto_now=True, editable=False, verbose_name=_('date of edition'))
def total_amount_base(self):
'''
counting total base price of all lots in particular stock
:return:
'''
summ = Decimal()
for lot in self.lot_set.all():
summ += lot.total_amount()
return summ
def __str__(self):
'''
str method for Stock model
:return:
'''
return self.name
class Meta: #pylint: disable=too-few-public-methods
'''
meta class for stock
'''
verbose_name = _('Stock')
verbose_name_plural = _('Stocks')
| b3cd0f79425f52f2ef3ca309cf52e4b87bd11fb2 | [
"Python",
"Text"
] | 13 | Python | flashboyka/CRM | 4ac624d0ce09397bfe3d474caa8f24fc05fd9cc3 | f04b4a7af120a797190ddbb6f0b8f18c023cb155 |
refs/heads/master | <repo_name>StewartNash/img_proc_7<file_sep>/README.md
# img_proc_7
Object detection and tracking based on color using OpenCV. Objects are isolated with morphologic processing and tracked using contour identification and center of mass. This program is designed to read in a video file and write to a stitched view of the original and new images.
<file_sep>/img_proc_7.cpp
/*
Author: <NAME>
File: img_proc_7.cpp
Description: Morphological isolation of red objects in video with contour tracking.
Arguments: img_proc_7.exe [input filename] [output filename]
*/
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
/*
Class pointstack is a stack of 2D float points. It has a LIFO structure.
If one attempts to push onto a full stack, the point will be pushed on
the top, and the first point will fall off of the bottom. Every element
will move down one.
The pop(Point2f & point) returns the integer place value of where the
point was popped from and places the point in the parameter passed by
reference. You could also say it returns one more than where the stack
pointer (current_point) points to after the pop(). This is returned
rather than the current stack location so that an empty stack that a
pop() was attempted on will return a zero. The push returns the position
where the point was pushed to to be consistent. This is one less than
the current position of the stack.
*/
class Pointstack
{
static const int MAX_STACK_RANGE = 250;
int current_point;
int max_point;
cv::Point2f point_array[MAX_STACK_RANGE];
public:
Pointstack();
int push(cv::Point2f point);
int pop(cv::Point2f & point);
cv::Point2f pop();
};
Pointstack::Pointstack()
{
current_point = 0;
max_point = MAX_STACK_RANGE - 1;
}
int Pointstack::push(cv::Point2f point)
{
int i;
if (current_point < max_point)
point_array[++current_point] = point;
else
{
for (i = 1; i < max_point; i++)
point_array[i-1] = point_array[i];
point_array[i-1] = point_array[i];
point_array[i] = point;
return current_point;
}
return current_point - 1;
}
cv::Point2f Pointstack::pop()
{
if (current_point > 0)
return point_array[current_point--];
else
{
//std::cout << "Error: attempted Pointstack::pop() with empty stack. Returning error_point (-1, -1).\n";
cv::Point2f error_point(-1, -1);
return error_point;
}
}
int Pointstack::pop(cv::Point2f & point)
{
if (current_point > 0)
point = point_array[current_point--];
else
{
//std::cout << "Error: attempted Pointstack::pop(cv::Point2f point) with empty stack. Returning 0. Point set to error_point, (-1, -1).\n";
cv::Point2f error_point(-1, -1);
point = error_point;
return 0;
}
return current_point + 1;
}
Pointstack myGlobalPoints;
//Create process_image with a class parameter which encapsulates hue, saturation and value.
int process_image(Mat & inputImage, Mat & outputImage);
//Track the detected objects with a bounding box and indication of center of mass.
int add_tracking(Mat & inputImage, Mat & outputImage);
const int RANGES = 2;
/*
Variables
---------
myVideo - input video file.
myOutput - created video file to write to.
myImage - captured frame for processing.
myCOpy - copy of captured frame for processing.
myMask - single channel storage for morphologic processing.
*/
int main(int argc, char * argv[])
{
VideoCapture myVideo;
VideoWriter myOutput;
Mat myImage;
Mat myCopy;
Mat myMask;
int elem_width;
int elem_height;
int i, j;
if (argc > 1)
myVideo.open(argv[1]);
else
{
std::cout << "No filename provided.";
waitKey(0);
return 0;
}
//myVideo.open("F:/Documents/Visual Studio 2010/Projects/img_proc_7/Debug/red_balloon.avi");
if (!myVideo.isOpened())
{
std::cout << "Unable to open file.";
waitKey(0);
return 0;
}
elem_width = (int) myVideo.get(CV_CAP_PROP_FRAME_WIDTH);
elem_height = (int) myVideo.get(CV_CAP_PROP_FRAME_HEIGHT);
Size mySize = Size(2 * elem_width, elem_height);
if (argc > 2)
myOutput.open(argv[2], CV_FOURCC('M','J','P','G'), myVideo.get(CV_CAP_PROP_FPS), mySize);
else
myOutput.open("output.avi", CV_FOURCC('M','J','P','G'), myVideo.get(CV_CAP_PROP_FPS), mySize);
//myOutput.open("F:/Documents/Visual Studio 2010/Projects/img_proc_7/Debug/img_proc_7_out.avi", CV_FOURCC('M','J','P','G'), myVideo.get(CV_CAP_PROP_FPS), mySize);
if (!myOutput.isOpened())
{
std::cout << "Unable to create file.";
waitKey(0);
return 0;
}
//Left and right halves of stitched video frame given a ROI.
Mat myStitch(elem_height, 2 * elem_width, CV_8UC3);
Mat myLeft(myStitch, Rect(0, 0, elem_width, elem_height));
Mat myRight(myStitch, Rect(elem_width, 0, elem_width, elem_height));
j = (int) myVideo.get(CV_CAP_PROP_FRAME_COUNT);
//j = 30000;
for (i = 0; i < j; i++)
{
std::cout << "frame " << i << " of " << j << std::endl;
myVideo >> myImage;
process_image(myImage, myMask);
cvtColor(myMask, myCopy, CV_GRAY2BGR);
add_tracking(myMask, myCopy);
myImage.copyTo(myLeft);
myCopy.copyTo(myRight);
myOutput << myStitch;
}
myVideo.release();
return 0;
}
int process_image(Mat & inputImage, Mat & outputImage)
{
Mat myCopy;
Mat myMask[RANGES];
Mat myKernel;
int lowHue[RANGES], highHue[RANGES], lowSat[RANGES], highSat[RANGES], lowVal[RANGES], highVal[RANGES];
int elem_size_x;
int elem_size_y;
int i;
elem_size_x = 7;
elem_size_y = 7;
lowHue[0] = 165;
highHue[0] = 179;
lowSat[0] = 230;
highSat[0] = 255;
lowVal[0] = 64;
highVal[0] = 255;
lowHue[1] = 0;
highHue[1] = 30;
lowSat[1] = 230;
highSat[1] = 255;
lowVal[1] = 64;
highVal[1] = 255;
myKernel = getStructuringElement(MORPH_RECT, Size(elem_size_x, elem_size_y));
cvtColor(inputImage, myCopy, COLOR_BGR2HSV);
for (i = 0; i < RANGES; i++)
inRange(myCopy, Scalar(lowHue[i], lowSat[i], lowVal[i]), Scalar(highHue[i], highSat[i], highVal[i]), myMask[i]);
myMask[0].copyTo(outputImage);
outputImage = Scalar(0);
//Combine masks with logical or.
for (i = 0; i < RANGES; i++)
bitwise_or(outputImage, myMask[i], outputImage);
//Perform morphological processing.
erode(outputImage, outputImage, myKernel);
dilate(outputImage, outputImage, myKernel);
dilate(outputImage, outputImage, myKernel);
erode(outputImage, outputImage, myKernel);
return 0;
}
int add_tracking(Mat & inputImage, Mat & outputImage)
{
vector <vector <Point>> vecContours;
vector <Vec4i> vecHeirarchy;
int contour_size;
int i;
int circ_radius;
float minimum_area;
Scalar myColor1(0, 255, 0);
Scalar myColor2(0, 0, 255);
Point2f temp_point(0, 0);
Pointstack myCopy;
minimum_area = 20 * 20;
circ_radius = 2;
findContours(inputImage, vecContours, vecHeirarchy, RETR_LIST, CHAIN_APPROX_SIMPLE);
contour_size = vecContours.size();
vector <int> vecContId(contour_size);
vector <float> vecContArea(contour_size);
vector <Moments> vecMoment(contour_size);
vector <Point2f> vecMassCenter(contour_size);
for (i = 0; i < contour_size; i++)
{
//Order objects by appearance and find areas.
vecContId[i] = i;
vecContArea[i] = contourArea(vecContours[i]);
//Find center of mass.
vecMoment[i] = moments(vecContours[i]);
vecMassCenter[i] = Point2f(vecMoment[i].m10 / vecMoment[i].m00, vecMoment[i].m01 / vecMoment[i].m00);
//Draw bounding rectangle and push mass centers of larger objects on stack.
if (vecContArea[i] >= minimum_area)
{
rectangle(outputImage, boundingRect(vecContours[i]), myColor1);
myGlobalPoints.push(vecMassCenter[i]);
}
}
//Display center of mass of all points on stack.
while (i = myGlobalPoints.pop(temp_point))
{
circle(outputImage, temp_point, circ_radius, myColor2);
myCopy.push(temp_point);
}
while (i = myCopy.pop(temp_point))
myGlobalPoints.push(temp_point);
return 0;
} | db5e4b744f6f627026b590bf080a3830d3be01f5 | [
"Markdown",
"C++"
] | 2 | Markdown | StewartNash/img_proc_7 | 230c18633520d0a73b7929808b8dbf262d897485 | ebb234c20c07862aa0572be96154f2f9f8f49dd2 |
refs/heads/master | <file_sep>import * as grpc from "grpc";
import * as invokerSvc from "../../src/lib/api/proto/invoker/v1/invoker_grpc_pb";
import * as invokerMsg from "../../src/lib/api/proto/invoker/v1/invoker_pb";
let server: grpc.Server;
function createInvokeRstFromReq(
req: invokerMsg.InvokeRequest,
) {
return createInvokeRst(
req.getActname(),
req.getArg(),
);
}
function createInvokeRst(
act: string,
arg: string,
) {
return `invoke requested for ${act} with ${arg} by Box`;
}
function createUnimplemented<TReq, TRes>() {
return (
_: grpc.ServerUnaryCall<TReq>,
cb: grpc.requestCallback<TRes>,
) => {
cb({
name: grpc.status.UNIMPLEMENTED.toString(),
code: grpc.status.UNIMPLEMENTED,
message: "out of scope for this package",
});
};
}
function serve(port = 5122, host = "0,0,0,0") {
server = new grpc.Server();
server.addService(invokerSvc.InvokerService, {
invoke: svcInvoke,
add: createUnimplemented<invokerMsg.AddRequest, invokerMsg.AddResponse>(),
list: createUnimplemented<invokerMsg.ListRequest, invokerMsg.ListResponse>(),
remove: createUnimplemented<invokerMsg.RemoveRequest, invokerMsg.RemoveResponse>(),
});
server.bind(`${host}:${port}`, grpc.ServerCredentials.createInsecure());
server.start();
}
function svcInvoke(
req: grpc.ServerUnaryCall<invokerMsg.InvokeRequest>,
cb: grpc.requestCallback<invokerMsg.InvokeResponse>,
) {
const args = req.request;
const res = new invokerMsg.InvokeResponse();
if (args.getActname() === "") {
cb({
name: grpc.status.INVALID_ARGUMENT.toString(),
code: grpc.status.INVALID_ARGUMENT,
message: "name of activity not provided",
});
return;
}
res.setResult(createInvokeRstFromReq(args));
cb(null, res);
}
function stop() {
server.forceShutdown();
}
export {
createInvokeRst,
serve,
stop,
};
<file_sep>import Box from "./box";
const HOST = process.env.AGENT_HOST || "0.0.0.0";
const PORT = process.env.AGENT_PORT || 5122;
export = new Box(HOST, PORT);
<file_sep>import * as grpc from "grpc";
import * as invokerSvc from "./lib/api/proto/invoker/v1/invoker_grpc_pb";
import * as invokerMsg from "./lib/api/proto/invoker/v1/invoker_pb";
class Box {
private _client: invokerSvc.InvokerClient;
constructor(
host: string,
port: string | number,
) {
const addr = `${host}:${port}`;
this._client = new invokerSvc.InvokerClient(addr, grpc.credentials.createInsecure());
}
public async invoke(act: string, arg: string) {
const req = new invokerMsg.InvokeRequest();
// the username will be decided by agent
req.setActname(act);
req.setArg(arg);
return new Promise((resolve, reject) => {
this._client.invoke(req, (err, res) => {
if (err) {
reject(err);
return;
}
res ? resolve(res.getResult())
: resolve(res);
});
});
}
}
export default Box;
<file_sep>"use strict";
const box_1 = require("./box");
const HOST = process.env.AGENT_HOST || "0.0.0.0";
const PORT = process.env.AGENT_PORT || 5122;
module.exports = new box_1.default(HOST, PORT);
<file_sep>import { expect, use } from "chai";
import * as chaiAsPromised from "chai-as-promised";
import Box from "../src/box";
import * as mockServer from "./mock/server";
use(chaiAsPromised);
const HOST = "0.0.0.0";
const PORT = 51201;
describe("box with the mock server", () => {
before(() => {
mockServer.serve(PORT, HOST);
});
after(() => {
mockServer.stop();
});
it("invokes an activity", async () => {
const act = "open";
const arg = "Jerry's stupid mayonnaise jar";
const box = new Box(HOST, PORT);
const rst = await box.invoke(act, arg);
expect(rst).to.equal(mockServer.createInvokeRst(act, arg));
});
it("must fail when request without activity name", async () => {
const act = "";
const arg = "two strokes off of Jerry's golf game";
const box = new Box(HOST, PORT);
await expect(box.invoke(act, arg)).to.eventually.be.rejected;
});
});
<file_sep>// package: mee6aas.agent.invoker.v1
// file: invoker.proto
/* tslint:disable */
import * as jspb from "google-protobuf";
export class InvokeRequest extends jspb.Message {
getUsername(): string;
setUsername(value: string): void;
getActname(): string;
setActname(value: string): void;
getArg(): string;
setArg(value: string): void;
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): InvokeRequest.AsObject;
static toObject(includeInstance: boolean, msg: InvokeRequest): InvokeRequest.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: InvokeRequest, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): InvokeRequest;
static deserializeBinaryFromReader(message: InvokeRequest, reader: jspb.BinaryReader): InvokeRequest;
}
export namespace InvokeRequest {
export type AsObject = {
username: string,
actname: string,
arg: string,
}
}
export class InvokeResponse extends jspb.Message {
getResult(): string;
setResult(value: string): void;
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): InvokeResponse.AsObject;
static toObject(includeInstance: boolean, msg: InvokeResponse): InvokeResponse.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: InvokeResponse, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): InvokeResponse;
static deserializeBinaryFromReader(message: InvokeResponse, reader: jspb.BinaryReader): InvokeResponse;
}
export namespace InvokeResponse {
export type AsObject = {
result: string,
}
}
export class AddRequest extends jspb.Message {
getUsername(): string;
setUsername(value: string): void;
getActname(): string;
setActname(value: string): void;
getMethod(): AddMethod;
setMethod(value: AddMethod): void;
getPath(): string;
setPath(value: string): void;
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): AddRequest.AsObject;
static toObject(includeInstance: boolean, msg: AddRequest): AddRequest.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: AddRequest, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): AddRequest;
static deserializeBinaryFromReader(message: AddRequest, reader: jspb.BinaryReader): AddRequest;
}
export namespace AddRequest {
export type AsObject = {
username: string,
actname: string,
method: AddMethod,
path: string,
}
}
export class AddResponse extends jspb.Message {
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): AddResponse.AsObject;
static toObject(includeInstance: boolean, msg: AddResponse): AddResponse.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: AddResponse, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): AddResponse;
static deserializeBinaryFromReader(message: AddResponse, reader: jspb.BinaryReader): AddResponse;
}
export namespace AddResponse {
export type AsObject = {
}
}
export class ListRequest extends jspb.Message {
getUsername(): string;
setUsername(value: string): void;
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): ListRequest.AsObject;
static toObject(includeInstance: boolean, msg: ListRequest): ListRequest.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: ListRequest, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): ListRequest;
static deserializeBinaryFromReader(message: ListRequest, reader: jspb.BinaryReader): ListRequest;
}
export namespace ListRequest {
export type AsObject = {
username: string,
}
}
export class ManagedActivity extends jspb.Message {
getName(): string;
setName(value: string): void;
getRuntime(): string;
setRuntime(value: string): void;
getAdded(): string;
setAdded(value: string): void;
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): ManagedActivity.AsObject;
static toObject(includeInstance: boolean, msg: ManagedActivity): ManagedActivity.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: ManagedActivity, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): ManagedActivity;
static deserializeBinaryFromReader(message: ManagedActivity, reader: jspb.BinaryReader): ManagedActivity;
}
export namespace ManagedActivity {
export type AsObject = {
name: string,
runtime: string,
added: string,
}
}
export class ListResponse extends jspb.Message {
clearActivitiesList(): void;
getActivitiesList(): Array<ManagedActivity>;
setActivitiesList(value: Array<ManagedActivity>): void;
addActivities(value?: ManagedActivity, index?: number): ManagedActivity;
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): ListResponse.AsObject;
static toObject(includeInstance: boolean, msg: ListResponse): ListResponse.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: ListResponse, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): ListResponse;
static deserializeBinaryFromReader(message: ListResponse, reader: jspb.BinaryReader): ListResponse;
}
export namespace ListResponse {
export type AsObject = {
activitiesList: Array<ManagedActivity.AsObject>,
}
}
export class RemoveRequest extends jspb.Message {
getUsername(): string;
setUsername(value: string): void;
getActname(): string;
setActname(value: string): void;
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): RemoveRequest.AsObject;
static toObject(includeInstance: boolean, msg: RemoveRequest): RemoveRequest.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: RemoveRequest, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): RemoveRequest;
static deserializeBinaryFromReader(message: RemoveRequest, reader: jspb.BinaryReader): RemoveRequest;
}
export namespace RemoveRequest {
export type AsObject = {
username: string,
actname: string,
}
}
export class RemoveResponse extends jspb.Message {
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): RemoveResponse.AsObject;
static toObject(includeInstance: boolean, msg: RemoveResponse): RemoveResponse.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: RemoveResponse, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): RemoveResponse;
static deserializeBinaryFromReader(message: RemoveResponse, reader: jspb.BinaryReader): RemoveResponse;
}
export namespace RemoveResponse {
export type AsObject = {
}
}
export enum AddMethod {
UNKOWN = 0,
LOCAL = 1,
GLOBAL = 2,
}
<file_sep>// package: mee6aas.agent.invoker.v1
// file: invoker.proto
/* tslint:disable */
import * as grpc from "grpc";
import * as invoker_pb from "./invoker_pb";
interface IInvokerService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
invoke: IInvokerService_IInvoke;
add: IInvokerService_IAdd;
list: IInvokerService_IList;
remove: IInvokerService_IRemove;
}
interface IInvokerService_IInvoke extends grpc.MethodDefinition<invoker_pb.InvokeRequest, invoker_pb.InvokeResponse> {
path: string; // "/mee6aas.agent.invoker.v1.Invoker/Invoke"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<invoker_pb.InvokeRequest>;
requestDeserialize: grpc.deserialize<invoker_pb.InvokeRequest>;
responseSerialize: grpc.serialize<invoker_pb.InvokeResponse>;
responseDeserialize: grpc.deserialize<invoker_pb.InvokeResponse>;
}
interface IInvokerService_IAdd extends grpc.MethodDefinition<invoker_pb.AddRequest, invoker_pb.AddResponse> {
path: string; // "/mee6aas.agent.invoker.v1.Invoker/Add"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<invoker_pb.AddRequest>;
requestDeserialize: grpc.deserialize<invoker_pb.AddRequest>;
responseSerialize: grpc.serialize<invoker_pb.AddResponse>;
responseDeserialize: grpc.deserialize<invoker_pb.AddResponse>;
}
interface IInvokerService_IList extends grpc.MethodDefinition<invoker_pb.ListRequest, invoker_pb.ListResponse> {
path: string; // "/mee6aas.agent.invoker.v1.Invoker/List"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<invoker_pb.ListRequest>;
requestDeserialize: grpc.deserialize<invoker_pb.ListRequest>;
responseSerialize: grpc.serialize<invoker_pb.ListResponse>;
responseDeserialize: grpc.deserialize<invoker_pb.ListResponse>;
}
interface IInvokerService_IRemove extends grpc.MethodDefinition<invoker_pb.RemoveRequest, invoker_pb.RemoveResponse> {
path: string; // "/mee6aas.agent.invoker.v1.Invoker/Remove"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<invoker_pb.RemoveRequest>;
requestDeserialize: grpc.deserialize<invoker_pb.RemoveRequest>;
responseSerialize: grpc.serialize<invoker_pb.RemoveResponse>;
responseDeserialize: grpc.deserialize<invoker_pb.RemoveResponse>;
}
export const InvokerService: IInvokerService;
export interface IInvokerServer {
invoke: grpc.handleUnaryCall<invoker_pb.InvokeRequest, invoker_pb.InvokeResponse>;
add: grpc.handleUnaryCall<invoker_pb.AddRequest, invoker_pb.AddResponse>;
list: grpc.handleUnaryCall<invoker_pb.ListRequest, invoker_pb.ListResponse>;
remove: grpc.handleUnaryCall<invoker_pb.RemoveRequest, invoker_pb.RemoveResponse>;
}
export interface IInvokerClient {
invoke(request: invoker_pb.InvokeRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.InvokeResponse) => void): grpc.ClientUnaryCall;
invoke(request: invoker_pb.InvokeRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.InvokeResponse) => void): grpc.ClientUnaryCall;
invoke(request: invoker_pb.InvokeRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.InvokeResponse) => void): grpc.ClientUnaryCall;
add(request: invoker_pb.AddRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.AddResponse) => void): grpc.ClientUnaryCall;
add(request: invoker_pb.AddRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.AddResponse) => void): grpc.ClientUnaryCall;
add(request: invoker_pb.AddRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.AddResponse) => void): grpc.ClientUnaryCall;
list(request: invoker_pb.ListRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.ListResponse) => void): grpc.ClientUnaryCall;
list(request: invoker_pb.ListRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.ListResponse) => void): grpc.ClientUnaryCall;
list(request: invoker_pb.ListRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.ListResponse) => void): grpc.ClientUnaryCall;
remove(request: invoker_pb.RemoveRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.RemoveResponse) => void): grpc.ClientUnaryCall;
remove(request: invoker_pb.RemoveRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.RemoveResponse) => void): grpc.ClientUnaryCall;
remove(request: invoker_pb.RemoveRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.RemoveResponse) => void): grpc.ClientUnaryCall;
}
export class InvokerClient extends grpc.Client implements IInvokerClient {
constructor(address: string, credentials: grpc.ChannelCredentials, options?: object);
public invoke(request: invoker_pb.InvokeRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.InvokeResponse) => void): grpc.ClientUnaryCall;
public invoke(request: invoker_pb.InvokeRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.InvokeResponse) => void): grpc.ClientUnaryCall;
public invoke(request: invoker_pb.InvokeRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.InvokeResponse) => void): grpc.ClientUnaryCall;
public add(request: invoker_pb.AddRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.AddResponse) => void): grpc.ClientUnaryCall;
public add(request: invoker_pb.AddRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.AddResponse) => void): grpc.ClientUnaryCall;
public add(request: invoker_pb.AddRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.AddResponse) => void): grpc.ClientUnaryCall;
public list(request: invoker_pb.ListRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.ListResponse) => void): grpc.ClientUnaryCall;
public list(request: invoker_pb.ListRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.ListResponse) => void): grpc.ClientUnaryCall;
public list(request: invoker_pb.ListRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.ListResponse) => void): grpc.ClientUnaryCall;
public remove(request: invoker_pb.RemoveRequest, callback: (error: grpc.ServiceError | null, response: invoker_pb.RemoveResponse) => void): grpc.ClientUnaryCall;
public remove(request: invoker_pb.RemoveRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: invoker_pb.RemoveResponse) => void): grpc.ClientUnaryCall;
public remove(request: invoker_pb.RemoveRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: invoker_pb.RemoveResponse) => void): grpc.ClientUnaryCall;
}
| ea4939851d72372d779487d524a5449f2e53d862 | [
"JavaScript",
"TypeScript"
] | 7 | TypeScript | mee6aas/box-nodejs | d890daa77b142734553eb0f9b9fa973460d11fbf | 5f9ae0fbdef048ec7f542c481bc5aca7ee298cdb |
refs/heads/master | <file_sep>// ****************************************************************************
// *** Arm, Disarm and Calibrate
// ****************************************************************************
void read_sticks(){
///////////////////////// REGULAR MODE ///////////////////////////////////
if (MODE_ST == 1) {
// Arm, Disarm and Calibrate
if(rcInput[RX_THRO] - throttletrim < OFFSTICK && rxFirst != 0) {
if(rxLoss < 50) {
if(rcInput[RX_AILE] < MAXTHRESH && rcInput[RX_AILE] > MINTHRESH) {
if(rcInput[RX_ELEV] > MAXTHRESH) {
// Arm
if(zeroThrotCounter++ > ZEROTHROTMAX) {
zeroThrotCounter = 0;
Arm();
}
}
else if(rcInput[RX_ELEV] < MINTHRESH) {
// Disarm
if(zeroThrotCounter++ > ZEROTHROTMAX) {
zeroThrotCounter = 0;
Disarm();
}
}
else {
zeroThrotCounter = 0;
}
}
else if(rcInput[RX_ELEV] < MAXTHRESH && rcInput[RX_ELEV] > MINTHRESH) {
if(rcInput[RX_AILE] > MAXTHRESH) {
// Request gyro calibration
// TODO: This needs to be swapped for orientation calibration
if(zeroThrotCounter++ > ZEROTHROTMAX) {
zeroThrotCounter = 0;
CalibrateGyro();
}
}
else if(rcInput[RX_AILE] < MINTHRESH) {
// Request magneto calibration
if(zeroThrotCounter++ > ZEROTHROTMAX) {
zeroThrotCounter = 0;
CalibrateMagneto();
}
}
}
}
else {
zeroThrotCounter = 0;
}
}
// General Flight Demands
else {
// In manual mode, set pitch and roll demands based on the user commands collected from the rx unit
user.pitch = -((float)MIDSTICK - (float)rcInput[RX_ELEV])*PITCH_SENS;
user.roll = ((float)MIDSTICK - (float)rcInput[RX_AILE])*ROLL_SENS;
float tempf = -(float)(yawtrim - rcInput[RX_RUDD])*YAW_SENS;
user.throttle = rcInput[RX_THRO] - throttletrim;
throttle = user.throttle;
if (throttle < 0) throttle = 0;
// A yaw rate is demanded by the rudder input, not an absolute angle.
// This code increments the demanded angle at a rate proportional to the rudder input
if(fabsf(tempf) > YAW_DEADZONE) {
user.yaw += tempf;
if(user.yaw > M_PI) {
user.yaw -= M_TWOPI;
}
else if(user.yaw < -M_PI) {
user.yaw += M_TWOPI;
}
}
}
}
}
void ReadRXInput(void) {
if(RXGetData(rcInput)) {
if(rxLoss > 10) rxLoss -= 10;
ilink_inputs0.channel[0] = rcInput[RX_THRO];
ilink_inputs0.channel[1] = rcInput[RX_AILE];
ilink_inputs0.channel[2] = rcInput[RX_ELEV];
ilink_inputs0.channel[3] = rcInput[RX_RUDD];
ilink_inputs0.channel[4] = rcInput[RX_AUX1];
ilink_inputs0.channel[5] = rcInput[RX_FLAP];
ilink_inputs0.isNew = 1;
if(rxFirst < 25) {
throttletrim = rcInput[RX_THRO];
rxFirst++;
}
// Controller's aux or gear switch (Can be switched permanently either way)
if(rcInput[RX_AUX1] > MIDSTICK) {
// TEMPORARY FOR TESTING, switches into GPS mode
if(auxState != 0) {
ilink_thalctrl_tx.command = 0x0091;
auxState = 0;
}
}
else {
// TEMPORARY FOR TESTING, switches into GPS mode
if(auxState != 1) {
ilink_thalctrl_tx.command = 0x0090;
auxState = 1;
}
}
// Controller's flap switch/ button (mechanically sprung return)
if(rcInput[RX_FLAP] > MIDSTICK) {
if((flapState == 0) && (flpswitch == 0)) {
flapState = 1;
flpswitch = 1;
}
if((flapState == 1) && (flpswitch == 0)) {
flapState = 0;
flpswitch = 1;
}
}
else {
flpswitch = 0;
}
flashVLED = 0;
LEDOff(VLED);
}
else {
rxLoss ++;
if(rxLoss > 50) {
rxLoss = 50;
// RC signal lost
// TODO: Perform RC signal loss state setting
if(armed) PWMSetNESW(THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET);
ilink_outputs0.channel[0] = THROTTLEOFFSET;
ilink_outputs0.channel[1] = THROTTLEOFFSET;
ilink_outputs0.channel[2] = THROTTLEOFFSET;
ilink_outputs0.channel[3] = THROTTLEOFFSET;
flashVLED = 2;
}
}
}<file_sep>// Initialiser function: sets everything up.
void setup() {
throttle_angle = 0;
// *** LED setup
LEDInit(PLED | VLED);
LEDOff(PLED | VLED);
flashPLED = 0;
flashVLED = 0;
flashRLED = 0;
armed = 0;
calib = 0;
zeroThrotCounter = 0;
// *** Timers and couters6
rxLoss = 50;
ultraLoss = ULTRA_OVTH + 1;
sysMS = 0;
sysUS = 0;
SysTickInit(); // SysTick enable (default 1ms)
// *** Parameters
paramCount = sizeof(paramStorage)/20;
EEPROMLoadAll();
paramSendCount = paramCount;
paramSendSingle = 0;
// *** Establish ILink
ilink_thalstat.sensorStatus = 1; // set ilink status to boot
ilink_thalstat.flightMode = (0x1 << 0); // attitude control
ilink_identify.deviceID = WHO_AM_I;
ilink_identify.firmVersion = FIRMWARE_VERSION;
ILinkInit(SLAVE);
// *** Initialise input
throttle = 0;
rxFirst = 0;
auxState = 0;
RXInit();
// *** Initialise Ultrasound
UltraInit();
// *** Battery sensor
ADCInit(CHN7);
ADCTrigger(CHN7);
Delay(1);
ilink_thalstat.battVoltage = (ADCGet() * 6325) >> 10; // Because the factor is 6325/1024, we can do this in integer maths by right-shifting 10 bits instead of dividing by 1024.
batteryVoltage = 0;
// *** Calibrate Sensors
Delay(500);
SensorInit();
SensorZero();
// *** quaternion AHRS init
q1 = 1;
q2 = 0;
q3 = 0;
q4 = 0;
// *** Rotation matrix Initialisation
M1 = 1;
M2 = 0;
M3 = 0;
M4 = 0;
M5 = 1;
M6 = 0;
M7 = 0;
M8 = 0;
M9 = 1;
// *** Rotation matrix Initialisation
RM1 = 1;
RM2 = 0;
RM3 = 0;
RM4 = 0;
RM5 = 1;
RM6 = 0;
RM7 = 0;
RM8 = 0;
RM9 = 1;
// *** Timer for AHRS
// Set high confidence in accelerometer/magneto to rotate AHRS to initial heading
float tempAccelKp = DRIFT_AccelKp;
float tempMagKp = DRIFT_MagKp;
//TODO: this is SO wrong
DRIFT_MagKp = 10;
DRIFT_AccelKp = 10;
Timer0Init(59);
Timer0Match0(1200000/FAST_RATE, INTERRUPT | RESET);
Delay(1000);
DRIFT_MagKp = tempMagKp;
DRIFT_AccelKp = tempAccelKp;
slowSoftscale = 0;
// *** Initialise PWM outputs
motorN = 0;
motorE = 0;
motorS = 0;
motorW = 0;
motorNav = 0;
motorEav = 0;
motorSav = 0;
motorWav = 0;
Gyro.Y.error = 0;
Gyro.X.error = 0;
Gyro.Z.error = 0;
throttleHoldOff = 1;
// *** Initialise timers and loops
//PWMInit(PWM_NESW);
PWMInit(PWM_X | PWM_Y);
RITInitms(1000/MESSAGE_LOOP_HZ);
flashPLED = 0;
LEDOff(PLED);
}<file_sep>#include "thal.h"
// Buttons and LED stuff
volatile unsigned int PRGTimer;
volatile unsigned int PRGLastState;
volatile unsigned int PRGPushTime;
volatile unsigned int PRGBlankTimer;
unsigned int PRGMode;
unsigned int sysMS;
unsigned int flashVLED;
// Xbee stuff
xbee_modem_status_t xbee_modem_status;
xbee_at_command_t xbee_at_command;
xbee_at_response_t xbee_at_response;
xbee_transmit_status_t xbee_transmit_status;
xbee_receive_packet_t xbee_receive_packet;
xbee_transmit_request_t xbee_transmit_request;
xbee_node_identification_indicator_t xbee_node_identification_indicator;
#define ADDRESSLIST_SIZE 20
#define STRIKE_COUNT_MAX 100
unsigned short networkAddressList[ADDRESSLIST_SIZE];
unsigned long long sourceAddressList[ADDRESSLIST_SIZE];
unsigned char strikeAddressList[ADDRESSLIST_SIZE];
unsigned int addressListCount;
void StrikeNetworkAddress(unsigned short networkAddress);
void AddNetworkAddress(unsigned short networkAddress, unsigned long long sourceAddress);
void SendToList(unsigned char * buffer, unsigned int length);
void AddNetworkAddress(unsigned short networkAddress, unsigned long long sourceAddress) {
unsigned int i, found;
found = 0;
for(i=0; i<addressListCount; i++) {
if(sourceAddressList[i] == sourceAddress) {
networkAddressList[i] = networkAddress;
strikeAddressList[i] = 0;
found = 1;
break;
}
}
if(found == 0) {
if(addressListCount < ADDRESSLIST_SIZE) {
networkAddressList[addressListCount] = networkAddress;
sourceAddressList[addressListCount] = sourceAddress;
strikeAddressList[addressListCount] = 0;
addressListCount++;
}
}
}
void StrikeNetworkAddress(unsigned short networkAddress) {
unsigned int i;
for(i=0; i<addressListCount; i++) {
if(networkAddressList[i] == networkAddress) {
strikeAddressList[i]++;
// check to see if maximum strikes reached
if(strikeAddressList[i] > STRIKE_COUNT_MAX) {
// drop the address and move the last address into place
if(addressListCount > 1) {
networkAddressList[i] = networkAddressList[addressListCount-1];
sourceAddressList[i] = sourceAddressList[addressListCount-1];
strikeAddressList[i] = strikeAddressList[addressListCount-1];
}
if(addressListCount > 0) addressListCount--;
}
break;
}
}
}
void SendToList(unsigned char * buffer, unsigned int length) {
unsigned int i;
for(i=0; i<length; i++) {
xbee_transmit_request.RFData[i] = buffer[i];
}
xbee_transmit_request.varLen = length;
for(i=0; i<addressListCount; i++) {
xbee_transmit_request.networkAddress = networkAddressList[i];
xbee_transmit_request.destinationAddress = sourceAddressList[i]; //broadcast (big-endian)
XBeeSendPacket();
}
}
// CDC stuff
#define CDCBUFSIZE 255
unsigned char CDCBuf[CDCBUFSIZE];
volatile unsigned int CDCCount;
volatile unsigned int CDCFlag;
volatile unsigned int CDCTimeout;
// Mode/EEPROM stuff
#define EEPROM_SETTING_ADDR 0x261
#define EEPROM_XBEE_MODE 0xff
#define EEPROM_BYPASS_MODE 0xfe
unsigned int XBeeBypassMode;
void setup () {
LEDInit(PLED);
LEDOn(PLED);
flashVLED = 0;
XBeeInit();
addressListCount = 0;
// Check to see if we should go into bypass mode
if(EEPROMReadByte(EEPROM_SETTING_ADDR) == EEPROM_BYPASS_MODE) {
XBeeStartBypass();
XBeeBypassMode = 1;
}
else {
XBeeBypassMode = 0;
}
// Initialise virtual serial port
CDCInit(VIRTUAL);
CDCCount = 0;
LEDOff(PLED);
LEDInit(VLED);
LEDWrite(VLED, XBeeBypassMode);
PRGBlankTimer = 100;
PRGPushTime = 0;
PRGTimer = 0;
PRGMode = 0;
}
void loop() {
if(PRGBlankTimer == 0) {
// provide some visual feedback when using the buttons, this LED comes on after 3 seconds, and then off after 8 (or vice versa in bypass mode)
if(PRGTimer > 8000) {
LEDWrite(VLED, XBeeBypassMode);
}
else if(PRGTimer > 3000) {
LEDWrite(VLED, 1-XBeeBypassMode);
}
// begin working out button presses
if(PRGPushTime > 15000) { // Factory reset the XBee
flashVLED = 5;
EEPROMWriteByte(EEPROM_SETTING_ADDR, EEPROM_XBEE_MODE);
XBeeStopBypass();
XBeeBypassMode = 0;
XBeeFactoryReset();
PRGPushTime = 0;
PRGTimer = 0;
PRGBlankTimer = 100;
}
else if(PRGPushTime > 8000) { // Toggle bypass mode
flashVLED = 5;
if(XBeeBypassMode) {
if(EEPROMReadByte(EEPROM_SETTING_ADDR) != EEPROM_XBEE_MODE) EEPROMWriteByte(EEPROM_SETTING_ADDR, EEPROM_XBEE_MODE);
XBeeStopBypass();
XBeeBypassMode = 0;
}
else {
if(EEPROMReadByte(EEPROM_SETTING_ADDR) != EEPROM_BYPASS_MODE) EEPROMWriteByte(EEPROM_SETTING_ADDR, EEPROM_BYPASS_MODE);
XBeeStartBypass();
XBeeBypassMode = 1;
}
PRGPushTime = 0;
PRGTimer = 0;
PRGBlankTimer = 100;
}
else if(PRGPushTime > 3000) { // Create new network
flashVLED = XBEE_JOINPERIOD*10;
XBeeCoordinatorJoin();
PRGMode = 1;
PRGPushTime = 0;
PRGTimer = 0;
PRGBlankTimer = 100;
}
else if(PRGPushTime > 50) {
if(PRGMode == 0) {
flashVLED = XBEE_JOINPERIOD*10;
XBeeAllowJoin();
PRGMode = 1;
}
else {
flashVLED = 1;
XBeeStopJoin();
PRGMode = 0;
}
PRGPushTime = 0;
PRGTimer = 0;
PRGBlankTimer = 100;
}
}
if(XBeeBypassMode == 0 && CDCTimeout == 0 && CDCCount > 0) {
SendToList(CDCBuf, CDCCount);
CDCCount = 0;
}
}
void SysTickInterrupt() {
if(PRGBlankTimer) {
PRGBlankTimer--;
}
else {
if(PRGPoll() == 0) {
PRGTimer++;
PRGLastState = 0;
}
else {
if(PRGLastState == 0) {
PRGPushTime = PRGTimer;
}
PRGTimer = 0;
PRGLastState = 1;
}
}
sysMS++;
if(sysMS % 100 == 0) {
if(flashVLED > 0) {
flashVLED--;
LEDToggle(VLED);
if(flashVLED == 0) LEDWrite(VLED, XBeeBypassMode);
}
}
if(CDCTimeout) {
CDCTimeout--;
}
}
void XBeeMessage(unsigned char id, unsigned char * buffer, unsigned short length) {
if(XBeeBypassMode) {
CDCWrite(buffer, length);
}
else {
unsigned char * ptr = 0;
unsigned int j;
unsigned int structsize;
// Select decode
switch(id) {
case ID_XBEE_MODEMSTATUS:
ptr = (unsigned char *) &xbee_modem_status;
structsize = sizeof(xbee_modem_status);
xbee_modem_status.isNew = 1;
break;
case ID_XBEE_ATRESPONSE:
ptr = (unsigned char *) &xbee_at_response;
structsize = sizeof(xbee_at_response);
xbee_at_response.isNew = 1;
xbee_at_response.varLen = length - 4;
break;
case ID_XBEE_TRANSMITSTATUS:
ptr = (unsigned char *) &xbee_transmit_status;
structsize = sizeof(xbee_transmit_status);
xbee_at_response.isNew = 1;
break;
case ID_XBEE_RECEIVEPACKET:
ptr = (unsigned char *) &xbee_receive_packet;
structsize = sizeof(xbee_receive_packet);
xbee_receive_packet.isNew = 1;
xbee_receive_packet.varLen = length - 11;
CDCWrite(buffer + 11,length - 11); // send direct to CDCWrite
break;
case IX_XBEE_NODEIDENTIFICATIONINDICATOR:
ptr = (unsigned char *) &xbee_node_identification_indicator;
structsize = sizeof(xbee_node_identification_indicator);
xbee_node_identification_indicator.isNew = 1;
break;
}
if(ptr) {
if(length > structsize-3) length = structsize-3;
for(j=0; j<length; j++) {
ptr[j] = buffer[j];
}
}
// take action
switch(id) {
case ID_XBEE_TRANSMITSTATUS:
if(xbee_transmit_status.deliveryStatus == 0x21) {
StrikeNetworkAddress(xbee_transmit_status.networkAddress);
}
break;
case ID_XBEE_RECEIVEPACKET:
AddNetworkAddress(xbee_receive_packet.networkAddress, xbee_receive_packet.sourceAddress);
break;
case IX_XBEE_NODEIDENTIFICATIONINDICATOR:
if(xbee_node_identification_indicator.sourceEvent == 0x02) { // if a join event
XBeeStopJoin(); // disallow joining
flashVLED = 3;
PRGMode = 0;
}
AddNetworkAddress(xbee_node_identification_indicator.remoteNetworkAddress, xbee_node_identification_indicator.remoteSourceAddress);
break;
}
}
}
void CDCReadByte(unsigned char byte) {
if(XBeeBypassMode) {
UARTWriteByte(byte);
}
else {
CDCFlag = 1;
if(CDCCount < 255) {
CDCBuf[CDCCount++] = byte;
}
else {
SendToList(CDCBuf, CDCCount);
CDCCount = 0;
}
CDCFlag = 0;
CDCTimeout = 10;
}
}<file_sep>#include "config.h"
#include "usb/mw_usbd_rom_api.h"
#include "usb/app_usbd_cfg.h"
// ****************************************************************************
// *** MSC descriptor
// ****************************************************************************
const unsigned char MSC_DeviceDescriptor[] = {
USB_DEVICE_DESC_SIZE, /* bLength */
USB_DEVICE_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x0200), /* 2.00 */ /* bcdUSB */
0x00, /* bDeviceClass */
0x00, /* bDeviceSubClass */
0x00, /* bDeviceProtocol */
USB_MAX_PACKET0, /* bMaxPacketSize0 */
WBVAL(USB_VENDOR_ID), /* idVendor */
WBVAL(USB_MSC_ID), /* idProduct */
WBVAL(0x0100), /* 1.00 */ /* bcdDevice */
0x01, /* iManufacturer */
0x02, /* iProduct */
0x03, /* iSerialNumber */
0x01 /* bNumConfigurations */
};
const unsigned char MSC_ConfigDescriptor[] = {
/* Configuration 1 */
USB_CONFIGUARTION_DESC_SIZE, /* bLength */
USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL( /* wTotalLength */
1*USB_CONFIGUARTION_DESC_SIZE +
1*USB_INTERFACE_DESC_SIZE +
2*USB_ENDPOINT_DESC_SIZE
),
0x01, /* bNumInterfaces */
0x01, /* bConfigurationValue */
0x00, /* iConfiguration */
USB_CONFIG_SELF_POWERED, /* bmAttributes */
USB_CONFIG_POWER_MA(100), /* bMaxPower */
/* Interface 0, Alternate Setting 0, MSC Class */
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
0x00, /* bInterfaceNumber */
0x00, /* bAlternateSetting */
0x02, /* bNumEndpoints */
USB_DEVICE_CLASS_STORAGE, /* bInterfaceClass */
MSC_SUBCLASS_SCSI, /* bInterfaceSubClass */
MSC_PROTOCOL_BULK_ONLY, /* bInterfaceProtocol */
0x04, /* iInterface */
/* Bulk In Endpoint */
USB_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
MSC_EP_IN, /* bEndpointAddress */
USB_ENDPOINT_TYPE_BULK, /* bmAttributes */
WBVAL(USB_MAX_BULK_PACKET), /* wMaxPacketSize */
0, /* bInterval */
/* Bulk Out Endpoint */
USB_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
MSC_EP_OUT, /* bEndpointAddress */
USB_ENDPOINT_TYPE_BULK, /* bmAttributes */
WBVAL(USB_MAX_BULK_PACKET), /* wMaxPacketSize */
0, /* bInterval */
/* Terminator */
0 /* bLength */
};
const unsigned char MSC_StringDescriptor[] = {
/* Index 0x00: LANGID Codes */
0x04, /* bLength */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x0409), /* US English */ /* wLANGID */
/* Index 0x01: Manufacturer */
(18*2 + 2), /* bLength (8 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'N', 0,
'X', 0,
'P', 0,
' ', 0,
'S', 0,
'e', 0,
'm', 0,
'i', 0,
'c', 0,
'o', 0,
'n', 0,
'd', 0,
'u', 0,
'c', 0,
't', 0,
'o', 0,
'r', 0,
's', 0,
/* Index 0x02: Product */
(14*2 + 2), /* bLength (13 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'L', 0,
'P', 0,
'C', 0,
'1', 0,
'3', 0,
'4', 0,
'7', 0,
' ', 0,
'M', 0,
'e', 0,
'm', 0,
'o', 0,
'r', 0,
'y', 0,
/* Index 0x03: Serial Number */
(8*2 + 2), /* bLength (13 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'U', 0,
'A', 0,
'i', 0,
'r', 0,
' ', 0,
'M', 0,
'S', 0,
'C', 0,
/* Index 0x04: Interface 0, Alternate Setting 0 */
(6*2 + 2), /* bLength (13 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'M', 0,
'e', 0,
'm', 0,
'o', 0,
'r', 0,
'y', 0,
};
// ****************************************************************************
// *** HID descriptor
// ****************************************************************************
const uint8_t HID_ReportDescriptor[] = {
HID_UsagePageVendor ( 0x00 ),
HID_Usage ( 0x01 ),
HID_Collection ( HID_Application ),
HID_LogicalMin ( 0 ), /* value range: 0 - 0xFF */
HID_LogicalMaxS ( 0xFF ),
HID_ReportSize ( 8 ), /* 8 bits */
HID_ReportCount ( HID_IN_BYTES ),
HID_Usage ( 0x01 ),
HID_Input ( HID_Data | HID_Variable | HID_Absolute ),
HID_ReportCount ( HID_OUT_BYTES ),
HID_Usage ( 0x01 ),
HID_Output ( HID_Data | HID_Variable | HID_Absolute ),
HID_ReportCount ( HID_FEATURE_BYTES ),
HID_Usage ( 0x01 ),
HID_Feature ( HID_Data | HID_Variable | HID_Absolute ),
HID_EndCollection,
};
const uint16_t HID_ReportDescSize = sizeof(HID_ReportDescriptor);
const uint8_t HID_DeviceDescriptor[] = {
USB_DEVICE_DESC_SIZE, /* bLength */
USB_DEVICE_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x0200), /* 2.00 */ /* bcdUSB */
0x00, /* bDeviceClass */
0x00, /* bDeviceSubClass */
0x00, /* bDeviceProtocol */
USB_MAX_PACKET0, /* bMaxPacketSize0 */
WBVAL(USB_VENDOR_ID), /* idVendor */
WBVAL(USB_HID_ID), /* idProduct */
WBVAL(0x0100), /* 1.00 */ /* bcdDevice */
0x01, /* iManufacturer */
0x02, /* iProduct */
0x03, /* iSerialNumber */
0x01 /* bNumConfigurations */
};
const uint8_t HID_ConfigDescriptor[] = {
/* Configuration 1 */
USB_CONFIGUARTION_DESC_SIZE, /* bLength */
USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL( /* wTotalLength */
1*USB_CONFIGUARTION_DESC_SIZE +
1*USB_INTERFACE_DESC_SIZE +
HID_DESC_SIZE +
2*USB_ENDPOINT_DESC_SIZE
),
0x01, /* bNumInterfaces */
0x01, /* bConfigurationValue */
0x00, /* iConfiguration */
USB_CONFIG_SELF_POWERED, /* bmAttributes */
USB_CONFIG_POWER_MA(100), /* bMaxPower */
/* Interface 0, Alternate Setting 0, HID Class */
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
0x00, /* bInterfaceNumber */
0x00, /* bAlternateSetting */
0x02, /* bNumEndpoints */
USB_DEVICE_CLASS_HUMAN_INTERFACE, /* bInterfaceClass */
HID_SUBCLASS_NONE, /* bInterfaceSubClass */
HID_PROTOCOL_NONE, /* bInterfaceProtocol */
0x04, /* iInterface */
/* HID Class Descriptor */
/* HID_DESC_OFFSET = 0x0012 */
HID_DESC_SIZE, /* bLength */
HID_HID_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x0100), /* 1.00 */ /* bcdHID */
0x00, /* bCountryCode */
0x01, /* bNumDescriptors */
HID_REPORT_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(sizeof(HID_ReportDescriptor)),/* wDescriptorLength */
/* Endpoint, HID Interrupt In */
USB_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
HID_EP_IN, /* bEndpointAddress */
USB_ENDPOINT_TYPE_INTERRUPT, /* bmAttributes */
WBVAL(HID_IN_BYTES), /* wMaxPacketSize */
HID_RATE, /* bInterval */
/* Endpoint, HID Interrupt Out */
USB_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
HID_EP_OUT, /* bEndpointAddress */
USB_ENDPOINT_TYPE_INTERRUPT, /* bmAttributes */
WBVAL(HID_OUT_BYTES), /* wMaxPacketSize */
HID_RATE, /* bInterval */
/* Terminator */
0 /* bLength */
};
const uint8_t HID_StringDescriptor[] = {
/* Index 0x00: LANGID Codes */
0x04, /* bLength */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x0409), /* US English */ /* wLANGID */
/* Index 0x01: Manufacturer */
(18*2 + 2), /* bLength (13 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'N', 0,
'X', 0,
'P', 0,
' ', 0,
'S', 0,
'e', 0,
'm', 0,
'i', 0,
'c', 0,
'o', 0,
'n', 0,
'd', 0,
'u', 0,
'c', 0,
't', 0,
'o', 0,
'r', 0,
's', 0,
/* Index 0x02: Product */
(12*2 + 2), /* bLength (13 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'L', 0,
'P', 0,
'C', 0,
'1', 0,
'3', 0,
'4', 0,
'7', 0,
' ', 0,
'H', 0,
'I', 0,
'D', 0,
' ', 0,
/* Index 0x03: Serial Number */
(8*2 + 2), /* bLength (8 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'U', 0,
'A', 0,
'i', 0,
'r', 0,
' ', 0,
'H', 0,
'I', 0,
'D', 0,
/* Index 0x04: Interface 0, Alternate Setting 0 */
(3*2 + 2), /* bLength (3 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'H', 0,
'I', 0,
'D', 0,
};
// ****************************************************************************
// *** CDC descriptor
// ****************************************************************************
const uint8_t CDC_DeviceDescriptor[] = {
USB_DEVICE_DESC_SIZE, /* bLength */
USB_DEVICE_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x0200), /* 2.0 */ /* bcdUSB */
USB_DEVICE_CLASS_COMMUNICATIONS, /* bDeviceClass CDC*/
0x00, /* bDeviceSubClass */
0x00, /* bDeviceProtocol */
USB_MAX_PACKET0, /* bMaxPacketSize0 */
WBVAL(USB_VENDOR_ID), /* idVendor */
WBVAL(USB_CDC_ID), /* idProduct */
WBVAL(0x0100), /* 1.00 */ /* bcdDevice */
0x01, /* iManufacturer */
0x02, /* iProduct */
0x03, /* iSerialNumber */
0x01 /* bNumConfigurations */
};
const uint8_t CDC_ConfigDescriptor[] = {
/* Configuration 1 */
USB_CONFIGUARTION_DESC_SIZE, /* bLength */
USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL( /* wTotalLength */
1*USB_CONFIGUARTION_DESC_SIZE +
1*USB_INTERFACE_DESC_SIZE + /* communication interface */
0x0013 + /* CDC functions */
1*USB_ENDPOINT_DESC_SIZE + /* interrupt endpoint */
1*USB_INTERFACE_DESC_SIZE + /* data interface */
2*USB_ENDPOINT_DESC_SIZE /* bulk endpoints */
),
0x02, /* bNumInterfaces */
0x01, /* bConfigurationValue: 0x01 is used to select this configuration */
0x00, /* iConfiguration: no string to describe this configuration */
USB_CONFIG_BUS_POWERED /*|*/ /* bmAttributes */
/*USB_CONFIG_REMOTE_WAKEUP*/,
USB_CONFIG_POWER_MA(100), /* bMaxPower, device power consumption is 100 mA */
/* Interface 0, Alternate Setting 0, Communication class interface descriptor */
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
USB_CDC_CIF_NUM, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x01, /* bNumEndpoints: One endpoint used */
CDC_COMMUNICATION_INTERFACE_CLASS, /* bInterfaceClass: Communication Interface Class */
CDC_ABSTRACT_CONTROL_MODEL, /* bInterfaceSubClass: Abstract Control Model */
0x00, /* bInterfaceProtocol: no protocol used */
0x04, /* iInterface: */
/*Header Functional Descriptor*/
0x05, /* bLength: Endpoint Descriptor size */
CDC_CS_INTERFACE, /* bDescriptorType: CS_INTERFACE */
CDC_HEADER, /* bDescriptorSubtype: Header Func Desc */
WBVAL(CDC_V1_10), /* 1.10 */ /* bcdCDC */
/*Call Management Functional Descriptor*/
0x05, /* bFunctionLength */
CDC_CS_INTERFACE, /* bDescriptorType: CS_INTERFACE */
CDC_CALL_MANAGEMENT, /* bDescriptorSubtype: Call Management Func Desc */
0x01, /* bmCapabilities: device handles call management */
0x01, /* bDataInterface: CDC data IF ID */
/*Abstract Control Management Functional Descriptor*/
0x04, /* bFunctionLength */
CDC_CS_INTERFACE, /* bDescriptorType: CS_INTERFACE */
CDC_ABSTRACT_CONTROL_MANAGEMENT, /* bDescriptorSubtype: Abstract Control Management desc */
0x02, /* bmCapabilities: SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported */
/*Union Functional Descriptor*/
0x05, /* bFunctionLength */
CDC_CS_INTERFACE, /* bDescriptorType: CS_INTERFACE */
CDC_UNION, /* bDescriptorSubtype: Union func desc */
USB_CDC_CIF_NUM, /* bMasterInterface: Communication class interface is master */
USB_CDC_DIF_NUM, /* bSlaveInterface0: Data class interface is slave 0 */
/*Endpoint 1 Descriptor*/ /* event notification (optional) */
USB_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
USB_CDC_EP_INT_IN, /* bEndpointAddress */
USB_ENDPOINT_TYPE_INTERRUPT, /* bmAttributes */
WBVAL(0x0010), /* wMaxPacketSize */
0x02, /* 2ms */ /* bInterval */
/* Interface 1, Alternate Setting 0, Data class interface descriptor*/
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
USB_CDC_DIF_NUM, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: no alternate setting */
0x02, /* bNumEndpoints: two endpoints used */
CDC_DATA_INTERFACE_CLASS, /* bInterfaceClass: Data Interface Class */
0x00, /* bInterfaceSubClass: no subclass available */
0x00, /* bInterfaceProtocol: no protocol used */
0x04, /* iInterface: */
/* Endpoint, EP3 Bulk Out */
USB_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
USB_CDC_EP_BULK_OUT, /* bEndpointAddress */
USB_ENDPOINT_TYPE_BULK, /* bmAttributes */
WBVAL(USB_MAX_BULK_PACKET), /* wMaxPacketSize */
0x00, /* bInterval: ignore for Bulk transfer */
/* Endpoint, EP3 Bulk In */
USB_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
USB_CDC_EP_BULK_IN, /* bEndpointAddress */
USB_ENDPOINT_TYPE_BULK, /* bmAttributes */
WBVAL(USB_MAX_BULK_PACKET), /* wMaxPacketSize */
0x00, /* bInterval: ignore for Bulk transfer */
/* Terminator */
0 /* bLength */
};
__attribute__ ((aligned(4))) const uint8_t CDC_StringDescriptor[] = {
/* Index 0x00: LANGID Codes */
0x04, /* bLength */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x0409), /* US English */ /* wLANGID */
/* Index 0x01: Manufacturer */
(18*2 + 2), /* bLength (13 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'N', 0,
'X', 0,
'P', 0,
' ', 0,
'S', 0,
'e', 0,
'm', 0,
'i', 0,
'c', 0,
'o', 0,
'n', 0,
'd', 0,
'u', 0,
'c', 0,
't', 0,
'o', 0,
'r', 0,
's', 0,
/* Index 0x02: Product */
(12*2 + 2), /* bLength (13 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'L', 0,
'P', 0,
'C', 0,
'1', 0,
'3', 0,
'4', 0,
'7', 0,
' ', 0,
'V', 0,
'C', 0,
'O', 0,
'M', 0,
/* Index 0x03: Serial Number */
(8*2 + 2), /* bLength (8 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'U', 0,
'A', 0,
'i', 0,
'r', 0,
' ', 0,
'C', 0,
'D', 0,
'C', 0,
/* Index 0x04: Interface 0, Alternate Setting 0 */
( 4*2 + 2), /* bLength (4 Char + Type + lenght) */
USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */
'V',0,
'C',0,
'O',0,
'M',0,
};<file_sep>
void filter_GPS_baro(){
//TODO, put in a more appropriate function
alt.gps = ilink_gpsfly.altitude;
alt.filtered += Filt_GPS_K * (alt.gps - alt.filtered);
alt.filtered += Filt_baroK * (alt.baro - alt.filtered);
//static float oldaltfilt = 0;
//TODO: substitute for real vel from gps, not differenced
//alt.vel = (float)SLOW_RATE * (alt.filtered - oldaltfilt);
alt.vel = -ilink_gpsfly.velD;
//oldaltfilt = alt.filtered;
}
void AHRS(){
// ****************************************************************************
// *** ATTITUDE HEADING REFERENCE SYSTEM
// ****************************************************************************
// CREATE THE MEASURED ROTATION MATRIX //
//Both mag and acc are normalized in their Read functions
// Compose the Measured Rotation Matrix from Accelerometer and Magnetometer Vectors
// Global Z axis in Local Frame/ RM Third Row - Accelerometer (already normalised)
RM7 = Accel.X.value;
RM8 = Accel.Y.value;
RM9 = Accel.Z.value;
// Global Y axis in local frame/ RM Second Row - Acclerometer cross Magnetometer
RM4 = Accel.Y.value*(Mag.Z.value) - (Accel.Z.value)*Mag.Y.value;
RM5 = (Accel.Z.value)*Mag.X.value - Accel.X.value*(Mag.Z.value);
RM6 = Accel.X.value*Mag.Y.value - Accel.Y.value*Mag.X.value;
// Normalise
float temp = sqrt(RM4*RM4 + RM5*RM5 + RM6*RM6);
RM4 = RM4/temp;
RM5 = RM5/temp;
RM6 = RM6/temp;
// Global X axis in Local Frame/ RM First Row - Y axis cross Z axis
RM1 = RM5*RM9 - RM6*RM8;
RM2 = RM6*RM7 - RM4*RM9;
RM3 = RM4*RM8 - RM5*RM7;
// Normalise
temp = sqrt(RM1*RM1 + RM2*RM2 + RM3*RM3);
RM1 = RM1/temp;
RM2= RM2/temp;
RM3 = RM3/temp;
// CREATE THE ESTIMATED ROTATION MATRIX //
// The measured quaternion updates the estimated quaternion via the Gyro.*.error terms applied to the gyros
float g1 = (Gyro.X.value - Gyro.X.error*DRIFT_AccelKp)/(float)FAST_RATE;
float g2 = (Gyro.Y.value - Gyro.Y.error*DRIFT_AccelKp)/(float)FAST_RATE;
float g3 = (Gyro.Z.value - Gyro.Z.error*DRIFT_MagKp)/(float)FAST_RATE;
// Increment the Estimated Rotation Matrix by the Gyro Rate
//First row is M1, M2, M3 - World X axis in local frame
M1 = M1 + g3*M2 - g2*M3;
M2 = M2 - g3*M1 + g1*M3;
M3 = M3 + g2*M1 - g1*M2;
//Second row is M4, M5, M6 - World Y axis in local frame
M4 = M4 + g3*M5 - g2*M6;
M5 = M5 - g3*M4 + g1*M6;
M6 = M6 + g2*M4 - g1*M5;
// We use the dot product and both X and Y axes to adjust any lack of orthogonality between the two.
float MX_dot_MY = M1*M4 + M2*M5 + M3*M6;
M1 = M1 - M4*(MX_dot_MY/2);
M2 = M2 - M5*(MX_dot_MY/2);
M3 = M3 - M6*(MX_dot_MY/2);
float sumsqu = finvSqrt(M1*M1 + M2*M2 + M3*M3);
M1 = M1*sumsqu;
M2 = M2*sumsqu;
M3 = M3*sumsqu;
M4 = M4 - M1*(MX_dot_MY/2);
M5 = M5 - M2*(MX_dot_MY/2);
M6 = M6 - M3*(MX_dot_MY/2);
sumsqu = finvSqrt(M4*M4 + M5*M5 + M6*M6);
M4 = M4*sumsqu;
M5 = M5*sumsqu;
M6 = M6*sumsqu;
//We find the Z axis by calculating the cross product of X and Y
M7 = M2*M6 - M3*M5;
M8 = M3*M4 - M1*M6;
M9 = M1*M5 - M2*M4;
sumsqu = finvSqrt(M7*M7 + M8*M8 + M9*M9);
M7 = M7*sumsqu;
M8 = M8*sumsqu;
M9 = M9*sumsqu;
// CALCULATE GYRO BIAS //
// The gyro errores adjust the estimated matrix towards the measured rotation matrix.
// Use x and y components of the Cross Product between the z vector from each Rotation Matrix for Gyro Biases
Gyro.X.error = RM9*M8 - RM8*M9;
Gyro.Y.error = RM7*M9 - RM9*M7;
// Use z component of the cross product between the x vector from each rotation matrix to create the Z gyro error
Gyro.Z.error = RM2*M1 - RM1*M2;
// CALCULATE THE ESTIMATED QUATERNION //
float trace = M1 + M5 + M9;
if( trace > 0 ) {
float s = 0.5f / sqrt(trace + 1.0f);
q1 = 0.25f / s;
q2 = ( M6 - M8 ) * s;
q3 = ( M7 - M3 ) * s;
q4 = ( M2 - M4 ) * s;
}
else {
if ( M1 > M5 && M1 > M9 ) {
float s = 2.0f * sqrt( 1.0f + M1 - M5 - M9);
q1 = (M6 - M8 ) / s;
q2 = 0.25f * s;
q3 = (M4 + M2 ) / s;
q4 = (M7 + M3 ) / s;
}
else if (M5 > M9) {
float s = 2.0f * sqrt( 1.0f + M5 - M1 - M9);
q1 = (M7 - M3 ) / s;
q2 = (M4 + M2 ) / s;
q3 = 0.25f * s;
q4 = (M8 + M6 ) / s;
}
else {
float s = 2.0f * sqrt( 1.0f + M9 - M1 - M5 );
q1 = (M2 - M4 ) / s;
q2 = (M7 + M3 ) / s;
q3 = (M8 + M6 ) / s;
q4 = 0.25f * s;
}
}
q1 = q1;
q2 = -q2;
q3 = -q3;
q4 = -q4;
// renormalise using fast inverse sq12re root
sumsqu = finvSqrt(q1*q1 + q2*q2 + q3*q3 + q4*q4);
q1 *= sumsqu;
q2 *= sumsqu;
q3 *= sumsqu;
q4 *= sumsqu;
// CALCULATE THE EULER ANGLES //
// precalculated values for optimisation
float q12 = q1 * q2;
float q13 = q1 * q3;
float q22 = q2 * q2;
float q23 = q2 * q4;
float q33 = q3 * q3;
float q34 = q3 * q4;
float q44 = q4 * q4;
float q22Pq33 = q22 + q33;
float Tq13Mq23 = 2 * (q13 - q23);
float Tq34Pq12 = 2 * (q34 + q12);
// avoid gimbal lock at singularity points
if (Tq13Mq23 == 1) {
psiAngle = 2 * fatan2(q2, q1);
thetaAngle = M_PI_2;
phiAngle = 0;
}
else if (Tq13Mq23 == -1) {
psiAngle = -2 * fatan2(q2, q1);
thetaAngle = - M_PI_2;
phiAngle = 0;
}
else {
thetaAngle = fasin(Tq13Mq23);
phiAngle = fatan2(Tq34Pq12, (1 - 2*q22Pq33));
psiAngle = fatan2((2*(q1 * q4 + q2 * q3)), (1 - 2*(q33 + q44)));
}
// Output angles over telemetry
ilink_attitude.roll = phiAngle;
ilink_attitude.pitch = thetaAngle;
ilink_attitude.yaw = psiAngle;
}<file_sep>// ****************************************************************************
// *** Copyright (c) 2011, Universal Air Ltd. All rights reserved.
// *** Source and binaries are released under the BSD 3-Clause license
// *** See readme files for the text of the license
// ****************************************************************************
#ifndef __CONFIG_H__
#define __CONFIG_H__
#define I_AM_NOTHING 0
#define I_AM_THALAMUS 1
#define I_AM_HYPO 2
#define I_AM_HYPX 3
// ****************************************************************************
// *** BOARD IDENTITY
// ****************************************************************************
#define WHO_AM_I I_AM_HYPX
// ****************************************************************************
// *** Misc Functions
// ****************************************************************************
#define IAP_EN 1 // Set to 1 to enable the IAP functions like Reprogram() (set to 0 to disable and save some RAM)
#define RAND_MERSENNE 0 // Set to 1 to use Mersenne Twister as pseudorandom number generator, otherwise use Linear Congruential
#define MERSENNE_N 624 // Size of the vector for Mersenne Twister random number generator
#define MERSENNE_M 397 // Coefficient for the Mersenne Twister random number generator
#define RAND_A 16644525 // Coefficient for the linear congruential random number generator
#define RAND_C 32767 // Coefficient for the linear congruential random number generator
#define CRP 0xffffffff // Code read protection settings
// 0xffffffff = No CRP
// 0x4e697370 = No ISP
// 0x12345678 = CRP1
// 0x87654321 = CRP2
// ********** = CRP3 WARNING! CRP3 STOPS EXTERNAL ACCESS TO PROGRAMMING MODE (user code must provide Reprogram() functionality to update flash)
// This is so dangerous, we're not giving you the value, it is up to you to seek this value out from the
// LPC1343 manuals and datasheets.
// ****************************************************************************
// *** Clock Functions
// ****************************************************************************
#define DEFAULT_CLOCK 0 // Default start-up/wake-up clock mode (0=72MHz crystal, 1=72MHz IRC, 2=12MHz IRC)
#define SYSTICK_EN 1 // Set to 1 to enable SysTick (set to 0 to disable and save some RAM)
#define SYSTICK_STARTUP 1 // Set to 1 to enable SysTick timer during startup
#define SYSTICK_US 1000 // SysTick period in microseconds (maximum: 233016us at 72MHz, 1398101us at 12MHz)
#define SYSTICK_PRIORITY 0 // SysTick interrupt priority
#define WDT_PRIORITY 0 // WDT interrupt priority
#define WDT_MODE 2 // WDT mode (0=reset on WDT timeout, 1=repeated interrupt on WDT timeout, 2=interrupt and then restart WDT)
#define WDT_CLK 1 // WDT clock (0=WDT OSC, 1=IRC)
#define RIT_RESET 1 // Repetitive Interrupt Timer reset (0=don't reset, 1=reset on match)
#define RIT_PRIORITY 4 // Repetitive Interrupt Timer priority (note to self: this needs to be <3 in some circumstances, can't work out why...)
// ****************************************************************************
// *** Power mode Config
// ****************************************************************************
/*
#define AUTOSLEEP 0 // Set to 1 to sleep on end of interrupt function
#define WAKEUP_HYS 0 // Set 1 to enable hysteresis on the WAKEUP pin
*/
#define STARTUP_DELAY 0 // Startup delay (in terms of empty loop
// ****************************************************************************
// *** GPIO Config
// ****************************************************************************
#define PORT_STARTUP_INIT 1 // Whether to initialise all ports during startup
/*
#define PORT0_PRIORITY 2 // Port 0 pins interrupt priority
#define PORT1_PRIORITY 2 // Port 1 pins interrupt priority
*/
// ****************************************************************************
// *** USB HID and MSC functions
// ****************************************************************************
#define USB_EN 1 // Set to 1 to enable USB ROM functions
#define USB_VENDOR_ID 0x1FC9 // The default NXP Vendor ID is 0x1FC9
#define USB_MSC_ID 0x0114 // Product ID for MSC device
#define USB_CDC_ID 0x0233 // Product ID for CDC device
#define USB_HID_ID 0x0003 // Product ID for HID device
#define HID_IN_BYTES 64 // The number of bytes for the HID input report (device to computer)
#define HID_OUT_BYTES 2 // The number of bytes for the HID output report (computer to device)
#define HID_FEATURE_BYTES 5 // The number of bytes for the HID feature report
#define HID_RATE 100 // HID report rate (ms)
#define MSC_BLOCK_SIZE 512 // The block size (bytes) of the MSC device
#define CDC_USE_PLED 0 // Use PLED as a flashing status indicator
#define USB_PRIORITY 2 // USB interrupt priority
// ****************************************************************************
// *** UART Config
// ****************************************************************************
#define UART_EN 1 // Set to 1 to enable UART (set to 0 to disable and save some RAM)
#define UART_FLOW 0 // Set to 1 to enable UART auto-flow control (CTS and RTS)
#define UART_BIT_LENGTH 3 // Bits per UART "word" (3=8-bit, 2=7-bit, 1=6-bit, 0=5-bit)
#define UART_STOP_BITS 0 // Stop bits (0=1 stop bit, 1=2 stop bits (or 1.5 stop bits if 5-bit data mode))
#define UART_PARITY_EN 0 // Parity (0=disable, 1=enable)
#define UART_PARITY 0 // Parity type (0=Odd parity, 1=Even parity, 2=force mark parity, 3=force space parity)
#define UART_FIFO_LEVEL 0 // Interrupt trigger level for buffer (0=Trigger every byte, 1=trigger if below 4 bytes, 2=trigger if below 8 bytes, 3=trigger if below 14 bytes)
#define UART_USE_FBR 1 // Set to 1 to use pre-defined fractional baud rates
#define UART_PRIORITY 2 // UART interrupt priority
#define UART_USE_OUTBUFFER 0 // Set to 1 to enable UART output buffer
#define UART_BUFFER_SIZE 128 // Size of the UART output buffer
// ****************************************************************************
// *** I2C Config
// ****************************************************************************
#define I2C_EN 0 // Set to 1 to enable I2C (set to 0 to disable and save some RAM)
#define I2C_SLAVE_EN 0 // Set to 1 to enable slave mode (set to 0 to save some RAM)
#define I2C_DATA_SIZE 68 // Size of I2C Slave buffer
#define I2C_TIMEOUT 0xff // Timeout for I2C
#define I2C_FASTMODE_PLUS 0 // Set to 1 for > 400kHz operation
#define I2C_SLAVE_ADR0 0xe8 // Slave address 0, only available in slave mode
#define I2C_SLAVE_ADR1 0x00 // Slave address 1, only available in slave mode
#define I2C_SLAVE_ADR2 0x00 // Slave address 2, only available in slave mode
#define I2C_SLAVE_ADR3 0x00 // Slave address 3, only available in slave mode
#define I2C_PRIORITY 1 // I2C interrupt priority
// ****************************************************************************
// *** SSP/SPI Config
// ****************************************************************************
#define SSP0_EN 0 // Set to 1 to enable SSP0
#define SSP0_SIZE 16 // Transfer size in bits (valid values are 4-bit to 16-bit)
#define SSP0_FORMAT 0 // Frame format (0=SPI, 1=TI, 2=Microware)
#define SSP0_CLK_POL 0 // Clock polarity (0=CLK low between frames, 1=CLK high between frames)
#define SSP0_CLK_PHA 0 // Clock phase (0=Capture data on transition away from inter-frame state, 1=Capture data on transition to inter-frame state)
#define SSP0_SSEL 1 // Use SSEL pin (2=automatically use SSEL, 1=manually use SSEL, 0=don't use)
#define SSP0_INT_LEVEL 0 // Interrupt level (0=interrupt whenever data received, 1=interrupt when FIFO half-full (4 frames)
#define SSP0_PRIORITY 1 // SSP interrupt priority
#define SSP1_EN 0 // Set to 1 to enable SSP0
#define SSP1_SIZE 16 // Transfer size in bits (valid values are 4-bit to 16-bit)
#define SSP1_FORMAT 0 // Frame format (0=SPI, 1=TI, 2=Microware)
#define SSP1_CLK_POL 0 // Clock polarity (0=CLK low between frames, 1=CLK high between frames)
#define SSP1_CLK_PHA 0 // Clock phase (0=Capture data on transition away from inter-frame state, 1=Capture data on transition to inter-frame state)
#define SSP1_SSEL 1 // Use SSEL pin (2=automatically use SSEL, 1=manually use SSEL, 0=don't use)
#define SSP1_INT_LEVEL 0 // Interrupt level (0=interrupt whenever data received, 1=interrupt when FIFO half-full (4 frames)
#define SSP1_PRIORITY 1 // SSP interrupt priority
// ****************************************************************************
// *** Timer Config
// ****************************************************************************
#define TIMER0_PRIORITY 2 // Timer priority
#define TMR0M2_PIN 0 // Select the pin for Timer 0 Match 2 (0=P0[10], 1=P1[15])
#define TIMER1_PRIORITY 2 // Timer priority
#define TIMER2_PRIORITY 0 // Timer priority
#define TIMER3_PRIORITY 2 // Timer priority
// ****************************************************************************
// *** ADC Config
// ****************************************************************************
#define ADC_MODE 0 // ADC mode (0=on-demand, 1=interrupt)
#define ADC_PRIORITY 1 // ADC interrupt priority
#define ADC_10BIT 0 // Set to enable 10 bit mode
#define ADC_LPWRMODE 0 // Set to enable low power mode (turns ADC off between samples)
// ****************************************************************************
// *** ILink Config
// ****************************************************************************
#define ILINK_EN 1 // Enable the Interlink functions (0=off, 1=on)
#define ILINK_BUFFER_SIZE 128 // ILink buffer size
#define ILINK_MAX_FETCH 128 // Maximum characters to fetch at once
#if WHO_AM_I == I_AM_THALAMUS
// ****************************************************************************
// *** PWM Functions (Thalamus only)
// ****************************************************************************
#define PWM_DEFAULT_N 1000 // Default PWM outputs (in microseconds),
#define PWM_DEFAULT_E 1000 // use low values (i.e. 1000) for ESCs
#define PWM_DEFAULT_S 1000
#define PWM_DEFAULT_W 1000
#define PWM_DEFAULT_X 1500
#define PWM_DEFAULT_Y 1500
#define PWM_FILTERS_ON 0 // PWM output filters (filter is SPR)
#define PWM_NESW_FILTER 0 // Filter coefficients for SPR
#define PWM_XY_FILTER 0 // value is between 0 and 1, lower is less filterig
#define PWM_NESWFREQ 400 // PWM frequency (maximum 450)
#define PWM_XYFREQ 50 // This value needs to be a fraction of PWM_NESWFREQ
// ****************************************************************************
// *** IMU Functions (Thalamus only)
// ****************************************************************************
#define ACCEL_RANGE 0 // Set the dynamic range: 0=+/- 2g, 1= +/- 4g, 2=+/-8g, 3=+/-16g
#define ACCEL_RATE 5 // Set the data rate: 0=off, 1=1Hz, 2=10Hz, 3=25Hz, 4=50Hz, 5=100Hz, 6=200Hz, 7=400Hz, 8=1.620kHz (low power mode ONLY), 9=1.344kHz (normal)/5.376kHz (low power mode)
#define ACCEL_LOW_POWER 0 // Set to enable low power mode
#define GYRO_RANGE 2 // Set dynamic range: 0=250dps, 1=500dps, 2=2000dps, 3=2000dps
#define GYRO_RATE 3 // Set the data rate: 0=100Hz, 1=200Hz, 2=400Hz, 3=800Hz
#define GYRO_BANDWIDTH 3 // Sets the bandwidth
// For Gyro rate 0 (100Hz): 0=12.5Hz, 1=25Hz, 2=25Hz, 3=25Hz
// For Gyro rate 1 (200Hz): 0=12.5Hz, 1=25Hz, 2=50Hz, 3=70Hz
// For Gyro rate 2 (400Hz): 0=20Hz, 1=25Hz, 2=50Hz, 3=110Hz
// For Gyro rate 3 (800Hz): 0=30Hz, 1=35Hz, 2=30Hz, 3=110Hz
#define GYRO_LPF 1 // Set to enable the low pass filter
#define MAGNETO_MODE 0 // Set to 0 for continuous mode, 1 for single-measurement mode
#define MAGNETO_AVERAGING 3 // Set to 0 for no averaging, 1 for two-sample, 2 for four-sample, and 3 for eight-sample averaging
#define MAGNETO_RATE 6 // Continuous mode sample rate, 0=0.75Hz, 1=1.5Hz, 2=3Hz, 3=7.5Hz, 4=15Hz, 5=30Hz, 6=75Hz
#define MAGNETO_BIAS 0 // Sets bias mode for all axes, set to 0 for no bias, 1 for positive bias, 2 for negative bias
#define MAGNETO_GAIN 1 // Sets gain for certain sensor ranges. 0=+/-0.88Ga, 1=+/-1.3Ga, 2=+/-1.9Ga, 3=+/-2.5Ga, 4=+/-4.0Ga, 5=+/-4.7Ga, 6=+/-5.6Ga, 7=+/-8.1Ga
#define MAGNETO_TRIES_MAX 5 // When in single-measurement mode, how many tries to read data from the stream before giving up?
#define MAGNETO_TRIES_DELAY 1 // Millisecond delay between trying to read data from the magneto
#define BARO_EN 0 // Set to 1 to enable the barometer functions (set to 0 to disable and save some RAM)
#define BARO_OVERSAMPLE 3 // Sets the barometer oversampling mode, 0: ultra low power, 1: standard, 2: high resolution, 3: ultra high resolution
#endif
#if WHO_AM_I == I_AM_HYPO
// ****************************************************************************
// *** PWM Functions (Hypo only)
// ****************************************************************************
#define PWM_DEFAULT_A 1500 // Default PWM outputs (in microseconds),
#define PWM_DEFAULT_B 1500 // use low values (i.e. 1000) for ESCs
#define PWM_DEFAULT_C 1500
#define PWM_DEFAULT_D 1500
#define PWM_DEFAULT_S 1500
#define PWM_FILTERS_ON 1 // PWM output filters (filter is SPR)
#define PWM_ABCD_FILTER 0 // Filter coefficients for SPR
#define PWM_S_FILTER 0 // value is between 0 and 1, lower is less filterig
#define PWM_ABCDFREQ 50 // PWM frequency (maximum 450)
#define PWM_SFREQ 50 // This value needs to be a fraction of PWM_ABCDFREQ
// ****************************************************************************
// *** GPS Functions (Hypo only)
// ****************************************************************************
#define GPS_EN 1 // Set to 1 to enable GPS code (set to 0 to save some RAM)
#define GPS_5HZ_RATE 1 // Set to 1 to allow up to 5Hz position rate (set to 0 for the default 0Hz)
#define GPS_AIRBORNE 0 // Set to 1 to allow GPSInit() function to set the dynamic platform model to "Airborne < 1g", and GPSFix() will only return if there is a 3D fix
#define GPS_METHOD 1 // Method, use 0 for the slow but simple polling method, or 1 for the faster but more complex periodic method
#define GPS_TRIES_MAX 15 // When polling, how many tries to read data from the stream before giving up?
#define GPS_TRIES_DELAY 100 // When polling, millisecond delay between trying to read data from the stream
#define GPS_BUFFER_SIZE 64 // Size of the GPS buffer, determines the largest packet that can be stored
// ****************************************************************************
// *** Flash Functions (Hypo only)
// ****************************************************************************
#define FLASH_EN 0 // Set to 1 to enable flash, NOTE: flash operation requires the use of 4kb of RAM for sector buffer!
#endif
#if WHO_AM_I == I_AM_HYPX
#define XBEE_EN 1 // Set to 1 to enable the XBee code
#define XBEE_POWER_LEVEL 0 // Set transmit power: 4=18dBm/63mW, 3=16dBm/40mW, 2=14dBm/25mW, 1=12dBm/16mW, 0=0dBm/1mW
#define XBEE_BUFFER_SIZE 128 // XBee buffer size
#define XBEE_JOINPERIOD 60 // Number of seconds to allow bind
#endif
#endif // __CONFIG_H__<file_sep>
void control_throttle(){
//PID states
static float targetZ = 0;
static float KerrI = 0;
//if we are not using the altitude controller, set input and output bias to be the current ones, for a stepless transition.
//if (MODE_ST != MODE_AUTO) //TODO: make it use the global state
if(auxState == 0)
{
targetZ = alt.filtered;
KerrI = throttle;
}
//only override throttle if we are in auto. If not, leave it to the throttle set previously by the user.
//if (MODE_ST == MODE_AUTO)
if(auxState == 1)
{
float errP = targetZ - alt.filtered;
//TODO: we need D term for setpoint for Derr.
float errD = -alt.vel;
KerrI += GPS_ALTKi * (1/(float)FAST_RATE) * errP;
throttle = GPS_ALTKp * errP + KerrI + GPS_ALTKd * errD;
}
}
// ****************************************************************************
// *** Attitude PID Control
// ****************************************************************************
void control_attitude(){
//TODO: use real states
if (auxState == 1)
{
//simplicty!
//attitude_demand_body.pitch = fsin(-psiAngle+psiAngleinit+M_PI_2) * user.pitch - fsin(-psiAngle+psiAngleinit) * user.roll;
//attitude_demand_body.roll = fsin(-psiAngle+psiAngleinit) * user.pitch + fsin(-psiAngle+psiAngleinit+M_PI_2) * user.roll;
attitude_demand_body.pitch = fsin(-psiAngle+M_PI_2) * ilink_gpsfly.northDemand - fsin(-psiAngle) * ilink_gpsfly.eastDemand;
attitude_demand_body.roll = fsin(-psiAngle) * ilink_gpsfly.northDemand + fsin(-psiAngle+M_PI_2) * ilink_gpsfly.eastDemand;
if (ilink_gpsfly.headingDemand == 42.0f){
attitude_demand_body.yaw = user.yaw;
}
else {
attitude_demand_body.yaw = ilink_gpsfly.headingDemand;
}
//debug
ilink_debug.debug0 = ilink_gpsfly.northDemand;
ilink_debug.debug1 = ilink_gpsfly.eastDemand;
ilink_debug.debug2 = ilink_gpsfly.headingDemand;
}
if (auxState == 0)
{
attitude_demand_body.pitch = user.pitch;
attitude_demand_body.roll = user.roll;
attitude_demand_body.yaw = user.yaw;
}
// This section of code applies some throttle increase with high tilt angles
//It doesn't seem hugely effective and maybe completely redundant when Barometer control is implemented
// TODO: Reassess whether it is useful or not
float M9temp;
if (M9 > 0) M9temp = M9;
else M9temp = -M9;
throttle_angle = ((throttle / M9temp) - throttle);
if (throttle_angle < 0) throttle_angle = 0;
static float rollold = 0;
static float pitchold = 0;
// This section of code limits the rate at which the craft is allowed to track angle demand changes
if ((attitude_demand_body.pitch - pitchold) > PITCH_SPL) attitude_demand_body.pitch = pitchold + PITCH_SPL;
if ((attitude_demand_body.pitch - pitchold) < -PITCH_SPL) attitude_demand_body.pitch = pitchold - PITCH_SPL;
pitchold = attitude_demand_body.pitch;
if ((attitude_demand_body.roll - rollold) > ROLL_SPL) attitude_demand_body.roll = rollold + ROLL_SPL;
if ((attitude_demand_body.roll - rollold) < -ROLL_SPL) attitude_demand_body.roll = rollold - ROLL_SPL;
rollold = attitude_demand_body.roll;
// This part of the code sets the maximum angle the quadrotor can go to in the pitch and roll axes
if(attitude_demand_body.pitch > LIM_ANGLE) attitude_demand_body.pitch = LIM_ANGLE;
if(attitude_demand_body.pitch < -LIM_ANGLE) attitude_demand_body.pitch = -LIM_ANGLE;
if(attitude_demand_body.roll > LIM_ANGLE) attitude_demand_body.roll = LIM_ANGLE;
if(attitude_demand_body.roll < -LIM_ANGLE) attitude_demand_body.roll = -LIM_ANGLE;
// Create the demand derivative (demand and external rotations are split) term for the attitude motor control
static float rollDemandOld = 0;
static float pitchDemandOld = 0;
static float yawDemandOld = 0;
float deltaPitch = (attitude_demand_body.pitch - pitchDemandOld);
float deltaRoll = (attitude_demand_body.roll - rollDemandOld);
float deltaYaw = (attitude_demand_body.yaw - yawDemandOld);
if(deltaYaw > M_PI) {
deltaYaw -= M_TWOPI;
}
else if(deltaYaw < -M_PI) {
deltaYaw += M_TWOPI;
}
pitchDemandOld = attitude_demand_body.pitch;
rollDemandOld = attitude_demand_body.roll;
yawDemandOld = attitude_demand_body.yaw;
// Use the Current and demanded angles to create the error for the proportional part of the PID loop
// TODO: it might be more mathematically elegant (but harder to understand)
//to express the demand as a quaternion, but this is not a high priority
float pitcherror = attitude_demand_body.pitch + thetaAngle;
float rollerror = attitude_demand_body.roll - phiAngle;
float yawerror = attitude_demand_body.yaw + psiAngle;
//Rescues craft if error gets too large at high throttles
// TODO: Test to see if this code solves the problem
if (((pitcherror > 0.08) || (pitcherror < -0.08) || (rollerror > 0.08) || (rollerror < -0.08)) && (throttle > 600)) throttle -= 200;
// This section ensures that on swapping between -PI and PI,
// the craft always takes the shortest route to the desired angle
if(pitcherror > M_PI) pitcherror -= M_TWOPI;
else if(pitcherror < -M_PI) pitcherror += M_TWOPI;
if(rollerror > M_PI) rollerror -= M_TWOPI;
else if(rollerror < -M_PI) rollerror += M_TWOPI;
if(yawerror > M_PI) yawerror -= M_TWOPI;
else if(yawerror < -M_PI) yawerror += M_TWOPI;
// Creating the integral for the motor PID
// TODO: Is this the cause of poor leveling on takeoff? (took out wierd throttle dependent rates)
//TODO: Check to see if added Yaw integral solves yaw offsets in autonomous flight
static float pitchIntegral = 0;
static float rollIntegral = 0;
static float yawIntegral = 0;
if (rcInput[RX_THRO] - throttletrim > OFFSTICK){
pitchIntegral += pitcherror;
rollIntegral += rollerror;
yawIntegral += yawerror;
} else {
pitchIntegral = 0;
rollIntegral = 0;
yawIntegral = 0;
}
// Detune at high throttle - We turn the tunings down at high throttle to prevent oscillations
// happening on account of the higher energy input to the system
float throttlefactor = throttle/MAXSTICK;
if(throttlefactor > 1) throttlefactor = 1;
float detunefactor = 1-(throttlefactor * DETUNE);
float thisPITCH_Kd = PITCH_Kd;
float thisPITCH_Kdd = PITCH_Kdd * detunefactor;
float thisROLL_Kd = ROLL_Kd;
float thisROLL_Kdd = ROLL_Kdd * detunefactor;
float thisPITCH_Ki = PITCH_Ki;
float thisROLL_Ki = ROLL_Ki;
// Attitude control PID Assembly - We use a proportional, derivative, and integral on pitch roll and yaw
// we add a double derivative term for pitch and roll.
static float oldGyroValuePitch = 0;
static float oldGyroValueRoll = 0;
float pitchcorrection = -((float)Gyro.Y.value - PITCH_Boost*deltaPitch) * thisPITCH_Kd;
pitchcorrection += -thisPITCH_Kdd*((float)Gyro.Y.value - oldGyroValuePitch);
pitchcorrection += -PITCH_Kp*pitcherror;
pitchcorrection += -thisPITCH_Ki*pitchIntegral;
float rollcorrection = -((float)Gyro.X.value - ROLL_Boost*deltaRoll) * thisROLL_Kd;
rollcorrection += -thisROLL_Kdd*((float)Gyro.X.value - oldGyroValueRoll);
rollcorrection += ROLL_Kp*rollerror;
rollcorrection += thisROLL_Ki*rollIntegral;
float yawcorrection = -((float)Gyro.Z.value + YAW_Boost*deltaYaw) * YAW_Kd;
yawcorrection += -YAW_Kp*yawerror;
// TODO: Check direction of yaw integral
yawcorrection += -YAW_Ki*yawIntegral;
// If the craft is upsidedown, turn off yaw control until control brings it back upright.
// TODO: Test this code
if (M9 < 0) {
yawcorrection = 0;
}
oldGyroValuePitch = (float)Gyro.Y.value;
oldGyroValueRoll = (float)Gyro.X.value;
//Assigning the PID results to the correct motors
// TODO: add support for multiple orientations here
motorN = pitchcorrection + rollcorrection;
motorE = pitchcorrection - rollcorrection;
motorS = -pitchcorrection - rollcorrection;
motorW = -pitchcorrection + rollcorrection;
motorN -= yawcorrection;
motorE += yawcorrection;
motorS -= yawcorrection;
motorW += yawcorrection;
// We run an LPF filter on the outputs to ensure they aren't too noisey and don't demand changes too quickly
// This seems to reduce power consumption a little and ESC heating a little also
motorNav *= LPF_OUT;
motorNav += (1-LPF_OUT) * motorN;
motorEav *= LPF_OUT;
motorEav += (1-LPF_OUT) * motorE;
motorSav *= LPF_OUT;
motorSav += (1-LPF_OUT) * motorS;
motorWav *= LPF_OUT;
motorWav += (1-LPF_OUT) * motorW;
}
// ****************************************************************************
// *** Handle throttle and motor outputs
// ****************************************************************************
void control_motors(){
// Combine attitude stabilisation demands from PID loop with throttle demands
tempN = (signed short)motorNav + (signed short)throttle + THROTTLEOFFSET + (signed short)throttle_angle;
tempE = (signed short)motorEav + (signed short)throttle + THROTTLEOFFSET + (signed short)throttle_angle;
tempS = (signed short)motorSav + (signed short)throttle + THROTTLEOFFSET + (signed short)throttle_angle;
tempW = (signed short)motorWav + (signed short)throttle + THROTTLEOFFSET + (signed short)throttle_angle;
// TODO: Add Auto Land on rxLoss!
if (rcInput[RX_THRO] - throttletrim < OFFSTICK || throttleHoldOff > 0 || rxLoss > 25) {
// Set throttle off
throttle = 0;
// Reset Important variables
motorN = 0;
motorE = 0;
motorS = 0;
motorW = 0;
motorNav = 0;
motorEav = 0;
motorSav = 0;
motorWav = 0;
// Reseting the yaw demand to the actual yaw angle continuously helps stop yawing happening on takeoff
user.yaw = -psiAngle;
// Reset the throttle hold variable, this prevents reactivation of the throttle until
// the input is dropped and re-applied
if(rcInput[RX_THRO] - throttletrim < OFFSTICK) throttleHoldOff = 0;
// If the craft is armed, set the PWM channels to the PWM value corresponding to off!
if(armed) PWMSetNESW(THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET);
// Output the motor PWM demand on the telemetry link
ilink_outputs0.channel[0] = THROTTLEOFFSET;
ilink_outputs0.channel[1] = THROTTLEOFFSET;
ilink_outputs0.channel[2] = THROTTLEOFFSET;
ilink_outputs0.channel[3] = THROTTLEOFFSET;
}
else if(armed) {
float temp;
// Limit the maximum throttle output to a percentage of the highest throttle available
// to allow additional throttle for manouevering
if(throttle > MAXTHROTTLE*MAXTHROTTLEPERCENT) throttle = MAXTHROTTLE*MAXTHROTTLEPERCENT;
// Set the PWM channels. Maximum of MAXTHROTTLE + THROTTLEOFFSET, MINMUM OF IDLETHROTTLE + THROTTLE OFFSET
// Throttle offset offsets the throttle readings (which start at 0) to the PWM values (in ms?) which need to start at around 1000
temp = tempN;
if(temp > (MAXTHROTTLE + THROTTLEOFFSET)) temp = (MAXTHROTTLE + THROTTLEOFFSET);
else if(temp < (IDLETHROTTLE + THROTTLEOFFSET)) temp = (IDLETHROTTLE + THROTTLEOFFSET);
PWMSetN(temp);
ilink_outputs0.channel[0] = temp;
temp = tempE;
if(temp > (MAXTHROTTLE + THROTTLEOFFSET)) temp = (MAXTHROTTLE + THROTTLEOFFSET);
else if(temp < (IDLETHROTTLE + THROTTLEOFFSET)) temp = (IDLETHROTTLE + THROTTLEOFFSET);
PWMSetE(temp);
ilink_outputs0.channel[1] = temp;
temp = tempS;
if(temp > (MAXTHROTTLE + THROTTLEOFFSET)) temp = (MAXTHROTTLE + THROTTLEOFFSET);
else if(temp < (IDLETHROTTLE + THROTTLEOFFSET)) temp = (IDLETHROTTLE + THROTTLEOFFSET);
PWMSetS(temp);
ilink_outputs0.channel[2] = temp;
temp = tempW;
if(temp > (MAXTHROTTLE + THROTTLEOFFSET)) temp = (MAXTHROTTLE + THROTTLEOFFSET);
else if(temp < (IDLETHROTTLE + THROTTLEOFFSET)) temp = (IDLETHROTTLE + THROTTLEOFFSET);
PWMSetW(temp);
ilink_outputs0.channel[3] = temp;
ilink_outputs0.isNew = 1;
}
}<file_sep>#include "thal.h"
#include "mavlink.h"
#include <math.h>
// GENERAL TODO list in order of priority
// Specific TODO's are listed next to the relevant bit of code.
//TODO: (HENRY DOES THIS, NEEDS LOTS OF SPACE AND SPARE PARTS!)
//Diagnose loss of control experienced at full throttle
//I ascended at full throttle while probably applying some pitch and roll demands and suddenly the craft just seemed to loose stability.
//It rolled/ pitched upside down a few times, luckily it recovered and I was able to bring it back safely.
//However, have heard that a backer had a similar problem.
//Possible causes are Yuan's Max throttle stuff, my roll angle prioritisation (less likely as wasn't in the backers code), ROLL/ PITCH SPL (spin limit). Or other!
// Have done some test flights and witnessed the loss of control at high throttles, it only does it when applying a high throttle and a large attitude demand, it inverts then enters a continual spin at high throttle
// Have added code on line 51 of control.h to try and solve this problem
//TODO: check all integrators for decoupling, and make sure they are locked in this case
// TODO: Assess and Improve leveling on take off and leveling in flight
// Key areas to investigate are integral gain on takeoff
// Accelerometer feedback gain
// Accelerometer feedback method - additional filtering needed?
// Switch to using vectors rather than angles for motor control.
// Angles will only be used for telemetry readout, could be calculated on Hypo.
// TODO: Reinsert Modes, build the State machines out to deal with changes in throttle functionality
// Add barometer, GPS and Ultrasound merging.
// TODO: Write code for Orientation calibration
// When disarmed, right stick all the way left should enter this mode.
// The craft should be position flat and level for at least 3 seconds. (45 degree tolerance)
// The craft should be tilted in the forward direction greater than 45 degrees and for at least 3 seconds. (snap to nearest 45 degree angle)
// TODO: Measure loop rates instead of just assuming it
// The control needs to know how fast they're going, right now we assume the loops are going at their specified rate
// however, it would be better to just time instead. Use one of the hardware timers to get sub-ms resolution.
// ****************************************************************************
// ****************************************************************************
// *** DECLARATIONS
// ****************************************************************************
// ****************************************************************************
// TODO: Needs sorting, there are unused parameters and a lack of categorisation throughout
////////////////////////////////////////// CONFIGURATION PARAMETERS ////////////////////////////////
#define FIRMWARE_VERSION 1 // Firmware version
#define MESSAGE_LOOP_HZ 15 // Max frequency of messages in Hz (keep this number low, like around 15)
#define RX_PANIC 2 // Number of seconds after missing RX before craft considered "disconnected"
#define FAST_RATE 400
#define SLOW_RATE 75
#define ZEROTHROTMAX 1*FAST_RATE
#define SLOW_DIVIDER FAST_RATE/SLOW_RATE
// TODO: check ESC response at THROTTLEOFFSET, consider raising THROTTLEOFFSET to 1000
#define THROTTLEOFFSET 900 // Corresponds to zero output PWM. Nominally 1000=1ms, but 800 works better
#define IDLETHROTTLE 175 // Minimum PWM output to ESC when in-flight to avoid motors turning off
#define MAXTHROTTLE 1200 // Maximum PWM output to ESC (PWM = THROTTLEOFFSET + MAXTHROTTLE)
#define MAXTHROTTLEPERCENT 0.9 // Maximum percentage throttle should be (reserves some extra output for stabilisation at high throttle).
#define OFFSTICK 50
#define MIDSTICK 512 // Corresponds to input when stick is in middle (approx value).
#define MAXSTICK 850 // Corresponds to input when stick is at the top
#define MAXTHRESH (MAXSTICK+MIDSTICK)/2 - 50
#define MINTHRESH (MIDSTICK+OFFSTICK)/2 + 50
#define EEPROM_MAX_PARAMS 100 // this should be greater than or equal to the above number of parameters
#define EEPROM_OFFSET 0 // EEPROM Offset used for moving the EEPROM values around storage (wear levelling I guess)
#define EEPROM_VERSION 32 // version of variables in EEPROM, change this value to invalidate EEPROM contents and restore defaults
// Running Average Lengths
#define GAV_LEN 8
#define AAV_LEN 30
#define MAV_LEN 30
//This is used with MODE_ST
#define MODE_MANUAL 1
#define MODE_AUTO 2
/////////////////////////////// FUNCTIONS //////////////////////////////////////
void SensorZero(void);
void CalibrateGyro(void);
void CalibrateGyroTemp(unsigned int seconds);
void CalibrateMagneto(void);
void Arm(void);
void Disarm(void);
void ReadGyroSensors(void);
void ReadAccelSensors(void);
void ReadMagSensors(void);
void ReadUltrasound(void);
void ReadBattVoltage(void);
void ReadRXInput(void);
void LinkInit(void);
void EEPROMLoadAll(void);
void EEPROMSaveAll(void);
void control_throttle(void);
void filter_GPS_baro();
///////////////////////////////////////////// ILINK ///////////////////////////////////////
ilink_identify_t ilink_identify;
ilink_thalstat_t ilink_thalstat;
ilink_thalctrl_t ilink_thalctrl_rx;
ilink_thalctrl_t ilink_thalctrl_tx;
ilink_imu_t ilink_rawimu;
ilink_imu_t ilink_scaledimu;
ilink_altitude_t ilink_altitude;
ilink_attitude_t ilink_attitude;
ilink_attitude_t ilink_attitude_demand;
ilink_thalparam_t ilink_thalparam_tx;
ilink_thalparam_t ilink_thalparam_rx;
ilink_thalpareq_t ilink_thalpareq;
ilink_iochan_t ilink_inputs0;
ilink_iochan_t ilink_outputs0;
ilink_gpsfly_t ilink_gpsfly;
ilink_debug_t ilink_debug;
///////////////////////////////////////// GLOBAL VARIABLE STRUCTURES /////////////////////
typedef struct {
float roll;
float pitch;
float yaw;
float throttle;
} userStruct;
userStruct user;
typedef struct {
float roll;
float pitch;
float yaw;
} attitude_demand_body_struct;
attitude_demand_body_struct attitude_demand_body = {0};
// typedef struct{
// float demand;
// float demandOld;
// float valueOld;
// float derivative;
// float integral;
// } directionStruct;
// directionStruct pitch;
// directionStruct roll;
// directionStruct yaw;
typedef struct
{
float baro;
float gps;
float filtered;
float ultra;
float vel;
} altStruct;
altStruct alt = {0};
typedef struct{
volatile signed short raw;
volatile float av;
volatile float value;
volatile float offset;
volatile signed int total;
float error;
signed short history[GAV_LEN];
} sensorStructGyro;
typedef struct{
sensorStructGyro X;
sensorStructGyro Y;
sensorStructGyro Z;
unsigned int count;
} threeAxisSensorStructGyro;
threeAxisSensorStructGyro Gyro;
typedef struct{
volatile signed short raw;
volatile float av;
volatile float value;
volatile signed int total;
signed short history[AAV_LEN];
} sensorStructAccel;
typedef struct{
sensorStructAccel X;
sensorStructAccel Y;
sensorStructAccel Z;
unsigned int count;
} threeAxisSensorStructAccel;
threeAxisSensorStructAccel Accel;
typedef struct{
volatile signed short raw;
volatile float av;
volatile float value;
volatile signed int total;
signed short history[AAV_LEN];
} sensorStructMag;
typedef struct{
sensorStructMag X;
sensorStructMag Y;
sensorStructMag Z;
unsigned int count;
} threeAxisSensorStructMag;
threeAxisSensorStructMag Mag;
typedef struct paramStorage_struct {
char name[16];
float value;
} paramStorage_t;
/////////////////////////////////// GLOBAL VARIABLES /////////////////////////////////
// TODO: Why don't we just set all the variable here? Some of them are being set here, and some in the setup function.
// Timers and counters
unsigned int sysMS;
unsigned long long sysUS;
unsigned short RxWatchdog;
unsigned short UltraWatchdog;
unsigned short slowSoftscale;
unsigned int paramSendCount;
unsigned int paramCount;
unsigned char paramSendSingle;
// LEDs
unsigned char flashPLED, flashVLED, flashRLED;
// Quaternion and Rotation Matrix
float q1, q2, q3, q4;
float M1, M2, M3, M4, M5, M6, M7, M8, M9;
float thetaAngle, phiAngle, psiAngle, psiAngleinit;
float RM1, RM2, RM3, RM4, RM5, RM6, RM7, RM8, RM9;
// Inputs
unsigned short rcInput[7];
unsigned int rxLoss;
unsigned int rxFirst;
signed short yawtrim;
signed short throttletrim;
float throttle;
float throttle_angle;
int throttleHoldOff;
unsigned int auxState, flapState;
float pitchDemandSpin = 0;
float rollDemandSpin = 0;
float pitchDemandSpinold = 0;
float rollDemandSpinold = 0;
float flpswitch = 0;
// Ultrasound
float ultra;
unsigned int ultraLoss;
// Outputs
float pitchcorrectionav, rollcorrectionav, yawcorrectionav;
float motorN, motorE, motorS, motorW;
float motorNav, motorEav, motorSav, motorWav;
float tempN;
float tempE;
float tempS;
float tempW;
// Arm
unsigned int armed, calib, zeroThrotCounter;
// Battery
float batteryVoltage;
// Button
unsigned int PRGBlankTimer; // Blanking time for button pushes
unsigned int PRGTimer; // Timer for button pushes, continuously increments as the button is held
unsigned int PRGPushTime; // Contains the time that a button was pushed for, populated after button is released
/////////////////////////////////////////// TUNABLE PARAMETERS ////////////////////////////////////
struct paramStorage_struct paramStorage[] = {
{"DRIFT_AKp", 0.4f},
{"DRIFT_MKp", 0.2f},
#define DRIFT_AccelKp paramStorage[0].value
#define DRIFT_MagKp paramStorage[1].value
{"LPF_ULTRA", 0.95f},
#define LPF_ULTRA paramStorage[2].value
{"YAW_SEN", 0.0001f},
{"PITCH_SEN", 0.0022f},
{"ROLL_SEN", 0.0022f},
{"YAW_DZN", 0.001f},
#define YAW_SENS paramStorage[3].value
#define PITCH_SENS paramStorage[4].value
#define ROLL_SENS paramStorage[5].value
#define YAW_DEADZONE paramStorage[6].value
{"PITCH_Kp", 400.0f},
{"PITCH_Ki", 2.0f},
{"PITCH_Kd", 100.0f},
{"PITCH_Kdd", 1500.0f},
{"PITCH_Bst", 0.0f},
{"PITCH_De", 0.999f},
#define PITCH_Kp paramStorage[7].value
#define PITCH_Ki paramStorage[8].value
#define PITCH_Kd paramStorage[9].value
#define PITCH_Kdd paramStorage[10].value
#define PITCH_Boost paramStorage[11].value
#define PITCH_De paramStorage[12].value
{"ROLL_Kp", 400.0f},
{"ROLL_Ki", 2.0f},
{"ROLL_Kd", 100.0f},
{"ROLL_Kdd", 1500.0f},
{"ROLL_Bst", 0.00f},
{"ROLL_De", 0.999f},
#define ROLL_Kp paramStorage[13].value
#define ROLL_Ki paramStorage[14].value
#define ROLL_Kd paramStorage[15].value
#define ROLL_Kdd paramStorage[16].value
#define ROLL_Boost paramStorage[17].value
#define ROLL_De paramStorage[18].value
{"YAW_Kp", 1000.0f},
{"YAW_Kd", 250.0f},
{"YAW_Bst", 0.00f},
#define YAW_Kp paramStorage[19].value
#define YAW_Kd paramStorage[20].value
#define YAW_Boost paramStorage[21].value
// Mode
{"MODE_ST", 1.0f}, //used with the #dfine MODE_MANUAL etc
#define MODE_ST paramStorage[22].value
//Limits
{"LIM_ANGLE", 0.35f}, // Roll and Pitch Angle Limit in Radians
{"LIM_ALT", 1000.0f}, // Altitude Limit in mm when in Ultrasound Mode
#define LIM_ANGLE paramStorage[23].value
#define LIM_ALT paramStorage[24].value
// Magneto Correction
{"CAL_MAGN1", 0.001756f},
{"CAL_MAGN2", 0.00008370f},
{"CAL_MAGN3", 0.00005155f},
{"CAL_MAGN5", 0.001964f},
{"CAL_MAGN6", 0.00002218f},
{"CAL_MAGN9", 0.001768f},
{"CAL_MAGM1", 0.0f},
{"CAL_MAGM2", 0.0f},
{"CAL_MAGM3", 0.0f},
#define MAGCOR_N1 paramStorage[25].value
#define MAGCOR_N2 paramStorage[26].value
#define MAGCOR_N3 paramStorage[27].value
#define MAGCOR_N5 paramStorage[28].value
#define MAGCOR_N6 paramStorage[29].value
#define MAGCOR_N9 paramStorage[30].value
#define MAGCOR_M1 paramStorage[31].value
#define MAGCOR_M2 paramStorage[32].value
#define MAGCOR_M3 paramStorage[33].value
// Ultrasound
{"ULTRA_Kp", 0.05f},
{"ULTRA_Kd", 5.0f},
{"ULTRA_Ki", 0.00001f},
{"ULTRA_De", 0.9999f},
{"ULTRA_TKOFF", 200.0f},
{"ULTRA_LND", 150.0f},
#define ULTRA_Kp paramStorage[34].value
#define ULTRA_Kd paramStorage[35].value
#define ULTRA_Ki paramStorage[36].value
#define ULTRA_De paramStorage[37].value
#define ULTRA_TKOFF paramStorage[38].value
#define ULTRA_LND paramStorage[39].value
// TODO: I don't think these should be tunable parameters should they? Remember that the gyros are calibrated on every Arm
{"CAL_GYROX", 0.0f},
{"CAL_GYROY", 0.0f},
{"CAL_GYROZ", 0.0f},
#define CAL_GYROX paramStorage[40].value
#define CAL_GYROY paramStorage[41].value
#define CAL_GYROZ paramStorage[42].value
{"DETUNE", 0.2f},
#define DETUNE paramStorage[43].value
{"LIM_RATE", 100.0f},
#define LIM_RATE paramStorage[44].value
{"LIM_ULTRA", 4.0f},
#define LIM_ULTRA paramStorage[45].value
{"ULTRA_DRMP", 3.0f},
{"ULTRA_DTCT", 6.0f},
#define ULTRA_DRMP paramStorage[46].value
#define ULTRA_DTCT paramStorage[47].value
{"LIM_THROT", 0.3f},
#define LIM_THROT paramStorage[48].value
{"ULTRA_OVDEC", 0.01f},
#define ULTRA_OVDEC paramStorage[49].value
{"ULTRA_DEAD", 100},
#define ULTRA_DEAD paramStorage[50].value
{"ULTRA_OVTH", 40},
#define ULTRA_OVTH paramStorage[51].value
{"CAL_AUTO", 1.0f},
#define CAL_AUTO paramStorage[52].value
{"LPF_OUT", 0.6f},
#define LPF_OUT paramStorage[53].value
{"BAT_LOW", 11000.0f},
{"BAT_CRIT", 10000.0f},
#define BATT_LOW paramStorage[54].value
#define BATT_CRIT paramStorage[55].value
{"ULTRA_OFFSET", 350},
#define ULTRA_OFFSET paramStorage[56].value
{"ROLL_SPL", 0.04},
#define ROLL_SPL paramStorage[57].value
{"PITCH_SPL", 0.04},
#define PITCH_SPL paramStorage[58].value
// TODO: Tune Yaw integral
{"YAW_Ki", 0.0},
#define YAW_Ki paramStorage[59].value
{"YAW_De", 1.0},
#define YAW_De paramStorage[60].value
{"Filt_GPS_K", 1.0},
#define Filt_GPS_K paramStorage[61].value
{"LPF_BARO", 1.0},
#define LPF_BARO paramStorage[62].value
{"GPS_ALTKp", 10.0f},
{"GPS_ALTKi", 0.0001f},
{"GPS_ALTDe", 1.0f},
{"GPS_ALTKd", 20.0f},
#define GPS_ALTKp paramStorage[63].value
#define GPS_ALTKi paramStorage[64].value
#define GPS_ALTDe paramStorage[65].value
#define GPS_ALTKd paramStorage[66].value
{"Filt_baroK", 0.0},
#define Filt_baroK paramStorage[67].value
};
// System functionality crudly split into files
// TODO: make it more standard
#include "setup.h"
#include "filter.h"
#include "userinput.h"
#include "control.h"
#include "sensors.h"
#include "eeprom.h"
#include "communication.h"
//Main loop, nothing much happens in here.
void loop() {
//if(idleCount < IDLE_MAX) idleCount++; // this is the counter for CPU idle time
//Deal with button push for entering bind mode for RX
if(PRGBlankTimer == 0) {
if(PRGTimer > 3000) {
RXBind();
PRGPushTime = 0;
PRGTimer = 0;
PRGBlankTimer = 200;
}
}
__WFI();
}
// SysTick timer: deals with general timing
void SysTickInterrupt(void) {
sysMS += 1;
sysUS += 1000;
//Deal with flashing LEDs
if(sysMS % 25 == 0) {
if(sysMS % 100 == 0) {
if(flashPLED) LEDToggle(PLED);
if(flashVLED) LEDToggle(VLED);
if(flashRLED) LEDToggle(RLED);
}
else {
if(flashPLED == 2) LEDToggle(PLED);
if(flashVLED == 2) LEDToggle(VLED);
if(flashRLED == 2) LEDToggle(RLED);
}
}
// Time the button pushes
if(PRGPoll() == 0) PRGTimer++;
else {
PRGPushTime = PRGTimer;
PRGTimer = 0;
if(PRGBlankTimer) PRGBlankTimer--;
}
}
// RIT interrupt, deal with timed iLink messages.
void RITInterrupt(void) {
// Deal with iLink parameter transmission
unsigned int i;
if(paramSendCount < paramCount) {
unsigned short thisParam = paramSendCount; // store this to avoid race hazard since paramSendCount can change outside this interrupt
ilink_thalparam_tx.paramID = thisParam;
ilink_thalparam_tx.paramValue = paramStorage[thisParam].value;
ilink_thalparam_tx.paramCount = paramCount;
for(i=0; i<16; i++) {
ilink_thalparam_tx.paramName[i] = paramStorage[thisParam].name[i];
if(paramStorage[thisParam].name[i] == '\0') break;
}
if(ILinkSendMessage(ID_ILINK_THALPARAM, (unsigned short *) & ilink_thalparam_tx, sizeof(ilink_thalparam_tx)/2 -1)) {
if(paramSendSingle) {
paramSendSingle = 0;
paramSendCount = paramCount;
}
else {
paramSendCount = thisParam+1;
}
}
}
}
//Main functional periodic loop
void Timer0Interrupt0() { // Runs at about 400Hz
// We collect some data at a slower rate
if(++slowSoftscale >= SLOW_DIVIDER) {
slowSoftscale = 0;
ReadMagSensors();
ReadRXInput();
read_sticks();
ReadUltrasound();
ReadBaroSensors();
ReadBattVoltage();
filter_GPS_baro();
}
ReadAccelSensors();
ReadGyroSensors();
AHRS();
control_throttle();
control_attitude();
control_motors();
}
void Arm(void) {
if(CAL_AUTO > 0) {
CalibrateGyroTemp(1);
}
PWMInit(PWM_NESW);
PWMSetNESW(THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET);
//TODO: inline Delays cause system hang.
if(armed == 0) {
Delay(500);
PWMSetNESW(THROTTLEOFFSET + IDLETHROTTLE, THROTTLEOFFSET + IDLETHROTTLE, THROTTLEOFFSET + IDLETHROTTLE, THROTTLEOFFSET + IDLETHROTTLE);
Delay(100);
PWMSetNESW(THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET);
Delay(300);
PWMSetNESW(THROTTLEOFFSET + IDLETHROTTLE, THROTTLEOFFSET + IDLETHROTTLE, THROTTLEOFFSET + IDLETHROTTLE, THROTTLEOFFSET + IDLETHROTTLE);
Delay(100);
PWMSetNESW(THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET);
}
psiAngleinit = psiAngle;
yawtrim = rcInput[RX_RUDD];
armed = 1;
ilink_thalstat.sensorStatus &= ~(0x7); // mask status
ilink_thalstat.sensorStatus |= 4; // active/armed
}
void Disarm(void) {
if(armed) {
PWMSetNESW(THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET, THROTTLEOFFSET);
//TODO: inline Delays cause system hang.
Delay(100);
PWMSetN(THROTTLEOFFSET + IDLETHROTTLE);
Delay(100);
PWMSetN(THROTTLEOFFSET);
Delay(33);
PWMSetE(THROTTLEOFFSET + IDLETHROTTLE);
Delay(100);
PWMSetE(THROTTLEOFFSET);
Delay(33);
PWMSetS(THROTTLEOFFSET + IDLETHROTTLE);
Delay(100);
PWMSetS(THROTTLEOFFSET);
Delay(33);
PWMSetW(THROTTLEOFFSET + IDLETHROTTLE);
Delay(100);
PWMSetW(THROTTLEOFFSET);
Delay(100);
}
PWMSetNESW(0, 0, 0, 0);
armed = 0;
ilink_thalstat.sensorStatus &= ~(0x7); // mask status
ilink_thalstat.sensorStatus |= 3; // standby
}
<file_sep>// ****************************************************************************
// *** Copyright (c) 2011, Universal Air Ltd. All rights reserved.
// *** Source and binaries are released under the BSD 3-Clause license
// *** See readme_forebrain.txt files for the text of the license
// ****************************************************************************
#ifndef __THAL_H__
#define __THAL_H__
#include "thal.h"
#include "config.h"
#include "lpc1347.h"
#include "usb/mw_usbd_rom_api.h"
#ifndef WEAK
#define WEAK __attribute__ ((weak))
#endif
#ifndef WEAK_ALIAS
#define WEAK_ALIAS(f) __attribute__ ((weak, alias (#f)));
#endif
#ifndef ALIAS
#define ALIAS(f) __attribute__ ((alias (#f)));
#endif
#ifndef PACKED
#define PACKED __attribute__ ((packed))
#endif
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#ifndef NULL
#ifdef __cplusplus // EC++
#define NULL 0
#else
#define NULL ((void *) 0)
#endif
#endif
#if defined (__cplusplus)
extern "C" {
#endif
// ****************************************************************************
// *** Misc Functions
// ****************************************************************************
// *** In-application programming functions
typedef void (*FUNCIAP)(unsigned int *, unsigned int *);
void Reprogram(void);
unsigned int ReadPID(void);
void ReadUID(unsigned int * uid);
unsigned int ReadUIDHash(void);
// *** EEPROM functions (a subset of IAP
void EEPROMWriteByte(unsigned int address, unsigned char data);
unsigned char EEPROMReadByte(unsigned int address);
void EEPROMWrite(unsigned int address, unsigned char * data, unsigned int length);
void EEPROMRead(unsigned int address, unsigned char * data, unsigned int length);
// *** Reset functions
void Reset(void);
static inline void ResetInit(void) { LPC_IOCON->RESET_PIO0_0 = 0x90; }
// *** Byte handling functions
/*static inline unsigned char LowByte(unsigned short value) { return (value & 0xff); }
static inline unsigned char HighByte(unsigned short value) { return (value >> 8) & 0xff; }
static inline unsigned char FirstByte(unsigned int value) { return (value & 0xff); }
static inline unsigned char SecondByte(unsigned int value) { return (value >> 8) & 0xff; }
static inline unsigned char ThirdByte(unsigned int value) { return (value >> 16) & 0xff; }
static inline unsigned char FourthByte(unsigned int value) { return (value >> 24) & 0xff; }
static inline unsigned short MakeShort(unsigned char byte2, unsigned char byte1) { return ((byte2 << 8) & byte1); }
static inline unsigned int MakeInt(unsigned char byte4, unsigned char byte3, unsigned char byte2, unsigned char byte1) { return ((byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1); }
*/
// *** Fast trig approximation functions
float invSqrt(float x);
float fatan2(float y, float x);
float fasin(float x);
float fsin(float x);
// *** Random number functions
#if RAND_MERSENNE
void RandomSeed(unsigned int seed);
unsigned int Random(void);
#else
extern volatile unsigned int FUNCRandomNumber;
static inline unsigned int Random(void) { FUNCRandomNumber = FUNCRandomNumber * RAND_A + RAND_C; return FUNCRandomNumber; };
static inline void RandomSeed(unsigned int seed) { FUNCRandomNumber = seed; };
#endif
typedef struct _PWRD {
void (*set_pll)(unsigned int * cmd, unsigned int * resp);
void (*set_power)(unsigned int * cmd, unsigned int * resp);
} PWRD;
typedef struct _ROM {
const USBD_API_T * pUSBD;
const unsigned p_clib;
const unsigned p_cand;
const PWRD * pPWRD;
const unsigned p_dev1;
const unsigned p_dev2;
const unsigned p_dev3;
const unsigned p_dev4;
} ROM;
// ****************************************************************************
// *** Clock Functions
// ****************************************************************************
// *** Clock mode functions
#define XTAL 0
#define IRC72 1
#define IRC12 2
void ClockModeXTAL(void);
void ClockModeIRC72(void);
void ClockModeIRC12(void);
// *** Delay functions
void Delay(unsigned int milliseconds);
void WaitDelay(unsigned int milliseconds);
// *** System tick timer functions
#if SYSTICK_EN
void SysTickInit(void);
void SysTickStop(void);
extern volatile unsigned int FUNCSysTicks, FUNCTimeout;
extern WEAK void SysTickInterrupt(void);
extern WEAK void SDTick(void);
void SysTickDelay(unsigned int milliseconds);
void SysTickUDelay(unsigned int microseconds);
#endif
// *** Watchdog timer functions
#define INTERRUPT 0x40
void WDTInit(unsigned int milliseconds);
void WDTStop(void);
static inline void WDTFeed(void) { LPC_WWDT->FEED = 0xAA; LPC_WWDT->FEED = 0x55; }
extern WEAK void WDTInterrupt(void);
/*
// *** Clockout functions
//#define OFF 0 // this defined as such elsewhere
#define IRCOSC 1
#define SYSOSC 2
#define WDTOSC 3
#define MAINCLK 4
#define USBSOF 5
void ClockOut(unsigned char mode, unsigned char divider);
*/
void RITInit(unsigned long long value);
void RITInitms(unsigned int value);
static inline void RITMask(unsigned long long mask) { LPC_RITIMER->MASK = mask & 0xffffffff; LPC_RITIMER->MASK_H = mask >> 32; }
static inline void RITStop(void) { LPC_RITIMER->CTRL &= ~0x8; }
static inline void RITGo(void) { LPC_RITIMER->CTRL |= 0x8; }
static inline void RITReset(void) { LPC_RITIMER->COUNTER=0; LPC_RITIMER->COUNTER_H=0; }
static inline unsigned long long RITValue(void) { return ((unsigned long long) LPC_RITIMER->COUNTER_H << 32) | LPC_RITIMER->COUNTER; }
extern WEAK void RITInterrupt(void);
/*
// ****************************************************************************
// *** Power mode Functions
// ****************************************************************************
// *** Sleep mode
void Sleep(void);
// *** Deep sleep
#define PORT0PIN0 0x0000000000000001ULL
#define PORT0PIN1 0x0000000000000002ULL
#define PORT0PIN2 0x0000000000000004ULL
#define PORT0PIN3 0x0000000000000008ULL
#define PORT0PIN4 0x0000000000000010ULL
#define PORT0PIN5 0x0000000000000020ULL
#define PORT0PIN6 0x0000000000000040ULL
#define PORT0PIN7 0x0000000000000080ULL
#define PORT0PIN8 0x0000000000000100ULL
#define PORT0PIN9 0x0000000000000200ULL
#define PORT0PIN10 0x0000000000000400ULL
#define PORT0PIN11 0x0000000000000800ULL
#define PORT1PIN0 0x0000000000001000ULL
#define PORT1PIN1 0x0000000000002000ULL
#define PORT1PIN2 0x0000000000004000ULL
#define PORT1PIN3 0x0000000000008000ULL
#define PORT1PIN4 0x0000000000010000ULL
#define PORT1PIN5 0x0000000000020000ULL
#define PORT1PIN6 0x0000000000040000ULL
#define PORT1PIN7 0x0000000000080000ULL
#define PORT1PIN8 0x0000000000100000ULL
#define PORT1PIN9 0x0000000000200000ULL
#define PORT1PIN10 0x0000000000400000ULL
#define PORT1PIN11 0x0000000000800000ULL
#define PORT2PIN0 0x0000000001000000ULL
#define PORT2PIN1 0x0000000002000000ULL
#define PORT2PIN2 0x0000000004000000ULL
#define PORT2PIN3 0x0000000008000000ULL
#define PORT2PIN4 0x0000000010000000ULL
#define PORT2PIN5 0x0000000020000000ULL
#define PORT2PIN6 0x0000000040000000ULL
#define PORT2PIN7 0x0000000080000000ULL
#define PORT2PIN8 0x0000000100000000ULL
#define PORT2PIN9 0x0000000200000000ULL
#define PORT2PIN10 0x0000000400000000ULL
#define PORT2PIN11 0x0000000800000000ULL
#define PORT3PIN0 0x0000001000000000ULL
#define PORT3PIN1 0x0000002000000000ULL
#define PORT3PIN2 0x0000004000000000ULL
#define PORT3PIN3 0x0000008000000000ULL
void DeepSleep(unsigned long long startpins, unsigned long long startdirection, unsigned int timer);
// *** Deep power down mode
void PowerDown(void);
static inline void WriteBootData0(unsigned int data) { LPC_PMU->GPREG0 = data; }
static inline void WriteBootData1(unsigned int data) { LPC_PMU->GPREG1 = data; }
static inline void WriteBootData2(unsigned int data) { LPC_PMU->GPREG2 = data; }
static inline void WriteBootData3(unsigned int data) { LPC_PMU->GPREG3 = data; }
static inline void WriteBootData4(unsigned int data) { LPC_PMU->GPREG4 &= ~(0xfffff << 11); LPC_PMU->GPREG4 |= ((data & 0xfffff) << 11); }
static inline unsigned int ReadBootData0(void) { return LPC_PMU->GPREG0; }
static inline unsigned int ReadBootData1(void) { return LPC_PMU->GPREG1; }
static inline unsigned int ReadBootData2(void) { return LPC_PMU->GPREG2; }
static inline unsigned int ReadBootData3(void) { return LPC_PMU->GPREG3; }
static inline unsigned int ReadBootData4(void) { return (LPC_PMU->GPREG4 >> 11) & 0xfffff; }
// *** Brownout detect
#define BOD0 0 // 1.69V assert 1.84V deassert
#define BOD1 1 // 2.29V assert 2.44V deassert
#define BOD2 2 // 2.59V assert 2.74V deassert
#define BOD3 3 // 2.87V assert 2.98V deassert
void BODInit(unsigned char interruptlevel);
void BODStop(void);
extern WEAK void BODInterrupt(void);
// *** Reset status
#define POWERON 0x1
#define EXTERNAL 0x2
#define WATCHDOG 0x4
#define BROWNOUT 0x8
#define SOFTWARE 0x10
#define POWEREDDOWN 0x20
unsigned char ResetStatus(void);
*/
// ****************************************************************************
// *** GPIO Functions
// ****************************************************************************
// *** Pin number definitions
#define PIN0 (0x1UL << 0)
#define PIN1 (0x1UL << 1)
#define PIN2 (0x1UL << 2)
#define PIN3 (0x1UL << 3)
#define PIN4 (0x1UL << 4)
#define PIN5 (0x1UL << 5)
#define PIN6 (0x1UL << 6)
#define PIN7 (0x1UL << 7)
#define PIN8 (0x1UL << 8)
#define PIN9 (0x1UL << 9)
#define PIN10 (0x1UL << 10)
#define PIN11 (0x1UL << 11)
#define PIN12 (0x1UL << 12)
#define PIN13 (0x1UL << 13)
#define PIN14 (0x1UL << 14)
#define PIN15 (0x1UL << 15)
#define PIN16 (0x1UL << 16)
#define PIN17 (0x1UL << 17)
#define PIN18 (0x1UL << 18)
#define PIN19 (0x1UL << 19)
#define PIN20 (0x1UL << 20)
#define PIN21 (0x1UL << 21)
#define PIN22 (0x1UL << 22)
#define PIN23 (0x1UL << 23)
#define PIN24 (0x1UL << 24)
#define PIN25 (0x1UL << 25)
#define PIN26 (0x1UL << 26)
#define PIN27 (0x1UL << 27)
#define PIN28 (0x1UL << 28)
#define PIN29 (0x1UL << 29)
#define PIN30 (0x1UL << 30)
#define PIN31 (0x1UL << 31)
#define ALL 0xffffffff
// *** Initialise pins as digital IO mode (note: default state is digital input)
void Port0Init(unsigned int pins);
void Port1Init(unsigned int pins);
// *** Sets pins as inputs or outputs
static inline void Port0SetIn(unsigned int pins) { LPC_GPIO->DIR[0] &= ~pins; }
static inline void Port1SetIn(unsigned int pins) { LPC_GPIO->DIR[1] &= ~pins; }
static inline void Port0SetOut(unsigned int pins) { LPC_GPIO->DIR[0] |= pins; }
static inline void Port1SetOut(unsigned int pins) { LPC_GPIO->DIR[1] |= pins; }
// *** Write high or low
static inline void Port0High(unsigned int pins) { LPC_GPIO->SET[0] = pins; }
static inline void Port1High(unsigned int pins) { LPC_GPIO->SET[1] = pins; }
static inline void Port0Low(unsigned int pins) { LPC_GPIO->CLR[0] = pins; }
static inline void Port1Low(unsigned int pins) { LPC_GPIO->CLR[1] = pins; }
// *** Writes digital high or low to pins that are in Output mode
static inline void Port0Write(unsigned int pins, unsigned char value) {
if(value) LPC_GPIO->SET[0] = pins;
else LPC_GPIO->CLR[0] = pins;
}
static inline void Port1Write(unsigned int pins, unsigned char value) {
if(value) LPC_GPIO->SET[1] = pins;
else LPC_GPIO->CLR[1] = pins;
}
// *** Writes digital high or low to pins that are in Output mode
static inline void Port0WriteMasked(unsigned int pins, unsigned int value) {
LPC_GPIO->MASK[0] = ~pins;
LPC_GPIO->MPIN[0] = value;
}
static inline void Port1WriteMasked(unsigned int pins, unsigned int value) {
LPC_GPIO->MASK[1] = ~pins;
LPC_GPIO->MPIN[1] = value;
}
// *** Toggle the status of a pin
static inline void Port0Toggle(unsigned int pins) { LPC_GPIO->NOT[0] = pins; }
static inline void Port1Toggle(unsigned int pins) { LPC_GPIO->NOT[0] = pins; }
// *** Returns the digital value on a pin that are in Input mode
static inline unsigned char Port0Read(unsigned int pins) {
if(LPC_GPIO->PIN[0] & pins) return 1;
else return 0;
}
static inline unsigned char Port1Read(unsigned int pins) {
if(LPC_GPIO->PIN[1] & pins) return 1;
else return 0;
}
// *** Returns the data on a whole port
static inline unsigned short Port0Data(void) { return LPC_GPIO->PIN[0]; }
static inline unsigned short Port1Data(void) { return LPC_GPIO->PIN[1]; }
// *** Returns the data on a whole port, but with masked pins
static inline unsigned int Port0DataMasked(unsigned int pins) {
LPC_GPIO->MASK[0] = ~pins;
return LPC_GPIO->MPIN[0];
}
static inline unsigned int Port1DataMasked(unsigned int pins) {
LPC_GPIO->MASK[1] = ~pins;
return LPC_GPIO->MPIN[1];
}
// *** Configure hysteresis on a pin (note: default stat is hysteresis disabled)
#define ON 1// this defined as such elsewhere
#define OFF 0// this defined as such elsewhere
void Port0Hysteresis(unsigned int pins, unsigned char value);
void Port1Hysteresis(unsigned int pins, unsigned char value);
// *** Configure hysteresis on a pin (note: default stat is hysteresis disabled)
#define INVERT 1
#define NORMAL 0
void Port0Invert(unsigned int pins, unsigned char value);
void Port1Invert(unsigned int pins, unsigned char value);
// *** Configure pull-up/-down resistors on a pin (note: default state is pull-up enabled)
#define PULLUP 0x2
#define PULLDOWN 0x1
#define REPEATER 0x3
void Port0Pull(unsigned int pins, unsigned char value);
void Port1Pull(unsigned int pins, unsigned char value);
// *** Configure interrupts on a pin (note: default state is interrupts disabled)
//#define OFF 0 // this defined as such elsewhere
#define RISING 0x1
#define FALLING 0x2
#define BOTH 0x3
#define LOW 0x10
#define HIGH 0x20
/*void Port0SetInterrupt(unsigned short pins, unsigned char mode);
void Port1SetInterrupt(unsigned short pins, unsigned char mode);
// *** Function prototypes for user-supplied port-wide interrupt functions
extern WEAK void Port0Interrupt(unsigned short GPIOPins);
extern WEAK void Port1Interrupt(unsigned short GPIOPins);
extern WEAK void Port2Interrupt(unsigned short GPIOPins);
extern WEAK void Port3Interrupt(unsigned short GPIOPins);
static inline unsigned short Port0GetInterrupt(void) { return LPC_GPIO0->MIS; }
static inline unsigned short Port1GetInterrupt(void) { return LPC_GPIO1->MIS; }
static inline unsigned short Port2GetInterrupt(void) { return LPC_GPIO2->MIS; }
static inline unsigned short Port3GetInterrupt(void) { return LPC_GPIO3->MIS; }
// *** Function prototypes for user-supplied pin-specific interrupt functions
extern WEAK void Port0Pin0Interrupt(void);
extern WEAK void Port0Pin1Interrupt(void);
extern WEAK void Port0Pin2Interrupt(void);
extern WEAK void Port0Pin3Interrupt(void);
extern WEAK void Port0Pin4Interrupt(void);
extern WEAK void Port0Pin5Interrupt(void);
extern WEAK void Port0Pin6Interrupt(void);
extern WEAK void Port0Pin7Interrupt(void);
extern WEAK void Port0Pin8Interrupt(void);
extern WEAK void Port0Pin9Interrupt(void);
extern WEAK void Port0Pin10Interrupt(void);
extern WEAK void Port0Pin11Interrupt(void);
extern WEAK void Port1Pin0Interrupt(void);
extern WEAK void Port1Pin1Interrupt(void);
extern WEAK void Port1Pin2Interrupt(void);
extern WEAK void Port1Pin3Interrupt(void);
extern WEAK void Port1Pin4Interrupt(void);
extern WEAK void Port1Pin5Interrupt(void);
extern WEAK void Port1Pin6Interrupt(void);
extern WEAK void Port1Pin7Interrupt(void);
extern WEAK void Port1Pin8Interrupt(void);
extern WEAK void Port1Pin9Interrupt(void);
extern WEAK void Port1Pin10Interrupt(void);
extern WEAK void Port1Pin11Interrupt(void);
extern WEAK void Port2Pin0Interrupt(void);
extern WEAK void Port2Pin1Interrupt(void);
extern WEAK void Port2Pin2Interrupt(void);
extern WEAK void Port2Pin3Interrupt(void);
extern WEAK void Port2Pin4Interrupt(void);
extern WEAK void Port2Pin5Interrupt(void);
extern WEAK void Port2Pin6Interrupt(void);
extern WEAK void Port2Pin7Interrupt(void);
extern WEAK void Port2Pin8Interrupt(void);
extern WEAK void Port2Pin9Interrupt(void);
extern WEAK void Port2Pin10Interrupt(void);
extern WEAK void Port2Pin11Interrupt(void);
extern WEAK void Port3Pin0Interrupt(void);
extern WEAK void Port3Pin1Interrupt(void);
extern WEAK void Port3Pin2Interrupt(void);
extern WEAK void Port3Pin3Interrupt(void);
*/
// ****************************************************************************
// *** UART Functions
// ****************************************************************************
#if UART_EN
// *** UART start, stop functions functions
#define AUTO 0
void UARTInit(unsigned int baud);
void UARTStop(void);
void UARTFlush(void);
// *** UART Write functions
void UARTWrite(unsigned char * data, unsigned int length);
void UARTWriteByte(unsigned char data);
// *** UART Read functions
static inline unsigned char UARTAvailable(void) { return LPC_USART->LSR & 0x1; }
static inline unsigned char UARTOverrun(void) { return (LPC_USART->LSR >> 1) & 0x1; }
unsigned char UARTReadByte(void);
extern WEAK void UARTInterrupt(unsigned char UARTData);
extern WEAK void UARTParityError(unsigned char UARTData);
#if UART_USE_OUTBUFFER
extern unsigned char FUNCUARTBuffer[UART_BUFFER_SIZE];
extern volatile unsigned short FUNCUARTBufferPush, FUNCUARTBufferPop;
unsigned short UARTBufferWritable(void);
unsigned short UARTBufferReadable(void);
unsigned char UARTBufferPop(void);
void UARTBufferPush(unsigned char data);
#endif
#endif
// ****************************************************************************
// *** I2C Functions
// ****************************************************************************
#if I2C_EN
// *** Some software state machine definitions
#define I2C_IDLE 0
#define I2C_STARTED 1
#define I2C_RESTARTED 2
#define I2C_REPEATED_START 3
#define I2C_ACK 4
#define I2C_NACK 5
#define I2C_NACK_END 6
#define I2C_WR_STARTED 7
#define I2C_RD_STARTED 8
#define I2C_GEN_STARTED 9
#define I2C_ERROR 255
#define I2C_AA 0x04
#define I2C_SI 0x08
#define I2C_STO 0x10
#define I2C_STA 0x20
#define I2C_ENA 0x40
#define SLAVE 0
// *** I2C global datas
extern volatile unsigned char FUNCI2CMasterState, FUNCI2CMasterState2, FUNCI2CSlaveState, FUNCI2CSlaveState2, FUNCI2CMode;
extern volatile unsigned int FUNCI2CRdLength, FUNCI2CWrLength;
extern volatile unsigned int FUNCI2CRdIndex, FUNCI2CWrIndex;
extern unsigned char FUNCI2CBuffer[I2C_DATA_SIZE];
// *** I2C functions
void I2CInit(unsigned short speed);
void I2CStop(void);
unsigned int I2CMaster(unsigned char * wrData, unsigned int wrLength, unsigned char * rdData, unsigned char rdLength);
// *** I2C user-provided interrupts (for slave mode only)
extern WEAK void I2CInterrupt(unsigned char * I2CData, unsigned int I2CWriteLength);
#endif
// ****************************************************************************
// *** SSP Functions
// ****************************************************************************
#if SSP0_EN
// *** SSP Initialise and stop
#ifndef SLAVE
#define SLAVE 0
#endif
void SSP0Init(unsigned short speed);
void SSP0Stop(void);
// ** Change SSP speed (used for example for reading from SD cards)
void SSP0SetSpeed(unsigned short speed);
// *** Read and write functions
void SSP0WriteByte(unsigned short data);
unsigned short SSP0ReadByte(void);
void SSP0Write(unsigned short * data, unsigned int i);
unsigned short SSP0Byte(unsigned short data);
void SSP0NextByte(unsigned short data);
// *** SSP SSEL functions
static inline void SSP0Wait(void) { while (LPC_SSP0->SR & 0x10); }
static inline void SSP0S0SEL(void) { Port0Write(PIN2, 0); }
static inline void SSP0S0CLR(void) { SSP0Wait(); Port0Write(PIN2, 1); }
// *** SSP user-provided interrupts (for slave mode only)
extern WEAK void SSP0Interrupt(unsigned short SSP0Data);
#endif
#if SSP1_EN
#ifndef SLAVE
#define SLAVE 0
#endif
// *** SSP Initialise and stop
void SSP1Init(unsigned short speed);
void SSP1Stop(void);
// ** Change SSP speed (used for example for reading from SD cards)
void SSP1SetSpeed(unsigned short speed);
// *** Read and write functions
void SSP1WriteByte(unsigned short data);
unsigned short SSP1ReadByte(void);
void SSP1Write(unsigned short * data, unsigned int i);
unsigned short SSP1Byte(unsigned short data);
void SSP1NextByte(unsigned short data);
// *** SSP SSEL functions
static inline void SSP1Wait(void) { while (LPC_SSP1->SR & 0x10); }
static inline void SSP1S0SEL(void) { Port1Write(PIN19, 0); }
static inline void SSP1S0CLR(void) { SSP1Wait(); Port1Write(PIN19, 1); }
static inline void SSP1S1SEL(void) { Port0Write(PIN12, 0); }
static inline void SSP1S1CLR(void) { SSP1Wait(); Port0Write(PIN12, 1); }
// *** SSP user-provided interrupts (for slave mode only)
extern WEAK void SSP1Interrupt(unsigned short SSP1Data);
#endif
// ****************************************************************************
// *** Timers Functions
// ****************************************************************************
// *** Initialisations and stops
void Timer0Init(unsigned short prescale);
void Timer1Init(unsigned short prescale);
void Timer2Init(unsigned int prescale);
void Timer3Init(unsigned int prescale);
void Timer0Stop(void);
void Timer1Stop(void);
void Timer2Stop(void);
void Timer3Stop(void);
// *** Timer controls
static inline void Timer0Go(void) { LPC_CT16B0->TCR = 1; }
static inline void Timer1Go(void) { LPC_CT16B1->TCR = 1; }
static inline void Timer2Go(void) { LPC_CT32B0->TCR = 1; }
static inline void Timer3Go(void) { LPC_CT32B1->TCR = 1; }
static inline void Timer0Pause(void) { LPC_CT16B0->TCR = 0; }
static inline void Timer1Pause(void) { LPC_CT16B1->TCR = 0; }
static inline void Timer2Pause(void) { LPC_CT32B0->TCR = 0; }
static inline void Timer3Pause(void) { LPC_CT32B1->TCR = 0; }
static inline void Timer0Reset(void) { LPC_CT16B0->TCR = 0; LPC_CT16B0->TC = 0; }
static inline void Timer1Reset(void) { LPC_CT16B1->TCR = 0; LPC_CT16B1->TC = 0; }
static inline void Timer2Reset(void) { LPC_CT32B0->TCR = 0; LPC_CT32B0->TC = 0; }
static inline void Timer3Reset(void) { LPC_CT32B1->TCR = 0; LPC_CT32B1->TC = 0; }
// *** Timer values
static inline unsigned short Timer0Read(void) { return LPC_CT16B0->TC; }
static inline unsigned short Timer1Read(void) { return LPC_CT16B1->TC; }
static inline unsigned int Timer2Read(void) { return LPC_CT32B0->TC; }
static inline unsigned int Timer3Read(void) { return LPC_CT32B1->TC; }
static inline void Timer0Write(unsigned short value) { LPC_CT16B0->TC = value; }
static inline void Timer1Write(unsigned short value) { LPC_CT16B1->TC = value; }
static inline void Timer2Write(unsigned int value) { LPC_CT32B0->TC = value; }
static inline void Timer3Write(unsigned int value) { LPC_CT32B1->TC = value; }
static inline unsigned short Timer0Prescaler(void) { return LPC_CT16B0->PC; }
static inline unsigned short Timer1Prescaler(void) { return LPC_CT16B1->PC; }
static inline unsigned int Timer2Prescaler(void) { return LPC_CT32B0->PC; }
static inline unsigned int Timer3Prescaler(void) { return LPC_CT32B1->PC; }
static inline void Timer0DisableInterrupt(void) { IRQDisable(CT16B0_IRQn); }
static inline void Timer1DisableInterrupt(void) { IRQDisable(CT16B1_IRQn); }
static inline void Timer2DisableInterrupt(void) { IRQDisable(CT32B0_IRQn); }
static inline void Timer3DisableInterrupt(void) { IRQDisable(CT32B1_IRQn); }
static inline void Timer0EnableInterrupt(void) { IRQEnable(CT16B0_IRQn); }
static inline void Timer1EnableInterrupt(void) { IRQEnable(CT16B1_IRQn); }
static inline void Timer2EnableInterrupt(void) { IRQEnable(CT32B0_IRQn); }
static inline void Timer3EnableInterrupt(void) { IRQEnable(CT32B1_IRQn); }
// *** Timer match control
//#define OFF 0 // already defined elsewhere
//#define INTERRUPT 0x40 // already defined elsewhere
#define RESET 0x2 // already defined elsewhere
#define STOP 0x4
#define PWM 0x8
#define OUTPUTOFF 0 // this one doesn't need to be specified
#define OUTPUTLOW 0x10
#define OUTPUTHIGH 0x20
#define OUTPUTTOGGLE 0x30
void Timer0Match0(unsigned short interval, unsigned char mode);
void Timer0Match1(unsigned short interval, unsigned char mode);
void Timer0Match2(unsigned short interval, unsigned char mode);
void Timer0Match3(unsigned short interval, unsigned char mode);
void Timer1Match0(unsigned short interval, unsigned char mode);
void Timer1Match1(unsigned short interval, unsigned char mode);
void Timer1Match2(unsigned short interval, unsigned char mode);
void Timer1Match3(unsigned short interval, unsigned char mode);
void Timer2Match0(unsigned int interval, unsigned char mode);
void Timer2Match1(unsigned int interval, unsigned char mode);
void Timer2Match2(unsigned int interval, unsigned char mode);
void Timer2Match3(unsigned int interval, unsigned char mode);
void Timer3Match0(unsigned int interval, unsigned char mode);
void Timer3Match1(unsigned int interval, unsigned char mode);
void Timer3Match2(unsigned int interval, unsigned char mode);
void Timer3Match3(unsigned int interval, unsigned char mode);
static inline void Timer0SetMatch0(unsigned short interval) { LPC_CT16B0->MR0 = interval; }
static inline void Timer0SetMatch1(unsigned short interval) { LPC_CT16B0->MR1 = interval; }
static inline void Timer0SetMatch2(unsigned short interval) { LPC_CT16B0->MR2 = interval; }
static inline void Timer0SetMatch3(unsigned short interval) { LPC_CT16B0->MR3 = interval; }
static inline void Timer1SetMatch0(unsigned short interval) { LPC_CT16B1->MR0 = interval; }
static inline void Timer1SetMatch1(unsigned short interval) { LPC_CT16B1->MR1 = interval; }
static inline void Timer1SetMatch2(unsigned short interval) { LPC_CT16B1->MR2 = interval; }
static inline void Timer1SetMatch3(unsigned short interval) { LPC_CT16B1->MR3 = interval; }
static inline void Timer2SetMatch0(unsigned int interval) { LPC_CT32B0->MR0 = interval; }
static inline void Timer2SetMatch1(unsigned int interval) { LPC_CT32B0->MR1 = interval; }
static inline void Timer2SetMatch2(unsigned int interval) { LPC_CT32B0->MR2 = interval; }
static inline void Timer2SetMatch3(unsigned int interval) { LPC_CT32B0->MR3 = interval; }
static inline void Timer3SetMatch0(unsigned int interval) { LPC_CT32B1->MR0 = interval; }
static inline void Timer3SetMatch1(unsigned int interval) { LPC_CT32B1->MR1 = interval; }
static inline void Timer3SetMatch2(unsigned int interval) { LPC_CT32B1->MR2 = interval; }
static inline void Timer3SetMatch3(unsigned int interval) { LPC_CT32B1->MR3 = interval; }
// *** Timer match status
#define MATCH0 0x1
#define MATCH1 0x2
#define MATCH2 0x4
#define MATCH3 0x8
static inline unsigned char Timer0Status(void) { return LPC_CT16B0->EMR & 0xf; }
static inline unsigned char Timer1Status(void) { return LPC_CT16B1->EMR & 0xf; }
static inline unsigned char Timer2Status(void) { return LPC_CT32B0->EMR & 0xf; }
static inline unsigned char Timer3Status(void) { return LPC_CT32B1->EMR & 0xf; }
static inline void Timer0SetStatus(unsigned char status) { LPC_CT16B0->EMR &= 0xfff0; LPC_CT16B0->EMR |= status & 0xf; }
static inline void Timer1SetStatus(unsigned char status) { LPC_CT16B1->EMR &= 0xfff0; LPC_CT16B1->EMR |= status & 0xf; }
static inline void Timer2SetStatus(unsigned char status) { LPC_CT32B0->EMR &= 0xfff0; LPC_CT32B0->EMR |= status & 0xf; }
static inline void Timer3SetStatus(unsigned char status) { LPC_CT32B1->EMR &= 0xfff0; LPC_CT32B1->EMR |= status & 0xf; }
// *** Timer capture control
// #define OFF 0 // already defined elsewhere
//#define RISING 0x1 // already defined elsewhere
//#define FALLING 0x2 // already defined elsewhere
// #define BOTH 0x3 // already defined elsewhere
// #define INTERRUPT 0x40 // already defined elsewhere
#define COUNTER 0x10
#define PWRESET 0x80
void Timer0Capture(unsigned char mode);
void Timer1Capture(unsigned char mode);
void Timer2Capture(unsigned char mode);
void Timer3Capture(unsigned char mode);
static inline unsigned short Timer0CaptureValue(void) { return LPC_CT16B0->CR0; }
static inline unsigned short Timer1CaptureValue(void) { return LPC_CT16B1->CR0; }
static inline unsigned int Timer2CaptureValue(void) { return LPC_CT32B0->CR0; }
static inline unsigned int Timer3CaptureValue(void) { return LPC_CT32B1->CR0; }
// *** Timer interrupts
//#define MATCH0 0x1 // defined as such elsewhere
//#define MATCH1 0x2 // defined as such elsewhere
//#define MATCH2 0x4 // defined as such elsewhere
//#define MATCH3 0x8 // defined as such elsewhere
#define CAPTURE 0x10
extern WEAK void Timer0Interrupt(unsigned char TimerMatch);
extern WEAK void Timer0Interrupt0(void);
extern WEAK void Timer0Interrupt1(void);
extern WEAK void Timer0Interrupt2(void);
extern WEAK void Timer0Interrupt3(void);
extern WEAK void Timer0InterruptC(unsigned short TimerValue);
extern WEAK void Timer1Interrupt(unsigned char TimerMatch);
extern WEAK void Timer1Interrupt0(void);
extern WEAK void Timer1Interrupt1(void);
extern WEAK void Timer1Interrupt2(void);
extern WEAK void Timer1Interrupt3(void);
extern WEAK void Timer1InterruptC(unsigned short TimerValue);
extern WEAK void Timer2Interrupt(unsigned char TimerMatch);
extern WEAK void Timer2Interrupt0(void);
extern WEAK void Timer2Interrupt1(void);
extern WEAK void Timer2Interrupt2(void);
extern WEAK void Timer2Interrupt3(void);
extern WEAK void Timer2InterruptC(unsigned int TimerValue);
extern WEAK void Timer3Interrupt(unsigned char TimerMatch);
extern WEAK void Timer3Interrupt0(void);
extern WEAK void Timer3Interrupt1(void);
extern WEAK void Timer3Interrupt2(void);
extern WEAK void Timer3Interrupt3(void);
extern WEAK void Timer3InterruptC(unsigned int TimerValue);
// ****************************************************************************
// *** ADC Functions
// ****************************************************************************
// *** ADC channel number definitions
#define CHN0 (0x1UL << 0)
#define CHN1 (0x1UL << 1)
#define CHN2 (0x1UL << 2)
#define CHN3 (0x1UL << 3)
#define CHN4 (0x1UL << 4)
#define CHN5 (0x1UL << 5)
#define CHN6 (0x1UL << 6)
#define CHN7 (0x1UL << 7)
// *** Initialise or stop ADC
void ADCInit(unsigned short channels);
void ADCStop(void);
// *** Read ADC value
unsigned short ADCRead(unsigned char channel);
static inline void ADCTrigger(unsigned char channel) {
LPC_ADC->CR &= ~0x000000ff;
LPC_ADC->CR |= 0x1000000 | channel; // Start now!
}
static inline unsigned short ADCGet(void) {
return ((LPC_ADC->GDR >> 4) & 0xFFF);
}
// *** Prototype for user-supplied ADC interrupt function (only used when ADC is set to interrupt mode)
extern WEAK void ADCInterrupt(unsigned char ADCChannel, unsigned short ADCValue);
// ****************************************************************************
// *** USB Functions
// ****************************************************************************
extern USBD_API_T* USBROM;
extern USBD_HANDLE_T hUsb;
void USBInit(void);
// MSC
#define KBYTE 1024
#define MBYTE 1048576
#define GBYTE 1073741824
extern unsigned char MSC_DeviceDescriptor[];
extern unsigned char MSC_StringDescriptor[];
extern unsigned char MSC_ConfigDescriptor[];
void MSCInit(unsigned int deviceCapacity);
void MSCRead(unsigned int offset, unsigned char ** buffer, unsigned int length);
void MSCWrite(unsigned int offset, unsigned char ** buffer, unsigned int length);
signed int MSCVerify(unsigned int offset, unsigned char * source, unsigned int length);
// HID
extern unsigned char HID_DeviceDescriptor[];
extern unsigned char HID_StringDescriptor[];
extern unsigned char HID_ConfigDescriptor[];
void HIDInit(void);
extern uint8_t* report_buffer;
extern ErrorCode_t USB_Configure_Event(USBD_HANDLE_T hUsb);
ErrorCode_t HID_GetReport( USBD_HANDLE_T hHid, USB_SETUP_PACKET* pSetup, uint8_t** pBuffer, uint16_t* plength);
ErrorCode_t HID_SetReport( USBD_HANDLE_T hHid, USB_SETUP_PACKET* pSetup, uint8_t** pBuffer, uint16_t length);
ErrorCode_t HID_Ep_Hdlr (USBD_HANDLE_T hUsb, void* data, uint32_t event) ;
void HIDOutReport(unsigned char * buffer);
unsigned char HIDInReport(unsigned char * buffer);
void HIDOutFeature(unsigned char * buffer);
unsigned char HIDInFeature(unsigned char * buffer);
// CDC
#define BRIDGED 1
#define VIRTUAL 0
extern unsigned char VCOM_isbridge;
extern unsigned char CDC_DeviceDescriptor[];
extern unsigned char CDC_StringDescriptor[];
extern unsigned char CDC_ConfigDescriptor[];
void CDCInit(unsigned char bridge);
void CDCReadByte(unsigned char byte);
void CDCWriteByte(unsigned char byte);
void CDCWrite(unsigned char * byte, unsigned int length);
struct VCOM_DATA;
typedef void (*VCOM_SEND_T) (struct VCOM_DATA* pVcom);
typedef struct VCOM_DATA {
USBD_HANDLE_T hUsb;
USBD_HANDLE_T hCdc;
uint8_t* rxBuf;
uint8_t* txBuf;
volatile uint8_t ser_pos;
volatile uint16_t rxlen;
volatile uint16_t txlen;
VCOM_SEND_T send_fn;
volatile uint32_t sof_counter;
volatile uint32_t last_ser_rx;
volatile uint16_t break_time;
volatile uint16_t usbrx_pend;
} VCOM_DATA_T;
extern VCOM_DATA_T g_vCOM;
void VCOM_usb_send(VCOM_DATA_T* pVcom);
void VCOM_init_bridge(VCOM_DATA_T* pVcom, CDC_LINE_CODING* line_coding);
void VCOM_uart_write(VCOM_DATA_T* pVcom);
void VCOM_uart_read(VCOM_DATA_T* pVcom);
void VCOM_uart_send(VCOM_DATA_T* pVcom);
void VCOM_virtual_send(VCOM_DATA_T* pVcom);
ErrorCode_t VCOM_SetLineCode (USBD_HANDLE_T hCDC, CDC_LINE_CODING* line_coding);
ErrorCode_t VCOM_sof_event(USBD_HANDLE_T hUsb);
ErrorCode_t VCOM_SendBreak (USBD_HANDLE_T hCDC, uint16_t mstime);
ErrorCode_t VCOM_bulk_in_hdlr(USBD_HANDLE_T hUsb, void* data, uint32_t event) ;
ErrorCode_t VCOM_bulk_out_hdlr(USBD_HANDLE_T hUsb, void* data, uint32_t event) ;
// ****************************************************************************
// *** LED Functions
// ****************************************************************************
#define RLED (0x1UL << 0)
#define PLED (0x1UL << 1)
#define ULED (0x1UL << 6)
#define VLED (0x1UL << 3)
#define ALLLED (RLED | PLED | ULED | VLED)
extern volatile unsigned char FUNCLEDStatus;
static inline void LEDOff(unsigned int pins) { Port0High(pins); FUNCLEDStatus &= ~pins;}
static inline void LEDOn(unsigned int pins) { Port0Low(pins); FUNCLEDStatus |= pins;}
static inline void LEDInit(unsigned int pins) { Port0Init(pins); Port0SetOut(pins); LEDOff(pins);}
static inline void LEDWrite(unsigned int pins, unsigned char value) { if(value) LEDOn(pins); else LEDOff(pins); }
static inline void LEDToggle(unsigned int pins) { Port0Toggle(pins); FUNCLEDStatus ^= pins;}
static inline void RSTInit(void) { Port0Init(PIN0); Port0SetIn(PIN0); }
static inline void PRGInit(void) { Port0Init(PIN1); Port0SetIn(PIN1); }
static inline unsigned char RSTRead(void) { Port0SetIn(PIN0); __NOP(); __NOP(); __NOP(); return Port0Read(PIN0); }
static inline unsigned char PRGRead(void) { Port0SetIn(PIN1); __NOP(); __NOP(); __NOP(); return Port0Read(PIN1); }
unsigned char RSTPoll(void);
unsigned char PRGPoll(void);
static inline void RSTReset(void) { ResetInit(); }
// ****************************************************************************
// *** UAir Interlink Functions
// ****************************************************************************
#if ILINK_EN && SSP0_EN
#define ID_ILINK_IDENTIFY 0x0000
#define ID_ILINK_CLEARBUF 0x0003
#define ID_ILINK_THALCTRL 0x0100
#define ID_ILINK_THALSTAT 0x0101
#define ID_ILINK_THALPARAM 0x0102
#define ID_ILINK_THALPAREQ 0x0103
#define ID_ILINK_INPUTS0 0x4000
#define ID_ILINK_OUTPUTS0 0x4100
#define ID_ILINK_RAWIMU 0x4200
#define ID_ILINK_SCALEDIMU 0x4201
#define ID_ILINK_ALTITUDE 0x7e00
#define ID_ILINK_ATTITUDE 0x7f00
typedef struct ilink_identify_struct { // Contains the ID of the craft
unsigned short deviceID; // ID: Thalamus is 1 for example
unsigned int firmVersion; // Firmware version: check that this matches
unsigned short isNew;
} PACKED ilink_identify_t;
typedef struct ilink_thalctrl_struct {
unsigned short command;
unsigned int data;
unsigned short isNew;
} PACKED ilink_thalctrl_t;
typedef struct ilink_thalstat_struct { // Flight status
unsigned short flightMode; // Bitfield, bit 3 is altitude control, bit 2 is yaw control, bit 1 is anglerate control, bit 0 is Attitude control
unsigned short sensorStatus; // Bitfield, bit 6 is Baro status, bit5 is magneto status, bit 4 is Gyro status, bit 3 is Accel status, bit 2-0 flight status (corresponds to MAV_STATE)
unsigned short battVoltage; // Battery voltage
unsigned short isNew;
} PACKED ilink_thalstat_t;
typedef struct ilink_imu_struct { // IMU data
signed short xAcc;
signed short yAcc;
signed short zAcc;
signed short xGyro;
signed short yGyro;
signed short zGyro;
signed short xMag;
signed short yMag;
signed short zMag;
unsigned short isNew;
} PACKED ilink_imu_t;
typedef struct ilink_attitude_struct { // Attitude data
float roll;
float pitch;
float yaw;
float rollRate;
float pitchRate;
float yawRate;
unsigned short isNew;
} PACKED ilink_attitude_t;
typedef struct ilink_thalparam_struct { // Parameters
unsigned short paramID;
float paramValue;
unsigned short paramCount;
char paramName[16];
unsigned short isNew;
} PACKED ilink_thalparam_t;
typedef struct ilink_thalpareq_struct { // Parameter request
unsigned short reqType; // Request type, 0 is get all, 1 is get One, 2 is save all, 3 is reload all
unsigned short paramID; // Parameter to request, set to 0xffff to fetch by name
char paramName[16]; // Parameter name to request
unsigned short isNew;
} PACKED ilink_thalpareq_t;
typedef struct ilink_iochan_struct { // Input/output channel data
unsigned short channel[6];
unsigned short isNew;
} PACKED ilink_iochan_t;
typedef struct ilink_altitude_struct { // Altitude data
float ultraAlt;
float baroAlt;
float GPSAlt;
unsigned short isNew;
} PACKED ilink_altitude_t;
extern volatile unsigned char FUNCILinkState;
extern volatile unsigned short FUNCILinkID, FUNCILinkChecksumA, FUNCILinkChecksumB, FUNCILinkLength, FUNCILinkPacket;
extern unsigned short FUNCILinkRxBuffer[ILINK_BUFFER_SIZE];
void ILinkInit(unsigned short speed);
void ILinkPoll(unsigned short message);
void ILinkProcess(unsigned short data);
void ILinkFetchData(void);
unsigned char ILinkSendMessage(unsigned short id, unsigned short * buffer, unsigned short length);
extern WEAK void ILinkMessage(unsigned short id, unsigned short * buffer, unsigned short length);
extern WEAK void ILinkMessageRequest(unsigned short id);
extern WEAK void ILinkMessageError(unsigned short id);
extern unsigned short FUNCILinkTxBuffer[ILINK_BUFFER_SIZE];
extern volatile unsigned short FUNCILinkTxBufferPushPtr, FUNCILinkTxBufferPopPtr;
unsigned short ILinkWritable(void);
unsigned short ILinkReadable(void);
unsigned short ILinkPop(void);
void ILinkPush(unsigned short data);
#endif
#if WHO_AM_I == I_AM_THALAMUS
// ****************************************************************************
// *** ULTRA Functions (Thalamus only)
// ****************************************************************************
extern volatile unsigned char FUNCUltraNewData;
extern volatile unsigned short FUNCUltraValueMM;
extern volatile unsigned char FUNCUltraOutOfRange;
extern volatile unsigned char FUNCUltraUnderRange;
extern volatile unsigned char FUNCUltraFastRate;
unsigned char UltraInit(void);
static inline void UltraSlow(void) { FUNCUltraFastRate = 0; }
static inline void UltraFast(void) { FUNCUltraFastRate = 1; }
unsigned short UltraGetData(void);
unsigned short UltraGetNewData(void);
unsigned short UltraGetRawData(void);
// ****************************************************************************
// *** RX Functions (Thalamus only)
// ****************************************************************************
void RXInit(void);
void RXBind(void);
void RXDelay(void);
static inline void RXPowerDown(void) { Port0Write(PIN17, 1); }
static inline void RXPowerUp(void) { Port0Write(PIN17, 0); }
#define RX_THRO 0
#define RX_AILE 1
#define RX_ELEV 2
#define RX_RUDD 3
#define RX_GEAR 4
#define RX_AUX1 4
#define RX_FLAP 5
#define RX_AUX2 6
extern volatile unsigned char FUNCRXCount;
extern volatile unsigned char FUNCRXLastByte;
extern volatile unsigned char FUNCRXChannel;
extern volatile unsigned char FUNCRXNewData;
extern unsigned short FUNCRXChanBuffer[7];
extern unsigned short FUNCRXChan[7];
unsigned char RXProcess(unsigned char RXByte);
unsigned char RXGetData(unsigned short * RXChannels);
// ****************************************************************************
// *** PWM Ouput Functions
// ****************************************************************************
#define PWM_N (1 << 0)
#define PWM_E (1 << 1)
#define PWM_S (1 << 2)
#define PWM_W (1 << 3)
#define PWM_X (1 << 4)
#define PWM_Y (1 << 5)
#define PWM_NESW 0x0f
#define PWM_ALL 0x3f
extern volatile unsigned char FUNCPWMPostscale;
extern volatile unsigned short FUNCPWMN_duty;
extern volatile unsigned short FUNCPWME_duty;
extern volatile unsigned short FUNCPWMS_duty;
extern volatile unsigned short FUNCPWMW_duty;
extern volatile unsigned short FUNCPWMX_duty;
extern volatile unsigned short FUNCPWMY_duty;
void PWMInit(unsigned char channels);
#if PWM_FILTERS_ON == 0
static inline void PWMSetN(unsigned int value) { FUNCPWMN_duty = value; }
static inline void PWMSetE(unsigned int value) { FUNCPWME_duty = value; }
static inline void PWMSetS(unsigned int value) { FUNCPWMS_duty = value; }
static inline void PWMSetW(unsigned int value) { FUNCPWMW_duty = value; }
static inline void PWMSetX(unsigned int value) { FUNCPWMX_duty = value; }
static inline void PWMSetY(unsigned int value) { FUNCPWMY_duty = value; }
#else
extern volatile unsigned int FUNCPWMN_fil;
extern volatile unsigned int FUNCPWME_fil;
extern volatile unsigned int FUNCPWMS_fil;
extern volatile unsigned int FUNCPWMW_fil;
extern volatile unsigned int FUNCPWMX_fil;
extern volatile unsigned int FUNCPWMY_fil;
static inline void PWMSetN(unsigned int value) { FUNCPWMN_fil *= PWM_NESW_FILTER; FUNCPWMN_fil += value * (1-PWM_NESW_FILTER); FUNCPWMN_duty = FUNCPWMN_fil; }
static inline void PWMSetE(unsigned int value) { FUNCPWME_fil *= PWM_NESW_FILTER; FUNCPWME_fil += value * (1-PWM_NESW_FILTER); FUNCPWME_duty = FUNCPWME_fil; }
static inline void PWMSetS(unsigned int value) { FUNCPWMS_fil *= PWM_NESW_FILTER; FUNCPWMS_fil += value * (1-PWM_NESW_FILTER); FUNCPWMS_duty = FUNCPWMS_fil; }
static inline void PWMSetW(unsigned int value) { FUNCPWMW_fil *= PWM_NESW_FILTER; FUNCPWMW_fil += value * (1-PWM_NESW_FILTER); FUNCPWMW_duty = FUNCPWMW_fil; }
static inline void PWMSetX(unsigned int value) { FUNCPWMX_fil *= PWM_XY_FILTER; FUNCPWMX_fil += value * (1-PWM_XY_FILTER); FUNCPWMX_duty = FUNCPWMX_fil; }
static inline void PWMSetY(unsigned int value) { FUNCPWMY_fil *= PWM_XY_FILTER; FUNCPWMY_fil += value * (1-PWM_XY_FILTER); FUNCPWMY_duty = FUNCPWMY_fil; }
#endif
static inline void PWMSetNESW(unsigned int valueN, unsigned int valueE, unsigned int valueS, unsigned int valueW) {
PWMSetN(valueN);
PWMSetE(valueE);
PWMSetS(valueS);
PWMSetW(valueW);
}
static inline void PWMSetNESWXY(unsigned int valueN, unsigned int valueE, unsigned int valueS, unsigned int valueW, unsigned int valueX, unsigned int valueY) {
PWMSetN(valueN);
PWMSetE(valueE);
PWMSetS(valueS);
PWMSetW(valueW);
PWMSetX(valueX);
PWMSetY(valueY);
}
// ****************************************************************************
// *** IMU Functions
// ****************************************************************************
#define ACCEL_ADDR 0x30
#define GYRO_ADDR 0xd0
#define MAGNETO_ADDR 0x3c
void SensorInit(void);
unsigned char GetAccel(signed short * data);
unsigned char GetGyro(signed short * data);
signed short GetTemp(void);
unsigned char GetMagneto(signed short * data);
void SensorSleep(void);
#endif
#if WHO_AM_I == I_AM_HYPO
// ****************************************************************************
// *** PWM Ouput Functions
// ****************************************************************************
#define PWM_A (1 << 0)
#define PWM_B (1 << 1)
#define PWM_C (1 << 2)
#define PWM_D (1 << 3)
#define PWM_S (1 << 4)
#define PWM_ALL 0x1f
extern volatile unsigned char FUNCPWMPostscale;
void PWMInit(unsigned char channels);
#if PWM_FILTERS_ON == 0
static inline void PWMSetA(unsigned int value) { Timer3SetMatch3(value); }
static inline void PWMSetB(unsigned int value) { Timer3SetMatch2(value); }
static inline void PWMSetC(unsigned int value) { Timer3SetMatch1(value); }
static inline void PWMSetD(unsigned int value) { Timer3SetMatch0(value); }
static inline void PWMSetS(unsigned int value) { Timer2SetMatch3(value); }
#else
extern volatile unsigned int FUNCPWMA_fil;
extern volatile unsigned int FUNCPWMB_fil;
extern volatile unsigned int FUNCPWMC_fil;
extern volatile unsigned int FUNCPWMD_fil;
extern volatile unsigned int FUNCPWMS_fil;
static inline void PWMSetA(unsigned int value) { FUNCPWMA_fil *= PWM_ABCD_FILTER; FUNCPWMA_fil += value * (1-PWM_ABCD_FILTER); Timer3SetMatch3(FUNCPWMA_fil); }
static inline void PWMSetB(unsigned int value) { FUNCPWMB_fil *= PWM_ABCD_FILTER; FUNCPWMB_fil += value * (1-PWM_ABCD_FILTER); Timer3SetMatch1(FUNCPWMB_fil); }
static inline void PWMSetC(unsigned int value) { FUNCPWMC_fil *= PWM_ABCD_FILTER; FUNCPWMC_fil += value * (1-PWM_ABCD_FILTER); Timer3SetMatch1(FUNCPWMC_fil); }
static inline void PWMSetD(unsigned int value) { FUNCPWMD_fil *= PWM_ABCD_FILTER; FUNCPWMD_fil += value * (1-PWM_ABCD_FILTER); Timer3SetMatch0(FUNCPWMD_fil); }
static inline void PWMSetS(unsigned int value) { FUNCPWMS_fil *= PWM_S_FILTER; FUNCPWMS_fil += value * (1-PWM_S_FILTER); Timer2SetMatch3(FUNCPWMS_fil); }
#endif
static inline void PWMSetABCD(unsigned int valueA, unsigned int valueB, unsigned int valueC, unsigned int valueD) {
PWMSetA(valueA);
PWMSetB(valueB);
PWMSetC(valueC);
PWMSetD(valueD);
}
// ****************************************************************************
// *** GPS Functions
// ****************************************************************************
#if GPS_EN
#define GPS_ADDR 0x84
#define ID_NAV_POSECEF 0x0101
#define ID_NAV_POSLLH 0x0102
#define ID_NAV_STATUS 0x0103
#define ID_NAV_SOL 0x0106
#define ID_NAV_VELNED 0x0112
#define ID_NAV_TIMEUTC 0x0121
void GPSInit(void);
void GPSHotstart(void);
void GPSSleep(void);
void GPSPoll(unsigned short id);
#if GPS_METHOD == 0
unsigned short GPSGetMessage(unsigned short id, unsigned char * buffer);
unsigned char GPSGetFix(void);
unsigned char GPSGetLocation(signed int * location);
void GPSClearBuffer(void);
#endif
#if GPS_METHOD == 1
extern volatile unsigned char FUNCGPSState, FUNCGPSChecksumA, FUNCGPSChecksumB, FUNCGPSID1, FUNCGPSID2;
extern volatile unsigned short FUNCGPSLength, FUNCGPSPacket, FUNCGPSID;
extern unsigned char FUNCGPSBuffer[GPS_BUFFER_SIZE];
typedef struct gps_nav_posecef_struct{
unsigned int iTOW;
signed int ecefX;
signed int ecefY;
signed int ecefZ;
unsigned int pAcc;
unsigned char isNew;
} PACKED gps_nav_posecef_t;
typedef struct gps_nav_posllh_struct {
unsigned int iTOW;
signed int lon;
signed int lat;
signed int height;
signed int hMSL;
unsigned int hAcc;
unsigned int vAcc;
unsigned char isNew;
} PACKED gps_nav_posllh_t;
typedef struct gps_nav_status_struct {
unsigned int iTOW;
unsigned char gpsFix;
unsigned char flags;
unsigned char fixStat;
unsigned char flags2;
unsigned int ttff;
unsigned int msss;
unsigned char isNew;
} PACKED gps_nav_status_t;
typedef struct gps_nav_sol_struct {
unsigned int iTOW;
signed int fTOW;
signed short week;
unsigned char gpsFix;
unsigned char flags;
signed int ecefX;
signed int ecefY;
signed int ecefZ;
unsigned int pAcc;
signed int ecefVX;
signed int ecefVY;
signed int ecefVZ;
unsigned int sAcc;
unsigned short pDOP;
unsigned char resl;
unsigned char numSV;
unsigned int res2;
unsigned char isNew;
} PACKED gps_nav_sol_t;
typedef struct gps_nav_velned_struct{
unsigned int iTOW;
signed int velN;
signed int vleE;
signed int velD;
unsigned int speed;
unsigned int gSpeed;
signed int heading;
unsigned int sAcc;
unsigned int cAcc;
unsigned char isNew;
} PACKED gps_nav_velned_t;
typedef struct gps_nav_timeutc_struct {
unsigned int iTOW;
unsigned int tAcc;
signed int nano;
unsigned short year;
unsigned char month;
unsigned char day;
unsigned char hour;
unsigned char min;
unsigned char sec;
unsigned char valid;
unsigned char isNew;
} PACKED gps_nav_timeutc_t;
void GPSSetRate(unsigned short it, unsigned char rate);
void GPSFetchData(void);
extern WEAK void GPSMessage(unsigned short id, unsigned char * buffer, unsigned short length);
#endif
#endif
// ****************************************************************************
// *** Flash Functions
// ****************************************************************************
#if SSP1_EN & FLASH_EN
static inline void FlashSEL(void) { Port0Write(PIN23, 0); }
static inline void FlashCLR(void) { SSP1Wait(); Port0Write(PIN23, 1); }
extern volatile unsigned int FUNCFlashCR0Reset, FUNCFlashCPSRReset;
void FlashInit(void);
void FlashStart(void);
void FlashEnd(void);
void FlashWait(void);
void FlashWrEn(void);
void FlashEraseChip(void);
void FlashErase4k(unsigned int address);
void FlashErase32k(unsigned int address);
void FlashErase64k(unsigned int address);
unsigned int FlashGetID(void);
unsigned char FlashGetMan(void);
unsigned char FlashGetType(void);
unsigned char FlashGetCapacity(void);
void FlashRawWriteByte(unsigned int address, unsigned char data);
void FlashRawWrite(unsigned int address, unsigned char * data, unsigned int length);
unsigned char FlashRawReadByte(unsigned int address);
void FlashRawRead(unsigned int address, unsigned char * data, unsigned int length);
unsigned char FlashVerify(unsigned int address, unsigned char * data, unsigned int length);
// buffered versions of the above
extern volatile unsigned int FUNCFlashCurrentSector;
extern unsigned char FUNCFlashSectorBuffer[4096];
extern volatile unsigned char FUNCFlashSectorChanged;
void FlashBufferSector(unsigned int address);
void FlashFlushBuffer(void);
void FlashWriteByte(unsigned int address, unsigned char data);
void FlashWrite(unsigned int address, unsigned char * data, unsigned int length);
unsigned char FlashReadByte(unsigned int address);
void FlashRead(unsigned int address, unsigned char * data, unsigned int length);
#endif
#endif
#if WHO_AM_I == I_AM_HYPO || WHO_AM_I == I_AM_HYPX
// ****************************************************************************
// *** XBee Functions
// ****************************************************************************
#if UART_EN && SYSTICK_EN && XBEE_EN
#define ID_XBEE_ATCOMMAND 0x08
#define ID_XBEE_ATCOMMANDQ 0x09
#define ID_XBEE_ATRESPONSE 0x88
#define ID_XBEE_TRANSMITSTATUS 0x8b
#define ID_XBEE_MODEMSTATUS 0x8A
#define ID_XBEE_RECEIVEPACKET 0x90
#define ID_XBEE_TRANSMITREQUEST 0x10
#define IX_XBEE_NODEIDENTIFICATIONINDICATOR 0x95
#define TBUF_LEN 10
typedef struct xbee_modem_status_struct {
unsigned char status;
volatile unsigned char isNew;
unsigned short varLen;
} PACKED xbee_modem_status_t;
typedef struct xbee_at_command_struct {
unsigned char frameID;
unsigned char ATCommand1;
unsigned char ATCommand2;
unsigned char parameterValue[16];
volatile unsigned char isNew;
unsigned short varLen;
} PACKED xbee_at_command_t;
typedef struct xbee_at_response_struct {
unsigned char frameID;
unsigned char ATCommand1;
unsigned char ATCommand2;
unsigned char commandStatus;
unsigned char commandData[8];
volatile unsigned char isNew;
unsigned short varLen;
} PACKED xbee_at_response_t;
typedef struct xbee_transmit_status_struct {
unsigned char frameID;
unsigned short networkAddress;
unsigned char transmitRetryCount;
unsigned char deliveryStatus;
unsigned char discoveryStatus;
volatile unsigned char isNew;
unsigned short varLen;
} PACKED xbee_transmit_status_t;
typedef struct xbee_receive_packet_struct {
unsigned long long sourceAddress;
unsigned short networkAddress;
unsigned char receiveOptions;
unsigned char RFData[255];
volatile unsigned char isNew;
unsigned short varLen;
} PACKED xbee_receive_packet_t;
typedef struct xbee_transmit_request_struct {
unsigned char frameID;
unsigned long long destinationAddress;
unsigned short networkAddress;
unsigned char broadcastRadius;
unsigned char options;
unsigned char RFData[255];
volatile unsigned char isNew;
unsigned short varLen;
} PACKED xbee_transmit_request_t;
typedef struct xbee_node_identification_indicator_struct {
unsigned long long senderSourceAddress;
unsigned short senderNetworkAddress;
unsigned char receiveOptions;
unsigned short remoteNetworkAddress;
unsigned long long remoteSourceAddress;
unsigned char NIString;
unsigned char null;
unsigned short parentNetworkAddress;
unsigned char deviceType;
unsigned char sourceEvent;
unsigned short digiProfileID;
unsigned short digiManufacturerID;
volatile unsigned char isNew;
unsigned short varLen;
} PACKED xbee_node_identification_indicator_t;
extern xbee_modem_status_t xbee_modem_status;
extern xbee_at_command_t xbee_at_command;
extern xbee_at_response_t xbee_at_response;
extern xbee_transmit_status_t xbee_transmit_status;
extern xbee_receive_packet_t xbee_receive_packet;
extern xbee_transmit_request_t xbee_transmit_request;
extern xbee_node_identification_indicator_t xbee_node_identification_indicator;
extern unsigned char FUNCXBeetBuf[TBUF_LEN];
extern volatile unsigned char FUNCXBeetBufCount;
unsigned int XBeetBufCompare(unsigned char * compare, unsigned int length);
extern volatile unsigned int FUNCXBeeState;
extern volatile unsigned short FUNCXBeeLength, FUNCXBeeID, FUNCXBeePacket;
extern volatile unsigned char FUNCXBeeChecksum;
extern unsigned char FUNCXBeeBuffer[XBEE_BUFFER_SIZE];
extern WEAK void XBeeMessage(unsigned char id, unsigned char * buffer, unsigned short length);
void XBeeInit(void);
void XBeeCommFail(void);
void XBeeSetDefaults(void);
void XBeeFactoryReset(void);
void XBeeCoordinatorJoin(void);
void XBeeAllowJoin(void);
void XBeeStopJoin(void);
void XBeeJoin(void);
void XBeeSendFrame(unsigned char id, unsigned char * buffer, unsigned short length);
unsigned char XBeeSendATCommand(void);
unsigned char XBeeSendPacket(void);
unsigned char XBeeWriteBroadcast(unsigned char * buffer, unsigned short length);
unsigned char XBeeWriteCoordinator(unsigned char * buffer, unsigned short length);
static inline void XBeeReset(void) { Port0Init(PIN20); Port0SetOut(PIN20); Port0Write(PIN20, 0); }
static inline void XBeeRelease(void) { Port0Init(PIN20); Port0SetOut(PIN20); Port0Write(PIN20, 1); }
static inline void XBeeInhibit(void) { Port0Write(PIN17, 1); IRQDisable(USART_IRQn); }
static inline void XBeeAllow(void) { Port0Write(PIN17, 0); IRQEnable(USART_IRQn); }
static inline void XBeeStartBypass(void) { FUNCXBeeState = 0xff;}
static inline void XBeeStopBypass(void) { FUNCXBeeState = 0;}
void XBeeInit(void);
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif<file_sep>// ****************************************************************************
// *** Copyright (c) 2011, Universal Air Ltd. All rights reserved.
// *** Source and binaries are released under the BSD 3-Clause license
// *** See readme_forebrain.txt files for the text of the license
// ****************************************************************************
#include "LPC1347.h"
#include "thal.h"
#ifndef WEAK
#define WEAK_ALIAS(f) __attribute__ ((weak, alias (#f)))
#define WEAK __attribute__ ((weak))
#define ALIAS(f) __attribute__ ((alias (#f)));
#endif
// ****************************************************************************
// *** Interrupt Handlers
// ****************************************************************************
#if defined (__cplusplus)
extern "C" {
#endif
extern WEAK int main(void);
extern WEAK void setup(void);
extern WEAK void loop(void);
extern void SystemInit(void);
__attribute__ ((section(".after_vectors"))) void GeneralFault(void) {
unsigned int i;
LPC_IOCON->PIO0_1 = 0x50;
LPC_IOCON->PIO0_3 = 0x50;
LPC_GPIO->DIR[0] |= 0x000a;
LPC_GPIO->MASK[0] = ~0x000a;
LPC_GPIO->MPIN[0] = 0x0002;
while(1) {
LPC_GPIO->NOT[0] = 0x000a;
for(i=0; i<500000; i++) {__NOP();}
}
}
__attribute__ ((section(".after_vectors"))) void EmptyFunction(void) {
return;
}
void NMI_Handler(void) WEAK_ALIAS(GeneralFault);
void HardFault_Handler(void) WEAK_ALIAS(GeneralFault);
void MemManage_Handler(void) WEAK_ALIAS(GeneralFault);
void BusFault_Handler(void) WEAK_ALIAS(GeneralFault);
void UsageFault_Handler(void) WEAK_ALIAS(GeneralFault);
void SVCall_Handler(void) WEAK_ALIAS(GeneralFault);
void DebugMon_Handler(void) WEAK_ALIAS(GeneralFault);
void PendSV_Handler(void) WEAK_ALIAS(GeneralFault);
void PIN_INT0_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PIN_INT1_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PIN_INT2_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PIN_INT3_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PIN_INT4_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PIN_INT5_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PIN_INT6_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PIN_INT7_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void GINT0_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void GINT1_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void RIT_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void SSP1_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void I2C_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void CT16B0_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void CT16B1_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void CT32B0_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void CT32B1_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void SSP0_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void USART_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void USB_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void USB_FIQHandler(void) WEAK_ALIAS(EmptyFunction);
void ADC_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void WDT_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void BOD_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void FMC_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void OSCFAIL_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void PVTCIRCUIT_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void USBWakeup_IRQHandler(void) WEAK_ALIAS(EmptyFunction);
void SysTick_Handler(void) WEAK_ALIAS(EmptyFunction);
void IntDefaultHandler(void) WEAK_ALIAS(EmptyFunction);
extern void __stack_top(void);
#if defined (__cplusplus)
} // extern "C"
#endif
// ****************************************************************************
// *** Startup functions
// ****************************************************************************
__attribute__ ((section(".after_vectors")))
void data_init(unsigned int romstart, unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int *pulSrc = (unsigned int*) romstart;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4)
*pulDest++ = *pulSrc++;
}
__attribute__ ((section(".after_vectors")))
void bss_init(unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4)
*pulDest++ = 0;
}
extern unsigned int __data_section_table;
extern unsigned int __data_section_table_end;
extern unsigned int __bss_section_table;
extern unsigned int __bss_section_table_end;
__attribute__ ((section(".after_vectors")))
void Reset_Handler(void) {
// Copy the data sections from flash to SRAM.
unsigned int LoadAddr, ExeAddr, SectionLen;
unsigned int *SectionTableAddr;
// Load base address of Global Section Table
SectionTableAddr = &__data_section_table;
// Copy the data sections from flash to SRAM.
while (SectionTableAddr < &__data_section_table_end) {
LoadAddr = *SectionTableAddr++;
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
data_init(LoadAddr, ExeAddr, SectionLen);
}
// At this point, SectionTableAddr = &__bss_section_table;
// Zero fill the bss segment
while (SectionTableAddr < &__bss_section_table_end) {
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
bss_init(ExeAddr, SectionLen);
}
#if STARTUP_DELAY
unsigned int i;
for(i=0; i<STARTUP_DELAY; i++);
#endif
// Set clock mode, DEFAULT_CLOCK is defined in config.h, and the default behaviour
// is to set the clock to 72MHz from the external crystal. Using defines here to
// reduce code space
#if DEFAULT_CLOCK == XTAL
ClockModeXTAL();
#elif DEFAULT_CLOCK == IRC72
ClockModeIRC72();
#elif DEFAULT_CLOCK == IRC12
ClockModeIRC12();
#endif
LPC_SYSCON->SYSAHBCLKDIV = 1;
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 6) | (1 << 16);
// Set all pins to digital inputs (except P0[0] which is the reset button)
#if PORT_STARTUP_INIT
Port0Init(ALL & ~PIN0);
Port1Init(ALL);
#endif
// Initialise and start the system tick timer if allowed by the SYSTICK_EN
// definition in config.h, if the system tick timer is running, then the Delay()
// function will use it, otherwise Delay() will use a fixed loop which is not
// accurate when there are interrupts running, as any interrupt would stop the
// loop and cuase the delay to be longer than expected
#if SYSTICK_EN && SYSTICK_STARTUP
SysTickInit();
#endif
// Run the user-supplied setup() function if it exists
if(setup) {
setup();
}
// Run the user-supplied main() function if it exists
if(main) {
main();
}
// Loop the user-supplied setup() function if it exists
if(loop) {
while(1) loop();
}
// Do nothing (except handle interrupts)
while(1);
}
// ****************************************************************************
// *** Vector Table
// ****************************************************************************
__attribute__ ((section(".vectors"), used))
const void *vectors[] = {
&__stack_top,
Reset_Handler,
NMI_Handler,
HardFault_Handler,
MemManage_Handler,
BusFault_Handler,
UsageFault_Handler,
0,0,0,0,
SVCall_Handler,
DebugMon_Handler,
0,
PendSV_Handler,
SysTick_Handler,
PIN_INT0_IRQHandler,
PIN_INT1_IRQHandler,
PIN_INT2_IRQHandler,
PIN_INT3_IRQHandler,
PIN_INT4_IRQHandler,
PIN_INT5_IRQHandler,
PIN_INT6_IRQHandler,
PIN_INT7_IRQHandler,
GINT0_IRQHandler,
GINT1_IRQHandler,
0,0,
RIT_IRQHandler,
0,
SSP1_IRQHandler,
I2C_IRQHandler,
CT16B0_IRQHandler,
CT16B1_IRQHandler,
CT32B0_IRQHandler,
CT32B1_IRQHandler,
SSP0_IRQHandler,
USART_IRQHandler,
USB_IRQHandler,
USB_FIQHandler,
ADC_IRQHandler,
WDT_IRQHandler,
BOD_IRQHandler,
FMC_IRQHandler,
OSCFAIL_IRQHandler,
PVTCIRCUIT_IRQHandler,
USBWakeup_IRQHandler,
0,
};<file_sep>#include "thal.h"
#include "mavlink.h"
// *** Config stuff
#define FIRMWARE_VERSION 1 // Firmware version
#define MESSAGE_LOOP_HZ 50 // Max frequency of message loop in Hz (keep this number low, like around 25)
#define XBEE_PANIC 3 // Number of seconds after missing heartbeat from GCS before considering XBee fail
#define GPS_PANIC 3 // Number of seconds after no message from GPS before considering GPS fail
#define THAL_PANIC 3 // Number of seconds after no message from Thalamus before considering Thalamus fail
#define IDLE_SPRF 0.9 // Some filtering on the CPU load
#define IDLE_MAX 0x1ff480 // Set this to the number that the idleCounter counts up to every second. This is used to measure the CPU load - when there are no interrupts (i.e. processor not "busy"), the idleCounter is being incremented
#define MAX_WAYPOINTS 20 // TODO: maybe move waypoints into EEPROM
#define WAYPOINT_HOME MAX_WAYPOINTS+1 // there is one waypoint storage location that is never used between Waypoint home and the last waypoint, this is in case I screw up with the waypoint management and accidentally try to send the craft back to home by mistake
#define WAYPOINT_TEMP MAX_WAYPOINTS+2
#define WAYPOINT_TIMEOUT 500/MESSAGE_LOOP_HZ // value = timeout in ms / message_loop_hz
#define WAYPOINT_TRIES 5 // number of times to retry waypoint
#define WAYPOINT_MIN_RADIUS 1
#define WAYPOINT_SAFE_HEIGHT 2 // altitude above home to use
// *** Status stuff
volatile unsigned int allowTransmit;
// *** LEDs and buttons stuff
volatile unsigned int flashVLED;
volatile unsigned int PRGTimer;
volatile unsigned int PRGLastState;
volatile unsigned int PRGPushTime;
volatile unsigned int PRGBlankTimer;
unsigned int counter = 0;
// *** Timers and counters
unsigned int sysMS;
unsigned long long sysUS;
unsigned int statusCounter;
unsigned int idleCount;
unsigned short heartbeatWatchdog;
unsigned short gpsWatchdog;
unsigned short thalWatchdog;
// *** MAVLINK stuff
unsigned char mavlinkID;
// Sent messages
mavlink_status_t mavlink_status;
mavlink_message_t mavlink_tx_msg;
mavlink_heartbeat_t mavlink_heartbeat;
mavlink_sys_status_t mavlink_sys_status;
mavlink_gps_raw_int_t mavlink_gps_raw_int;
mavlink_raw_imu_t mavlink_raw_imu;
mavlink_scaled_imu_t mavlink_scaled_imu;
mavlink_attitude_t mavlink_attitude;
mavlink_command_ack_t mavlink_command_ack;
mavlink_param_value_t mavlink_param_value;
mavlink_rc_channels_raw_t mavlink_rc_channels_raw;
mavlink_rc_channels_scaled_t mavlink_rc_channels_scaled;
mavlink_servo_output_raw_t mavlink_servo_output_raw;
mavlink_gps_global_origin_t mavlink_gps_global_origin;
mavlink_named_value_float_t mavlink_named_value_float;
mavlink_named_value_int_t mavlink_named_value_int;
mavlink_debug_vect_t mavlink_debug_vect;
mavlink_debug_t mavlink_debug;
mavlink_statustext_t mavlink_statustext;
mavlink_mission_request_t mavlink_mission_request;
mavlink_mission_item_t mavlink_mission_item;
mavlink_mission_ack_t mavlink_mission_ack;
mavlink_mission_item_reached_t mavlink_mission_item_reached;
// Received messages
mavlink_message_t mavlink_rx_msg;
mavlink_request_data_stream_t mavlink_request_data_stream;
mavlink_command_long_t mavlink_command_long;
mavlink_param_request_list_t mavlink_param_request_list;
mavlink_param_set_t mavlink_param_set;
mavlink_param_request_read_t mavlink_param_request_read;
mavlink_manual_control_t mavlink_manual_control;
mavlink_mission_count_t mavlink_mission_count;
mavlink_set_gps_global_origin_t mavlink_set_gps_global_origin;
mavlink_mission_request_list_t mavlink_mission_request_list;
mavlink_mission_count_t mavlink_mission_count;
mavlink_mission_clear_all_t mavlink_mission_clear_all;
mavlink_mission_set_current_t mavlink_mission_set_current;
mavlink_mission_current_t mavlink_mission_current;
mavlink_set_mode_t mavlink_set_mode;
// Disabled messages
// mavlink_global_position_setpoint_int_t
//
// mavlink_raw_pressure_t
// mavlink_vfr_hud_t
mavlink_mission_request_list_t mavlink_mission_request_list;
// Variables
unsigned char mavlink_message_buf[MAVLINK_MAX_PACKET_LEN];
unsigned short mavlink_message_len;
// Timers
unsigned char dataRate[MAV_DATA_STREAM_ENUM_END];
unsigned char heartbeatCounter;
unsigned short extra3ChannelCounter;
unsigned short extra2ChannelCounter;
unsigned short extra1ChannelCounter;
unsigned short rcChannelCounter;
unsigned short rawControllerCounter;
unsigned short positionStreamCounter;
unsigned short extStatusStreamCounter;
unsigned short rawSensorStreamCounter;
unsigned int gpsSendCounter, posupdate;
// Functions
void MAVLinkInit(void);
void MAVSendHeartbeat(void);
void MAVSendFloat(char * name, float value);
void MAVSendInt(char * name, int value);
void MAVSendVector(char * name, float valX, float valY, float valZ);
void MAVSendText(unsigned char severity, char * text);
void MAVLinkParse(unsigned char UARTData);
// *** GPS stuff
gps_nav_posecef_t gps_nav_posecef;
gps_nav_posllh_t gps_nav_posllh;
gps_nav_status_t gps_nav_status;
gps_nav_sol_t gps_nav_sol;
gps_nav_velned_t gps_nav_velned;
gps_nav_timeutc_t gps_nav_timeutc;
// *** ILink stuff
ilink_identify_t ilink_identify;
ilink_thalstat_t ilink_thalstat;
ilink_thalctrl_t ilink_thalctrl_rx;
ilink_imu_t ilink_rawimu;
ilink_imu_t ilink_scaledimu;
ilink_altitude_t ilink_altitude;
ilink_attitude_t ilink_attitude;
ilink_thalparam_t ilink_thalparam_rx;
ilink_thalparam_t ilink_thalparam_tx;
ilink_thalpareq_t ilink_thalpareq;
ilink_iochan_t ilink_inputs0;
ilink_iochan_t ilink_outputs0;
ilink_atdemand_t ilink_atdemand;
ilink_gpsfly_t ilink_gpsfly;
ilink_debug_t ilink_debug;
typedef struct paramBuffer_struct {
char name[16];
float value;
unsigned short id;
} paramBuffer_t;
#define PARAMBUFFER_SIZE 50
paramBuffer_t paramBuffer[PARAMBUFFER_SIZE];
unsigned int paramPointer = PARAMBUFFER_SIZE;
// *** Xbee stuff
xbee_modem_status_t xbee_modem_status;
xbee_at_command_t xbee_at_command;
xbee_at_response_t xbee_at_response;
xbee_receive_packet_t xbee_receive_packet;
xbee_transmit_request_t xbee_transmit_request;
// ****** waypoints
typedef struct {
unsigned char command;
unsigned char autocontinue;
float param1;
float param2;
float param3;
float param4;
float x;
float y;
float z;
} waypointStruct;
waypointStruct waypoint[MAX_WAYPOINTS+3];
unsigned short waypointCurrent, waypointCount, waypointReceiveIndex;
unsigned char waypointTries, waypointValid, waypointHomeValid, waypointGo, waypointReached;
unsigned short waypointTimer;
unsigned int waypointLoiter;
unsigned char waypointProviderID, waypointProviderComp;
float waypointPhase;
float lat_diff_i;
float lon_diff_i;
float GPS_Kp = 0.03f;
float GPS_Ki = 0.00005f;
float GPS_Kd = 0.1f;
unsigned int gpsFixed;
unsigned int gpsChange;
unsigned int horizontalHold;
float horizontalHoldLon;
float horizontalHoldLat;
// ****************************************************************************
// *** Initialiseation
// ****************************************************************************
void setup() {
// *** LED setup
LEDInit(PLED);
LEDOn(PLED);
flashVLED = 0;
// *** Timers and couters
heartbeatWatchdog = 0;
gpsWatchdog = 0;
thalWatchdog = 0;
sysMS = 0;
sysUS = 0;
idleCount = 0;
// *** XBee and MAVLink
allowTransmit = 1;
XBeeInit();
MAVLinkInit();
heartbeatCounter = 0;
MAVSendHeartbeat();
// *** GPS
GPSInit();
GPSSetRate(ID_NAV_POSLLH, 5);
GPSSetRate(ID_NAV_STATUS, 1);
GPSSetRate(ID_NAV_VELNED, 5);
lat_diff_i = 0;
lon_diff_i = 0;
horizontalHold = 0;
gpsFixed = 0;
mavlink_sys_status.onboard_control_sensors_present |= MAVLINK_SENSOR_GPS | MAVLINK_CONTROL_Z | MAVLINK_CONTROL_XY;
mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_SENSOR_GPS;
mavlink_sys_status.onboard_control_sensors_health = mavlink_sys_status.onboard_control_sensors_enabled;
// *** Waypoints
waypointCurrent = 0;
waypointGo = 0;
waypointHomeValid = 0;
waypointCount = 0;
waypointValid = 0;
waypointTimer = 0;
waypointReceiveIndex = 0;
// *** Establish ILink and Look for Thalamus
ILinkInit(6000);
XBeeInhibit();
ILinkPoll(ID_ILINK_CLEARBUF); // forces Thalamus to clear its output buffers
ILinkPoll(ID_ILINK_IDENTIFY);
XBeeAllow();
// *** Things start happening as soon as RIT is enabled!
RITInitms(1000/MESSAGE_LOOP_HZ); // RIT at 25Hz
LEDOff(PLED);
LEDInit(VLED);
}
void MAVLinkInit() {
mavlinkID = 10;
mavlink_heartbeat.type = MAV_TYPE_QUADROTOR;
mavlink_heartbeat.autopilot = MAV_AUTOPILOT_GENERIC;
mavlink_heartbeat.base_mode = MAV_MODE_PREFLIGHT;
mavlink_heartbeat.system_status = MAV_STATE_BOOT;
mavlink_heartbeat.mavlink_version = MAVLINK_VERSION;
mavlink_sys_status.onboard_control_sensors_present = 0;
mavlink_sys_status.onboard_control_sensors_enabled = 0;
mavlink_sys_status.onboard_control_sensors_health = 0;
mavlink_sys_status.load = 0;
mavlink_sys_status.voltage_battery = 0;
mavlink_sys_status.current_battery = -1;
mavlink_sys_status.battery_remaining = -1;
dataRate[MAV_DATA_STREAM_EXTENDED_STATUS] = 2;
dataRate[MAV_DATA_STREAM_RAW_SENSORS] = 0;
dataRate[MAV_DATA_STREAM_RAW_CONTROLLER] = 0;
dataRate[MAV_DATA_STREAM_RC_CHANNELS] = 0;
dataRate[MAV_DATA_STREAM_POSITION] = 5;
dataRate[MAV_DATA_STREAM_EXTRA1] = 0;
dataRate[MAV_DATA_STREAM_EXTRA2] = 0;
dataRate[MAV_DATA_STREAM_EXTRA3] = 0;
}
// ****************************************************************************
// *** Main loop and timer loops
// ****************************************************************************
void loop() {
if(idleCount < IDLE_MAX) idleCount++; // this is the counter for CPU idle time
if(PRGBlankTimer == 0) {
if(PRGTimer > 3000) {
flashVLED = 0;
LEDOn(VLED);
}
if(PRGPushTime > 3000) {
flashVLED = 0xffffffffUL;
XBeeJoin();
flashVLED = 5;
PRGPushTime = 0;
PRGTimer = 0;
PRGBlankTimer = 100;
}
}
if(xbee_modem_status.isNew) {
xbee_modem_status.isNew = 0;
if(xbee_modem_status.status == 2) {
allowTransmit = 1;
}
else if(xbee_modem_status.status == 3) {
allowTransmit = 0;
}
}
}
void SysTickInterrupt(void) {
// deal with button(s)
if(PRGBlankTimer) {
PRGBlankTimer--;
}
else {
if(PRGPoll() == 0) {
PRGTimer++;
PRGLastState = 0;
}
else {
if(PRGLastState == 0) {
PRGPushTime = PRGTimer;
}
PRGTimer = 0;
PRGLastState = 1;
}
}
sysMS ++;
sysUS += 1000;
if(waypointLoiter < 0xffffffff) waypointLoiter ++;
// deal with flashing LEDs
if(sysMS % 100 == 0) {
if(flashVLED > 0) {
flashVLED--;
LEDToggle(VLED);
if(flashVLED == 0) LEDOff(VLED);
}
}
}
void RITInterrupt(void) {
heartbeatCounter++;
heartbeatWatchdog++;
gpsWatchdog++;
statusCounter++;
thalWatchdog++;
rawSensorStreamCounter++;
extStatusStreamCounter++;
rcChannelCounter++;
rawControllerCounter++;
positionStreamCounter++;
extra1ChannelCounter++;
extra2ChannelCounter++;
extra3ChannelCounter++;
waypointTimer++;
gpsSendCounter++;
// *** Watchdogs
// Incoming heartbeat watchdog
if(heartbeatWatchdog >= MESSAGE_LOOP_HZ*XBEE_PANIC) {
// heartbeat from ground control lost
heartbeatWatchdog = MESSAGE_LOOP_HZ*(XBEE_PANIC+1); // prevent overflow
//flashVLED = 5;
}
// GPS watchdog
if(gpsWatchdog >= MESSAGE_LOOP_HZ*GPS_PANIC) {
// GPS signal loss/no-fix
gpsWatchdog = MESSAGE_LOOP_HZ*(GPS_PANIC+1); // prevent overflow
mavlink_gps_raw_int.fix_type = 0;
mavlink_gps_raw_int.satellites_visible = 0;
gpsFixed = 0;
}
// Thalamus watchdog
if(thalWatchdog >= MESSAGE_LOOP_HZ*THAL_PANIC) {
// thalamus signal loss/no-fix
// should probably output something intelligible here to signify thalamus lost
//thalWatchdog = MESSAGE_LOOP_HZ*(THAL_PANIC+1); // prevent overflow
thalWatchdog = 0;
XBeeInhibit();
ILinkPoll(ID_ILINK_IDENTIFY);
XBeeAllow();
}
// *** Process GPS
XBeeInhibit(); // XBee input needs to be inhibited while processing GPS to avoid disrupting the I2C
GPSFetchData();
XBeeAllow();
// *** Status and GPS
if(statusCounter >= MESSAGE_LOOP_HZ/5) {
statusCounter = 0;
XBeeInhibit();
ILinkPoll(ID_ILINK_THALCTRL);
XBeeAllow();
}
if(gpsSendCounter >= MESSAGE_LOOP_HZ/5) {
gpsSendCounter = 0;
if(gps_nav_status.isNew) {
gpsChange = 1;
gps_nav_status.isNew = 0;
gpsWatchdog = 0;
if(gps_nav_status.flags & 0x1) { // fix is valid
mavlink_gps_raw_int.fix_type = gps_nav_status.gpsFix;
gpsFixed = 1;
}
else {
mavlink_gps_raw_int.fix_type = 0;
gpsFixed = 0;
}
//mavlink_gps_raw_int.satellites_visible = gps_nav_sol.numSV;
}
if(gps_nav_posllh.isNew) {
gpsChange = 1;
gps_nav_posllh.isNew = 0;
mavlink_gps_raw_int.lat = gps_nav_posllh.lat;
mavlink_gps_raw_int.lon = gps_nav_posllh.lon;
mavlink_gps_raw_int.alt = gps_nav_posllh.hMSL;
mavlink_gps_raw_int.eph = gps_nav_posllh.hAcc / 10;
mavlink_gps_raw_int.epv = gps_nav_posllh.vAcc / 10;
}
if(gps_nav_velned.isNew) {
gpsChange = 1;
gps_nav_velned.isNew = 0;
mavlink_gps_raw_int.vel = gps_nav_velned.gSpeed;
mavlink_gps_raw_int.cog = gps_nav_velned.heading / 100; // because GPS assumes cog IS heading.
}
// send GPS position
if(posupdate == 1 && gpsFixed == 1) {
posupdate = 0;
float craftX = gps_nav_posllh.lat / 10000000.0f;
float craftY = gps_nav_posllh.lon / 10000000.0f;
float craftZ = (float)gps_nav_posllh.hMSL/ 1000.0f;
float targetX;
float targetY;
float targetZ;
float targetYaw;
if(horizontalHold == 1) { // request horizontal hold
horizontalHoldLat = craftX;
horizontalHoldLon = craftY;
horizontalHold = 2; // now in hold
}
if(horizontalHold == 2) { // with hold
targetX = horizontalHoldLat;
targetY = horizontalHoldLon;
targetZ = craftZ;
targetYaw = 42.0f;
}
else if((waypointCurrent == WAYPOINT_HOME && waypointHomeValid == 1) || (waypointCurrent < waypointCount && waypointValid == 1)) { // with
targetX = waypoint[waypointCurrent].x;
targetY = waypoint[waypointCurrent].y;
targetZ = waypoint[waypointCurrent].z;
targetYaw = waypoint[waypointCurrent].param4 * 0.01745329251994329577f; // param4 is yaw angle, degrees to radian conversion M_PI / 180.0f = 0.01745329251994329577...
}
else {
targetX = craftX;
targetY = craftY;
targetZ = craftZ;
targetYaw = 42.0f;
}
float lat_diff = (double)(targetX - craftX) * (double)111194.92664455873734580834; // 111194.92664455873734580834f is radius of earth and deg-rad conversion: 6371000*PI()/180
float lon_diff = (double)(targetY - craftY) * (double)111194.92664455873734580834 * fcos((float)((double)craftX*(double)0.01745329251994329577)); // 0.01745329251994329577f is deg-rad conversion PI()/180
float alt_diff = (float)(targetZ - craftZ);
lat_diff_i += lat_diff;
lon_diff_i += lon_diff;
ilink_gpsfly.northDemand = GPS_Kp*lat_diff /*+ GPS_Ki*lat_diff_i*/ + GPS_Kd*( 0 /*targ vel*/ - gps_nav_velned.velN / 100.0f);
ilink_gpsfly.eastDemand = GPS_Kp*lon_diff /*+ GPS_Ki*lon_diff_i*/ + GPS_Kd*( 0 /*targ vel*/- gps_nav_velned.velE / 100.0f);
ilink_gpsfly.headingDemand = targetYaw;
ilink_gpsfly.altitudeDemand = targetZ;
ilink_gpsfly.altitude = craftZ;
ilink_gpsfly.vAcc = (float)gps_nav_posllh.vAcc / 1000.0f; // we think this is 1 sigma
ilink_gpsfly.velD = (float)gps_nav_velned.velD / 100.0f;
XBeeInhibit();
ILinkSendMessage(ID_ILINK_GPSFLY, (unsigned short *) & ilink_gpsfly, sizeof(ilink_gpsfly)/2-1);
XBeeAllow();
if(horizontalHold == 0 && ((waypointCurrent == WAYPOINT_HOME && waypointHomeValid == 1) || (waypointCurrent < waypointCount && waypointValid == 1))) {
float radius = waypoint[waypointCurrent].param2; // param2 is radius in QGroumdcontrol 1.0.1
if(radius < 1) radius = 1;
//float lat_diff2 = lat_diff; // for orbit phase calculation
//float lon_diff2 = lon_diff;
// assume cube of sides 2*radius rather than a sphere for target detection
if(lat_diff < 0) lat_diff = -lat_diff;
if(lon_diff < 0) lon_diff = -lon_diff;
if(alt_diff < 0) alt_diff = -alt_diff;
if(lat_diff < radius && lon_diff < radius && alt_diff < radius) {
// target reached
if(waypointReached == 0) {
waypointReached = 1;
waypointLoiter = 0;
mavlink_mission_item_reached.seq = waypointCurrent;
mavlink_msg_mission_item_reached_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_mission_item_reached);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
// waypointPhase = fatan2(-lon_diff2, -lat_diff2);
}
}
if(waypointReached == 1) {
switch(waypoint[waypointCurrent].command) {
case MAV_CMD_NAV_WAYPOINT:
if(waypointLoiter >= waypoint[waypointCurrent].param1) { // Param1 in this case is wait time
if(waypointCurrent < waypointCount) {
waypointCurrent ++;
waypointReached = 0;
waypointLoiter = 0;
}
}
/*ilink_payldctrl.camRoll = 0;
ilink_payldctrl.camPitch = 0;
ilink_payldctrl.camYaw = waypoint[waypointCurrent].param4 * 0.01745329251994329577f; // param4 is yaw angle, degrees to radian conversion M_PI / 180.0f = 0.01745329251994329577...;
ilink_payldctrl.controlMask = 0b100;
XBeeInhibit();
ILinkSendMessage(ID_ILINK_PAYLDCTRL, (unsigned short *) & ilink_payldctrl, sizeof(ilink_payldctrl)/2-1);
XBeeAllow();*/
// TODO: tween yaw between waypoints
break;
case MAV_CMD_NAV_LOITER_UNLIM:
case MAV_CMD_NAV_LOITER_TIME:
case MAV_CMD_NAV_LOITER_TURNS:
// attempting to achieve a speed of 3m/s
//waypointPhase += 0.1;
// don't need to do anything to hold position
// TODO: loiter radius/time/turns
/*ilink_payldctrl.camRoll = 0;
ilink_payldctrl.camPitch = 0;
ilink_payldctrl.camYaw = waypoint[waypointCurrent].param4 * M_PI / 180.0f;
ilink_payldctrl.controlMask = 0b100;
XBeeInhibit();
ILinkSendMessage(ID_ILINK_PAYLDCTRL, (unsigned short *) & ilink_payldctrl, sizeof(ilink_payldctrl)/2-1);
XBeeAllow();*/
break;
case MAV_CMD_NAV_RETURN_TO_LAUNCH:
waypointCurrent = WAYPOINT_HOME;
waypointReached = 0;
break;
case MAV_CMD_NAV_LAND:
//ilink_position.state = 0; // LAND NOW
break;
}
}
}
}
}
// *** MAVLink messages
if(heartbeatCounter >= MESSAGE_LOOP_HZ) { // 1Hz loop
heartbeatCounter = 0;
MAVSendHeartbeat();
unsigned short load = (1000*(IDLE_MAX - idleCount))/IDLE_MAX; // Idle load is calculated here as this loop runs at 1Hz
if(mavlink_sys_status.load == 0) mavlink_sys_status.load = load;
mavlink_sys_status.load *= IDLE_SPRF;
mavlink_sys_status.load += (1-IDLE_SPRF)*load;
idleCount = 0;
}
if(allowTransmit) {
if(paramPointer < PARAMBUFFER_SIZE) {
unsigned int i;
// shunt this along to GCS
for(i=0; i<MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN; i++) {
mavlink_param_value.param_id[i] = paramBuffer[paramPointer].name[i];
if(paramBuffer[paramPointer].name[i] == '\0') break;
}
mavlink_param_value.param_value = paramBuffer[paramPointer].value;
mavlink_param_value.param_count = ilink_thalparam_rx.paramCount; // this value shouldn't change
mavlink_param_value.param_index = paramBuffer[paramPointer].id;
mavlink_param_value.param_type = MAV_PARAM_TYPE_REAL32;
paramPointer++;
mavlink_msg_param_value_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_param_value);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
else if(waypointReceiveIndex < waypointCount) {
if(waypointTimer > WAYPOINT_TIMEOUT) {
mavlink_mission_request.seq = waypointReceiveIndex;
mavlink_mission_request.target_system = waypointProviderID;
mavlink_mission_request.target_component = waypointProviderComp;
mavlink_msg_mission_request_encode(mavlinkID, MAV_COMP_ID_MISSIONPLANNER, &mavlink_tx_msg, &mavlink_mission_request);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
waypointTimer = 0;
waypointTries++;
}
if(waypointTries > waypointTries) { // timeout failure
waypointCount = 0;
MAVSendText(255, "Receiving Waypoint timeout");
}
}
//else if(ilink_thalctrl_rx.isNew) {
// TODO translate mavlink command to thalctrl
/*ilink_thalctrl_rx.isNew = 0;
if(ilink_thalctrl_rx.command == MAVLINK_MSG_ID_COMMAND_LONG) {
mavlink_command_ack.result = 0;
mavlink_command_ack.command = ilink_thalctrl_rx.data;
mavlink_msg_command_ack_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_command_ack);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
}*/
//}
else if(dataRate[MAV_DATA_STREAM_RAW_SENSORS] && rawSensorStreamCounter >= MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_RAW_SENSORS]) {
rawSensorStreamCounter = 0;
if(ilink_rawimu.isNew) {
ilink_rawimu.isNew = 0;
mavlink_raw_imu.xacc = ilink_rawimu.xAcc;
mavlink_raw_imu.yacc = ilink_rawimu.yAcc;
mavlink_raw_imu.zacc = ilink_rawimu.zAcc;
mavlink_raw_imu.xgyro = ilink_rawimu.xGyro;
mavlink_raw_imu.ygyro = ilink_rawimu.yGyro;
mavlink_raw_imu.zgyro = ilink_rawimu.zGyro;
mavlink_raw_imu.xmag = ilink_rawimu.xMag;
mavlink_raw_imu.ymag = ilink_rawimu.yMag;
mavlink_raw_imu.zmag = ilink_rawimu.zMag;
mavlink_msg_raw_imu_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_raw_imu);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
XBeeInhibit();
ILinkPoll(ID_ILINK_RAWIMU);
XBeeAllow();
}
else if(dataRate[MAV_DATA_STREAM_EXTENDED_STATUS] && extStatusStreamCounter >= MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_EXTENDED_STATUS]) {
extStatusStreamCounter = 0;
// GPS_STATUS, CONTROL_STATUS, AUX_STATUS
// Sys status
if(ilink_thalstat.isNew) {
ilink_thalstat.isNew = 0;
switch(ilink_thalstat.sensorStatus & 0x7) {
case 0:
mavlink_heartbeat.system_status = MAV_STATE_UNINIT;
mavlink_heartbeat.base_mode = MAV_MODE_PREFLIGHT;
break;
case 1:
mavlink_heartbeat.system_status = MAV_STATE_BOOT;
mavlink_heartbeat.base_mode = MAV_MODE_PREFLIGHT;
break;
case 2:
mavlink_heartbeat.system_status = MAV_STATE_CALIBRATING;
mavlink_heartbeat.base_mode = MAV_MODE_PREFLIGHT;
break;
case 3:
mavlink_heartbeat.system_status = MAV_STATE_STANDBY;
mavlink_heartbeat.base_mode &= ~MAV_MODE_FLAG_DECODE_POSITION_SAFETY;
break;
case 4:
mavlink_heartbeat.system_status = MAV_STATE_ACTIVE;
mavlink_heartbeat.base_mode |= MAV_MODE_FLAG_DECODE_POSITION_SAFETY;
break;
case 5: mavlink_heartbeat.system_status = MAV_STATE_CRITICAL; break;
default: mavlink_heartbeat.system_status = MAV_STATE_UNINIT; break;
}
if(ilink_thalstat.sensorStatus & (0x1 << 3)) mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_SENSOR_ACCEL;
else mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_SENSOR_ACCEL;
if(ilink_thalstat.sensorStatus & (0x1 << 4)) mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_SENSOR_GYRO;
else mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_SENSOR_GYRO;
if(ilink_thalstat.sensorStatus & (0x1 << 5)) mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_SENSOR_MAGNETO;
else mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_SENSOR_MAGNETO;
if(ilink_thalstat.sensorStatus & (0x1 << 6)) mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_SENSOR_BARO;
else mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_SENSOR_BARO;
if(ilink_thalstat.flightMode & (0x1 << 0)) {
mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_CONTROL_ATTITUDE;
mavlink_heartbeat.base_mode |= MAV_MODE_FLAG_DECODE_POSITION_STABILIZE;
}
else {
mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_CONTROL_ATTITUDE;
mavlink_heartbeat.base_mode &= ~MAV_MODE_FLAG_DECODE_POSITION_STABILIZE;
}
if(ilink_thalstat.flightMode & (0x1 << 1)) mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_CONTROL_ANGLERATE;
else mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_CONTROL_ANGLERATE;
if(ilink_thalstat.flightMode & (0x1 << 2)) mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_CONTROL_YAW;
else mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_CONTROL_YAW;
if(ilink_thalstat.flightMode & (0x1 << 3)) mavlink_sys_status.onboard_control_sensors_enabled |= MAVLINK_CONTROL_Z;
else mavlink_sys_status.onboard_control_sensors_enabled &= ~MAVLINK_CONTROL_Z;
if(ilink_thalstat.flightMode & (0x1 << 4)) {
mavlink_heartbeat.base_mode |= MAV_MODE_FLAG_DECODE_POSITION_GUIDED;
}
else {
mavlink_heartbeat.base_mode &= ~MAV_MODE_FLAG_DECODE_POSITION_GUIDED;
}
mavlink_sys_status.onboard_control_sensors_health = mavlink_sys_status.onboard_control_sensors_enabled;
mavlink_sys_status.voltage_battery = ilink_thalstat.battVoltage;
}
XBeeInhibit();
ILinkPoll(ID_ILINK_THALSTAT);
XBeeAllow();
// Note: system load was calculated in the Heartbeat as it is on an invariable 1Hz loop)
mavlink_msg_sys_status_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_sys_status);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
else if(dataRate[MAV_DATA_STREAM_RC_CHANNELS] && rcChannelCounter >= MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_RC_CHANNELS]) {
// RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW
rcChannelCounter= 0;
if(ilink_outputs0.isNew) {
ilink_outputs0.isNew = 0;
mavlink_servo_output_raw.time_usec = sysUS;
mavlink_servo_output_raw.servo1_raw = ilink_outputs0.channel[0];
mavlink_servo_output_raw.servo2_raw = ilink_outputs0.channel[1];
mavlink_servo_output_raw.servo3_raw = ilink_outputs0.channel[2];
mavlink_servo_output_raw.servo4_raw = ilink_outputs0.channel[3];
mavlink_servo_output_raw.servo5_raw = ilink_outputs0.channel[4];
mavlink_servo_output_raw.servo6_raw = ilink_outputs0.channel[5];
mavlink_servo_output_raw.servo7_raw = 0;
mavlink_servo_output_raw.servo8_raw = 0;
mavlink_servo_output_raw.port = 0;
/*mavlink_msg_servo_output_raw_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_servo_output_raw);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();*/
//MAVSendVector("OUTPUT0", ilink_outputs0.channel[0], ilink_outputs0.channel[1], ilink_outputs0.channel[2]);
//MAVSendVector("OUTPUT1", ilink_outputs0.channel[3], ilink_outputs0.channel[4], ilink_outputs0.channel[5]);
MAVSendInt("MOTOR_N", ilink_outputs0.channel[0]);
MAVSendInt("MOTOR_E", ilink_outputs0.channel[1]);
MAVSendInt("MOTOR_S", ilink_outputs0.channel[2]);
MAVSendInt("MOTOR_W", ilink_outputs0.channel[3]);
}
XBeeInhibit();
ILinkPoll(ID_ILINK_OUTPUTS0);
XBeeAllow();
if(ilink_inputs0.isNew) {
ilink_inputs0.isNew = 0;
mavlink_rc_channels_raw.time_boot_ms = sysMS;
mavlink_rc_channels_raw.chan1_raw = ilink_inputs0.channel[0];
mavlink_rc_channels_raw.chan2_raw = ilink_inputs0.channel[1];
mavlink_rc_channels_raw.chan3_raw = ilink_inputs0.channel[2];
mavlink_rc_channels_raw.chan4_raw = ilink_inputs0.channel[3];
mavlink_rc_channels_raw.chan5_raw = ilink_inputs0.channel[4];
mavlink_rc_channels_raw.chan6_raw = ilink_inputs0.channel[5];
mavlink_rc_channels_raw.chan7_raw = 0;
mavlink_rc_channels_raw.chan8_raw = 0;
mavlink_rc_channels_raw.port = 0;
mavlink_rc_channels_raw.rssi = 255;
mavlink_msg_rc_channels_raw_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_rc_channels_raw);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
/*
mavlink_rc_channels_scaled.time_boot_ms = sysMS;
mavlink_rc_channels_scaled.chan1_scaled = (signed int)ilink_inputs0.channel[0] * 11.8;
mavlink_rc_channels_scaled.chan2_scaled = ((signed int)ilink_inputs0.channel[1] - (signed int)511) * 29.4;
mavlink_rc_channels_scaled.chan3_scaled = ((signed int)ilink_inputs0.channel[2] - (signed int)511) * 29.4;
mavlink_rc_channels_scaled.chan4_scaled = ((signed int)ilink_inputs0.channel[3] - (signed int)511) * 29.4;
if(ilink_inputs0.channel[4] < 500) mavlink_rc_channels_scaled.chan5_scaled = 0;
else mavlink_rc_channels_scaled.chan5_scaled = 10000;
if(ilink_inputs0.channel[5] < 500) mavlink_rc_channels_scaled.chan6_scaled = 0;
else mavlink_rc_channels_scaled.chan6_scaled = 10000;
mavlink_rc_channels_scaled.chan7_scaled = 0;
mavlink_rc_channels_scaled.chan8_scaled = 0;
mavlink_rc_channels_scaled.port = 0;
mavlink_rc_channels_scaled.rssi = 255;
mavlink_msg_rc_channels_scaled_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_rc_channels_scaled);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();*/
}
XBeeInhibit();
ILinkPoll(ID_ILINK_INPUTS0);
XBeeAllow();
}
else if(dataRate[MAV_DATA_STREAM_RAW_CONTROLLER] && rawControllerCounter >= MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_RAW_CONTROLLER]) {
//ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, NAV_CONTROLLER_OUTPUT
rawControllerCounter = 0;
if(ilink_attitude.isNew) {
ilink_attitude.isNew = 0;
mavlink_attitude.time_boot_ms = sysMS;
mavlink_attitude.roll = ilink_attitude.roll;
mavlink_attitude.pitch = ilink_attitude.pitch;
mavlink_attitude.yaw = ilink_attitude.yaw;
mavlink_attitude.rollspeed = ilink_attitude.rollRate;
mavlink_attitude.pitchspeed = ilink_attitude.pitchRate;
mavlink_attitude.yawspeed = ilink_attitude.yawRate;
mavlink_msg_attitude_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_attitude);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
XBeeInhibit();
ILinkPoll(ID_ILINK_ATTITUDE);
XBeeAllow();
}
else if(dataRate[MAV_DATA_STREAM_POSITION] && positionStreamCounter >= MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_POSITION]) {
positionStreamCounter= 0;
if(gpsChange) {
mavlink_gps_raw_int.time_usec = sysUS;
mavlink_msg_gps_raw_int_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_gps_raw_int);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
}
else if(dataRate[MAV_DATA_STREAM_EXTRA1] && extra1ChannelCounter >= MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_EXTRA1]) {
extra1ChannelCounter = 0;
if(ilink_scaledimu.isNew) {
ilink_scaledimu.isNew = 0;
mavlink_scaled_imu.xacc = ilink_scaledimu.xAcc;
mavlink_scaled_imu.yacc = ilink_scaledimu.yAcc;
mavlink_scaled_imu.zacc = ilink_scaledimu.zAcc;
mavlink_scaled_imu.xgyro = ilink_scaledimu.xGyro;
mavlink_scaled_imu.ygyro = ilink_scaledimu.yGyro;
mavlink_scaled_imu.zgyro = ilink_scaledimu.zGyro;
mavlink_scaled_imu.xmag = ilink_scaledimu.xMag;
mavlink_scaled_imu.ymag = ilink_scaledimu.yMag;
mavlink_scaled_imu.zmag = ilink_scaledimu.zMag;
mavlink_msg_scaled_imu_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_scaled_imu);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
XBeeInhibit();
ILinkPoll(ID_ILINK_SCALEDIMU);
XBeeAllow();
}
else if(dataRate[MAV_DATA_STREAM_EXTRA2] && extra2ChannelCounter > MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_EXTRA2]) {
extra2ChannelCounter = 0;
if(ilink_altitude.isNew) {
ilink_altitude.isNew = 0;
MAVSendFloat("ALT_ULTRA", ilink_altitude.ultra);
MAVSendFloat("ALT_BARO", ilink_altitude.baro);
MAVSendFloat("ALT_FILT", ilink_altitude.filtered);
}
XBeeInhibit();
ILinkPoll(ID_ILINK_ALTITUDE);
XBeeAllow();
}
else if(dataRate[MAV_DATA_STREAM_EXTRA3] && extra3ChannelCounter > MESSAGE_LOOP_HZ/dataRate[MAV_DATA_STREAM_EXTRA3]) {
extra3ChannelCounter = 0;
if(ilink_debug.isNew) {
ilink_debug.isNew = 0;
MAVSendFloat("DEBUG0", ilink_debug.debug0);
MAVSendFloat("DEBUG1", ilink_debug.debug1);
MAVSendFloat("DEBUG2", ilink_debug.debug2);
MAVSendFloat("DEBUG3", ilink_debug.debug3);
MAVSendFloat("DEBUG4", ilink_debug.debug4);
MAVSendFloat("DEBUG5", ilink_debug.debug5);
MAVSendFloat("DEBUG6", ilink_debug.debug6);
MAVSendFloat("DEBUG7", ilink_debug.debug7);
}
XBeeInhibit();
ILinkPoll(ID_ILINK_DEBUG);
XBeeAllow();
}
}
// *** Process ILink
/*XBeeInhibit();
ILinkFetchData();
XBeeAllow();*/
// *** Process ILink
XBeeInhibit();
ILinkFetchData();
XBeeAllow();
}
// ****************************************************************************
// *** Communications
// ****************************************************************************
// *** Mavlink messages
void MAVSendHeartbeat(void) {
//if(allowTransmit) {
mavlink_msg_heartbeat_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_heartbeat);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit(); // XBee input needs to be inhibited before transmitting as some incomming messages cause UART responses which could disrupt XBeeWriteCoordinator if it is interrupted.
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
//}
}
void MAVSendFloat(char * name, float value) {
if(allowTransmit) {
unsigned int i;
for(i=0; i<MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN; i++) {
mavlink_named_value_float.name[i] = name[i];
if(name[i] == '\0') break;
}
mavlink_named_value_float.time_boot_ms = sysMS;
mavlink_named_value_float.value = value;
mavlink_msg_named_value_float_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_named_value_float);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit();
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
}
void MAVSendInt(char * name, int value) {
if(allowTransmit) {
unsigned int i;
for(i=0; i<MAVLINK_MSG_NAMED_VALUE_INT_FIELD_NAME_LEN; i++) {
mavlink_named_value_int.name[i] = name[i];
if(name[i] == '\0') break;
}
mavlink_named_value_int.time_boot_ms = sysMS;
mavlink_named_value_int.value = value;
mavlink_msg_named_value_int_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_named_value_int);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit();
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
}
void MAVSendVector(char * name, float valX, float valY, float valZ) {
if(allowTransmit) {
unsigned int i;
for(i=0; i<MAVLINK_MSG_DEBUG_VECT_FIELD_NAME_LEN; i++) {
mavlink_debug_vect.name[i] = name[i];
if(name[i] == '\0') break;
}
mavlink_debug_vect.time_usec = sysUS;
mavlink_debug_vect.x = valX;
mavlink_debug_vect.y = valY;
mavlink_debug_vect.z = valZ;
mavlink_msg_debug_vect_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_debug_vect);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit();
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
}
void MAVSendText(unsigned char severity, char * text) {
if(allowTransmit) {
unsigned int i;
mavlink_statustext.severity = severity;
for(i=0; i<MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN; i++) {
mavlink_statustext.text[i] = text[i];
if(text[i] == '\0') break;
}
mavlink_msg_statustext_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_statustext);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeInhibit();
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
XBeeAllow();
}
}
// XBee interrupt (for MAVLink)
void XBeeMessage(unsigned char id, unsigned char * buffer, unsigned short length) {
unsigned char * ptr = 0;
unsigned int j;
switch(id) {
case ID_XBEE_MODEMSTATUS:
ptr = (unsigned char *) &xbee_modem_status;
xbee_modem_status.isNew = 1;
break;
case ID_XBEE_ATRESPONSE:
ptr = (unsigned char *) &xbee_at_response;
xbee_at_response.isNew = 1;
xbee_at_response.varLen = length - 4;
break;
case ID_XBEE_RECEIVEPACKET:
/*ptr = (unsigned char *) &xbee_receive_packet;
xbee_receive_packet.isNew = 1;
xbee_receive_packet.varLen = length - 11;*/
// bypass copy, send direct to MAVLINK Parse
for(j=11; j<length; j++) {
MAVLinkParse(buffer[j]);
}
break;
}
if(ptr) {
for(j=0; j<length; j++) {
ptr[j] = buffer[j];
}
}
}
void MAVLinkParse(unsigned char UARTData) {
if(mavlink_parse_char(MAVLINK_COMM_0, UARTData, &mavlink_rx_msg, &mavlink_status)) {
//mavlinkSendDebugV("MSGID", mavlink_rx_msg.msgid, 0, 0);
switch(mavlink_rx_msg.msgid) {
case MAVLINK_MSG_ID_HEARTBEAT:
// count heartbeat messages
heartbeatWatchdog = 0;
allowTransmit = 1;
break;
case MAVLINK_MSG_ID_MANUAL_CONTROL:
mavlink_msg_manual_control_decode(&mavlink_rx_msg, &mavlink_manual_control);
if(mavlink_manual_control.target == mavlinkID) {
ilink_atdemand.roll = mavlink_manual_control.roll;
ilink_atdemand.pitch = mavlink_manual_control.pitch;
ilink_atdemand.yaw = mavlink_manual_control.yaw;
ilink_atdemand.thrust = mavlink_manual_control.thrust;
ILinkSendMessage(ID_ILINK_ATDEMAND, (unsigned short *) & ilink_atdemand, sizeof(ilink_atdemand)/2-1);
}
break;
case MAVLINK_MSG_ID_SET_MODE:
mavlink_msg_set_mode_decode(&mavlink_rx_msg, &mavlink_set_mode);
if (mavlink_set_mode.target_system == mavlinkID) {
//mavlink_heartbeat.base_mode = mavlink_set_mode.base_mode;
//mavlink_heartbeat.custom_mode = mavlink_set_mode.custom_mode;
/*ilink_thalctrl_rx.command = MAVLINK_MSG_ID_SET_MODE;
ilink_thalctrl_rx.data = mavlink_set_mode.base_mode;
ILinkSendMessage(ID_ILINK_THALCTRL, (unsigned short *) & ilink_thalctrl_rx, sizeof(ilink_thalctrl_rx)/2-1);*/
}
break;
case MAVLINK_MSG_ID_COMMAND_LONG:
// actions!
mavlink_msg_command_long_decode(&mavlink_rx_msg, &mavlink_command_long);
if (mavlink_command_long.target_system == mavlinkID) {
switch(mavlink_command_long.command) {
case 0: // custom 0, reset
mavlink_command_ack.result = 0;
mavlink_command_ack.command = mavlink_command_long.command;
mavlink_msg_command_ack_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_command_ack);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
Reset();
break;
//case MAV_CMD_NAV_WAYPOINT:
// param1 Hold time in decimal seconds.
// Acceptance radius in meters
// 0 to pass through the WP, if > 0 radius in meters to pass by WP
// Positive value for clockwise orbit, negative value for counter-clockwise orbit
// Desired yaw angle at MISSION (rotary wing)
//| Latitude| Longitude| Altitude|
// use this for FOLLOW-ME mode (or without mission planner)
// break;
// MAV_CMD_NAV_LOITER_UNLIM=17, // Loiter around this MISSION an unlimited amount of time |Empty| Empty| Radius around MISSION, in meters. If positive loiter clockwise, else counter-clockwise| Desired yaw angle.| Latitude| Longitude| Altitude|
// MAV_CMD_NAV_LOITER_TURNS=18, // Loiter around this MISSION for X turns |Turns| Empty| Radius around MISSION, in meters. If positive loiter clockwise, else counter-clockwise| Desired yaw angle.| Latitude| Longitude| Altitude|
// MAV_CMD_NAV_LOITER_TIME=19, // Loiter around this MISSION for X seconds |Seconds (decimal)| Empty| Radius around MISSION, in meters. If positive loiter clockwise, else counter-clockwise| Desired yaw angle.| Latitude| Longitude| Altitude|
// MAV_CMD_NAV_RETURN_TO_LAUNCH=20, // Return to launch location |Empty| Empty| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_NAV_ROI=80, // Sets the region of interest (ROI) |Region of intereset mode. (see MAV_ROI enum)| MISSION index/ target ID. (see MAV_ROI enum)| ROI index (allows a vehicle to manage multiple ROI's)| Empty| x the location of the fixed ROI (see MAV_FRAME)| y| z|
// MAV_CMD_NAV_PATHPLANNING=81, // Control autonomous path planning on the MAV. |0: Disable local obstacle avoidance / local path planning (without resetting map), 1: Enable local path planning, 2: Enable and reset local path planning| 0: Disable full path planning (without resetting map), 1: Enable, 2: Enable and reset map/occupancy grid, 3: Enable and reset planned route, but not occupancy grid| Empty| Yaw angle at goal, in compass degrees, [0..360]| Latitude/X of goal| Longitude/Y of goal| Altitude/Z of goal|
// MAV_CMD_CONDITION_DELAY=112, // Delay mission state machine. |Delay in seconds (decimal)| Empty| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_CONDITION_CHANGE_ALT=113, // Ascend/descend at rate. Delay mission state machine until desired altitude reached. |Descent / Ascend rate (m/s)| Empty| Empty| Empty| Empty| Empty| Finish Altitude|
// MAV_CMD_CONDITION_DISTANCE=114, // Delay mission state machine until within desired distance of next NAV point. |Distance (meters)| Empty| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_CONDITION_YAW=115, // Reach a certain target angle. |target angle: [0-360], 0 is north| speed during yaw change:[deg per second]| direction: negative: counter clockwise, positive: clockwise [-1,1]| relative offset or absolute angle: [ 1,0]| Empty| Empty| Empty|
// MAV_CMD_CONDITION_LAST=159, // NOP - This command is only used to mark the upper limit of the CONDITION commands in the enumeration |Empty| Empty| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_DO_SET_MODE=176, // Set system mode. |Mode, as defined by ENUM MAV_MODE| Empty| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_DO_JUMP=177, // Jump to the desired command in the mission list. Repeat this action only the specified number of times |Sequence number| Repeat count| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_DO_CHANGE_SPEED=178, // Change speed and/or throttle set points. |Speed type (0=Airspeed, 1=Ground Speed)| Speed (m/s, -1 indicates no change)| Throttle ( Percent, -1 indicates no change)| Empty| Empty| Empty| Empty|
// case MAV_CMD_DO_SET_HOME:
// MAV_CMD_DO_SET_PARAMETER=180, // Set a system parameter. Caution! Use of this command requires knowledge of the numeric enumeration value of the parameter. |Parameter number| Parameter value| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_DO_SET_RELAY=181, // Set a relay to a condition. |Relay number| Setting (1=on, 0=off, others possible depending on system hardware)| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_DO_REPEAT_RELAY=182, // Cycle a relay on and off for a desired number of cyles with a desired period. |Relay number| Cycle count| Cycle time (seconds, decimal)| Empty| Empty| Empty| Empty|
// MAV_CMD_DO_SET_SERVO=183, // Set a servo to a desired PWM value. |Servo number| PWM (microseconds, 1000 to 2000 typical)| Empty| Empty| Empty| Empty| Empty|
// MAV_CMD_DO_REPEAT_SERVO=184, // Cycle a between its nominal setting and a desired PWM for a desired number of cycles with a desired period. |Servo number| PWM (microseconds, 1000 to 2000 typical)| Cycle count| Cycle time (seconds)| Empty| Empty| Empty|
// MAV_CMD_DO_CONTROL_VIDEO=200, // Control onboard camera system. |Camera ID (-1 for all)| Transmission: 0: disabled, 1: enabled compressed, 2: enabled raw| Transmission mode: 0: video stream, >0: single images every n seconds (decimal)| Recording: 0: disabled, 1: enabled compressed, 2: enabled raw| Empty| Empty| Empty|
// MAV_CMD_PREFLIGHT_CALIBRATION=241, // Trigger calibration. This command will be only accepted if in pre-flight mode. |Gyro calibration: 0: no, 1: yes| Magnetometer calibration: 0: no, 1: yes| Ground pressure: 0: no, 1: yes| Radio calibration: 0: no, 1: yes| Empty| Empty| Empty|
// MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS=242, // Set sensor offsets. This command will be only accepted if in pre-flight mode. |Sensor to adjust the offsets for: 0: gyros, 1: accelerometer, 2: magnetometer, 3: barometer, 4: optical flow| X axis offset (or generic dimension 1), in the sensor's raw units| Y axis offset (or generic dimension 2), in the sensor's raw units| Z axis offset (or generic dimension 3), in the sensor's raw units| Generic dimension 4, in the sensor's raw units| Generic dimension 5, in the sensor's raw units| Generic dimension 6, in the sensor's raw units|
case MAV_CMD_PREFLIGHT_STORAGE:
if(mavlink_command_long.param1 == 0) ilink_thalpareq.reqType = 3; // read all
else ilink_thalpareq.reqType = 2; // save all
ILinkSendMessage(ID_ILINK_THALPAREQ, (unsigned short *) & ilink_thalpareq, sizeof(ilink_thalpareq)/2-1);
break;
case MAV_CMD_NAV_LAND:
case MAV_CMD_NAV_TAKEOFF:
case MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN: // KILL UAS
/*ilink_thalctrl_rx.command = MAVLINK_MSG_ID_COMMAND_LONG;
ilink_thalctrl_rx.data = mavlink_command_long.command;
ILinkSendMessage(ID_ILINK_THALCTRL, (unsigned short *) & ilink_thalctrl_rx, sizeof(ilink_thalctrl_rx)/2-1);*/
break;
case MAV_CMD_OVERRIDE_GOTO:
if(mavlink_command_long.param1 == MAV_GOTO_DO_HOLD) {
waypointGo = 0;
}
else if(mavlink_command_long.param1 == MAV_GOTO_DO_CONTINUE) {
if(waypointGo == 1) {
if(waypoint[waypointCurrent].command == MAV_CMD_NAV_LOITER_UNLIM && waypointCurrent < waypointCount) {
waypointCurrent++;
}
}
waypointGo = 1;
waypointReached = 0;
}
break;
default:
mavlink_command_ack.result = MAV_CMD_ACK_ERR_NOT_SUPPORTED;
mavlink_command_ack.command = mavlink_command_long.command;
mavlink_msg_command_ack_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_command_ack);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
break;
}
break;
}
break;
case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
// request send of all parameters
ilink_thalpareq.reqType = 0; // request all
ILinkSendMessage(ID_ILINK_THALPAREQ, (unsigned short *) & ilink_thalpareq, sizeof(ilink_thalpareq)/2-1);
break;
case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
// request send of all parameters
mavlink_msg_param_request_read_decode(&mavlink_rx_msg, &mavlink_param_request_read);
ilink_thalpareq.reqType = 1; // request one
unsigned short i;
for(i=0; i<MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN; i++) {
ilink_thalpareq.paramName[i] = mavlink_param_request_read.param_id[i];
if(mavlink_param_set.param_id[i] == '\0') break;
}
ilink_thalpareq.paramID = mavlink_param_request_read.param_index;
ILinkSendMessage(ID_ILINK_THALPAREQ, (unsigned short *) & ilink_thalpareq, sizeof(ilink_thalpareq)/2-1);
break;
case MAVLINK_MSG_ID_PARAM_SET:
// request set parameter
mavlink_msg_param_set_decode(&mavlink_rx_msg, &mavlink_param_set);
if(mavlink_param_set.target_system == mavlinkID) {
unsigned short i;
for(i=0; i<MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN; i++) {
ilink_thalparam_tx.paramName[i] = mavlink_param_set.param_id[i];
if(mavlink_param_set.param_id[i] == '\0') break;
}
ilink_thalparam_tx.paramID = 0;
ilink_thalparam_tx.paramValue = mavlink_param_set.param_value;
ilink_thalparam_tx.paramCount = 0;
ILinkSendMessage(ID_ILINK_THALPARAM, (unsigned short *) &ilink_thalparam_tx, sizeof(ilink_thalparam_tx)/2 - 1);
}
break;
case MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN:
mavlink_msg_set_gps_global_origin_decode(&mavlink_rx_msg, &mavlink_set_gps_global_origin);
if (mavlink_set_gps_global_origin.target_system == mavlinkID) {
waypoint[WAYPOINT_HOME].command = MAV_CMD_NAV_LAND;
waypoint[WAYPOINT_HOME].autocontinue = 0;
waypoint[WAYPOINT_HOME].param1 = 0;
waypoint[WAYPOINT_HOME].param2 = 0;
waypoint[WAYPOINT_HOME].param3 = 0;
waypoint[WAYPOINT_HOME].param4 = 0;
waypoint[WAYPOINT_HOME].x = (float)mavlink_set_gps_global_origin.latitude / 10000000.0f;
waypoint[WAYPOINT_HOME].y = (float)mavlink_set_gps_global_origin.longitude / 10000000.0f;
waypoint[WAYPOINT_HOME].z = (float)mavlink_set_gps_global_origin.altitude / 1000.0f;
waypointHomeValid = 1;
}
case MAVLINK_MSG_ID_MISSION_CLEAR_ALL:
mavlink_msg_mission_clear_all_decode(&mavlink_rx_msg, &mavlink_mission_clear_all);
if (mavlink_mission_clear_all.target_system == mavlinkID) {
waypointCurrent = 0;
waypointCount = 0;
waypointValid = 0;
mavlink_mission_ack.type = MAV_MISSION_ACCEPTED;
mavlink_msg_mission_ack_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_mission_ack);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
}
break;
case MAVLINK_MSG_ID_MISSION_SET_CURRENT:
mavlink_msg_mission_set_current_decode(&mavlink_rx_msg, &mavlink_mission_set_current);
if (mavlink_mission_set_current.target_system == mavlinkID) {
waypointCurrent = mavlink_mission_set_current.seq;
mavlink_mission_current.seq = waypointCurrent;
mavlink_msg_mission_current_encode(mavlinkID, MAV_COMP_ID_MISSIONPLANNER, &mavlink_tx_msg, &mavlink_mission_current);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
}
break;
case MAVLINK_MSG_ID_MISSION_COUNT:
mavlink_msg_mission_count_decode(&mavlink_rx_msg, &mavlink_mission_count);
if (mavlink_mission_count.target_system == mavlinkID) {
waypointCount = mavlink_mission_count.count;
waypointReceiveIndex = 0;
waypointTimer = WAYPOINT_TIMEOUT; // set waypoint timeout to timed out so that request is immediate
waypointTries = 0;
waypointValid = 0; // invalidate waypoint storage until full set is received
waypointProviderID = mavlink_rx_msg.sysid;
waypointProviderComp = mavlink_rx_msg.compid;
}
break;
case MAVLINK_MSG_ID_MISSION_REQUEST_LIST:
mavlink_msg_mission_request_list_decode(&mavlink_rx_msg, &mavlink_mission_request_list);
if (mavlink_mission_request_list.target_system == mavlinkID) {
if(waypointValid == 0) {
mavlink_mission_count.count = 0;
}
else {
mavlink_mission_count.count = waypointCount;
}
mavlink_mission_count.target_system = mavlink_rx_msg.sysid;
mavlink_mission_count.target_component = mavlink_rx_msg.compid;
mavlink_msg_mission_count_encode(mavlinkID, MAV_COMP_ID_SYSTEM_CONTROL, &mavlink_tx_msg, &mavlink_mission_count);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
}
break;
case MAVLINK_MSG_ID_MISSION_REQUEST:
mavlink_msg_mission_request_decode(&mavlink_rx_msg, &mavlink_mission_request);
if (mavlink_mission_request.target_system == mavlinkID) {
if(waypointValid != 0) {
mavlink_mission_item.target_system = mavlink_rx_msg.sysid;
mavlink_mission_item.target_component = mavlink_rx_msg.compid;
mavlink_mission_item.seq = mavlink_mission_request.seq;
mavlink_mission_item.frame = MAV_FRAME_GLOBAL;
mavlink_mission_item.command = waypoint[mavlink_mission_request.seq].command;
mavlink_mission_item.autocontinue = waypoint[mavlink_mission_request.seq].autocontinue;
mavlink_mission_item.param1 = waypoint[mavlink_mission_request.seq].param1;
mavlink_mission_item.param2 = waypoint[mavlink_mission_request.seq].param2;
mavlink_mission_item.param3 = waypoint[mavlink_mission_request.seq].param3;
mavlink_mission_item.param4 = waypoint[mavlink_mission_request.seq].param4;
mavlink_mission_item.x = waypoint[mavlink_mission_request.seq].x;
mavlink_mission_item.y = waypoint[mavlink_mission_request.seq].y;
mavlink_mission_item.z = waypoint[mavlink_mission_request.seq].z;
if(waypointCurrent == mavlink_mission_request.seq) {
mavlink_mission_item.current = 1;
}
else {
mavlink_mission_item.current = 0;
}
mavlink_msg_mission_item_encode(mavlinkID, MAV_COMP_ID_MISSIONPLANNER, &mavlink_tx_msg, &mavlink_mission_item);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
}
}
break;
case MAVLINK_MSG_ID_MISSION_ITEM:
mavlink_msg_mission_item_decode(&mavlink_rx_msg, &mavlink_mission_item);
if (mavlink_mission_item.target_system == mavlinkID) {
mavlink_mission_ack.type = MAV_MISSION_ERROR;
if(mavlink_mission_item.frame == MAV_FRAME_GLOBAL) {
if(mavlink_mission_item.seq < MAX_WAYPOINTS) {
//waypoint[mavlink_mission_item.seq].frame = mavlink_mission_item.frame;
waypoint[mavlink_mission_item.seq].command = mavlink_mission_item.command;
waypoint[mavlink_mission_item.seq].autocontinue = mavlink_mission_item.autocontinue;
waypoint[mavlink_mission_item.seq].param1 = mavlink_mission_item.param1;
waypoint[mavlink_mission_item.seq].param2 = mavlink_mission_item.param2;
waypoint[mavlink_mission_item.seq].param3 = mavlink_mission_item.param3;
waypoint[mavlink_mission_item.seq].param4 = mavlink_mission_item.param4;
waypoint[mavlink_mission_item.seq].x = mavlink_mission_item.x;
waypoint[mavlink_mission_item.seq].y = mavlink_mission_item.y;
waypoint[mavlink_mission_item.seq].z = mavlink_mission_item.z;
if(mavlink_mission_item.current == 1) {
waypointCurrent = mavlink_mission_item.seq;
}
waypointReceiveIndex++;
waypointTimer = WAYPOINT_TIMEOUT; // set waypoint timeout to timed out so that request is immediate
waypointTries = 0;
mavlink_mission_ack.target_system = mavlink_rx_msg.sysid;
mavlink_mission_ack.target_component = mavlink_rx_msg.compid;
if(waypointReceiveIndex >= waypointCount) {
mavlink_mission_ack.type = MAV_MISSION_ACCEPTED;
waypointValid = 1;
}
else if(waypointReceiveIndex >= MAX_WAYPOINTS) {
mavlink_mission_ack.type = MAV_MISSION_NO_SPACE;
}
}
else {
mavlink_mission_ack.type = MAV_MISSION_NO_SPACE;
}
}
else {
mavlink_mission_ack.type = MAV_MISSION_UNSUPPORTED_FRAME;
}
mavlink_msg_mission_ack_encode(mavlinkID, MAV_COMP_ID_MISSIONPLANNER, &mavlink_tx_msg, &mavlink_mission_ack);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
}
break;
case MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST:
mavlink_mission_ack.type = MAV_MISSION_UNSUPPORTED;
mavlink_msg_mission_ack_encode(mavlinkID, MAV_COMP_ID_MISSIONPLANNER, &mavlink_tx_msg, &mavlink_mission_ack);
mavlink_message_len = mavlink_msg_to_send_buffer(mavlink_message_buf, &mavlink_tx_msg);
XBeeWriteCoordinator(mavlink_message_buf, mavlink_message_len);
break;
case MAVLINK_MSG_ID_MISSION_ACK:
//ignored
break;
case MAVLINK_MSG_ID_REQUEST_DATA_STREAM:
// Sets the output data rates
mavlink_msg_request_data_stream_decode(&mavlink_rx_msg, &mavlink_request_data_stream);
if (mavlink_request_data_stream.target_system == mavlinkID) {
if(mavlink_request_data_stream.req_message_rate > 255) mavlink_request_data_stream.req_message_rate = 255;
dataRate[mavlink_request_data_stream.req_stream_id] = mavlink_request_data_stream.req_message_rate;
}
break;
default:
MAVSendInt("CMDIGNORE", mavlink_rx_msg.msgid);
break;
}
//if(mavlink_rx_msg.msgid != 0) MAVSendInt("CMD", mavlink_rx_msg.msgid);
}
}
// *** GPS messages
void GPSMessage(unsigned short id, unsigned char * buffer, unsigned short length) {
unsigned char * ptr = 0;
unsigned short j;
switch(id) {
case ID_NAV_POSECEF: ptr = (unsigned char *) &gps_nav_posecef; break;
case ID_NAV_POSLLH: ptr = (unsigned char *) &gps_nav_posllh; posupdate = 1; break;
case ID_NAV_STATUS: ptr = (unsigned char *) &gps_nav_status; break;
case ID_NAV_SOL: ptr = (unsigned char *) &gps_nav_sol; break;
case ID_NAV_VELNED: ptr = (unsigned char *) &gps_nav_velned; break;
case ID_NAV_TIMEUTC: ptr = (unsigned char *) &gps_nav_timeutc; break;
}
if(ptr) {
for(j=0; j<length; j++) {
ptr[j] = buffer[j];
}
ptr[j] = 1; // this is the "isNew" byte
}
}
void ILinkMessage(unsigned short id, unsigned short * buffer, unsigned short length) {
unsigned short * ptr = 0;
unsigned int j;
switch(id) {
case ID_ILINK_IDENTIFY: ptr = (unsigned short *) &ilink_identify; break;
case ID_ILINK_THALSTAT: ptr = (unsigned short *) &ilink_thalstat; break;
case ID_ILINK_THALCTRL: ptr = (unsigned short *) &ilink_thalctrl_rx; break;
case ID_ILINK_RAWIMU: ptr = (unsigned short *) &ilink_rawimu; break;
case ID_ILINK_SCALEDIMU: ptr = (unsigned short *) &ilink_scaledimu; break;
case ID_ILINK_ALTITUDE: ptr = (unsigned short *) &ilink_altitude; break;
case ID_ILINK_ATTITUDE: ptr = (unsigned short *) &ilink_attitude; break;
case ID_ILINK_THALPARAM: ptr = (unsigned short *) &ilink_thalparam_rx; break;
case ID_ILINK_INPUTS0: ptr = (unsigned short *) &ilink_inputs0; break;
case ID_ILINK_OUTPUTS0: ptr = (unsigned short *) &ilink_outputs0; break;
case ID_ILINK_THALPAREQ: ptr = (unsigned short *) &ilink_thalpareq; break;
case ID_ILINK_DEBUG: ptr = (unsigned short *) &ilink_debug; break;
}
if(ptr) {
for(j=0; j<length; j++) {
ptr[j] = buffer[j];
}
ptr[j] = 1; // this is the "isNew" byte
switch(id) {
case ID_ILINK_THALCTRL:
switch(ilink_thalctrl_rx.command) {
case 0x0090: // horizontal hold
if(horizontalHold == 0) {
horizontalHold = 1;
}
break;
case 0x0091: // horizontal releas
horizontalHold = 0;
break;
}
break;
case ID_ILINK_THALPARAM: // store parameters in buffer
if(paramPointer > 0) {
paramPointer--;
paramBuffer[paramPointer].value = ilink_thalparam_rx.paramValue;
paramBuffer[paramPointer].id = ilink_thalparam_rx.paramID;
for(j=0; j<16; j++) {
paramBuffer[paramPointer].name[j] = ilink_thalparam_rx.paramName[j];
if(ilink_thalparam_rx.paramName[j] == '\r') break;
}
}
break;
case ID_ILINK_THALPAREQ:
if(ilink_thalpareq.reqType == 2) {
// output something intelligible to user to signify successful EEPROM save
}
break;
case ID_ILINK_IDENTIFY:
if(ilink_identify.firmVersion == FIRMWARE_VERSION && ilink_identify.deviceID == I_AM_THALAMUS) {
mavlink_sys_status.onboard_control_sensors_present |= MAVLINK_SENSOR_GYRO | MAVLINK_SENSOR_ACCEL | MAVLINK_SENSOR_MAGNETO | MAVLINK_SENSOR_BARO | MAVLINK_CONTROL_ANGLERATE | MAVLINK_CONTROL_ATTITUDE | MAVLINK_CONTROL_YAW | MAVLINK_CONTROL_Z;
mavlink_sys_status.onboard_control_sensors_health = mavlink_sys_status.onboard_control_sensors_enabled;
}
break;
}
thalWatchdog = 0;
}
}
<file_sep>Mavrx-firmware
==============
<file_sep>
// ****************************************************************************
// *** Communications Functions
// ****************************************************************************
// *** Deal with ilink requets
void ILinkMessageRequest(unsigned short id) {
unsigned short * ptr = 0;
unsigned short maxlength = 0;
switch(id) {
case ID_ILINK_IDENTIFY: ptr = (unsigned short *) &ilink_identify; maxlength = sizeof(ilink_identify)/2 - 1; break;
case ID_ILINK_THALCTRL: ptr = (unsigned short *) &ilink_thalctrl_tx; maxlength = sizeof(ilink_thalctrl_tx)/2 - 1; break;
case ID_ILINK_THALSTAT: ptr = (unsigned short *) &ilink_thalstat; maxlength = sizeof(ilink_thalstat)/2 - 1; break;
case ID_ILINK_RAWIMU: ptr = (unsigned short *) &ilink_rawimu; maxlength = sizeof(ilink_rawimu)/2 - 1; break;
case ID_ILINK_SCALEDIMU: ptr = (unsigned short *) &ilink_scaledimu; maxlength = sizeof(ilink_scaledimu)/2 - 1; break;
case ID_ILINK_ALTITUDE: ptr = (unsigned short *) &ilink_altitude; maxlength = sizeof(ilink_altitude)/2 - 1; break;
case ID_ILINK_ATTITUDE: ptr = (unsigned short *) &ilink_attitude; maxlength = sizeof(ilink_attitude)/2 - 1; break;
case ID_ILINK_INPUTS0: ptr = (unsigned short *) &ilink_inputs0; maxlength = sizeof(ilink_inputs0)/2 - 1; break;
case ID_ILINK_OUTPUTS0: ptr = (unsigned short *) &ilink_outputs0; maxlength = sizeof(ilink_outputs0)/2 - 1; break;
case ID_ILINK_DEBUG: ptr = (unsigned short *) &ilink_debug; maxlength = sizeof(ilink_debug)/2 - 1; break;
case ID_ILINK_CLEARBUF:
FUNCILinkTxBufferPushPtr = 0;
FUNCILinkTxBufferPopPtr = 0;
break;
}
if(ptr) {
ILinkSendMessage(id, ptr, maxlength);
}
}
// *** iLink interrupt handler
void ILinkMessage(unsigned short id, unsigned short * buffer, unsigned short length) {
unsigned short * ptr = 0;
unsigned int i, j;
switch(id) {
case ID_ILINK_THALPAREQ: ptr = (unsigned short *) &ilink_thalpareq; break;
case ID_ILINK_THALPARAM: ptr = (unsigned short *) &ilink_thalparam_rx; break;
case ID_ILINK_THALCTRL: ptr = (unsigned short *) &ilink_thalctrl_rx; break;
case ID_ILINK_GPSFLY: ptr = (unsigned short *) &ilink_gpsfly; break;
}
if(ptr) {
for(i=0; i<length; i++) {
ptr[i] = buffer[i];
}
ptr[i] = 1; // this should be the isNew byte
}
switch(id) {
case ID_ILINK_THALPAREQ:
ilink_thalpareq.isNew = 0;
switch(ilink_thalpareq.reqType) {
case 1: // get one
if(ilink_thalpareq.paramID == 0xffff) {
for (i=0; i<paramCount; i++){
unsigned char match = 1;
for (j=0; j<16; j++) {
if (paramStorage[i].name[j] != ilink_thalparam_rx.paramName[j]) {
match = 0;
break;
}
if (paramStorage[i].name[j] == '\0') break;
}
if(match == 1) {
// when a match is found get the iD
paramSendCount = i;
paramSendSingle = 1;
break;
}
}
}
else {
paramSendCount = ilink_thalpareq.paramID;
paramSendSingle = 1;
}
break;
case 2: // save all
EEPROMSaveAll();
ilink_thalpareq.isNew = 1;
ilink_thalctrl_rx.command = MAVLINK_MSG_ID_COMMAND_LONG;
ilink_thalctrl_rx.data = MAV_CMD_PREFLIGHT_STORAGE;
//ILinkSendMessage(ID_ILINK_THALCTRL, (unsigned short *) &ilink_thalctrl_rx, sizeof(ilink_thalctrl_rx)/2 - 1);
break;
case 3: // reload all
EEPROMLoadAll();
ilink_thalpareq.isNew = 1;
ilink_thalctrl_rx.command = MAVLINK_MSG_ID_COMMAND_LONG;
ilink_thalctrl_rx.data = MAV_CMD_PREFLIGHT_STORAGE;
//ILinkSendMessage(ID_ILINK_THALCTRL, (unsigned short *) &ilink_thalctrl_rx, sizeof(ilink_thalctrl_rx)/2 - 1);
// fall through to get all
default:
case 0: // get all
paramSendCount = 0;
paramSendSingle = 0;
break;
}
break;
case ID_ILINK_THALCTRL:
switch(ilink_thalctrl_rx.command) {
case 0:
break;
}
break;
case ID_ILINK_THALPARAM:
// match up received parameter with stored parameter.
for (i=0; i<paramCount; i++){
unsigned char match = 1;
for (j=0; j<16; j++) {
if (paramStorage[i].name[j] != ilink_thalparam_rx.paramName[j]) {
match = 0;
break;
}
if (paramStorage[i].name[j] == '\0') break;
}
if(match == 1) {
// when a match is found, save it to paramStorage
paramStorage[i].value = ilink_thalparam_rx.paramValue;
// then order the value to be sent out again using the param send engine
// but deal with cases where it's already in the process of sending out data
if(paramSendCount < paramCount) {
// parameter engine currently sending out data
if(paramSendCount >= i) {
// if parameter engine already sent out this now-changed data, redo this one, otherwise no action needed
paramSendCount = i;
}
}
else {
// parameter engine not currently sending out data, so send single parameter
paramSendCount = i;
paramSendSingle = 1;
}
break;
}
}
break;
}
}<file_sep>// ****************************************************************************
// *** Copyright (c) 2011, Universal Air Ltd. All rights reserved.
// *** Source and binaries are released under the BSD 3-Clause license
// *** See readme_forebrain.txt files for the text of the license
// ****************************************************************************
#include "lpc1347.h"
#include "thal.h"
#include "config.h"
#include <stdint.h>
#include <string.h>
#include <math.h>
#if defined (__cplusplus)
extern "C" {
#endif
// ****************************************************************************
// *** Misc Functions
// ****************************************************************************
// *** In-application programmingfunctions
static const FUNCIAP FUNCIAPEntry = (FUNCIAP)0x1fff1ff1;
// *** Reprogram function
/*void Reprogram(void) {
unsigned int command[5], result[4];
command[0] = 57; // 57 is code to reinvoke ISP
LPC_SYSCON->SYSAHBCLKDIV = 1; // make sure clock divider is 1
LPC_SYSCON->SYSAHBCLKCTRL |= 0x14440; // turn on USB clock, Timer 32B1, GPIO, and IO blocks
__set_MSP(*((unsigned int *)0x1FFF0000)); // set pointer to bootloader ROM location
//__set_Stack(0x10002000);
FUNCIAPEntry(command, result);
}*/
// *** Read chip's part identifier
unsigned int ReadPID(void) {
unsigned int command[5], result[4];
command[0] = 54; // 54 is code to read PID
FUNCIAPEntry(command, result);
return result[0];
}
// *** Read chip's unique identifier
void ReadUID(unsigned int * uid) {
unsigned int command[5];
command[0] = 58; // 58 is code to read UID
FUNCIAPEntry(command, uid);
}
// *** Provide a simple hash of the unique identifier to avoid user having to deal with 128 bits
// there is a chace of collision reducing 128 to 32bits, but much easier to handle
// This is a modified Berstein Hash
unsigned int ReadUIDHash(void) {
unsigned int command[5], result[4], hash;
command[0] = 58; // 58 is code to read UID
FUNCIAPEntry(command, result);
hash = result[0];
hash *= 33;
hash ^= result[1];
hash *= 33;
hash ^= result[2];
hash *= 33;
hash ^= result[3];
return hash;
}
void EEPROMWriteByte(unsigned int address, unsigned char data) {
unsigned char datas[1];
EEPROMWrite(address, datas, 1);
}
unsigned char EEPROMReadByte(unsigned int address){
unsigned char datas[1];
EEPROMRead(address, datas, 1);
return datas[0];
}
void EEPROMWrite(unsigned int address, unsigned char * data, unsigned int length) {
unsigned int command[5], result[4];
command[0] = 61; // 61 is code to write to eeprom
command[1] = address+64; // address in EEPROM, avoiding reserved 64 bytes
command[2] = (unsigned int) data; // address in RAM of data
command[3] = length; // number of bytes read
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
command[4] = 72000; // clock speed in kHz
}
else {
command[4] = 12000; // clock speed in kHz
}
FUNCIAPEntry(command, result);
}
void EEPROMRead(unsigned int address, unsigned char * data, unsigned int length) {
unsigned int command[5], result[4];
command[0] = 62; // 61 is code to read from eeprom
command[1] = address+64; // address in EEPROM, avoiding reserved 64 bytes
command[2] = (unsigned int) data; // address in RAM of data
command[3] = length; // number of bytes read
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
command[4] = 72000; // clock speed in kHz
}
else {
command[4] = 12000; // clock speed in kHz
}
FUNCIAPEntry(command, result);
}
// *** Reset function
void Reset(void) {
__DSB(); // Wait for write ops to clear
SCB->AIRCR = (0x5FA << 16) | (SCB->AIRCR & (0x7 << 8)) | (0x1 << 2);
__DSB(); // Wait for write ops to clear
while(1); // Wait for reset
}
// *** Fast trigonometry approximation functions
float invSqrt(float x) {
union {
float f;
int i;
} tmp;
tmp.f = x;
tmp.i = 0x5f3759df - (tmp.i >> 1);
float y = tmp.f;
return y * (1.5f - 0.5f * x * y * y);
}
float fatan2(float y, float x) {
if (x == 0.0f) {
if (y > 0.0f) return M_PI_2;
if (y == 0.0f) return 0.0f;
return -M_PI_2;
}
float atan;
float z = y/x;
if (fabsf(z) < 1.0f) {
atan = z/(1.0f + 0.28f*z*z);
if (x < 0.0f) {
if (y < 0.0f) return atan - M_PI;
return atan + M_PI;
}
}
else {
atan = M_PI_2 - z/(z*z + 0.28f);
if (y < 0.0f) return atan - M_PI;
}
return atan;
}
float fasin(float x) {
float temp, arcsin, xabs;
xabs = fabsf(x);
temp = M_PI_2 - (1.5707288f + (-0.2121144f + (0.0742610f - 0.0187293f*xabs)*xabs)*xabs)/invSqrt(1-xabs);
arcsin = copysignf(temp, x);
return arcsin;
}
float fsin(float x) {
const float B = 4/M_PI;
const float C = -4/(M_PI*M_PI);
while(x > M_PI) x-= M_TWOPI;
while(x < -M_PI) x+= M_TWOPI;
float y = B * x + C * x * fabsf(x);
// const float Q = 0.775;
const float P = 0.225;
y = P * (y * fabsf(y) - y) + y; // Q * y + P * y * abs(y)
return y;
}
// *** Random number functions
#if RAND_MERSENNE
volatile unsigned int FUNCMersenne[MERSENNE_N];
volatile unsigned int FUNCMersenneIndex;
volatile unsigned int FUNCMersenneMag[2]={0x0UL, 0x9908b0dfUL};
void RandomSeed(unsigned int seed) {
unsigned int i;
FUNCMersenne[0]= seed;
for (i=1; i<623; i++) {
FUNCMersenne[i] = (1812433253UL * (FUNCMersenne[i-1] ^ (FUNCMersenne[i-1] >> 30)) + i);
}
FUNCMersenneIndex = 0;
}
unsigned int Random(void) {
unsigned int i, y;
if (FUNCMersenneIndex > MERSENNE_N-1) {
for (i=0;i<MERSENNE_N-MERSENNE_M;i++) {
y = (FUNCMersenne[i]&0x80000000UL)|(FUNCMersenne[i+1]&0x7fffffffUL);
FUNCMersenne[i] = FUNCMersenne[i+MERSENNE_M] ^ (y >> 1) ^ FUNCMersenneMag[y & 0x1UL];
}
for (;i<MERSENNE_N-1;i++) {
y = (FUNCMersenne[i]&0x80000000UL)|(FUNCMersenne[i+1]&0x7fffffffUL);
FUNCMersenne[i] = FUNCMersenne[i+(MERSENNE_M-MERSENNE_N)] ^ (y >> 1) ^ FUNCMersenneMag[y & 0x1UL];
}
y = (FUNCMersenne[MERSENNE_N-1]&0x80000000UL)|(FUNCMersenne[0]&0x7fffffffUL);
FUNCMersenne[MERSENNE_N-1] = FUNCMersenne[MERSENNE_M-1] ^ (y >> 1) ^ FUNCMersenneMag[y & 0x1UL];
FUNCMersenneIndex = 0;
}
// tempering
y = FUNCMersenne[FUNCMersenneIndex];
y ^= (y >> 11);
y ^= (y << 7) & 2636928640UL;
y ^= (y << 15) & 4022730752UL;
y ^= (y >> 18);
FUNCMersenneIndex++;
return y;
}
#else
volatile unsigned int FUNCRandomNumber;
#endif
// *** Set Code Read Protection
__attribute__ ((section(".crp"))) const unsigned int CRP_WORD = CRP;
// ****************************************************************************
// *** Clock Functions
// ****************************************************************************
__attribute__ ((section(".after_vectors"))) void ClockModeXTAL(void) {
unsigned int i;
LPC_SYSCON->PDRUNCFG &= ~(0x1UL << 5); // Power up system oscillator
LPC_SYSCON->SYSOSCCTRL = 0; // System oscillator setup - not bypass, 1-20MHz range
for(i = 0; i < 200; i++) __NOP(); // Brief delay
LPC_SYSCON->SYSPLLCLKSEL = 0x01; // Select system oscillator as PLL source
LPC_SYSCON->SYSPLLCTRL = 0x25; // Select PLL divider to 6 (12MHz - 72MHz)
LPC_SYSCON->PDRUNCFG &= ~(0x1UL << 7); // Power up PLL
while(!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock
LPC_SYSCON->MAINCLKSEL = 0x03; // Select PLL as main clock source
//LPC_SYSCON->PDRUNCFG |= (0x1UL <<0) | (0x1UL <<1); // Shut down IRC
}
void ClockModeIRC72(void) {
unsigned int i;
LPC_SYSCON->PDRUNCFG &= ~((0x1UL <<0) | (0x1UL <<1)); // Power up IRC oscillator
LPC_SYSCON->SYSOSCCTRL = 0; // System oscillator setup - not bypass, 1-20MHz range
for(i = 0; i < 200; i++) __NOP(); // Brief delay
LPC_SYSCON->SYSPLLCLKSEL = 0x00; // Select system oscillator as PLL source
LPC_SYSCON->SYSPLLCTRL = 0x25; // Select PLL divider to 6 (12MHz - 72MHz)
LPC_SYSCON->PDRUNCFG &= ~(0x1UL << 7); // Power up PLL
while(!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock
LPC_SYSCON->MAINCLKSEL = 0x03; // Select PLL as main clock source
LPC_SYSCON->PDRUNCFG |= (0x1UL <<5); // Shut down system oscillator
}
void ClockModeIRC12(void) {
unsigned int i;
LPC_SYSCON->PDRUNCFG &= ~((0x1UL <<0) | (0x1UL <<1)); // Power up IRC oscillator
for(i = 0; i < 200; i++); // Brief delay
LPC_SYSCON->MAINCLKSEL = 0x00; // Select IRC as main clock source
LPC_SYSCON->PDRUNCFG |= ((0x1UL <<5) | (0x1UL <<7)); // Power down system oscillator and PLL
}
// *** Delay functions
void Delay(unsigned int milliseconds) {
// detect if Systick is enabled (and turned on) and use the relevant delay function
#if SYSTICK_EN
if(SysTick->CTRL & 0x1) SysTickDelay(milliseconds);
else WaitDelay(milliseconds);
#else
WaitDelay(milliseconds);
#endif
}
void WaitDelay(unsigned int milliseconds) {
volatile unsigned int i, j;
// Some empty loops depending on the clock setting
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
for(j=0; j<milliseconds; j++) {
for(i=0; i<6000; i++);
}
}
else {
// assume 12MHz operation
for(j=0; j<milliseconds; j++) {
for(i=0; i<1000; i++);
}
}
}
#if SYSTICK_EN
volatile unsigned int FUNCSysTicks, FUNCTimeout;
// *** System tick timer functions
void SysTickInit(void) { // this function is run automaticlly by the startup script if SysTick is enabled
// configure the timer based on oscillator speed, these are already defined in core_cm3
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
SysTick->LOAD = ((72 * SYSTICK_US) & 0xffffff) - 1;
SysTick->VAL = 0;
SysTick->CTRL = 0x07;
IRQPriority(SysTick_IRQn, SYSTICK_PRIORITY);
}
else {
// assume 12MHz operation
SysTick->LOAD = ((12 * SYSTICK_US) & 0xffffff) - 1;
SysTick->VAL = 0;
SysTick->CTRL = 0x07;
IRQPriority(SysTick_IRQn, SYSTICK_PRIORITY);
}
FUNCSysTicks = 0;
}
void SysTickStop(void) {
SysTick->CTRL = 0x00; // Stop the SysTick timer
}
void SysTick_Handler(void) {
FUNCSysTicks++; // increment tick timer variable for use with Delays
if(FUNCTimeout>0) FUNCTimeout--;
if(SysTickInterrupt) SysTickInterrupt(); // Run user-supplied interrupt function if available
if(SDTick) SDTick();
}
// Systick-based delay
__attribute__ ((section(".after_vectors"))) void SysTickDelay(unsigned int milliseconds) {
FUNCSysTicks = 0; // zero tick timer variable
while(FUNCSysTicks < (milliseconds*1000)/SYSTICK_US); // wait until tick timer variable reaches required number
}
void SysTickUDelay(unsigned int microseconds) {
FUNCSysTicks = 0; // zero tick timer variable
while(FUNCSysTicks < microseconds/SYSTICK_US); // wait until tick timer variable reaches required number
}
#endif
// *** Watchdog timer initialise
void WDTInit(unsigned int milliseconds) {
LPC_SYSCON->SYSAHBCLKCTRL |= (0x1UL << 15); // Enable clock to WDT block
LPC_SYSCON->PDRUNCFG &= ~(0x1UL << 6); // Power up the WDT oscillator
#if WDT_CLK == 0
LPC_SYSCON->WDTOSCCTRL = 0x020; // Default rate of divider of 2, clock rate of 0.5MHz, WDT divides by 4 again = 62.5kHz clock
LPC_WWDT->CLKSEL = 0x01; // Select the watchdog oscillator as input
#else
LPC_WWDT->CLKSEL = 0x00; // Select IRC as input
#endif
#if WDT_MODE
// in interrupt mode 1 and 2, enable interrupts
IRQClear(WDT_IRQn);
IRQEnable(WDT_IRQn);
IRQPriority(WDT_IRQn, WDT_PRIORITY);
LPC_WWDT->MOD = 0x1;
#else
// in reset mode, enable reset
LPC_WWDT->MOD = 0x3;
#endif
// Set up WDT period with minimum and maximum values
#if WDT_CLK == 0
if(milliseconds < 1) {
LPC_WWDT->TC = 1;
}
else if(milliseconds > 268435) { // maximum 268.435 seconds
LPC_WWDT->TC = 268435;
}
else {
LPC_WWDT->TC = 62.5 * milliseconds;
}
#else
if(milliseconds < 1) {
LPC_WWDT->TC = 1;
}
else if(milliseconds > 5592) { // maximum 5.592 seconds
LPC_WWDT->TC = 5592;
}
else {
LPC_WWDT->TC = 3000 * milliseconds;
}
#endif
WDTFeed(); // feed WDT
}
// *** Watchdog timer stop
void WDTStop(void) {
LPC_WWDT->MOD &= ~0x1;
IRQDisable(WDT_IRQn);
}
// *** Watchdog timer interrupt
void WDT_IRQHandler(void) {
if(WDTInterrupt) WDTInterrupt();
#if WDT_MODE == 2
LPC_WWDT->MOD &= ~0x04;
LPC_WWDT->MOD = 0x1;
WDTFeed(); // feed WDT
#endif
}
/*
// *** Clockout confiig
void ClockOut(unsigned char mode, unsigned char divider) {
if(mode == USBSOF) {
// Set up USB start-of-frame output (1ms)
LPC_IOCON->PIO0_1 = 0x53;
}
else if((mode & 0x3) == 0) {
// Turn clockout off
LPC_SYSCON->CLKOUTDIV = 0;
}
else {
// Otherwise one of the other modes
mode--;
LPC_IOCON->PIO0_1 = 0x51;
LPC_SYSCON->CLKOUTDIV = divider;
LPC_SYSCON->CLKOUTCLKSEL = mode;
LPC_SYSCON->CLKOUTUEN = 0;
LPC_SYSCON->CLKOUTUEN = 1;
}
}
*/
void RITInit(unsigned long long value) {
//LPC_SYSCON->SYSAHBCLKCTRL |= (0x1UL << 25); // Enable clock to RIT, apparently this bit doesn't exist...?
LPC_RITIMER->COMPVAL = value & 0xffffffffUL;
LPC_RITIMER->COMPVAL_H = value >> 32;
#if RIT_RESET
LPC_RITIMER->CTRL = 0x2;
#else
LPC_RITIMER->CTRL = 0;
#endif
LPC_RITIMER->CTRL |= 0x1; // clear interrupt flag
RITReset();
RITGo();
IRQClear(RIT_IRQn);
IRQPriority(RIT_IRQn, RIT_PRIORITY);
IRQEnable(RIT_IRQn);
}
void RITInitms(unsigned int value) {
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
if(value > 3909374676UL) value = 3909374676UL; // prevent overflow, though maximum value is something like 45 days
RITInit((unsigned long long) value * (unsigned long long) 72000);
}
else {
// assume 12MHz operation
RITInit((unsigned long long) value * (unsigned long long) 12000);
}
}
void RIT_IRQHandler(void) {
if(RITInterrupt) RITInterrupt();
LPC_RITIMER->CTRL |= 0x1;
}
/*
// ****************************************************************************
// *** Power mode Functions
// ****************************************************************************
// *** Sleep mode, peripherals remain active, and processor wakes up on interrupt
void Sleep(void) {
LPC_PMU->PCON |= (0x1UL << 11); // Clear the deep power-down power flag
SCB->SCR &= ~(0x1UL <<2); // Deselect deep sleep/power-down mode
__WFI(); // Sleep and wait for interrupt
}
// *** Deep sleep, chip shuts down, wakes up on GPIO or timer
void DeepSleep(unsigned long long startpins, unsigned long long startdirection, unsigned int timer) {
unsigned int i;
// *** If timer is enabled
if(timer) {
// *** Use T3[3]/P1[4]
if(timer > 0x63FF9C) timer = 0x63FF9C;
Timer2Init(9); // 10 prescale = ms
if(startdirection & PORT0PIN1) {
// User demanded a rising edge on this pin, Timer wakeup must also make use of rising edge
Timer2Match2(timer, OUTPUTHIGH | RESET); // set match to measure in ms
}
else {
// User demanded a falling edge on this pin (or did not specify), Timer wakeup to use falling edge
Timer2Match2(timer, OUTPUTLOW | RESET); // set match to measure in ms
}
startpins |= PORT0PIN1; // P0[1] is also the T2[2] pin
LPC_SYSCON->PDRUNCFG &= ~(0x1UL <<6 | 1<<9 | 0x3); // Power up the WDT oscillator
LPC_SYSCON->PDAWAKECFG = LPC_SYSCON->PDRUNCFG; // Set wakeup power config
LPC_SYSCON->WDTOSCCTRL = 0x03F; // Lowest rate: 0.5MHz
LPC_SYSCON->MAINCLKSEL = 0x02; // Select WDT as main clock source
LPC_SYSCON->MAINCLKUEN = 0x00; // Update clock source
LPC_SYSCON->MAINCLKUEN = 0x01;
while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); // Wait for clock update
LPC_SYSCON->PDRUNCFG = ~((0x1UL <<6) | (0x1UL <<2) | (0x1UL <<9)); // Switch off everything unneeded
if(LPC_SYSCON->BODCTRL & (0x1UL <<4)) {
LPC_SYSCON->PDSLEEPCFG = 0x00000FB7; // Use brown-out detect
}
else {
LPC_SYSCON->PDSLEEPCFG = 0x00000FBF; // Don't use brown-out
}
}
else {
LPC_SYSCON->PDRUNCFG &= ~(0x3); // Power up the IRC
LPC_SYSCON->PDAWAKECFG = LPC_SYSCON->PDRUNCFG; //Set wakeup power config
LPC_SYSCON->MAINCLKSEL = 0; // Select IRC as main clock source
LPC_SYSCON->MAINCLKUEN = 0; // Update clock source
LPC_SYSCON->MAINCLKUEN = 1;
while(!(LPC_SYSCON->MAINCLKUEN & 0x1)); // Wait for clock update
LPC_SYSCON->PDRUNCFG = ~(0x7 | 1<<9);
if(LPC_SYSCON->BODCTRL & (0x1UL <<4)) {
LPC_SYSCON->PDSLEEPCFG = 0x00000FF7; // Use brown-out detect
}
else {
LPC_SYSCON->PDSLEEPCFG = 0x00000FFF; // Don't use brown-out
}
}
LPC_PMU->PCON |= (0x1UL <<8); // Clear sleep flag
SCB->SCR |= (0x1UL <<2); // Select deep sleep/power-down mode
// Set wakeup pins
LPC_SYSCON->STARTAPRP0 = startdirection & 0xffffffff;
LPC_SYSCON->STARTRSRP0CLR = startpins & 0xffffffff;
LPC_SYSCON->STARTERP0 = startpins & 0xffffffff;
LPC_SYSCON->STARTAPRP1 = (startdirection >> 32) & 0xff;
LPC_SYSCON->STARTRSRP1CLR = (startpins >> 32) & 0xff;
LPC_SYSCON->STARTERP1 = (startpins >> 32) & 0xff;
// Set wakeup interrupts
for(i=0; i<40; i++) {
if(startpins & (0x1UL <<i)) {
IRQClear(i);
IRQEnable(i);
}
else {
IRQDisable(i);
}
}
__WFI(); // Sleep and wait for interrupt
if(timer) Timer2Stop(); // Stop timer
ClockMode(DEFAULT_CLOCK); // Reinstate clock
}
// *** Wakeup interrupt handler
void WAKEUP_IRQHandler(void){
LPC_SYSCON->STARTRSRP0CLR |= LPC_SYSCON->STARTERP0; // Clear wakeup pin interrupts
LPC_SYSCON->STARTRSRP1CLR |= LPC_SYSCON->STARTERP1;
}
// *** Deep power-down mode, only wakes up on low signal on P1[4]
void PowerDown(void) {
#if WAKEUP_HYS
LPC_PMU->GPREG4 | = 1 << 10; // Enable hysteresis
#endif
LPC_PMU->PCON = (0x1UL <<1) | (0x1UL <<11); // Select deep power-down mode, and clear flag
SCB->SCR |= (0x1UL <<2); // Select deep power-down/sleep mode
LPC_SYSCON->PDRUNCFG &= ~(0x3); // Turn on IRC
__WFI(); // Sleep
}
// *** Brownout detect
void BODInit(unsigned char interruptlevel) {
LPC_SYSCON->BODCTRL = ((interruptlevel & 0x3) << 2) | (0x1UL <<4); // Set interrupt level
IRQClear(BOD_IRQn); // Clear and enable BOD
IRQEnable(BOD_IRQn);
}
// *** Stop Brownout
void BODStop(void) {
LPC_SYSCON->BODCTRL = 0;
IRQDisable(BOD_IRQn);
}
// *** Brownout interrupt handler
void BOD_IRQHandler(void) {
if(BODInterrupt) BODInterrupt();
}
// *** Reset status
unsigned char ResetStatus(void) {
unsigned char status;
status = LPC_SYSCON->SYSRESSTAT & 0x1f; // Read reset status
LPC_SYSCON->SYSRESSTAT = status; // Clear reset status
if(LPC_PMU->PCON & (0x1UL <<11)) { // Check deep power-down flag
LPC_PMU->PCON |= (0x1UL <<11);
status |= POWEREDDOWN;
}
return status;
}
*/
// ****************************************************************************
// *** GPIO Functions
// ****************************************************************************
// *** Initialise pins as digital IO mode (note: default state is digital input)
__attribute__ ((section(".after_vectors"))) void Port0Init(unsigned int pins) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE;
for(i=0x1; i<(0x1UL <<24); i<<=1) { // Set various pins to GPIO when specified, Port 0 only goes up to pin 23
if(pins & i) *ptr = 0x90;
ptr++;
}
if(pins & PIN0) LPC_IOCON->RESET_PIO0_0 = 0x91; // special cases
if(pins & PIN10) LPC_IOCON->SWCLK_PIO0_10 = 0x91;
if(pins & PIN11) LPC_IOCON->TDI_PIO0_11 = 0x91;
if(pins & PIN12) LPC_IOCON->TMS_PIO0_12 = 0x91;
if(pins & PIN13) LPC_IOCON->TDO_PIO0_13 = 0x91;
if(pins & PIN14) LPC_IOCON->TRST_PIO0_14 = 0x91;
if(pins & PIN15) LPC_IOCON->SWDIO_PIO0_15 = 0x91;
Port0SetIn(pins); // Set the specified pins as input
}
void Port1Init(unsigned int pins) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE + 24;
for(i=0x1; i>0; i<<=1) { // Set various pins to GPIO when specified,
if(pins & i) *ptr = 0x90;
ptr++;
}
Port1SetIn(pins); // Set the specified pins as input
}
void Port0Hysteresis(unsigned int pins, unsigned char value) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE;
for(i=0x1; i>(0x1UL <<24); i<<=1) { // Set various pins to GPIO when specified, Port 0 only goes up to pin 23
if(pins & i) {
if(value) *ptr |= (0x1UL << 5);
else *ptr &= ~(0x1UL << 5);
}
ptr++;
}
}
void Port1Hysteresis(unsigned int pins, unsigned char value) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE + 24;
for(i=0x1; i>0; i<<=1) { // Set various pins to GPIO when specified,
if(pins & i) {
if(value) *ptr |= (0x1UL << 5);
else *ptr &= ~(0x1UL << 5);
}
ptr++;
}
}
void Port0Invert(unsigned int pins, unsigned char value) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE;
for(i=0x1; i>(0x1UL <<24); i<<=1) { // Set various pins to GPIO when specified, Port 0 only goes up to pin 23
if(pins & i) {
if(value) *ptr |= (0x1UL << 6);
else *ptr &= ~(0x1UL << 6);
}
ptr++;
}
}
void Port1Invert(unsigned int pins, unsigned char value) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE + 24;
for(i=0x1; i>0; i<<=1) { // Set various pins to GPIO when specified,
if(pins & i) {
if(value) *ptr |= (0x1UL << 6);
else *ptr &= ~(0x1UL << 6);
}
ptr++;
}
}
void Port0Pull(unsigned int pins, unsigned char value) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE;
for(i=0x1; i>(0x1UL <<24); i<<=1) { // Set various pins to GPIO when specified, Port 0 only goes up to pin 23
if(pins & i) {
*ptr &= ~(0x3UL << 3);
*ptr |= (value << 6);
}
ptr++;
}
}
void Port1Pull(unsigned int pins, unsigned char value) {
unsigned int i;
unsigned int * ptr;
ptr = (unsigned int *)LPC_IOCON_BASE + 24;
for(i=0x1; i>0; i<<=1) { // Set various pins to GPIO when specified,
if(pins & i) {
*ptr &= ~(0x3UL << 3);
*ptr |= (value << 6);
}
ptr++;
}
}
/*
// *** Configure interrupts on a pin (note: default state is interrupts disabled)
void Port0SetInterrupt(unsigned short pins, unsigned char mode) {
// turn on and configure interrupt for specified pins if mode isn't OFF, otherwise disable
if(mode) {
LPC_GPIO0->IE |= pins; // enable interrupts
switch(mode) {
case FALLING:
LPC_GPIO0->IS &= ~(pins); // edge or level sensitive setting
LPC_GPIO0->IBE &= ~(pins); // both or single edges setting
LPC_GPIO0->IEV &= ~(pins); // rising/falling edge or high/low level setting
break;
case RISING:
LPC_GPIO0->IS &= ~(pins);
LPC_GPIO0->IBE &= ~(pins);
LPC_GPIO0->IEV |= pins;
break;
case BOTH:
LPC_GPIO0->IS &= ~(pins);
LPC_GPIO0->IBE |= pins;
//LPC_GPIO0->IEV &= ~(pins); // doesn't matter
break;
case LOW:
LPC_GPIO0->IS |= pins;
LPC_GPIO0->IBE &= ~(pins);
LPC_GPIO0->IEV &= ~(pins);
break;
case HIGH:
LPC_GPIO0->IS |= pins;
LPC_GPIO0->IBE &= ~(pins);
LPC_GPIO0->IEV |= pins;
break;
default:
LPC_GPIO0->IE &= ~(pins);
}
}
else {
LPC_GPIO0->IE &= ~(pins);
}
// check if there are any interrupts enabled interrupts, or disable if there are none
if(LPC_GPIO0->IE & 0xfff) {
IRQClear(EINT0_IRQn);
IRQEnable(EINT0_IRQn);
IRQPriority(EINT0_IRQn, PORT0_PRIORITY);
}
else {
IRQDisable(EINT0_IRQn);
}
}
void Port1SetInterrupt(unsigned short pins, unsigned char mode) {
// turn on and configure interrupt for specified pins if mode isn't OFF, otherwise disable
if(mode) {
LPC_GPIO1->IE |= pins; // enable interrupts
switch(mode) {
case FALLING:
LPC_GPIO1->IS &= ~(pins); // edge or level sensitive setting
LPC_GPIO1->IBE &= ~(pins); // both or single edges setting
LPC_GPIO1->IEV &= ~(pins); // rising/falling edge or high/low level setting
break;
case RISING:
LPC_GPIO1->IS &= ~(pins);
LPC_GPIO1->IBE &= ~(pins);
LPC_GPIO1->IEV |= pins;
break;
case BOTH:
LPC_GPIO1->IS &= ~(pins);
LPC_GPIO1->IBE |= pins;
//LPC_GPIO1->IEV &= ~(pins); // doesn't matter
break;
case LOW:
LPC_GPIO1->IS |= pins;
LPC_GPIO1->IBE &= ~(pins);
LPC_GPIO1->IEV &= ~(pins);
break;
case HIGH:
LPC_GPIO1->IS |= pins;
LPC_GPIO1->IBE &= ~(pins);
LPC_GPIO1->IEV |= pins;
break;
default:
LPC_GPIO1->IE &= ~(pins);
}
}
else {
LPC_GPIO1->IE &= ~(pins);
}
// check if there are any interrupts enabled interrupts, or disable if there are none
if(LPC_GPIO1->IE & 0xfff) {
IRQClear(EINT1_IRQn);
IRQEnable(EINT1_IRQn);
IRQPriority(EINT1_IRQn, PORT1_PRIORITY);
}
else {
IRQDisable(EINT1_IRQn);
}
}
void Port2SetInterrupt(unsigned short pins, unsigned char mode) {
// turn on and configure interrupt for specified pins if mode isn't OFF, otherwise disable
if(mode) {
LPC_GPIO2->IE |= pins; // enable interrupts
switch(mode) {
case FALLING:
LPC_GPIO2->IS &= ~(pins); // edge or level sensitive setting
LPC_GPIO2->IBE &= ~(pins); // both or single edges setting
LPC_GPIO2->IEV &= ~(pins); // rising/falling edge or high/low level setting
break;
case RISING:
LPC_GPIO2->IS &= ~(pins);
LPC_GPIO2->IBE &= ~(pins);
LPC_GPIO2->IEV |= pins;
break;
case BOTH:
LPC_GPIO2->IS &= ~(pins);
LPC_GPIO2->IBE |= pins;
//LPC_GPIO2->IEV &= ~(pins); // doesn't matter
break;
case LOW:
LPC_GPIO2->IS |= pins;
LPC_GPIO2->IBE &= ~(pins);
LPC_GPIO2->IEV &= ~(pins);
break;
case HIGH:
LPC_GPIO2->IS |= pins;
LPC_GPIO2->IBE &= ~(pins);
LPC_GPIO2->IEV |= pins;
break;
default:
LPC_GPIO2->IE &= ~(pins);
}
}
else {
LPC_GPIO2->IE &= ~(pins);
}
// check if there are any interrupts enabled interrupts, or disable if there are none
if(LPC_GPIO2->IE & 0xfff) {
IRQClear(EINT2_IRQn);
IRQEnable(EINT2_IRQn);
IRQPriority(EINT2_IRQn, PORT2_PRIORITY);
}
else {
IRQDisable(EINT2_IRQn);
}
}
void Port3SetInterrupt(unsigned short pins, unsigned char mode) {
// turn on and configure interrupt for specified pins if mode isn't OFF, otherwise disable
if(mode) {
LPC_GPIO3->IE |= pins; // enable interrupts
switch(mode) {
case FALLING:
LPC_GPIO3->IS &= ~(pins); // edge or level sensitive setting
LPC_GPIO3->IBE &= ~(pins); // both or single edges setting
LPC_GPIO3->IEV &= ~(pins); // rising/falling edge or high/low level setting
break;
case RISING:
LPC_GPIO3->IS &= ~(pins);
LPC_GPIO3->IBE &= ~(pins);
LPC_GPIO3->IEV |= pins;
break;
case BOTH:
LPC_GPIO3->IS &= ~(pins);
LPC_GPIO3->IBE |= pins;
//LPC_GPIO3->IEV &= ~(pins); // doesn't matter
break;
case LOW:
LPC_GPIO3->IS |= pins;
LPC_GPIO3->IBE &= ~(pins);
LPC_GPIO3->IEV &= ~(pins);
break;
case HIGH:
LPC_GPIO3->IS |= pins;
LPC_GPIO3->IBE &= ~(pins);
LPC_GPIO3->IEV |= pins;
break;
default:
LPC_GPIO3->IE &= ~(pins);
}
}
else {
LPC_GPIO3->IE &= ~(pins);
}
// check if there are any interrupts enabled interrupts, or disable if there are none
if(LPC_GPIO3->IE & 0xfff) {
IRQClear(EINT3_IRQn);
IRQEnable(EINT3_IRQn);
IRQPriority(EINT3_IRQn, PORT3_PRIORITY);
}
else {
IRQDisable(EINT3_IRQn);
}
}
// *** Port nterrupt functions
void PIOINT0_IRQHandler(void) {
if(Port0Interrupt) Port0Interrupt(LPC_GPIO0->MIS); // Port-wide interrupt, passing the pins that interrupted
if(LPC_GPIO0->MIS & 0x001 && Port0Pin0Interrupt) Port0Pin0Interrupt(); // Pin-specific interrupt
if(LPC_GPIO0->MIS & 0x002 && Port0Pin1Interrupt) Port0Pin1Interrupt();
if(LPC_GPIO0->MIS & 0x004 && Port0Pin2Interrupt) Port0Pin2Interrupt();
if(LPC_GPIO0->MIS & 0x008 && Port0Pin3Interrupt) Port0Pin3Interrupt();
if(LPC_GPIO0->MIS & 0x010 && Port0Pin4Interrupt) Port0Pin4Interrupt();
if(LPC_GPIO0->MIS & 0x020 && Port0Pin5Interrupt) Port0Pin5Interrupt();
if(LPC_GPIO0->MIS & 0x040 && Port0Pin6Interrupt) Port0Pin6Interrupt();
if(LPC_GPIO0->MIS & 0x080 && Port0Pin7Interrupt) Port0Pin7Interrupt();
if(LPC_GPIO0->MIS & 0x100 && Port0Pin8Interrupt) Port0Pin8Interrupt();
if(LPC_GPIO0->MIS & 0x200 && Port0Pin9Interrupt) Port0Pin9Interrupt();
if(LPC_GPIO0->MIS & 0x400 && Port0Pin10Interrupt) Port0Pin10Interrupt();
if(LPC_GPIO0->MIS & 0x800 && Port0Pin11Interrupt) Port0Pin11Interrupt();
LPC_GPIO0->IC = LPC_GPIO0->RIS; // Clear the interrupt
}
void PIOINT1_IRQHandler(void) {
if(Port1Interrupt) Port1Interrupt(LPC_GPIO1->MIS); // Port-wide interrupt, passing the pins that interrupted
if(LPC_GPIO1->MIS & 0x001 && Port1Pin0Interrupt) Port1Pin0Interrupt(); // Pin-specific interrupt
if(LPC_GPIO1->MIS & 0x002 && Port1Pin1Interrupt) Port1Pin1Interrupt();
if(LPC_GPIO1->MIS & 0x004 && Port1Pin2Interrupt) Port1Pin2Interrupt();
if(LPC_GPIO1->MIS & 0x008 && Port1Pin3Interrupt) Port1Pin3Interrupt();
if(LPC_GPIO1->MIS & 0x010 && Port1Pin4Interrupt) Port1Pin4Interrupt();
if(LPC_GPIO1->MIS & 0x020 && Port1Pin5Interrupt) Port1Pin5Interrupt();
if(LPC_GPIO1->MIS & 0x040 && Port1Pin6Interrupt) Port1Pin6Interrupt();
if(LPC_GPIO1->MIS & 0x080 && Port1Pin7Interrupt) Port1Pin7Interrupt();
if(LPC_GPIO1->MIS & 0x100 && Port1Pin8Interrupt) Port1Pin8Interrupt();
if(LPC_GPIO1->MIS & 0x200 && Port1Pin9Interrupt) Port1Pin9Interrupt();
if(LPC_GPIO1->MIS & 0x400 && Port1Pin10Interrupt) Port1Pin10Interrupt();
if(LPC_GPIO1->MIS & 0x800 && Port1Pin11Interrupt) Port1Pin11Interrupt();
LPC_GPIO1->IC = LPC_GPIO1->RIS; // Clear the interrupt
}
void PIOINT2_IRQHandler(void) {
if(Port2Interrupt) Port2Interrupt(LPC_GPIO2->MIS); // Port-wide interrupt, passing the pins that interrupted
if(LPC_GPIO2->MIS & 0x001 && Port2Pin0Interrupt) Port2Pin0Interrupt(); // Pin-specific interrupt
if(LPC_GPIO2->MIS & 0x002 && Port2Pin1Interrupt) Port2Pin1Interrupt();
if(LPC_GPIO2->MIS & 0x004 && Port2Pin2Interrupt) Port2Pin2Interrupt();
if(LPC_GPIO2->MIS & 0x008 && Port2Pin3Interrupt) Port2Pin3Interrupt();
if(LPC_GPIO2->MIS & 0x010 && Port2Pin4Interrupt) Port2Pin4Interrupt();
if(LPC_GPIO2->MIS & 0x020 && Port2Pin5Interrupt) Port2Pin5Interrupt();
if(LPC_GPIO2->MIS & 0x040 && Port2Pin6Interrupt) Port2Pin6Interrupt();
if(LPC_GPIO2->MIS & 0x080 && Port2Pin7Interrupt) Port2Pin7Interrupt();
if(LPC_GPIO2->MIS & 0x100 && Port2Pin8Interrupt) Port2Pin8Interrupt();
if(LPC_GPIO2->MIS & 0x200 && Port2Pin9Interrupt) Port2Pin9Interrupt();
if(LPC_GPIO2->MIS & 0x400 && Port2Pin10Interrupt) Port2Pin10Interrupt();
if(LPC_GPIO2->MIS & 0x800 && Port2Pin11Interrupt) Port2Pin11Interrupt();
LPC_GPIO2->IC = LPC_GPIO2->RIS; // Clear the interrupt
}
void PIOINT3_IRQHandler(void) {
if(Port3Interrupt) Port3Interrupt(LPC_GPIO3->MIS); // Port-wide interrupt, passing the pins that interrupted
if(LPC_GPIO3->MIS & 0x001 && Port3Pin0Interrupt) Port3Pin0Interrupt(); // Pin-specific interrupt
if(LPC_GPIO3->MIS & 0x002 && Port3Pin1Interrupt) Port3Pin1Interrupt();
if(LPC_GPIO3->MIS & 0x004 && Port3Pin2Interrupt) Port3Pin2Interrupt();
if(LPC_GPIO3->MIS & 0x008 && Port3Pin3Interrupt) Port3Pin3Interrupt();
LPC_GPIO3->IC = LPC_GPIO3->RIS; // Clear the interrupt
}
*/
// ****************************************************************************
// *** UART Functions
// ****************************************************************************
#if UART_EN
void UARTInit(unsigned int baud) {
unsigned int baudval;
IRQDisable(USART_IRQn);
// Enable the pins
LPC_SYSCON->SYSAHBCLKCTRL |= (0x1UL <<12); // Enable clock to IOCON block and UART block
LPC_IOCON->PIO0_18 = 0x11; // Rx
LPC_IOCON->PIO0_19 = 0x11; // Tx
// ...and flow control if enabled
#if UART_FLOW
LPC_IOCON->PIO0_7 = 0x11; // #CTS
LPC_IOCON->PIO0_17 = 0x11; // #RTS
LPC_USART->MCR |= (0x1UL <<6) | (0x1UL <<7);
#endif
// Set clock settings
LPC_SYSCON->UARTCLKDIV = 0x01; // Clock divider at 1
LPC_USART->LCR = 0x80; // enable access to divisor (clock) latches
if(baud == AUTO) {
// In autobaud mode, wait for ascii 'A' or 'a' to be sent on the UART (don't send anything else, weirdness results
LPC_USART->ACR = 0x003; // start Autobaud
while((LPC_USART->ACR & 0x001) == 1); // wait for Autobaud to finish
}
else {
// Here are a massive list of pre-calculated fractional baud rates
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
#if UART_USE_FBR
switch(baud) { // some predefined baud rates with pre-calculated fractional baud rates
/*case 110: LPC_USART->DLM = 0x92; LPC_USART->DLL = 0x7c; LPC_USART->FDR = 0xb1; break;
case 4800: LPC_USART->DLM = 0x03; LPC_USART->DLL = 0x6b; LPC_USART->FDR = 0xe1; break;*/
case 9600: LPC_USART->DLM = 0x01; LPC_USART->DLL = 0x77; LPC_USART->FDR = 0x41; break;
/*case 14400: LPC_USART->DLM = 0; LPC_USART->DLL = 0xfa; LPC_USART->FDR = 0x41; break;
case 19200: LPC_USART->DLM = 0; LPC_USART->DLL = 0x7d; LPC_USART->FDR = 0x87; break;
case 28800: LPC_USART->DLM = 0; LPC_USART->DLL = 0x7d; LPC_USART->FDR = 0x41; break;
case 38400: LPC_USART->DLM = 0; LPC_USART->DLL = 0x4a; LPC_USART->FDR = 0xc7; break;
case 56000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x4b; LPC_USART->FDR = 0xe1; break;
case 57600: LPC_USART->DLM = 0; LPC_USART->DLL = 0x47; LPC_USART->FDR = 0xa1; break;*/
case 115200: LPC_USART->DLM = 0; LPC_USART->DLL = 0x17; LPC_USART->FDR = 0xa7; break;
/*case 128000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x1f; LPC_USART->FDR = 0xf2; break;
case 153600: LPC_USART->DLM = 0; LPC_USART->DLL = 0x17; LPC_USART->FDR = 0xb3; break;
case 230400: LPC_USART->DLM = 0; LPC_USART->DLL = 0x10; LPC_USART->FDR = 0x92; break;
case 256000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x10; LPC_USART->FDR = 0xa1; break;
case 460800: LPC_USART->DLM = 0; LPC_USART->DLL = 0x8; LPC_USART->FDR = 0x92; break;
case 921600: LPC_USART->DLM = 0; LPC_USART->DLL = 0x4; LPC_USART->FDR = 0x92; break;
case 1000000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x4; LPC_USART->FDR = 0x81; break;
case 2000000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x2; LPC_USART->FDR = 0x81; break;
case 3000000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x1; LPC_USART->FDR = 0x21; break;
case 4000000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x1; LPC_USART->FDR = 0x81; break;*/
default:
LPC_USART->FDR = 0x10;
baudval = 4500000/baud; // baud rate
if(baudval > 0xffff) baudval = 0xffff;
else if(baudval == 0) baudval = 1;
LPC_USART->DLM = (baudval >> 8) & 0xff;
LPC_USART->DLL = baudval & 0xff;
}
#else
baudval = 4500000/baud; // baud rate
if(baudval > 0xffff) baudval = 0xffff;
else if(baudval == 0) baudval = 1;
LPC_USART->DLM = (baudval >> 8) & 0xff;
LPC_USART->DLL = baudval & 0xff;
#endif
}
else {
// assume 12MHz operation
#if UART_USE_FBR
switch(baud) { // some predefined baud rates with pre-calculated fractional baud rates
/*case 110: LPC_USART->DLM = 0x18; LPC_USART->DLL = 0x6a; LPC_USART->FDR = 0xb1; break;
case 2400: LPC_USART->DLM = 0; LPC_USART->DLL = 0xfa; LPC_USART->FDR = 0x41; break;
case 4800: LPC_USART->DLM = 0; LPC_USART->DLL = 0x7d; LPC_USART->FDR = 0x41; break;
case 9600: LPC_USART->DLM = 0; LPC_USART->DLL = 0x47; LPC_USART->FDR = 0xa1; break;
case 14400: LPC_USART->DLM = 0; LPC_USART->DLL = 0x1b; LPC_USART->FDR = 0xed; break;
case 19200: LPC_USART->DLM = 0; LPC_USART->DLL = 0x17; LPC_USART->FDR = 0xa7; break;
case 28800: LPC_USART->DLM = 0; LPC_USART->DLL = 0x17; LPC_USART->FDR = 0xf2; break;
case 38400: LPC_USART->DLM = 0; LPC_USART->DLL = 0x10; LPC_USART->FDR = 0x92; break;
case 56000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x7; LPC_USART->FDR = 0xcb; break;
case 57600: LPC_USART->DLM = 0; LPC_USART->DLL = 0xd; LPC_USART->FDR = 0x10; break;
case 115200: LPC_USART->DLM = 0; LPC_USART->DLL = 0x6; LPC_USART->FDR = 0xc1; break;
case 128000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x4; LPC_USART->FDR = 0xf7; break;
case 153600: LPC_USART->DLM = 0; LPC_USART->DLL = 0x4; LPC_USART->FDR = 0x92; break;
case 230400: LPC_USART->DLM = 0; LPC_USART->DLL = 0x3; LPC_USART->FDR = 0xc1; break;
case 256000: LPC_USART->DLM = 0; LPC_USART->DLL = 0x2; LPC_USART->FDR = 0xf7; break;
case 460800: LPC_USART->DLM = 0; LPC_USART->DLL = 0x1; LPC_USART->FDR = 0x85; break;*/
default:
LPC_USART->FDR = 0x10;
baudval = 750000/baud; // baud rate
if(baudval > 0xffff) baudval = 0xffff;
else if(baudval == 0) baudval = 1;
LPC_USART->DLM = (baudval >> 8) & 0xff;
LPC_USART->DLL = baudval & 0xff;
}
#else
baudval = 750000/baud; // baud rate
if(baudval > 0xffff) baudval = 0xffff;
else if(baudval == 0) baudval = 1;
LPC_USART->DLM = (baudval >> 8) & 0xff;
LPC_USART->DLL = baudval & 0xff;
#endif
}
}
// Data format
LPC_USART->LCR = ((UART_PARITY & 0x3) << 4) | ((UART_PARITY_EN & 0x1) << 3) | ((UART_STOP_BITS & 0x1) << 2) | (UART_BIT_LENGTH & 0x3); // disable access to divisor latches, and set data format
// Set interrupt stuff
LPC_USART->IER = 0x05; // Enable UART receive interrupt and line interrupt
#if UART_USE_OUTBUFFER
LPC_USART->IER |= 0x02; // Enables the THRE interrupt
FUNCUARTBufferPush = 0;
FUNCUARTBufferPop = 0;
// FIFO needs at least two characters to get out of an "initialisation" condition.
// nothing gets sent because the TXEN is disabled and then the FIFO is cleared afterwards
LPC_USART->TER = 0;
LPC_USART->THR = 0x00;
LPC_USART->THR = 0x00;
#endif
// Flush any residual data and clear FIFO
LPC_USART->FCR = 0x06; // Reset buffers
LPC_USART->FCR = (UART_FIFO_LEVEL & 0x3) << 6 | 0x01; // set RX FIFO interrupt levels, and enable FIFOs.
LPC_USART->SCR = LPC_USART->LSR;
while (LPC_USART->LSR & 0x01) LPC_USART->SCR = LPC_USART->RBR; // Dump any data
LPC_USART->TER = 0x80;
IRQClear(USART_IRQn);
IRQPriority(USART_IRQn, UART_PRIORITY);
IRQEnable(USART_IRQn);
#if UART_USE_OUTBUFFER
// this is a workaround for the above mentioned FIFO two character thing
LPC_USART->TER = 0;
LPC_USART->THR = 0x00;
LPC_USART->THR = 0x00;
LPC_USART->FCR = 0x06; // Reset buffers
LPC_USART->FCR = (UART_FIFO_LEVEL & 0x3) << 6 | 0x01; // set RX FIFO interrupt levels, and enable FIFOs.
LPC_USART->TER = 0x80;
#endif
}
void UARTStop(void) {
LPC_USART->IER = 0;
IRQDisable(USART_IRQn);
LPC_SYSCON->SYSAHBCLKCTRL &= ~(0x1UL << 12); // Disable clock to UART block
}
void UARTWriteByte(unsigned char data) {
#if UART_USE_OUTBUFFER
while(UARTBufferWritable() == 0);
UARTBufferPush(data);
#else
//LPC_USART->IER &= ~0x001; // Disable receive interrupt while transmitting (causes problems in loop-back mode)
while ((LPC_USART->LSR & 0x20) == 0);
LPC_USART->THR = data;
//LPC_USART->IER |= 0x001; // Re-enable receive interrupt
#endif
}
void UARTWrite(unsigned char * data, unsigned int length) {
#if UART_USE_OUTBUFFER
while(length > 0) {
while(UARTBufferWritable() == 0);
UARTBufferPush(data[0]);
length--;
data++;
}
#else
unsigned int i;
//LPC_USART->IER &= ~0x001; // Disable receive interrupt while transmitting (causes problems in loop-back mode)
for(i=0; i<length; i++) {
while ((LPC_USART->LSR & 0x20) == 0);
LPC_USART->THR = data[i];
}
//LPC_USART->IER |= 0x001; // Re-enable receive interrupt
#endif
}
unsigned char UARTReadByte(void) {
#if UART_MODE
unsigned char lsr, byte;
// In interrupt mode, running this function triggers the user-supplied interrupt code and returns zero
if(UARTInterrupt) {
while(LPC_USART->LSR & 0x01) {
lsr = LPC_USART->LSR;
byte = LPC_USART->RBR;
if((lsr & 0x04) && UARTParityError) UARTParityError(byte);
else UARTInterrupt(byte);
}
}
return 0;
#else
// Otherwise grab what data is available
return LPC_USART->RBR;
#endif
}
#if UART_USE_OUTBUFFER
unsigned char FUNCUARTBuffer[UART_BUFFER_SIZE];
volatile unsigned short FUNCUARTBufferPush, FUNCUARTBufferPop;
unsigned short UARTBufferWritable(void) {
if(FUNCUARTBufferPush+1 == FUNCUARTBufferPop || (FUNCUARTBufferPush == (UART_BUFFER_SIZE-1) && FUNCUARTBufferPop == 0)) return 0;
else return 1;
}
unsigned short UARTBufferReadable(void) {
if(FUNCUARTBufferPush == FUNCUARTBufferPop) return 0;
else return 1;
}
unsigned char UARTBufferPop(void) {
unsigned char retval;
retval = FUNCUARTBuffer[FUNCUARTBufferPop++];
if(FUNCUARTBufferPop >= UART_BUFFER_SIZE) FUNCUARTBufferPop = 0;
return retval;
}
void UARTBufferPush(unsigned char data) {
FUNCUARTBuffer[FUNCUARTBufferPush++] = data;
LPC_USART->IER |= 0x02;
if(FUNCUARTBufferPush >= UART_BUFFER_SIZE) FUNCUARTBufferPush = 0;
}
#endif
void USART_IRQHandler(void) {
unsigned char byte = 0;
unsigned char iir, lsr;
VCOM_DATA_T* pVcom = &g_vCOM;
unsigned short serial_state = 0;
iir = (LPC_USART->IIR >> 1) & 0x07; // interrupt identification register
switch(iir) {
case 0x3: // 1 - Receive Line Status (RLS)
if(VCOM_isbridge) {
lsr = LPC_USART->LSR;
/* There are errors or break interrupt update serial_state */
if (lsr & 0x02) serial_state |= CDC_SERIAL_STATE_OVERRUN;
if (lsr & 0x04) serial_state |= CDC_SERIAL_STATE_PARITY;
if (lsr & 0x08) serial_state |= CDC_SERIAL_STATE_FRAMING;
if (lsr & 0x10) serial_state |= CDC_SERIAL_STATE_BREAK;
USBROM->cdc->SendNotification(pVcom->hCdc, CDC_NOTIFICATION_SERIAL_STATE, serial_state);
}
else {
lsr = LPC_USART->LSR;
if(lsr & 0x1) {
while(LPC_USART->LSR & 0x01) {
lsr = LPC_USART->LSR;
byte = LPC_USART->RBR;
if((lsr & 0x04) && UARTParityError) UARTParityError(byte);
else UARTInterrupt(byte);
}
}
if(lsr & 0x9c) {
while(LPC_USART->LSR & 0x01) {
byte = LPC_USART->RBR;
}
}
}
break;
case 0x2: // 2a - Receive Data Available (RDA)
if(VCOM_isbridge) {
#if CDC_USE_PLED
LEDOn(PLED);
#endif
VCOM_uart_read(pVcom);
}
else {
while(LPC_USART->LSR & 0x01) {
lsr = LPC_USART->LSR;
byte = LPC_USART->RBR;
if((lsr & 0x04) && UARTParityError) UARTParityError(byte);
else UARTInterrupt(byte);
}
}
break;
case 0x6: // 2b - Character Time-out indicator (CTI)
if(VCOM_isbridge) {
#if CDC_USE_PLED
LEDOn(PLED);
#endif
VCOM_uart_read(pVcom);
}
break;
case 0x1: // 3 - THRE interrupt
//lsr = LPC_USART->LSR;
if(VCOM_isbridge) {
if (pVcom->rxlen) {
#if CDC_USE_PLED
LEDOn(PLED);
#endif
VCOM_uart_write(pVcom);
}
}
#if UART_USE_OUTBUFFER
else {
byte = 16;
while(byte-- > 0) {
if(UARTBufferReadable()) {
LPC_USART->THR = UARTBufferPop();
}
else {
LPC_USART->IER &= ~(0x0002); // Disable the THRE interrupt
break;
}
}
}
#endif
break;
case 0x0: // 4 - Modem interrupt
break;
}
}
#endif
// ****************************************************************************
// *** I2C Functions
// ****************************************************************************
#if I2C_EN
volatile unsigned char FUNCI2CMasterState, FUNCI2CMasterState2, FUNCI2CSlaveState, FUNCI2CSlaveState2, FUNCI2CSlaveMode;
volatile unsigned int FUNCI2CRdLength, FUNCI2CWrLength;
volatile unsigned int FUNCI2CRdIndex, FUNCI2CWrIndex;
unsigned char FUNCI2CBuffer[I2C_DATA_SIZE];
// ******* Initialisation, set speed (in kHz)
void I2CInit(unsigned short speed) {
unsigned int i;
for(i=0; i<I2C_DATA_SIZE; i++) {
FUNCI2CBuffer[i] = 0;
}
FUNCI2CSlaveMode = 0;
if(speed == SLAVE) {
FUNCI2CSlaveMode = 1;
}
FUNCI2CMasterState=I2C_IDLE;
FUNCI2CSlaveState=I2C_IDLE;
FUNCI2CRdLength=0;
FUNCI2CWrLength=0;
FUNCI2CRdIndex=0;
FUNCI2CWrIndex=0;
LPC_SYSCON->SYSAHBCLKCTRL |= (0x1UL << 5); // Enable clock to I2C
LPC_IOCON->PIO0_4 = 0x01; // Set up pins PIO0_4 and PIO0_5 for I2C
LPC_IOCON->PIO0_5 = 0x01;
#if I2C_FASTMODE_PLUS
// if speed is greater than 400k, set to Fast-mode Plus
LPC_IOCON->PIO0_4 |= (0x1UL << 9);
LPC_IOCON->PIO0_5 |= (0x1UL << 9);
#endif
LPC_SYSCON->PRESETCTRL |= (0x1UL << 1); // I2C reset de-asserted
LPC_I2C->CONCLR = I2C_AA | I2C_SI | I2C_STA | I2C_ENA; // Clear status fags
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
LPC_I2C->SCLL = (36000 / speed) & 0xffff; // Set speed
LPC_I2C->SCLH = (36000 / speed) & 0xffff;
}
else {
// assume 12MHz operation
LPC_I2C->SCLL = (6000 / speed) & 0xffff; // Set speed
LPC_I2C->SCLH = (6000 / speed) & 0xffff;
}
if(FUNCI2CSlaveMode == 1) {
// set slave mode (I2C_MODE = 1)
LPC_I2C->ADR0 = I2C_SLAVE_ADR0; // slave mode addresses
LPC_I2C->ADR1 = I2C_SLAVE_ADR1;
LPC_I2C->ADR2 = I2C_SLAVE_ADR2;
LPC_I2C->ADR3 = I2C_SLAVE_ADR3;
}
IRQClear(I2C_IRQn);
IRQPriority(I2C_IRQn, I2C_PRIORITY);
IRQEnable(I2C_IRQn);
LPC_I2C->CONSET = I2C_ENA | I2C_SI;
}
void I2CStop(void) {
IRQDisable(I2C_IRQn);
LPC_SYSCON->PRESETCTRL &= ~(0x1UL << 1); // I2C reset asserted
LPC_SYSCON->SYSAHBCLKCTRL &= ~(0x1UL << 5); // Disable clock to I2C
}
// ****** The I2C Engine, does the I2C stuff
unsigned int I2CMaster(unsigned char * wrData, unsigned int wrLength, unsigned char * rdData, unsigned char rdLength) {
unsigned int timeout = 0, i;
FUNCI2CMasterState = I2C_IDLE;
FUNCI2CMasterState2 = I2C_IDLE;
FUNCI2CRdIndex = 0;
FUNCI2CWrIndex = 0;
FUNCI2CRdLength = rdLength;
FUNCI2CWrLength = wrLength;
if(rdLength > 0) wrLength++;
for(i=0;i<wrLength; i++) {
FUNCI2CBuffer[i] = wrData[i];
}
LPC_I2C->CONSET = I2C_STA; // set start condition
while(1) {
// loop until start condition transmit detected or timeout and send stop
if (FUNCI2CMasterState == I2C_STARTED) {
while (1) {
// once start state is transmitted, loop until NACK state then send stop
if (FUNCI2CMasterState2 == I2C_NACK){
LPC_I2C->CONSET = I2C_STO; // set stop condition
LPC_I2C->CONCLR = I2C_SI; // clear interrupt flag
timeout = 0;
while((LPC_I2C->CONSET & I2C_STO) && (timeout++ < I2C_TIMEOUT)); // wait until a stop condition
break;
}
}
break;
}
if (timeout++ > I2C_TIMEOUT) {
// timeout, send stop
LPC_I2C->CONSET = I2C_STO; // set stop condition
LPC_I2C->CONCLR = I2C_SI; // clear interrupt flag
timeout = 0;
while((LPC_I2C->CONSET & I2C_STO) && (timeout++ < I2C_TIMEOUT)); // wait until a stop condition
break;
}
}
for(i=0;i<rdLength; i++) {
rdData[i] = FUNCI2CBuffer[i];
}
return FUNCI2CRdIndex;
}
// ****** Interrupt handler - I2C state is implemented using interrupts
void I2C_IRQHandler(void) {
unsigned char state;
state = LPC_I2C->STAT & 0xff;
if(FUNCI2CSlaveMode == 0) {
switch (state) {
case 0x08: // A START condition has been transmitted
FUNCI2CWrIndex = 0;
LPC_I2C->DAT = FUNCI2CBuffer[FUNCI2CWrIndex++];
LPC_I2C->CONCLR = I2C_STA;
FUNCI2CMasterState = I2C_STARTED;
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x10: // A Repeated START condition has been transmitted
FUNCI2CRdIndex = 0;
LPC_I2C->DAT = FUNCI2CBuffer[FUNCI2CWrIndex++];
LPC_I2C->CONCLR = I2C_STA;
FUNCI2CMasterState = I2C_RESTARTED;
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x18: // SLA+W has been transmitted; ACK has been received
if (FUNCI2CMasterState == I2C_STARTED) {
LPC_I2C->DAT = FUNCI2CBuffer[FUNCI2CWrIndex++];
FUNCI2CMasterState = I2C_ACK;
}
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x20: // SLA+W has not been transmitted; NOT ACK has been received
FUNCI2CMasterState = I2C_NACK;
FUNCI2CMasterState2 = I2C_NACK;
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x28: // Data byte in I2DAT has been transmitted; ACK has been received
if (FUNCI2CWrIndex < FUNCI2CWrLength) {
LPC_I2C->DAT = FUNCI2CBuffer[FUNCI2CWrIndex++];
FUNCI2CMasterState = I2C_ACK;
}
else {
if (FUNCI2CRdLength > 0) {
LPC_I2C->CONSET = I2C_STA;
FUNCI2CMasterState = I2C_REPEATED_START;
}
else {
FUNCI2CMasterState = I2C_ACK;
FUNCI2CMasterState2 = I2C_NACK; // very very dirty hax, I2CMasterState used for ACK polling in EEPROM while I2CMasterState2 used for end of I2C operation detection!
LPC_I2C->CONSET = I2C_STO;
}
}
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x30: // Data byte in I2DAT has been transmitted; NOT ACK has been received
FUNCI2CMasterState = I2C_NACK;
FUNCI2CMasterState2 = I2C_NACK;
LPC_I2C->CONSET = I2C_STO;
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x38: // Arbitration lost
FUNCI2CMasterState = I2C_ERROR;
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x40: // SLA+R has been trnasmitted; ACK has been received
if (FUNCI2CRdLength == 1) {
LPC_I2C->CONCLR = I2C_AA;
}
else {
LPC_I2C->CONSET = I2C_AA;
}
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x48: // SLA+R has not been transmitted; NOT ACK has been received
FUNCI2CMasterState = I2C_NACK;
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x50: // Data byte has been receievd; ACK has been returned
FUNCI2CBuffer[FUNCI2CRdIndex++] = LPC_I2C->DAT;
if (FUNCI2CRdIndex + 1 < FUNCI2CRdLength) {
FUNCI2CMasterState = I2C_ACK;
LPC_I2C->CONSET = I2C_AA;
}
else {
FUNCI2CMasterState = I2C_NACK;
LPC_I2C->CONCLR = I2C_AA;
}
LPC_I2C->CONCLR = I2C_SI;
break;
case 0x58: // Data byte has been received; NOT ACK has been returned
FUNCI2CBuffer[FUNCI2CRdIndex++] = LPC_I2C->DAT;
FUNCI2CMasterState = I2C_NACK;
FUNCI2CMasterState2 = I2C_NACK; // hax is needed (I2CMasterState changes too quickly to register in I2CEngine()
LPC_I2C->CONSET = I2C_STO;
LPC_I2C->CONCLR = I2C_SI;
break;
default:
LPC_I2C->CONCLR = I2C_SI;
break;
}
}
#if I2C_SLAVE_EN
else if(FUNCI2CSlaveMode == 1) {
switch (state) {
case 0x60: // Own SLA+W has been received; ACK has been returned
case 0x68: // Arbitration lost in SLA+R/W as master; Own SLA+W has been received, ACK returned
FUNCI2CWrIndex = 0;
FUNCI2CRdIndex = 0;
LPC_I2C->CONSET = I2C_AA;
LPC_I2C->CONCLR = I2C_SI;
FUNCI2CSlaveState = I2C_WR_STARTED;
FUNCI2CSlaveState2 = I2C_WR_STARTED;
break;
case 0x70: // General call address (0x00) has been received; ACK has been returned
case 0x78: // Arbitration lost in SLA+R/W as master; General call address has been received, ACK has been returned
FUNCI2CWrIndex = 0;
FUNCI2CRdIndex = 0;
LPC_I2C->CONSET = I2C_AA;
LPC_I2C->CONCLR = I2C_SI;
FUNCI2CSlaveState = I2C_GEN_STARTED;
FUNCI2CSlaveState2 = I2C_GEN_STARTED;
break;
case 0x80: // Previously addressed with own SLV address; DATA has been received, ACK has been returned
case 0x90: // Previously addressed with General Call; DATA byte has been received; ACK has been returned
if (FUNCI2CSlaveState == I2C_WR_STARTED) {
FUNCI2CBuffer[FUNCI2CWrIndex++] = LPC_I2C->DAT;
LPC_I2C->CONSET = I2C_AA;
}
else {
LPC_I2C->CONCLR = I2C_AA;
}
LPC_I2C->CONCLR = I2C_SI;
break;
case 0xA8: // Own SLA+R has been received; ACK has been returned
case 0xB0: // Arbitration lost in SLA+R/W as master; Own SLA+R has been received, ACK has been returned
FUNCI2CRdIndex = 0;
LPC_I2C->CONSET = I2C_AA;
LPC_I2C->CONCLR = I2C_SI;
LPC_I2C->DAT = FUNCI2CBuffer[FUNCI2CRdIndex++];
FUNCI2CSlaveState = I2C_RD_STARTED;
FUNCI2CSlaveState2 = I2C_RD_STARTED;
break;
case 0xB8: // Data byte in I2DAT has been transmitted; ACK has been received
case 0xC8: // Data byte in I2DAT has been transmitted; NOT ACK has been received.
if (FUNCI2CSlaveState == I2C_RD_STARTED) {
LPC_I2C->DAT = FUNCI2CBuffer[FUNCI2CRdIndex++];
LPC_I2C->CONSET = I2C_AA;
}
else {
LPC_I2C->CONCLR = I2C_AA;
}
LPC_I2C->CONCLR = I2C_SI;
break;
case 0xC0: // Data byte in I2DAT has been transmitted; NOT ACK has been received
LPC_I2C->CONSET = I2C_AA;
LPC_I2C->CONCLR = I2C_SI;
FUNCI2CSlaveState = I2C_NACK;
break;
case 0xA0: // A STOP condition or Repeated START condition has been received while still addressed as SLV/REC or SLV/TRX
LPC_I2C->CONSET = I2C_AA;
LPC_I2C->CONCLR = I2C_SI;
FUNCI2CSlaveState = I2C_IDLE;
if(I2CInterrupt) I2CInterrupt(FUNCI2CBuffer, FUNCI2CWrIndex);
break;
default:
LPC_I2C->CONCLR = I2C_SI;
LPC_I2C->CONSET = I2C_ENA | I2C_SI;
break;
}
}
#endif
}
#endif
// ****************************************************************************
// *** SSP Functions
// ****************************************************************************
#if SSP0_EN
void SSP0Init(unsigned short speed) {
unsigned char i;
unsigned short dummy=dummy;
LPC_SYSCON->PRESETCTRL &= ~0x1;
LPC_SYSCON->PRESETCTRL |= 0x1; // deassert reset on SSP
// Set up pins
LPC_SYSCON->SYSAHBCLKCTRL |= (0x1UL << 11);
LPC_IOCON->PIO0_8 = 0x01;
LPC_IOCON->PIO0_9 = 0x01;
LPC_IOCON->SWCLK_PIO0_10 = 0x02;
#if SSP0_SSEL == 2
LPC_IOCON->PIO0_2 = 0x01; // enable SSEL if used
#elif SSP0_SSEL == 1
Port0Init(PIN2);
Port0SetOut(PIN2);
SSP0S0CLR();
#endif
// SSP config
LPC_SSP0->CR0 = ((SSP0_CLK_PHA & 0x1) << 6) | ((SSP0_CLK_POL & 0x1) << 6) | ((SSP0_FORMAT & 0x3) << 4) | ((SSP0_SIZE - 1) & 0xf);
LPC_SYSCON->SSP0CLKDIV = 1;
for(i=0; i<16; i++ ) dummy = LPC_SSP0->DR; // Clear out FIFO buffer
// set mode
if(speed) { // master mode
SSP0SetSpeed(speed);
LPC_SSP0->CR1 = 0; // Clear CR1 (and set master mode)
LPC_SSP0->CR1 |= 0x1 << 1; // Enable SSP
}
else { // slave mode
LPC_IOCON->PIO0_2 = 0x01; // enable SSEL always for slave mode
#if SSP0_INT_LEVEL == 0
LPC_SSP0->IMSC = 0x6;
#else
LPC_SSP0->IMSC = 0x4; // enable interrupt on RX FIFO half-full.
#endif
LPC_SSP0->CR1 = 0; // Clear CR1
LPC_SSP0->CR1 = 0x4; // Select slave mode
LPC_SSP0->CR1 |= 0x1 << 1; // Enable SSP
IRQClear(SSP0_IRQn);
IRQPriority(SSP0_IRQn, SSP0_PRIORITY);
IRQEnable(SSP0_IRQn);
}
}
void SSP0Stop(void) {
IRQDisable(SSP0_IRQn);
LPC_SSP0->CR1 &= ~(0x1 << 1); // Disable SSP
LPC_SYSCON->PRESETCTRL &= ~0x1; // Assert SSP reset
}
void SSP0SetSpeed(unsigned short speed) {
unsigned int scale;
if(speed == 0) speed = 1; // avoid divide by zero
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
scale = (72000 + (speed/2))/speed; // 72000/speed but hax to round up using integer mathematics
}
else {
// assume 12MHz operation
scale = (12000 + (speed/2))/speed;
}
// work out ssp scale clock
if(scale > 254) scale = 254;
else if(scale < 2) scale = 2;
LPC_SSP0->CPSR = scale & 0xfe;
}
void SSP0WriteByte(unsigned short data) {
unsigned short dummy=dummy;
while ((LPC_SSP0->SR & 0x02) == 0);
LPC_SSP0->DR = data;
while ((LPC_SSP0->SR & 0x14) != 0x04);
dummy = LPC_SSP0->DR;
}
void SSP0Write(unsigned short * data, unsigned int length) {
unsigned int i;
for(i=0; i<length; i++) {
SSP0WriteByte(data[i]);
}
}
unsigned short SSP0ReadByte(void) {
while ((LPC_SSP0->SR & 0x02) == 0);
LPC_SSP0->DR = 0xffff;
while ((LPC_SSP0->SR & 0x14) != 0x04);
return (LPC_SSP0->DR);
}
unsigned short SSP0Byte(unsigned short data) {
while((LPC_SSP0->SR & 0x02) == 0);
LPC_SSP0->DR = data;
while ((LPC_SSP0->SR & 0x14) != 0x04);
return (LPC_SSP0->DR);
}
void SSP0NextByte(unsigned short data) {
while((LPC_SSP0->SR & 0x02) == 0);
LPC_SSP0->DR = data;
}
void SSP0_IRQHandler(void) {
while(LPC_SSP0->SR & 0x4) {// Receive FIFO Not Empty
if(SSP0Interrupt) SSP0Interrupt(LPC_SSP0->DR);
}
LPC_SSP0->ICR = 0x3;
}
#endif
#if SSP1_EN
void SSP1Init(unsigned short speed) {
unsigned char i;
unsigned short dummy=dummy;
LPC_SYSCON->PRESETCTRL &= ~0x4;
LPC_SYSCON->PRESETCTRL |= 0x4; // deassert reset on SSP
// Set up pins
LPC_SYSCON->SYSAHBCLKCTRL |= (0x1UL << 18);
LPC_IOCON->PIO0_21 = 0x02;
LPC_IOCON->PIO0_22 = 0x83;
LPC_IOCON->PIO1_15 = 0x03;
#if SSP1_SSEL == 2
LPC_IOCON->PIO1_19 = 0x02; // enable SSEL if used
Port0Init(PIN12); // enable pin on 0_12 (SSEL1)
Port0SetOut(PIN12);
SSP1S1CLR();
#elif SSP1_SSEL == 1
Port1Init(PIN19);
Port1SetOut(PIN19);
SSP1S0CLR();
Port0Init(PIN12);
Port0SetOut(PIN12);
SSP1S1CLR();
#endif
// SSP config
LPC_SSP1->CR0 = ((SSP1_CLK_PHA & 0x1) << 6) | ((SSP1_CLK_POL & 0x1) << 6) | ((SSP1_FORMAT & 0x3) << 4) | ((SSP1_SIZE - 1) & 0xf);
LPC_SYSCON->SSP1CLKDIV = 1;
for(i=0; i<16; i++ ) dummy = LPC_SSP1->DR; // Clear out FIFO buffer
// set mode
if(speed) { // master mode
SSP1SetSpeed(speed);
LPC_SSP1->CR1 = 0; // Clear CR1 (and set master mode)
LPC_SSP1->CR1 |= 0x1 << 1; // Enable SSP
}
else {
#if SSP1_INT_LEVEL == 0
LPC_SSP1->IMSC = 0x6;
#else
LPC_SSP1->IMSC = 0x4; // enable interrupt on RX FIFO half-full.
#endif
LPC_SSP1->CR1 = 0; // Clear CR1
LPC_SSP1->CR1 = 0x4; // Select slave mode
LPC_SSP1->CR1 |= 0x1 << 1; // Enable SSP
IRQClear(SSP1_IRQn);
IRQPriority(SSP1_IRQn, SSP1_PRIORITY);
IRQEnable(SSP1_IRQn);
}
}
void SSP1Stop(void) {
IRQDisable(SSP1_IRQn);
LPC_SSP1->CR1 &= ~(0x1 << 1); // Disable SSP
LPC_SYSCON->PRESETCTRL &= ~0x4; // Assert SSP reset
}
void SSP1SetSpeed(unsigned short speed) {
unsigned int scale;
if(speed == 0) speed = 1; // avoid divide by zero
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
scale = (72000 + (speed/2))/speed; // 72000/speed but hax to round up using integer mathematics
}
else {
// assume 12MHz operation
scale = (12000 + (speed/2))/speed;
}
// work out ssp scale clock
if(scale > 254) scale = 254;
else if(scale < 2) scale = 2;
LPC_SSP1->CPSR = scale & 0xfe;
}
void SSP1WriteByte(unsigned short data) {
unsigned short dummy=dummy;
while ((LPC_SSP1->SR & 0x02) == 0);
LPC_SSP1->DR = data;
//while ((LPC_SSP1->SR & 0x14) != 0x04);
while ((LPC_SSP1->SR & 0x10));
dummy = LPC_SSP1->DR;
}
void SSP1Write(unsigned short * data, unsigned int length) {
unsigned int i;
for(i=0; i<length; i++) {
SSP1WriteByte(data[i]);
}
}
unsigned short SSP1ReadByte(void) {
while ((LPC_SSP1->SR & 0x02) == 0);
LPC_SSP1->DR = 0xffff;
while ((LPC_SSP1->SR & 0x14) != 0x04);
return (LPC_SSP1->DR);
}
unsigned short SSP1Byte(unsigned short data) {
while ((LPC_SSP1->SR & 0x02) == 0);
LPC_SSP1->DR = data;
while ((LPC_SSP1->SR & 0x14) != 0x04);
return (LPC_SSP1->DR);
}
void SSP1NextByte(unsigned short data) {
while ((LPC_SSP1->SR & 0x02) == 0);
LPC_SSP1->DR = data;
}
void SSP1_IRQHandler(void) {
while(LPC_SSP1->SR & 0x4) {// Receive FIFO Not Empty
if(SSP1Interrupt) SSP1Interrupt(LPC_SSP1->DR);
}
LPC_SSP1->ICR = 0x3;
}
#endif
// ****************************************************************************
// *** Timers Functions
// ****************************************************************************
void Timer0Init(unsigned short prescale) {
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<7;
LPC_CT16B0->PR = prescale;
LPC_CT16B0->MCR = 0;
LPC_CT16B0->CCR = 0;
LPC_CT16B0->EMR = 0;
LPC_CT16B0->CTCR = 0;
LPC_CT16B0->PWMC = 0;
LPC_CT16B0->TCR = 1;
IRQClear(CT16B0_IRQn);
IRQPriority(CT16B0_IRQn, TIMER0_PRIORITY);
IRQEnable(CT16B0_IRQn);
}
void Timer1Init(unsigned short prescale) {
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<8;
LPC_CT16B1->PR = prescale;
LPC_CT16B1->MCR = 0;
LPC_CT16B1->CCR = 0;
LPC_CT16B1->EMR = 0;
LPC_CT16B1->CTCR = 0;
LPC_CT16B1->PWMC = 0;
LPC_CT16B1->TCR = 1;
IRQClear(CT16B1_IRQn);
IRQPriority(CT16B1_IRQn, TIMER1_PRIORITY);
IRQEnable(CT16B1_IRQn);
}
void Timer2Init(unsigned int prescale) {
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<9;
LPC_CT32B0->PR = prescale;
LPC_CT32B0->MCR = 0;
LPC_CT32B0->CCR = 0;
LPC_CT32B0->EMR = 0;
LPC_CT32B0->CTCR = 0;
LPC_CT32B0->PWMC = 0;
LPC_CT32B0->TCR = 1;
IRQClear(CT32B0_IRQn);
IRQPriority(CT32B0_IRQn, TIMER2_PRIORITY);
IRQEnable(CT32B0_IRQn);
}
void Timer3Init(unsigned int prescale) {
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<10;
LPC_CT32B1->PR = prescale;
LPC_CT32B1->MCR = 0;
LPC_CT32B1->CCR = 0;
LPC_CT32B1->EMR = 0;
LPC_CT32B1->CTCR = 0;
LPC_CT32B1->PWMC = 0;
LPC_CT32B1->TCR = 1;
IRQClear(CT32B1_IRQn);
IRQPriority(CT32B1_IRQn, TIMER3_PRIORITY);
IRQEnable(CT32B1_IRQn);
}
void Timer0Stop(void) {
LPC_CT16B0->TCR = 0x2;
IRQDisable(CT16B0_IRQn);
LPC_SYSCON->SYSAHBCLKCTRL &= ~(0x1UL <<7);
LPC_CT16B0->TCR = 0x0;
}
void Timer1Stop(void) {
LPC_CT16B1->TCR = 0x2;
IRQDisable(CT16B1_IRQn);
LPC_SYSCON->SYSAHBCLKCTRL &= ~(0x1UL <<8);
LPC_CT16B1->TCR = 0x0;
}
void Timer2Stop(void) {
LPC_CT32B0->TCR = 0x2;
IRQDisable(CT32B0_IRQn);
LPC_SYSCON->SYSAHBCLKCTRL &= ~(0x1UL <<9);
LPC_CT32B0->TCR = 0x0;
}
void Timer3Stop(void) {
LPC_CT32B1->TCR = 0x2;
IRQDisable(CT32B1_IRQn);
LPC_SYSCON->SYSAHBCLKCTRL &= ~(0x1UL <<10);
LPC_CT32B1->TCR = 0x0;
}
void Timer0Match0(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B0->MR0 = interval;
LPC_CT16B0->MCR &= ~0x7;
LPC_CT16B0->EMR &= ~0x30;
LPC_CT16B0->PWMC &= ~0x1;
LPC_CT16B0->MCR |= (mode & 0x7);
if(mode & OUTPUTTOGGLE) {
LPC_CT16B0->EMR |= (mode & 0x30);
LPC_IOCON->PIO0_8 = 0x02;
if(mode & OUTPUTLOW) LPC_CT16B0->EMR |= 1;
else if(mode & OUTPUTHIGH) LPC_CT16B0->EMR &= ~1;
}
if(mode & PWM) LPC_CT16B0->PWMC |= 0x1;
}
void Timer0Match1(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B0->MR1 = interval;
LPC_CT16B0->MCR &= ~(0x7 << 3);
LPC_CT16B0->EMR &= ~(0x30 << 2);
LPC_CT16B0->PWMC &= ~(0x1 << 1);
LPC_CT16B0->MCR |= (mode & 0x7) << 3;
if(mode & OUTPUTTOGGLE) {
LPC_CT16B0->EMR |= (mode & 0x30) << 2;
LPC_IOCON->PIO0_9 = 0x02;
if(mode & OUTPUTLOW) LPC_CT16B0->EMR |= 1<<1;
else if(mode & OUTPUTHIGH) LPC_CT16B0->EMR &= ~(0x1UL <<1);
}
if(mode & PWM) LPC_CT16B0->PWMC |= 0x1 << 1;
}
void Timer0Match2(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B0->MR2 = interval;
LPC_CT16B0->MCR &= ~(0x7 << 6);
LPC_CT16B0->EMR &= ~(0x30 << 4);
LPC_CT16B0->PWMC &= ~(0x1 << 2);
LPC_CT16B0->MCR |= (mode & 0x7) << 6;
if(mode & OUTPUTTOGGLE) {
LPC_CT16B0->EMR |= (mode & 0x30) << 4;
#if TMR0M2_PIN == 0
LPC_IOCON->SWCLK_PIO0_10 = 0x03;
#else
LPC_IOCON->PIO1_15 = 0x02;
#endif
if(mode & OUTPUTLOW) LPC_CT16B0->EMR |= 1<<2;
else if(mode & OUTPUTHIGH) LPC_CT16B0->EMR &= ~(0x1UL <<2);
}
if(mode & PWM) LPC_CT16B0->PWMC |= 0x1 << 2;
}
void Timer0Match3(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B0->MR3 = interval;
LPC_CT16B0->MCR &= ~(0x7 << 9);
LPC_CT16B0->EMR &= ~(0x30 << 6);
LPC_CT16B0->PWMC &= ~(0x1 << 3);;
LPC_CT16B0->MCR |= (mode & 0x7) << 9;
if(mode & OUTPUTTOGGLE) {
LPC_CT16B0->EMR |= (mode & 0x30) << 6;
if(mode & OUTPUTLOW) LPC_CT16B0->EMR |= 1<<3;
else if(mode & OUTPUTHIGH) LPC_CT16B0->EMR &= ~(0x1UL <<3);
}
if(mode & PWM) LPC_CT16B0->PWMC |= 0x1 << 3;
}
void Timer0Capture(unsigned char mode) {
if(mode) {
if(mode & COUNTER) {
LPC_CT16B0->CTCR = mode & 0x3;
LPC_CT16B0->TC = 0;
}
else {
LPC_CT16B0->CTCR = 0;
if(mode & (PWRESET | FALLING)) { // captures on falling edge, therefore resets on rising edge
LPC_CT16B0->CTCR = (0x1 << 4);
}
else if(mode & (PWRESET | RISING)) { // captures on rising edge, therefore resets on falling edge
LPC_CT16B0->CTCR = (0x1 << 4) | (0x1 << 5);
}
if(mode & INTERRUPT) mode |= 0x4;
LPC_CT16B0->CCR = mode & 0x7;
}
LPC_IOCON->PIO0_2 &= ~(0x07);
LPC_IOCON->PIO0_2 |= 0x02;
}
}
void Timer1Match0(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B1->MR0 = interval;
LPC_CT16B1->MCR &= ~0x7;
LPC_CT16B1->EMR &= ~0x30;
LPC_CT16B1->PWMC &= ~0x1;
LPC_CT16B1->MCR |= (mode & 0x7);
if(mode & OUTPUTTOGGLE) {
LPC_CT16B1->EMR |= (mode & 0x30);
LPC_IOCON->PIO0_21 = 0x01;
if(mode & OUTPUTLOW) LPC_CT16B1->EMR |= 1;
else if(mode & OUTPUTHIGH) LPC_CT16B1->EMR &= ~1;
}
if(mode & PWM) LPC_CT16B1->PWMC |= 0x1;
}
void Timer1Match1(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B1->MR1 = interval;
LPC_CT16B1->MCR &= ~(0x7 << 3);
LPC_CT16B1->EMR &= ~(0x30 << 2);
LPC_CT16B1->PWMC &= ~(0x1 << 1);
LPC_CT16B1->MCR |= (mode & 0x7) << 3;
if(mode & OUTPUTTOGGLE) {
LPC_CT16B1->EMR |= (mode & 0x30) << 2;
LPC_IOCON->PIO0_22 = 0x02;
if(mode & OUTPUTLOW) LPC_CT16B1->EMR |= 1<<1;
else if(mode & OUTPUTHIGH) LPC_CT16B1->EMR &= ~(0x1UL <<1);
}
if(mode & PWM) LPC_CT16B1->PWMC |= 0x1 << 1;
}
void Timer1Match2(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B1->MR2 = interval;
LPC_CT16B1->MCR &= ~(0x7 << 6);
LPC_CT16B1->EMR &= ~(0x30 << 4);
LPC_CT16B1->PWMC &= ~(0x1 << 2);
LPC_CT16B1->MCR |= (mode & 0x7) << 6;
if(mode & OUTPUTTOGGLE) {
LPC_CT16B1->EMR |= (mode & 0x30) << 4;
if(mode & OUTPUTLOW) LPC_CT16B1->EMR |= 1<<2;
else if(mode & OUTPUTHIGH) LPC_CT16B1->EMR &= ~(0x1UL <<2);
}
if(mode & PWM) LPC_CT16B1->PWMC |= 0x1 << 2;
}
void Timer1Match3(unsigned short interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT16B1->MR3 = interval;
LPC_CT16B1->MCR &= ~(0x7 << 9);
LPC_CT16B1->EMR &= ~(0x30 << 6);
LPC_CT16B1->PWMC &= ~(0x1 << 3);;
LPC_CT16B1->MCR |= (mode & 0x7) << 9;
if(mode & OUTPUTTOGGLE) {
LPC_CT16B1->EMR |= (mode & 0x30) << 6;
if(mode & OUTPUTLOW) LPC_CT16B1->EMR |= 1<<3;
else if(mode & OUTPUTHIGH) LPC_CT16B1->EMR &= ~(0x1UL <<3);
}
if(mode & PWM) LPC_CT16B1->PWMC |= 0x1 << 3;
}
void Timer1Capture(unsigned char mode) {
if(mode) {
if(mode & COUNTER) {
LPC_CT16B1->CTCR = mode & 0x3;
LPC_CT16B1->TC = 0;
}
else {
LPC_CT16B1->CTCR = 0;
if(mode & (PWRESET | FALLING)) { // captures on falling edge, therefore resets on rising edge
LPC_CT16B1->CTCR = (0x1 << 4);
}
else if(mode & (PWRESET | RISING)) { // captures on rising edge, therefore resets on falling edge
LPC_CT16B1->CTCR = (0x1 << 4) | (0x1 << 5);
}
if(mode & INTERRUPT) mode |= 0x4;
LPC_CT16B1->CCR = mode & 0x7;
}
LPC_IOCON->PIO0_20 &= ~(0x07);
LPC_IOCON->PIO0_20 |= 0x01;
}
}
void Timer2Match0(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B0->MR0 = interval;
LPC_CT32B0->MCR &= ~0x7;
LPC_CT32B0->EMR &= ~0x30;
LPC_CT32B0->PWMC &= ~0x1;
LPC_CT32B0->MCR |= (mode & 0x7);
if(mode & OUTPUTTOGGLE) {
LPC_CT32B0->EMR |= (mode & 0x30);
LPC_IOCON->PIO0_18 = 0x02;
if(mode & OUTPUTLOW) LPC_CT32B0->EMR |= 1;
else if(mode & OUTPUTHIGH) LPC_CT32B0->EMR &= ~1;
}
if(mode & PWM) LPC_CT32B0->PWMC |= 0x1;
}
void Timer2Match1(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B0->MR1 = interval;
LPC_CT32B0->MCR &= ~(0x7 << 3);
LPC_CT32B0->EMR &= ~(0x30 << 2);
LPC_CT32B0->PWMC &= ~(0x1 << 1);
LPC_CT32B0->MCR |= (mode & 0x7) << 3;
if(mode & OUTPUTTOGGLE) {
LPC_CT32B0->EMR |= (mode & 0x30) << 2;
LPC_IOCON->PIO0_19 = 0x02;
if(mode & OUTPUTLOW) LPC_CT32B0->EMR |= 1<<1;
else if(mode & OUTPUTHIGH) LPC_CT32B0->EMR &= ~(0x1UL <<1);
}
if(mode & PWM) LPC_CT32B0->PWMC |= 0x1 << 1;
}
void Timer2Match2(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B0->MR2 = interval;
LPC_CT32B0->MCR &= ~(0x7 << 6);
LPC_CT32B0->EMR &= ~(0x30 << 4);
LPC_CT32B0->PWMC &= ~(0x1 << 2);
LPC_CT32B0->MCR |= (mode & 0x7) << 6;
if(mode & OUTPUTTOGGLE) {
LPC_CT32B0->EMR |= (mode & 0x30) << 4;
LPC_IOCON->PIO0_1 = 0x02;
if(mode & OUTPUTLOW) LPC_CT32B0->EMR |= 1<<2;
else if(mode & OUTPUTHIGH) LPC_CT32B0->EMR &= ~(0x1UL <<2);
}
if(mode & PWM) LPC_CT32B0->PWMC |= 0x1 << 2;
}
void Timer2Match3(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B0->MR3 = interval;
LPC_CT32B0->MCR &= ~(0x7 << 9);
LPC_CT32B0->EMR &= ~(0x30 << 6);
LPC_CT32B0->PWMC &= ~(0x1 << 3);
LPC_CT32B0->MCR |= (mode & 0x7) << 9;
if(mode & OUTPUTTOGGLE) {
LPC_CT32B0->EMR |= (mode & 0x30) << 6;
LPC_IOCON->TDI_PIO0_11 = 0x03;
if(mode & OUTPUTLOW) LPC_CT32B0->EMR |= 1<<3;
else if(mode & OUTPUTHIGH) LPC_CT32B0->EMR &= ~(0x1UL <<3);
}
if(mode & PWM) LPC_CT32B0->PWMC |= 0x1 << 3;
}
void Timer2Capture(unsigned char mode) {
if(mode) {
if(mode & COUNTER) {
LPC_CT32B0->CTCR = mode & 0x3;
LPC_CT32B0->TC = 0;
}
else {
LPC_CT32B0->CTCR = 0;
if(mode & (PWRESET | FALLING)) { // captures on falling edge, therefore resets on rising edge
LPC_CT32B0->CTCR = (0x1 << 4);
}
else if(mode & (PWRESET | RISING)) { // captures on rising edge, therefore resets on falling edge
LPC_CT32B0->CTCR = (0x1 << 4) | (0x1 << 5);
}
if(mode & INTERRUPT) mode |= 0x4;
LPC_CT32B0->CCR = mode & 0x7;
}
LPC_IOCON->PIO0_17 &= ~(0x07);
LPC_IOCON->PIO0_17 |= 0x02;
}
}
void Timer3Match0(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B1->MR0 = interval;
LPC_CT32B1->MCR &= ~0x7;
LPC_CT32B1->EMR &= ~0x30;
LPC_CT32B1->PWMC &= ~0x1;
LPC_CT32B1->MCR |= (mode & 0x7);
if(mode & OUTPUTTOGGLE) {
LPC_CT32B1->EMR |= (mode & 0x30);
LPC_IOCON->TDO_PIO0_13 = 0x03;
if(mode & OUTPUTLOW) LPC_CT32B1->EMR |= 1;
else if(mode & OUTPUTHIGH) LPC_CT32B1->EMR &= ~1;
}
if(mode & PWM) LPC_CT32B1->PWMC |= 0x1;
}
void Timer3Match1(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B1->MR1 = interval;
LPC_CT32B1->MCR &= ~(0x7 << 3);
LPC_CT32B1->EMR &= ~(0x30 << 2);
LPC_CT32B1->PWMC &= ~(0x1 << 1);
LPC_CT32B1->MCR |= (mode & 0x7) << 3;
if(mode & OUTPUTTOGGLE) {
LPC_CT32B1->EMR |= (mode & 0x30) << 2;
LPC_IOCON->TRST_PIO0_14 = 0x03;
if(mode & OUTPUTLOW) LPC_CT32B1->EMR |= 1<<1;
else if(mode & OUTPUTHIGH) LPC_CT32B1->EMR &= ~(0x1UL <<1);
}
if(mode & PWM) LPC_CT32B1->PWMC |= 0x1 << 1;
}
void Timer3Match2(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B1->MR2 = interval;
LPC_CT32B1->MCR &= ~(0x7 << 6);
LPC_CT32B1->EMR &= ~(0x30 << 4);
LPC_CT32B1->PWMC &= ~(0x1 << 2);
LPC_CT32B1->MCR |= (mode & 0x7) << 6;
if(mode & OUTPUTTOGGLE) {
LPC_CT32B1->EMR |= (mode & 0x30) << 4;
LPC_IOCON->SWDIO_PIO0_15 = 0x03;
if(mode & OUTPUTLOW) LPC_CT32B1->EMR |= 1<<2;
else if(mode & OUTPUTHIGH) LPC_CT32B1->EMR &= ~(0x1UL <<2);
}
if(mode & PWM) LPC_CT32B1->PWMC |= 0x1 << 2;
}
void Timer3Match3(unsigned int interval, unsigned char mode) {
if(mode & INTERRUPT) mode |= 0x1;
LPC_CT32B1->MR3 = interval;
LPC_CT32B1->MCR &= ~(0x7 << 9);
LPC_CT32B1->EMR &= ~(0x30 << 6);
LPC_CT32B1->PWMC &= ~(0x1 << 3);;
LPC_CT32B1->MCR |= (mode & 0x7) << 9;
if(mode & OUTPUTTOGGLE) {
LPC_CT32B1->EMR |= (mode & 0x30) << 6;
LPC_IOCON->PIO0_16 = 0x02;
if(mode & OUTPUTLOW) LPC_CT32B1->EMR |= 1<<3;
else if(mode & OUTPUTHIGH) LPC_CT32B1->EMR &= ~(0x1UL <<3);
}
if(mode & PWM) LPC_CT32B1->PWMC |= 0x1 << 3;
}
void Timer3Capture(unsigned char mode) {
if(mode) {
if(mode & COUNTER) {
LPC_CT32B1->CTCR = mode & 0x3;
LPC_CT32B1->TC = 0;
}
else {
LPC_CT32B1->CTCR = 0;
if(mode & (PWRESET | FALLING)) { // captures on falling edge, therefore resets on rising edge
LPC_CT32B1->CTCR = (0x1 << 4);
}
else if(mode & (PWRESET | RISING)) { // captures on rising edge, therefore resets on falling edge
LPC_CT32B1->CTCR = (0x1 << 4) | (0x1 << 5);
}
if(mode & INTERRUPT) mode |= 0x4;
LPC_CT32B1->CCR = mode & 0x7;
}
LPC_IOCON->TMS_PIO0_12 &= ~(0x07);
LPC_IOCON->TMS_PIO0_12 |= 0x03;
}
}
void CT16B0_IRQHandler(void) {
if(Timer0Interrupt) Timer0Interrupt(LPC_CT16B0->IR & 0x1f);
if(LPC_CT16B0->IR & 0x1 && Timer0Interrupt0) Timer0Interrupt0();
if(LPC_CT16B0->IR & 0x2 && Timer0Interrupt1) Timer0Interrupt1();
if(LPC_CT16B0->IR & 0x4 && Timer0Interrupt2) Timer0Interrupt2();
if(LPC_CT16B0->IR & 0x8 && Timer0Interrupt3) Timer0Interrupt3();
if(LPC_CT16B0->IR & 0x10 && Timer0InterruptC) Timer0InterruptC(LPC_CT16B0->CR0);
LPC_CT16B0->IR = 0x1f;
__NOP(); __NOP();
}
void CT16B1_IRQHandler(void) {
if(Timer1Interrupt) Timer1Interrupt(LPC_CT16B1->IR & 0x1f);
if(LPC_CT16B1->IR & 0x1 && Timer1Interrupt0) Timer1Interrupt0();
if(LPC_CT16B1->IR & 0x2 && Timer1Interrupt1) Timer1Interrupt1();
if(LPC_CT16B1->IR & 0x4 && Timer1Interrupt2) Timer1Interrupt2();
if(LPC_CT16B1->IR & 0x8 && Timer1Interrupt3) Timer1Interrupt3();
if(LPC_CT16B1->IR & 0x10 && Timer1InterruptC) Timer1InterruptC(LPC_CT16B1->CR0);
LPC_CT16B1->IR = 0x1f;
__NOP(); __NOP();
}
void CT32B0_IRQHandler(void) {
if(Timer2Interrupt) Timer2Interrupt(LPC_CT32B0->IR & 0x1f);
if(LPC_CT32B0->IR & 0x1 && Timer2Interrupt0) Timer2Interrupt0();
if(LPC_CT32B0->IR & 0x2 && Timer2Interrupt1) Timer2Interrupt1();
if(LPC_CT32B0->IR & 0x4 && Timer2Interrupt2) Timer2Interrupt2();
if(LPC_CT32B0->IR & 0x8 && Timer2Interrupt3) Timer2Interrupt3();
if(LPC_CT32B0->IR & 0x10 && Timer2InterruptC) Timer2InterruptC(LPC_CT32B0->CR0);
LPC_CT32B0->IR = 0x1f;
__NOP(); __NOP();
}
void CT32B1_IRQHandler(void) {
if(Timer3Interrupt) Timer3Interrupt(LPC_CT32B1->IR & 0x1f);
if(LPC_CT32B1->IR & 0x1 && Timer3Interrupt0) Timer3Interrupt0();
if(LPC_CT32B1->IR & 0x2 && Timer3Interrupt1) Timer3Interrupt1();
if(LPC_CT32B1->IR & 0x4 && Timer3Interrupt2) Timer3Interrupt2();
if(LPC_CT32B1->IR & 0x8 && Timer3Interrupt3) Timer3Interrupt3();
if(LPC_CT32B1->IR & 0x10 && Timer3InterruptC) Timer3InterruptC(LPC_CT32B1->CR0);
LPC_CT32B1->IR = 0x1f;
__NOP(); __NOP();
}
// ****************************************************************************
// *** ADC Functions
// ****************************************************************************
// *** Initialise the ADC
void ADCInit(unsigned short channels) {
if(channels) {
if(channels & CHN0) LPC_IOCON->TDI_PIO0_11 = 0x02; // Sets AD0 to Analogue mode if specified
if(channels & CHN1) LPC_IOCON->TMS_PIO0_12 = 0x02; // Sets AD1 to Analogue mode if specified
if(channels & CHN2) LPC_IOCON->TDO_PIO0_13 = 0x02; // Sets AD2 to Analogue mode if specified
if(channels & CHN3) LPC_IOCON->TRST_PIO0_14 = 0x02; // Sets AD3 to Analogue mode if specified
if(channels & CHN4) LPC_IOCON->SWDIO_PIO0_15 = 0x02; // Sets AD4 to Analogue mode if specified
if(channels & CHN5) LPC_IOCON->PIO0_16 = 0x01; // Sets AD5 to Analogue mode if specified
if(channels & CHN6) LPC_IOCON->PIO0_22 = 0x01; // Sets AD6 to Analogue mode if specified
if(channels & CHN7) LPC_IOCON->PIO0_23 = 0x01; // Sets AD7 to Analogue mode if specified
LPC_SYSCON->SYSAHBCLKCTRL |= (0x1UL <<13); // Enable clock to the ADC peripheral
LPC_SYSCON->PDRUNCFG &= ~(0x1UL <<4); // Enable power to the ADC peripheral
// Set sample rates depending on clock speed, attempt to get as close to the 15.5MHz maximum ADC clock rate (12-bit) or 31MHz (10-bit) as possible
if((LPC_SYSCON->MAINCLKSEL & 0x03) == 0x03) {
// assume 72MHz operation
#if ADC_10BIT
LPC_ADC->CR = 0x0200; // Sample at 24MHz clock, at 10bits
#else
LPC_ADC->CR = 0x0400; // Sample at 14.4MHz clock, at 12bits
#endif
}
else {
// assume 12MHz operation
LPC_ADC->CR = 0x0000; // Sample at 12MHz clock
}
#if ADC_LPWRMODE
LPC_ADC->CR |= (0x1UL << 22);
#else
LPC_ADC->CR &= ~(0x1UL << 22);
#endif
#if ADC_10BIT
LPC_ADC->CR |= (0x1UL << 23);
#else
LPC_ADC->CR &= ~(0x1UL << 23);
#endif
#if ADC_MODE
// in interrupt mode, set up burst mode and global interrupts
LPC_ADC->CR |= 0x010000 | channels; // Burst mode
LPC_ADC->INTEN = 0x100; // Enable global interrupt
IRQClear(ADC_IRQn);
IRQPriority(ADC_IRQn, ADC_PRIORITY);
IRQEnable(ADC_IRQn);
#else
// in on-demand mode, disable burst mode and interrupts
LPC_ADC->INTEN = 0x000; // Disable global interrupt
#endif
}
}
// *** Stop the ADC
void ADCStop(void) {
IRQDisable(ADC_IRQn);
LPC_ADC->CR = 0x000F00; // Disable burst mode
LPC_SYSCON->SYSAHBCLKCTRL &= ~(0x1UL <<13); // Disable clock to the ADC peripheral
LPC_SYSCON->PDRUNCFG |= (0x1UL <<4); // Disable power to the ADC peripheral
}
// *** Read ADC value
unsigned short ADCRead(unsigned char channel) {
#if ADC_MODE
// in interrupt mode, select channel and return last data value for that channel
#if ADC_10BIT
if(channel & CHN0) return ((LPC_ADC->DR[0] >> 6) & 0x3FF);
else if(channel & CHN1) return ((LPC_ADC->DR[1] >> 6) & 0x3FF);
else if(channel & CHN2) return ((LPC_ADC->DR[2] >> 6) & 0x3FF);
else if(channel & CHN3) return ((LPC_ADC->DR[3] >> 6) & 0x3FF);
else if(channel & CHN4) return ((LPC_ADC->DR[4] >> 6) & 0x3FF);
else if(channel & CHN5) return ((LPC_ADC->DR[5] >> 6) & 0x3FF);
else if(channel & CHN6) return ((LPC_ADC->DR[6] >> 6) & 0x3FF);
else if(channel & CHN7) return ((LPC_ADC->DR[7] >> 6) & 0x3FF);
else return 0xffff;
#else
if(channel & CHN0) return ((LPC_ADC->DR[0] >> 4) & 0xFFF);
else if(channel & CHN1) return ((LPC_ADC->DR[1] >> 4) & 0xFFF);
else if(channel & CHN2) return ((LPC_ADC->DR[2] >> 4) & 0xFFF);
else if(channel & CHN3) return ((LPC_ADC->DR[3] >> 4) & 0xFFF);
else if(channel & CHN4) return ((LPC_ADC->DR[4] >> 4) & 0xFFF);
else if(channel & CHN5) return ((LPC_ADC->DR[5] >> 4) & 0xFFF);
else if(channel & CHN6) return ((LPC_ADC->DR[6] >> 4) & 0xFFF);
else if(channel & CHN7) return ((LPC_ADC->DR[7] >> 4) & 0xFFF);
else return 0xffff;
#endif
#else
// in on-demand mode, initialise a reading
LPC_ADC->CR &= ~0x000000ff;
LPC_ADC->CR |= 0x1000000 | channel; // Start now!
while(!(LPC_ADC->GDR & (0x1UL << 31))); // Wait for ADC to complete
#if ADC_10BIT
return ((LPC_ADC->GDR >> 6) & 0x3FF); // Return the ADC value
#else
return ((LPC_ADC->GDR >> 4) & 0xFFF); // Return the ADC value
#endif
#endif
}
// *** ADC interrupt handler
#if ADC_MODE
void ADC_IRQHandler(void) {
unsigned int gdr;
gdr = LPC_ADC->GDR;
#if ADC_10BIT
if(ADCInterrupt) ADCInterrupt(((gdr >> 24) & 0x7), ((gdr >> 6) & 0x3FF)); // If user-supplied handler is available, run it, passing data and channel
#else
if(ADCInterrupt) ADCInterrupt(((gdr >> 24) & 0x7), ((gdr >> 4) & 0xFFF));
#endif
}
#endif
// ****************************************************************************
// *** USB Functions
// ****************************************************************************
USBD_API_T* USBROM;
USBD_HANDLE_T hUsb;
void USBInit(void) {
// Config USB Clock
LPC_SYSCON->PDRUNCFG &= ~((1 << 10) | (1 << 8)); // Enable power to the USB PHY and PLL
LPC_SYSCON->USBPLLCLKSEL = 0x01; // Select PLL as clock source
LPC_SYSCON->USBPLLCTRL = 0x23; // Select PLL divider to 4 (12Mhz - 48MHz)
while (!(LPC_SYSCON->USBPLLSTAT & 0x01)); // Wait for PLL lock
LPC_SYSCON->USBCLKSEL = 0x00; // Selec USB PLL input for USB Clock
LPC_SYSCON->USBCLKDIV = 0x01; // Set USB clock divider
// Configure USB pins
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 14) | (1 << 27); // Enable clock to USB and USB RAM
LPC_IOCON->PIO0_3 = 0x01; // VBUS
LPC_IOCON->PIO0_6 = 0x01; // Soft connect
USBROM = (USBD_API_T*)((*(ROM **)(0x1FFF1FF8))->pUSBD);
}
// MSC
void MSCDummy(unsigned int address, unsigned char ** bufferAdr, unsigned int length) { return; }
signed int MSCDummy2(unsigned int address, unsigned char * buffer, unsigned int length) { return 0; }
void MSCRead(unsigned int address, unsigned char ** bufferAdr, unsigned int length) WEAK_ALIAS(MSCDummy);
void MSCWrite(unsigned int address, unsigned char ** bufferAdr, unsigned int length) WEAK_ALIAS(MSCDummy);
signed int MSCVerify(unsigned int address, unsigned char * buffer, unsigned int length) WEAK_ALIAS(MSCDummy2);
void MSCInit(unsigned int deviceCapacity) {
USBD_API_INIT_PARAM_T usb_param;
USB_CORE_DESCS_T desc;
USBInit();
desc.device_desc = MSC_DeviceDescriptor;
desc.string_desc = MSC_StringDescriptor;
desc.full_speed_desc = MSC_ConfigDescriptor;
desc.high_speed_desc = MSC_ConfigDescriptor;
desc.device_qualifier = 0;
memset((void*)&usb_param, 0, sizeof(USBD_API_INIT_PARAM_T));
usb_param.usb_reg_base = LPC_USB_BASE;
usb_param.mem_base = 0x20004000;
usb_param.mem_size = 0x800;
//usb_param.mem_base = 0x10001000;
//usb_param.mem_size = 0x1000;
usb_param.max_num_ep = 2;
USBROM->hw->Init(&hUsb, &desc, &usb_param);
USB_INTERFACE_DESCRIPTOR* pIntfDesc = (USB_INTERFACE_DESCRIPTOR *)&MSC_ConfigDescriptor[sizeof(USB_CONFIGURATION_DESCRIPTOR)];
USBD_MSC_INIT_PARAM_T msc_param;
memset((void*)&msc_param, 0, sizeof(USBD_MSC_INIT_PARAM_T));
msc_param.mem_base = usb_param.mem_base;
msc_param.mem_size = usb_param.mem_size;
/* mass storage paramas */
msc_param.InquiryStr = (uint8_t*)"UAirDisk";
/*msc_param.BlockCount = deviceCapacity / MSC_BLOCK_SIZE;
msc_param.MemorySize = deviceCapacity;*/
#define MSC_MemorySize ((uint32_t)(8 * 1024))
#define MSC_BlockCount (MSC_MemorySize / MSC_BLOCK_SIZE)
msc_param.BlockCount = deviceCapacity / MSC_BLOCK_SIZE;
msc_param.BlockSize = MSC_BLOCK_SIZE;
msc_param.MemorySize = deviceCapacity;
if ((pIntfDesc == 0) ||
(pIntfDesc->bInterfaceClass != USB_DEVICE_CLASS_STORAGE) ||
(pIntfDesc->bInterfaceSubClass != MSC_SUBCLASS_SCSI) )
return;
msc_param.intf_desc = (uint8_t*)pIntfDesc;
/* user defined functions */
msc_param.MSC_Write = (void(*)(uint32_t offset, uint8_t** src, uint32_t length))MSCWrite;
msc_param.MSC_Read = (void(*)(uint32_t offset, uint8_t** src, uint32_t length))MSCRead;
msc_param.MSC_Verify = (ErrorCode_t (*)( uint32_t offset, uint8_t* buf, uint32_t length))MSCVerify;
USBROM->msc->init(hUsb, &msc_param);
/* update memory variables */
usb_param.mem_base = msc_param.mem_base;
usb_param.mem_size = msc_param.mem_size;
IRQClear(USB_IRQn);
IRQPriority(USB_IRQn, USB_PRIORITY);
IRQEnable(USB_IRQn);
USBROM->hw->Connect(hUsb, 1);
}
// HID
unsigned char * report_buffer;
void HIDDummy(unsigned char * buffer) { return; }
unsigned char HIDDummy2(unsigned char * buffer) { return 0; }
void HIDOutReport(unsigned char * buffer) WEAK_ALIAS(HIDDummy);
unsigned char HIDInReport(unsigned char * buffer) WEAK_ALIAS(HIDDummy2);
void HIDOutFeature(unsigned char * buffer) WEAK_ALIAS(HIDDummy);
unsigned char HIDInFeature(unsigned char * buffer) WEAK_ALIAS(HIDDummy2);
void HIDInit(void) {
USBD_API_INIT_PARAM_T usb_param;
USB_CORE_DESCS_T desc;
USBInit();
desc.device_desc = HID_DeviceDescriptor;
desc.string_desc = HID_StringDescriptor;
desc.full_speed_desc = HID_ConfigDescriptor;
desc.high_speed_desc = HID_ConfigDescriptor;
desc.device_qualifier = 0;
memset((void*)&usb_param, 0, sizeof(USBD_API_INIT_PARAM_T));
usb_param.usb_reg_base = LPC_USB_BASE;
usb_param.mem_base = 0x20004000;
usb_param.mem_size = 0x800;
usb_param.max_num_ep = 2;
usb_param.USB_Configure_Event = USB_Configure_Event; // HID only
USBROM->hw->Init(&hUsb, &desc, &usb_param);
USB_INTERFACE_DESCRIPTOR* pIntfDesc = (USB_INTERFACE_DESCRIPTOR *)&HID_ConfigDescriptor[sizeof(USB_CONFIGURATION_DESCRIPTOR)];
USBD_HID_INIT_PARAM_T hid_param;
USB_HID_REPORT_T reports_data[1];
memset((void*)&hid_param, 0, sizeof(USBD_HID_INIT_PARAM_T));
/* HID paramas */
hid_param.max_reports = 1;
/* Init reports_data */
reports_data[0].len = HID_ReportDescSize;
reports_data[0].idle_time = 0;
reports_data[0].desc = (uint8_t *)&HID_ReportDescriptor[0];
if ((pIntfDesc == 0) || (pIntfDesc->bInterfaceClass != USB_DEVICE_CLASS_HUMAN_INTERFACE)) return;
hid_param.mem_base = usb_param.mem_base;
hid_param.mem_size = usb_param.mem_size;
hid_param.intf_desc = (uint8_t*)pIntfDesc;
/* user defined functions */
hid_param.HID_GetReport = HID_GetReport;
hid_param.HID_SetReport = HID_SetReport;
hid_param.HID_EpIn_Hdlr = HID_Ep_Hdlr;
hid_param.HID_EpOut_Hdlr = HID_Ep_Hdlr;
hid_param.report_data = reports_data;
USBROM->hid->init(hUsb, &hid_param);
/* allocate USB accessable memory space for report data */
report_buffer = (unsigned char*)hid_param.mem_base;
hid_param.mem_base += 4;
hid_param.mem_size += 4;
/* update memory variables */
usb_param.mem_base = hid_param.mem_base;
usb_param.mem_size = hid_param.mem_size;
IRQClear(USB_IRQn);
IRQPriority(USB_IRQn, USB_PRIORITY);
IRQEnable(USB_IRQn);
USBROM->hw->Connect(hUsb, 1);
}
ErrorCode_t USB_Configure_Event (USBD_HANDLE_T hUsb) {
USB_CORE_CTRL_T* pCtrl = (USB_CORE_CTRL_T*)hUsb;
if (pCtrl->config_value) { /* Check if USB is configured */
USBROM->hw->WriteEP(hUsb, HID_EP_IN, report_buffer, 1);
}
return LPC_OK;
}
ErrorCode_t HID_GetReport( USBD_HANDLE_T hHid, USB_SETUP_PACKET* pSetup, uint8_t** pBuffer, uint16_t* plength) {
switch (pSetup->wValue.WB.H) {
case HID_REPORT_FEATURE:
*pBuffer = report_buffer;
if(HIDInFeature(report_buffer)) {
*plength = HID_FEATURE_BYTES;
}
else {
*plength = 0;
}
break;
case HID_REPORT_INPUT: /* Not Supported */
case HID_REPORT_OUTPUT: /* Not Supported */
return (ERR_USBD_STALL);
}
return (LPC_OK);
}
ErrorCode_t HID_SetReport( USBD_HANDLE_T hHid, USB_SETUP_PACKET* pSetup, uint8_t** pBuffer, uint16_t length) {
if (length == 0) return LPC_OK;
switch (pSetup->wValue.WB.H) {
case HID_REPORT_FEATURE:
HIDOutFeature(*pBuffer);
break;
case HID_REPORT_INPUT: /* Not Supported */
case HID_REPORT_OUTPUT: /* Not Supported */
return (ERR_USBD_STALL);
}
return (LPC_OK);
}
ErrorCode_t HID_Ep_Hdlr (USBD_HANDLE_T hUsb, void* data, uint32_t event) {
USB_HID_CTRL_T* pHidCtrl = (USB_HID_CTRL_T*)data;
switch (event) {
case USB_EVT_IN:
if(HIDInReport(report_buffer)) {
USBROM->hw->WriteEP(hUsb, pHidCtrl->epin_adr, report_buffer, HID_IN_BYTES);
}
else {
USBROM->hw->WriteEP(hUsb, pHidCtrl->epin_adr, report_buffer, 0);
}
break;
case USB_EVT_OUT:
USBROM->hw->ReadEP(hUsb, pHidCtrl->epout_adr, report_buffer);
HIDOutReport(report_buffer);
break;
}
return LPC_OK;
}
// CDC
VCOM_DATA_T g_vCOM;
unsigned char VCOM_isbridge;
void CDCInit(unsigned char bridge) {
USBD_API_INIT_PARAM_T usb_param;
USBD_CDC_INIT_PARAM_T cdc_param;
USB_CORE_DESCS_T desc;
USBD_HANDLE_T hCdc;
uint32_t ep_indx;
USBInit();
VCOM_isbridge = bridge;
desc.device_desc = CDC_DeviceDescriptor;
desc.string_desc = CDC_StringDescriptor;
desc.full_speed_desc = CDC_ConfigDescriptor;
desc.high_speed_desc = CDC_ConfigDescriptor;
desc.device_qualifier = 0;
memset((void*)&usb_param, 0, sizeof(USBD_API_INIT_PARAM_T));
usb_param.usb_reg_base = LPC_USB_BASE;
usb_param.mem_base = 0x10001000;
usb_param.mem_size = 0x800;
// usb_param.mem_base = 0x20004000;
// usb_param.mem_size = 0x800;
usb_param.max_num_ep = 3;
/* init CDC params */
memset((void*)&cdc_param, 0, sizeof(USBD_CDC_INIT_PARAM_T));
/* user defined functions */
cdc_param.SetLineCode = VCOM_SetLineCode;
usb_param.USB_SOF_Event = VCOM_sof_event;
cdc_param.SendBreak = VCOM_SendBreak;
/* USB Initialization */
USBROM->hw->Init(&hUsb, &desc, &usb_param);
// init CDC params
cdc_param.mem_base = usb_param.mem_base;
cdc_param.mem_size = usb_param.mem_size;
cdc_param.cif_intf_desc = (uint8_t *)&CDC_ConfigDescriptor[USB_CONFIGUARTION_DESC_SIZE];
cdc_param.dif_intf_desc = (uint8_t *)&CDC_ConfigDescriptor[USB_CONFIGUARTION_DESC_SIZE + USB_INTERFACE_DESC_SIZE + 0x0013 + USB_ENDPOINT_DESC_SIZE ];
USBROM->cdc->init(hUsb, &cdc_param, &hCdc);
/* store USB handle */
memset((void*)&g_vCOM, 0, sizeof(VCOM_DATA_T));
g_vCOM.hUsb = hUsb;
g_vCOM.hCdc = hCdc;
g_vCOM.send_fn = VCOM_usb_send;
/* allocate transfer buffers */
g_vCOM.rxBuf = (uint8_t*)(cdc_param.mem_base + (0 * USB_MAX_BULK_PACKET));
g_vCOM.txBuf = (uint8_t*)(cdc_param.mem_base + (1 * USB_MAX_BULK_PACKET));
cdc_param.mem_size -= (4 * USB_MAX_BULK_PACKET);
/* register endpoint interrupt handler */
ep_indx = (((USB_CDC_EP_BULK_IN & 0x0F) << 1) + 1);
USBROM->core->RegisterEpHandler (hUsb, ep_indx, VCOM_bulk_in_hdlr, &g_vCOM);
/* register endpoint interrupt handler */
ep_indx = ((USB_CDC_EP_BULK_OUT & 0x0F) << 1);
USBROM->core->RegisterEpHandler (hUsb, ep_indx, VCOM_bulk_out_hdlr, &g_vCOM);
/* enable IRQ */
IRQPriority(USB_IRQn, USB_PRIORITY);
IRQEnable(USB_IRQn); // enable USB0 interrrupts
g_vCOM.send_fn = VCOM_uart_send;
if(VCOM_isbridge) {
/* init UART for bridge */
VCOM_init_bridge(&g_vCOM, 0);
/* enable IRQ */
IRQPriority(USART_IRQn, UART_PRIORITY);
IRQEnable(USART_IRQn); // enable Uart interrrupt
#if CDC_USE_PLED
LEDInit(PLED);
#endif
}
/* USB Connect */
USBROM->hw->Connect(hUsb, 1);
}
void VCOM_usb_send(VCOM_DATA_T* pVcom) {
/* data received send it back */
pVcom->txlen -= USBROM->hw->WriteEP (pVcom->hUsb, USB_CDC_EP_BULK_IN, pVcom->txBuf, pVcom->txlen);
}
void VCOM_init_bridge(VCOM_DATA_T* pVcom, CDC_LINE_CODING* line_coding) {
uint32_t Fdiv, baud = 9600;
uint8_t lcr = 0x3; /* 8 bits, no Parity, 1 Stop bit */
if(line_coding) {
if(line_coding->bCharFormat) {
lcr |= (1 << 2); /* Number of stop bits */
}
if(line_coding->bParityType) { /* Parity bit type */
lcr |= (1 << 3);
lcr |= (((line_coding->bParityType - 1) & 0x3) << 4);
}
if(line_coding->bDataBits) {
lcr |= ((line_coding->bDataBits - 5) & 0x3);
}
else {
lcr |= 0x3;
}
baud = line_coding->dwDTERate;
/* enable SOF after we are connected */
USBROM->hw->EnableEvent(pVcom->hUsb, 0, USB_EVT_SOF, 1);
}
else {
/* Enable UART clock */
LPC_SYSCON->SYSAHBCLKCTRL |= (1<<12);
LPC_SYSCON->UARTCLKDIV = 0x1; /* divided by 1 */
LPC_IOCON->PIO0_18 &= ~0x07; /* UART I/O config */
LPC_IOCON->PIO0_18 |= 0x01; /* UART RXD */
LPC_IOCON->PIO0_19 &= ~0x07;
LPC_IOCON->PIO0_19 |= 0x01; /* UART TXD */
#if UART_FLOW
LPC_IOCON->PIO0_7 = 0x11; // #CTS
LPC_IOCON->PIO0_17 = 0x11; // #RTS
LPC_USART->MCR |= (0x1UL <<6) | (0x1UL <<7);
#endif
}
Fdiv = ( (72000000/LPC_SYSCON->UARTCLKDIV) / 16 ) / baud ; /*baud rate */
LPC_USART->IER = 0;
LPC_USART->LCR = lcr | 0x80; /* DLAB = 1 */
LPC_USART->DLM = Fdiv / 256;
LPC_USART->DLL = Fdiv % 256;
LPC_USART->FDR = 0x10; // reset fractional baud generator
LPC_USART->LCR = lcr; /* DLAB = 0 */
LPC_USART->FCR = 0x07; /* Enable and reset TX and RX FIFO.
Rx trigger level 4 chars*/
LPC_USART->IER = 0x07; /* Enable UART1 interrupt */
}
void VCOM_uart_write(VCOM_DATA_T* pVcom) {
uint8_t *pbuf = pVcom->rxBuf;
uint32_t tx_cnt = 16;
/* find space in TX fifo */
tx_cnt = 0xF - (tx_cnt & 0xF);
if (tx_cnt > (pVcom->rxlen - pVcom->ser_pos)) {
tx_cnt = (pVcom->rxlen - pVcom->ser_pos);
}
while(tx_cnt) {
if(LPC_USART->LSR & 0x20) {
LPC_USART->THR = pbuf[pVcom->ser_pos++];
tx_cnt--;
}
}
/* if done check anything pending */
if (pVcom->ser_pos == pVcom->rxlen) {
/* Tx complete free the buffer */
pVcom->ser_pos = 0;
pVcom->rxlen = 0;
if(pVcom->usbrx_pend) {
pVcom->usbrx_pend = 0;
VCOM_bulk_out_hdlr(pVcom->hUsb, (void*)pVcom, USB_EVT_OUT);
}
}
return;
}
void VCOM_uart_read(VCOM_DATA_T* pVcom) {
uint8_t *pbuf;
pbuf = pVcom->txBuf;
if( (LPC_USART->LSR & 0x01) && (pVcom->txlen < USB_MAX_BULK_PACKET) ) {
pbuf[pVcom->txlen++] = LPC_USART->RBR;
}
if (pVcom->txlen == USB_MAX_BULK_PACKET) {
VCOM_usb_send(pVcom);
}
pVcom->last_ser_rx = pVcom->sof_counter;
}
void CDCWriteByte(unsigned char byte) {
VCOM_DATA_T* pVcom = &g_vCOM;
if(pVcom->txlen < USB_MAX_BULK_PACKET) {
pVcom->txBuf[pVcom->txlen++] = byte;
}
if (pVcom->txlen == USB_MAX_BULK_PACKET) {
VCOM_usb_send(pVcom);
}
pVcom->last_ser_rx = pVcom->sof_counter;
}
void VCOM_uart_send(VCOM_DATA_T* pVcom) {
unsigned int tx_cnt;
unsigned char *pbuf = pVcom->rxBuf;
if(VCOM_isbridge) {
/* data received on USB send it to UART */
#if CDC_USE_PLED
LEDOn(PLED);
#endif
VCOM_uart_write(pVcom);
}
else {
tx_cnt = (pVcom->rxlen - pVcom->ser_pos);
while(tx_cnt) {
CDCReadByte(pbuf[pVcom->ser_pos++]);
tx_cnt--;
}
pVcom->ser_pos = 0;
pVcom->rxlen = 0;
if(pVcom->usbrx_pend) {
pVcom->usbrx_pend = 0;
VCOM_bulk_out_hdlr(pVcom->hUsb, (void*)pVcom, USB_EVT_OUT);
}
}
}
void CDCWrite(unsigned char * byte, unsigned int length) {
unsigned int i;
for(i=0; i<length; i++) {
CDCWriteByte(byte[i]);
}
}
void CDCDummy(unsigned char byte) { return; }
void CDCReadByte(unsigned char byte) WEAK_ALIAS(CDCDummy);
ErrorCode_t VCOM_SetLineCode (USBD_HANDLE_T hCDC, CDC_LINE_CODING* line_coding) {
VCOM_DATA_T* pVcom = &g_vCOM;
//int i;
/* baud rate change reset buffers */
pVcom->ser_pos = 0;
pVcom->rxlen = pVcom->txlen = 0;
if(VCOM_isbridge) VCOM_init_bridge(pVcom, line_coding);
else if(line_coding) USBROM->hw->EnableEvent(pVcom->hUsb, 0, USB_EVT_SOF, 1);
return LPC_OK;
}
ErrorCode_t VCOM_sof_event(USBD_HANDLE_T hUsb) {
VCOM_DATA_T* pVcom = &g_vCOM;
uint8_t lcr;
uint32_t diff = pVcom->sof_counter - pVcom->last_ser_rx;
pVcom->sof_counter++;
if (pVcom->break_time) {
pVcom->break_time--;
if (pVcom->break_time == 0) {
if(VCOM_isbridge) {
lcr = LPC_USART->LCR;
if (lcr & (1 << 6)) {
lcr &= ~(1 << 6);
LPC_USART->LCR = lcr;
}
}
}
}
if ( pVcom->last_ser_rx && (diff > 5)) {
VCOM_usb_send(pVcom);
}
return LPC_OK;
}
ErrorCode_t VCOM_SendBreak(USBD_HANDLE_T hCDC, uint16_t mstime) {
VCOM_DATA_T* pVcom = &g_vCOM;
uint8_t lcr;
if(VCOM_isbridge) {
lcr = LPC_USART->LCR;
if ( mstime) {
lcr |= (1 << 6);
} else {
lcr &= ~(1 << 6);
}
LPC_USART->LCR = lcr;
}
pVcom->break_time = mstime;
return LPC_OK;
}
ErrorCode_t VCOM_bulk_in_hdlr(USBD_HANDLE_T hUsb, void* data, uint32_t event) {
return LPC_OK;
}
ErrorCode_t VCOM_bulk_out_hdlr(USBD_HANDLE_T hUsb, void* data, uint32_t event) {
VCOM_DATA_T* pVcom = (VCOM_DATA_T*) data;
if(event == USB_EVT_OUT) {
if (pVcom->rxlen == 0) {
pVcom->rxlen = USBROM->hw->ReadEP(hUsb, USB_CDC_EP_BULK_OUT, pVcom->rxBuf);
pVcom->send_fn(pVcom);
}
else {
/* indicate bridge write buffer pending in USB buf */
pVcom->usbrx_pend = 1;
}
}
return LPC_OK;
}
void USB_IRQHandler(void) {
USBROM->hw->ISR(hUsb);
}
// ****************************************************************************
// *** LED Functions
// ****************************************************************************
volatile unsigned char FUNCLEDStatus;
unsigned char RSTPoll(void) {
unsigned char result;
result = RSTRead();
Port0SetOut(PIN0);
LEDWrite(RLED, FUNCLEDStatus & RLED);
return result;
}
unsigned char PRGPoll(void) {
unsigned char result;
result = PRGRead();
Port0SetOut(PIN1);
LEDWrite(PLED, FUNCLEDStatus & PLED);
return result;
}
// ****************************************************************************
// *** UAir Interlink Functions
// ****************************************************************************
#if ILINK_EN & SSP0_EN
volatile unsigned char FUNCILinkState;
volatile unsigned short FUNCILinkID, FUNCILinkChecksumA, FUNCILinkChecksumB, FUNCILinkLength, FUNCILinkPacket;
unsigned short FUNCILinkRxBuffer[ILINK_BUFFER_SIZE];
void ILinkInit(unsigned short speed) {
SSP0Init(speed);
FUNCILinkState = 0;
}
void ILinkPoll(unsigned short message) {
unsigned short tempBufferA, tempBufferB, tempBufferC, tempBufferD;
SSP0S0SEL();
tempBufferA = SSP0Byte(0xec41);
SSP0S0CLR();
SSP0S0SEL();
tempBufferB = SSP0Byte(0x13be);
SSP0S0CLR();
SSP0S0SEL();
tempBufferC = SSP0Byte(message);
SSP0S0CLR();
SSP0S0SEL();
tempBufferD = SSP0Byte(0);
SSP0S0CLR();
ILinkProcess(tempBufferA);
ILinkProcess(tempBufferB);
ILinkProcess(tempBufferC);
ILinkProcess(tempBufferD);
}
void ILinkProcess(unsigned short data) {
switch(FUNCILinkState) {
default: // fall through to case 0
case 0: // search for 0xec41 sync characters
if(data == 0xec41) FUNCILinkState = 1;
break;
case 1: // search for 0xec41 sync characters
if(data == 0x13be) FUNCILinkState = 2;
else FUNCILinkState = 0;
break;
case 2: // read the ID
FUNCILinkID = data;
FUNCILinkChecksumA = data;
FUNCILinkChecksumB = FUNCILinkChecksumA;
FUNCILinkState = 3;
break;
case 3: // read the packet length
FUNCILinkLength = data;
FUNCILinkChecksumA += data;
FUNCILinkChecksumB += FUNCILinkChecksumA;
if(FUNCILinkLength >= ILINK_BUFFER_SIZE) FUNCILinkState = 0;
else if(FUNCILinkLength > 0) FUNCILinkState = 4;
else { // special case for zero-length packet
if(ILinkMessageRequest) ILinkMessageRequest(FUNCILinkID);
FUNCILinkState = 0;
}
FUNCILinkPacket = 0;
break;
case 4: // read a byte of payload
FUNCILinkRxBuffer[FUNCILinkPacket++] = data;
if(FUNCILinkPacket >= FUNCILinkLength) FUNCILinkState = 5;
FUNCILinkChecksumA += data;
FUNCILinkChecksumB += FUNCILinkChecksumA;
break;
case 5: // check first checksum
if(data == FUNCILinkChecksumA) FUNCILinkState = 6;
else {
if(ILinkMessageError) ILinkMessageError(FUNCILinkID);
FUNCILinkState = 0;
}
break;
case 6: // check second checksum
if(data == FUNCILinkChecksumB) {
if(ILinkMessage) ILinkMessage(FUNCILinkID, FUNCILinkRxBuffer, FUNCILinkLength);
}
else {
if(ILinkMessageError) ILinkMessageError(FUNCILinkID);
}
FUNCILinkState = 0;
break;
}
}
void ILinkFetchData(void) {
unsigned char idle = 0;
unsigned int count = ILINK_MAX_FETCH;
unsigned short data;
while(idle < 3 && count-- > 0) {
if(ILinkReadable()) {
SSP0S0SEL();
data = SSP0Byte(ILinkPop());
SSP0S0CLR();
ILinkProcess(data);
}
else {
SSP0S0SEL();
data = SSP0Byte(0xffff);
SSP0S0CLR();
ILinkProcess(data);
if(FUNCILinkState < 2) idle++;
}
}
}
unsigned char ILinkSendMessage(unsigned short id, unsigned short * buffer, unsigned short length) {
unsigned short value;
unsigned int j;
unsigned short chkA, chkB;
if(ILinkWritable() > length+6) {
ILinkPush(0xec41);
ILinkPush(0x13be);
ILinkPush(id);
ILinkPush(length);
chkA = id + length;
chkB = chkA + id;
for(j=0; j<length; j++) {
value = buffer[j];
ILinkPush(value);
chkA += value;
chkB += chkA;
}
ILinkPush(chkA);
ILinkPush(chkB);
return 1;
}
else return 0;
}
//#if ILINK_EN == 2
unsigned short FUNCILinkTxBuffer[ILINK_BUFFER_SIZE];
volatile unsigned short FUNCILinkTxBufferPushPtr, FUNCILinkTxBufferPopPtr;
unsigned short ILinkWritable(void) {
if(FUNCILinkTxBufferPushPtr < FUNCILinkTxBufferPopPtr) return FUNCILinkTxBufferPopPtr - FUNCILinkTxBufferPushPtr - 1;
else return ILINK_BUFFER_SIZE + FUNCILinkTxBufferPopPtr - FUNCILinkTxBufferPushPtr - 1;
}
unsigned short ILinkReadable(void) {
if(FUNCILinkTxBufferPushPtr < FUNCILinkTxBufferPopPtr) return ILINK_BUFFER_SIZE + FUNCILinkTxBufferPushPtr - FUNCILinkTxBufferPopPtr;
else return FUNCILinkTxBufferPushPtr - FUNCILinkTxBufferPopPtr;
}
unsigned short ILinkPop(void) {
unsigned short retval;
retval = FUNCILinkTxBuffer[FUNCILinkTxBufferPopPtr++];
if(FUNCILinkTxBufferPopPtr >= ILINK_BUFFER_SIZE) FUNCILinkTxBufferPopPtr = 0;
return retval;
}
void ILinkPush(unsigned short data) {
FUNCILinkTxBuffer[FUNCILinkTxBufferPushPtr++] = data;
if(FUNCILinkTxBufferPushPtr >= ILINK_BUFFER_SIZE) FUNCILinkTxBufferPushPtr = 0;
}
void SSP0Interrupt(unsigned short data) {
while(ILinkReadable() && (LPC_SSP0->SR & 0x02)) {
SSP0NextByte(ILinkPop());
}
ILinkProcess(data);
}
//#endif
#endif
#if WHO_AM_I == I_AM_THALAMUS
// ****************************************************************************
// *** ULTRA Functions (Thalamus only)
// ****************************************************************************
volatile unsigned char FUNCUltraNewData;
volatile unsigned short FUNCUltraValue;
volatile unsigned char FUNCUltraOutOfRange;
volatile unsigned char FUNCUltraUnderRange;
volatile unsigned char FUNCUltraFastRate;
unsigned char UltraInit(void) {
Port0SetOut(PIN7);
Port0Write(PIN7, 0);
Timer1Init(71); // runs at 1us
Timer1Match0(10, INTERRUPT); // Pulse interrupt
Timer1Match1(6666, INTERRUPT); //
Timer1Match3(12000, RESET | INTERRUPT); // overrun interrupt
Timer1Capture(FALLING | PWRESET | INTERRUPT); // step6: set capture interrupt for falling edge of echo;
FUNCUltraFastRate = 0;
return 1;
}
unsigned short UltraGetData(void) {
if(FUNCUltraOutOfRange) return 0;
else return (FUNCUltraValue * 170)/1000;
}
unsigned short UltraGetRawData(void) {
if(FUNCUltraOutOfRange) return 0;
else return FUNCUltraValue;
}
unsigned short UltraGetNewData(void) {
if(FUNCUltraNewData) {
FUNCUltraNewData = 0;
if(FUNCUltraOutOfRange) return 0;
else return (FUNCUltraValue * 170)/1000;
}
else return 0;
}
void Timer1InterruptC(unsigned short timerValue) {
if(FUNCUltraOutOfRange) {
FUNCUltraOutOfRange = 0;
}
else {
FUNCUltraValue = timerValue;
FUNCUltraNewData = 1;
if(FUNCUltraFastRate) {
if(timerValue < 6500) {
FUNCUltraUnderRange = 1;
}
else {
FUNCUltraUnderRange = 0;
Port0Write(PIN7, 1);
Timer1Reset();
Timer1Go();
}
}
}
}
void Timer1Interrupt0(void) {
Port0Write(PIN7, 0);
}
void Timer1Interrupt1(void) {
if(FUNCUltraUnderRange) {
FUNCUltraUnderRange = 0;
Port0Write(PIN7, 1);
Timer1Reset();
Timer1Go();
}
}
void Timer1Interrupt3(void) {
if(Port0Read(PIN20)) { // if signal is high, then Ultrasound timeout/out of range
FUNCUltraOutOfRange = 1;
}
FUNCUltraUnderRange = 0;
Port0Write(PIN7, 1);
}
// ****************************************************************************
// *** RX Functions (Thalamus)
// ****************************************************************************
volatile unsigned char FUNCRXCount;
volatile unsigned char FUNCRXLastByte;
volatile unsigned char FUNCRXChannel;
volatile unsigned char FUNCRXNewData;
unsigned short FUNCRXChanBuffer[7];
unsigned short FUNCRXChan[7];
void RXInit(void) {
Port0Init(PIN17 | PIN18);
Port0SetOut(PIN17 | PIN18); // PIN17 is power pin to PNP base, PIN18 is RX pin
Port0Write(PIN17 | PIN18, 0);
Delay(500);
UARTInit(115200);
WDTInit(5);
}
void RXBind(void) {
UARTStop();
Port0Init(PIN17 | PIN18);
Port0SetOut(PIN17 | PIN18); // PIN17 is power pin to PNP base, PIN18 is RX pin
Port0Write(PIN17, 1); // Power off
Delay(500);
Port0Write(PIN18, 1); // RX pin high during power on to go into bind mode
Port0Write(PIN17, 0); // Power On
Delay(100); // Delay after Rx startup is needed
// Three low pulses to go into Master bind mode
Port0Write(PIN18, 0); RXDelay(); Port0Write(PIN18, 1); RXDelay();
Port0Write(PIN18, 0); RXDelay(); Port0Write(PIN18, 1); RXDelay();
Port0Write(PIN18, 0); RXDelay(); Port0Write(PIN18, 1); RXDelay();
FUNCRXCount = 0;
FUNCRXNewData = 0;
UARTInit(115200);
}
void RXDelay(void) {
volatile unsigned int i;
for(i=0; i<600; i++);
}
void WDTInterrupt(void) {
FUNCRXCount = 0;
}
unsigned char RXProcess(unsigned char RXByte) {
if(FUNCRXCount == 0) { // sync byte 1
if(RXByte == 0x03) FUNCRXCount++;
}
else if(FUNCRXCount == 1) { // sync byte 2
//if(RXByte == 0x01) FUNCRXCount++; // Not clear what this sync byte does, we've gotten 0x01 on DX6e and DX5e, and 0x29 and 0xa2 for DX4e
//else FUNCRXCount = 0;
FUNCRXCount++;
}
else {
if(FUNCRXCount % 2 == 0) { // even bytes
FUNCRXLastByte = RXByte;
FUNCRXChannel = (RXByte >> 2) & 0x7;
}
else { // odd bytes
FUNCRXChanBuffer[FUNCRXChannel] = (FUNCRXLastByte & 0x3) << 8 | RXByte;
}
FUNCRXCount++;
if(FUNCRXCount >= 16) {
FUNCRXCount = 0;
FUNCRXNewData = 1;
FUNCRXChan[0] = FUNCRXChanBuffer[0];
FUNCRXChan[1] = FUNCRXChanBuffer[1];
FUNCRXChan[2] = FUNCRXChanBuffer[2];
FUNCRXChan[3] = FUNCRXChanBuffer[3];
FUNCRXChan[4] = FUNCRXChanBuffer[4];
FUNCRXChan[5] = FUNCRXChanBuffer[5];
FUNCRXChan[6] = FUNCRXChanBuffer[6];
return 1;
}
}
return 0;
}
unsigned char RXGetData(unsigned short * RXChannels) {
if(FUNCRXNewData) {
RXChannels[0] = FUNCRXChan[0];
RXChannels[1] = FUNCRXChan[1];
RXChannels[2] = FUNCRXChan[2];
RXChannels[3] = FUNCRXChan[3];
RXChannels[4] = FUNCRXChan[4];
RXChannels[5] = FUNCRXChan[5];
RXChannels[6] = FUNCRXChan[6];
FUNCRXNewData = 0;
return 1;
}
else return 0;
}
void UARTInterrupt(unsigned char UARTData){
RXProcess(UARTData);
WDTFeed();
}
// ****************************************************************************
// *** PWM Ouput Functions (Thalamus)
// ****************************************************************************
volatile unsigned char FUNCPWMPostscale;
volatile unsigned short FUNCPWMN_duty;
volatile unsigned short FUNCPWME_duty;
volatile unsigned short FUNCPWMS_duty;
volatile unsigned short FUNCPWMW_duty;
volatile unsigned short FUNCPWMX_duty;
volatile unsigned short FUNCPWMY_duty;
#if PWM_FILTERS_ON == 1
volatile unsigned int FUNCPWMN_fil;
volatile unsigned int FUNCPWME_fil;
volatile unsigned int FUNCPWMS_fil;
volatile unsigned int FUNCPWMW_fil;
volatile unsigned int FUNCPWMX_fil;
volatile unsigned int FUNCPWMY_fil;
#endif
void PWMInit(unsigned char channels) {
Timer2Init(71); // set to 1uS
Timer3Init(71); // set to 1uS
Timer2Match0(1000000/PWM_NESWFREQ, INTERRUPT);
#if PWM_FILTERS_ON == 1
FUNCPWMN_fil = PWM_DEFAULT_N;
FUNCPWME_fil = PWM_DEFAULT_E;
FUNCPWMS_fil = PWM_DEFAULT_S;
FUNCPWMW_fil = PWM_DEFAULT_W;
FUNCPWMX_fil = PWM_DEFAULT_X;
FUNCPWMW_fil = PWM_DEFAULT_Y;
#endif
FUNCPWMN_duty = PWM_DEFAULT_N;
FUNCPWME_duty = PWM_DEFAULT_E;
FUNCPWMS_duty = PWM_DEFAULT_S;
FUNCPWMW_duty = PWM_DEFAULT_W;
FUNCPWMX_duty = PWM_DEFAULT_X;
FUNCPWMY_duty = PWM_DEFAULT_Y;
if(channels & PWM_S) { Timer3Match3(PWM_DEFAULT_S, OUTPUTLOW); }
if(channels & PWM_E) { Timer3Match1(PWM_DEFAULT_E, OUTPUTLOW); }
if(channels & PWM_N) { Timer3Match0(PWM_DEFAULT_N, OUTPUTLOW); }
if(channels & PWM_W) { Timer3Match2(PWM_DEFAULT_W, OUTPUTLOW); }
if(channels & PWM_X) { Timer2Match3(PWM_DEFAULT_X, OUTPUTLOW); }
if(channels & PWM_Y) { Timer2Match1(PWM_DEFAULT_Y, OUTPUTLOW); }
FUNCPWMPostscale = 0;
}
void Timer2Interrupt0() {
Timer3SetMatch3(FUNCPWMS_duty);
Timer3SetMatch1(FUNCPWME_duty);
Timer3SetMatch0(FUNCPWMN_duty);
Timer3SetMatch2(FUNCPWMW_duty);
if(FUNCPWMPostscale++ > PWM_NESWFREQ/PWM_XYFREQ) {
Timer2SetMatch3(FUNCPWMX_duty);
Timer2SetMatch1(FUNCPWMY_duty);
Timer2SetStatus(MATCH1 | MATCH3);
FUNCPWMPostscale = 0;
}
Timer3SetStatus(MATCH0 | MATCH1 | MATCH2 | MATCH3);
Timer2Reset();
Timer2Go();
Timer3Reset();
Timer3Go();
}
// ****************************************************************************
// *** IMU Functions (Thalamus)
// ****************************************************************************
void SensorInit(void) {
unsigned char I2CBuffer[5];
I2CInit(400);
// *** Accelerometer
I2CBuffer[0] = ACCEL_ADDR;
I2CBuffer[1] = 0x20 + 0x80; // Control Register CTRL_REG1_A
I2CBuffer[2] = ((ACCEL_RATE & 0xf) << 4) | ((ACCEL_LOW_POWER & 0x1) << 3) | 0x7; // XYZ axis enable
I2CMaster(I2CBuffer, 3, 0, 0);
I2CBuffer[0] = ACCEL_ADDR;
I2CBuffer[1] = 0x23 + 0x80; // Control Register CTRL_REG4_A
I2CBuffer[2] = 0x80 | ((ACCEL_RANGE & 0x3) << 4) | (((~ACCEL_LOW_POWER) & 0x1) << 3);
I2CMaster(I2CBuffer, 3, 0, 0);
// I2CBuffer[0] = ACCEL_ADDR;
// I2CBuffer[1] = 0x24 + 0x80; // Control Register CTRL_REG5_A
// I2CBuffer[2] = 0x40; // FIFO enable
// I2CMaster(I2CBuffer, 3, 0, 0);
// I2CBuffer[0] = ACCEL_ADDR;
// I2CBuffer[1] = 0x2e + 0x80; // Control Register FIFO_CTRL_REG_A
// I2CBuffer[2] = 0x40; // FIFO mode
// I2CMaster(I2CBuffer, 3, 0, 0);
// *** Gyroscope
I2CBuffer[0] = GYRO_ADDR;
I2CBuffer[1] = 0x20 + 0x80; // Control Register CTRL_REG1_G
I2CBuffer[2] = ((GYRO_RATE & 0x3) << 6) | ((GYRO_BANDWIDTH & 0x3) << 4) | 0xf; // XYZ axis enable
I2CMaster(I2CBuffer, 3, 0, 0);
I2CBuffer[0] = GYRO_ADDR;
I2CBuffer[1] = 0x23 + 0x80; // Control Register CTRL_REG4_G
I2CBuffer[2] = 0x80 | ((GYRO_RANGE & 0x3) << 4); // Set dynamic range
I2CMaster(I2CBuffer, 3, 0, 0);
I2CBuffer[0] = GYRO_ADDR;
I2CBuffer[1] = 0x24 + 0x80; // Control Register CTRL_REG5_G
I2CBuffer[2] = ((GYRO_LPF & 0x1) << 1) ; // Set the secondary low pass filter
I2CMaster(I2CBuffer, 3, 0, 0);
// *** Magneto
I2CBuffer[0] = MAGNETO_ADDR;
I2CBuffer[1] = 0x00; // Config address start location
I2CBuffer[2] = ((MAGNETO_AVERAGING & 0x3) << 5) | ((MAGNETO_RATE & 0x7) << 2) | (MAGNETO_BIAS & 0x3); // Configuration Register A
I2CBuffer[3] = (MAGNETO_GAIN & 0x7) << 5; // Configuration Register B
I2CBuffer[4] = MAGNETO_MODE & 0x3; // Mode Register
I2CMaster(I2CBuffer, 5, 0, 0);
}
unsigned char GetAccel(signed short * data) {
unsigned char I2CBuffer[6];
unsigned char * ptr; // mess with pointers to shoehorn chars into signed short array
ptr = (unsigned char *) data;
I2CBuffer[0] = ACCEL_ADDR;
I2CBuffer[1] = 0x28 + 0x80; // Data register start
I2CBuffer[2] = ACCEL_ADDR | 1;
if(I2CMaster(I2CBuffer, 2, I2CBuffer, 6)){
ptr[0] = I2CBuffer[0]; // Thalamus X LSB
ptr[1] = I2CBuffer[1]; // Thalamus X MSB
ptr[2] = I2CBuffer[4]; // Thalamus Y LSB
ptr[3] = I2CBuffer[5]; // Thalamus Y MSB
ptr[4] = I2CBuffer[2]; // Thalamus Z LSB
ptr[5] = I2CBuffer[3]; // Thalamus Z MSB
data[2] = -data[2];
return 1;
}
else return 0;
}
unsigned char GetGyro(signed short * data) {
unsigned char I2CBuffer[8];
unsigned char * ptr; // mess with pointers to shoehorn chars into signed short array
char temp;
ptr = (unsigned char *) data;
I2CBuffer[0] = GYRO_ADDR;
I2CBuffer[1] = 0x26 + 0x80; // Data register start
I2CBuffer[2] = GYRO_ADDR | 1;
if(I2CMaster(I2CBuffer, 2, I2CBuffer, 8)) {
ptr[0] = I2CBuffer[2]; // Thalamus X LSB
ptr[1] = I2CBuffer[3]; // Thalamus X MSB
ptr[2] = I2CBuffer[6]; // Thalamus Y LSB
ptr[3] = I2CBuffer[7]; // Thalamus Y MSB
ptr[4] = I2CBuffer[4]; // Thalamus Z LSB
ptr[5] = I2CBuffer[5]; // Thalamus Z MSB
data[2] = -data[2];
temp = I2CBuffer[0]; // Temperature
data[3] = (signed short) temp;
return 1;
}
else return 0;
}
signed short GetTemp(void) {
unsigned char I2CBuffer[3];
char temp;
I2CBuffer[0] = GYRO_ADDR;
I2CBuffer[1] = 0x26 + 0x80; // Temperature data
I2CBuffer[2] = GYRO_ADDR | 1;
I2CMaster(I2CBuffer, 2, I2CBuffer, 1);
temp = I2CBuffer[0];
return (signed short) temp;
}
unsigned char GetMagneto(signed short * data) {
unsigned char I2CBuffer[6];
unsigned char * ptr; // mess with pointers to shoehorn chars into signed short array
ptr = (unsigned char *) data;
#if MAGNETO_MODE
unsigned char tries, length= 0;
I2CBuffer[0] = MAGNETO_ADDR;
I2CBuffer[1] = 0x02; // Mode Register
I2CBuffer[2] = 0x1; // Set to start Single-Measurement Mode
I2CMaster(I2CBuffer, 5, 0, 0);
tries = 0;
while(tries++ < MAGNETO_TRIES_MAX) {
I2CBuffer[0] = MAGNETO_ADDR;
I2CBuffer[1] = 0x09; // Contains the RDY flag
I2CBuffer[2] = MAGNETO_ADDR | 1;
if(I2CMaster(I2CBuffer, 2, I2CBuffer, 1)) {
if(I2CBuffer[0] & 0x01) {
length = 1;
break;
}
else Delay(MAGNETO_TRIES_DELAY);
}
else {
break;
}
}
if(length > 0) {
#endif
I2CBuffer[0] = MAGNETO_ADDR;
I2CBuffer[1] = 0x03; // data Register start
I2CBuffer[2] = MAGNETO_ADDR | 1;
if(I2CMaster(I2CBuffer, 2, I2CBuffer, 6)) {
ptr[0] = I2CBuffer[1]; // Seraphim X LSB
ptr[1] = I2CBuffer[0]; // Seraphim X MSB
ptr[2] = I2CBuffer[5]; // Seraphim Y LSB
ptr[3] = I2CBuffer[4]; // Seraphim Y MSB
ptr[4] = I2CBuffer[3]; // Seraphim Z LSB
ptr[5] = I2CBuffer[2]; // Seraphim Z MSB
data[2] = -data[2];
return 1;
}
else return 0;
#if MAGNETO_MODE
}
return 0;
#endif
}
void SensorSleep(void) {
// Magneto sleep
unsigned char I2CBuffer[3];
I2CBuffer[0] = ACCEL_ADDR;
I2CBuffer[1] = 0x20; // Control Register CTRL_REG1_A
I2CBuffer[2] = ((ACCEL_RATE & 0xf) << 4) | ((ACCEL_LOW_POWER & 0x1) << 3) | 0x0; // XYZ axis disable
I2CMaster(I2CBuffer, 3, 0, 0);
I2CBuffer[0] = GYRO_ADDR;
I2CBuffer[1] = 0x20; // Control Register CTRL_REG1_G
I2CBuffer[2] = ((GYRO_RATE & 0x3) << 6) | ((GYRO_BANDWIDTH & 0x3) << 4) | 0x8; // XYZ axis disable
I2CMaster(I2CBuffer, 3, 0, 0);
I2CBuffer[0] = MAGNETO_ADDR;
I2CBuffer[1] = 0x02; // Mode Register
I2CBuffer[2] = 0x02; // Idle mode
I2CMaster(I2CBuffer, 3, 0, 0);
}
#endif
#if WHO_AM_I == I_AM_HYPO
// ****************************************************************************
// *** PWM Ouput Functions (Hypo)
// TODO: fix PWM a la Thalamus
// ****************************************************************************
volatile unsigned char FUNCPWMPostscale;
#if PWM_FILTERS_ON == 1
volatile unsigned int FUNCPWMA_fil;
volatile unsigned int FUNCPWMB_fil;
volatile unsigned int FUNCPWMC_fil;
volatile unsigned int FUNCPWMD_fil;
volatile unsigned int FUNCPWMS_fil;
#endif
void PWMInit(unsigned char channels) {
Timer2Init(71); // set to 1uS
Timer3Init(71); // set to 1uS
Timer2Match0(1000000/PWM_ABCDFREQ, INTERRUPT);
#if PWM_FILTERS_ON == 1
FUNCPWMA_fil = PWM_DEFAULT_A;
FUNCPWMB_fil = PWM_DEFAULT_B;
FUNCPWMC_fil = PWM_DEFAULT_C;
FUNCPWMD_fil = PWM_DEFAULT_D;
FUNCPWMS_fil = PWM_DEFAULT_S;
#endif
if(channels & PWM_A) { Timer3Match3(PWM_DEFAULT_A, OUTPUTLOW); }
if(channels & PWM_B) { Timer3Match1(PWM_DEFAULT_B, OUTPUTLOW); }
if(channels & PWM_C) { Timer3Match0(PWM_DEFAULT_C, OUTPUTLOW); }
if(channels & PWM_D) { Timer3Match2(PWM_DEFAULT_D, OUTPUTLOW); }
if(channels & PWM_S) { Timer2Match3(PWM_DEFAULT_S, OUTPUTLOW); }
FUNCPWMPostscale = 0;
}
void Timer2Interrupt0() {
Timer2Reset();
Timer2Go();
Timer3Reset();
Timer3Go();
if(FUNCPWMPostscale++ > PWM_ABCDFREQ/PWM_SFREQ) {
Timer2SetStatus(MATCH1 | MATCH3);
FUNCPWMPostscale = 0;
}
Timer3SetStatus(MATCH0 | MATCH1 | MATCH2 | MATCH3);
}
// ****************************************************************************
// *** GPS Functions (Hypo)
// ****************************************************************************
#if GPS_EN
void GPSInit(void) {
unsigned char UBX_CFG_RST[13] = { GPS_ADDR, 0xb5, 0x62, 0x06, 0x04, 0x04, 0x00, 0xff, 0xff, 0x09, 0x00, 0x15, 0x6f}; // CFG-PM2 Power management config: set wake up
unsigned char UBX_CFG_PRT[29] = { GPS_ADDR, 0xb5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x96 }; // CFG-PRT Port config: sets DDC slave address to 0x84 (0x42 in 7 bit), sets UBX protocol only.
unsigned char UBX_CFG_TPS[41] = { GPS_ADDR, 0xb5, 0x62, 0x06, 0x31, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0xc0, 0xc6, 0x2d, 0x00, 0x20, 0xa1, 0x07, 0x00, 0xa0, 0x86, 0x01, 0x00, 0xa0, 0x86, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf7, 0x00, 0x00, 0x00, 0x49, 0xEC }; // CFG-TPS Timepulse config: three second pulses when not locked, half pulse when locked
#if GPS_5HZ_RATE
unsigned char UBX_CFG_RATE[15] = { GPS_ADDR, 0xb5, 0x62, 0x06, 0x08, 0x06, 0x00, 0xc8, 0x00, 0x01, 0x00, 0x01, 0x00, 0xde, 0x6a }; // CFG-RATE Navigation/Measurement Rate Settings: set to 5Hz rate (max supported by NEO-6Q)
#else
unsigned char UBX_CFG_RATE[15] = { GPS_ADDR, 0xb5, 0x62, 0x06, 0x08, 0x06, 0x00, 0xe8, 0x03, 0x01, 0x00, 0x01, 0x00, 0x01, 0x39 }; // CFG-RATE Navigation/Measurement Rate Settings: set to 1Hz rate
#endif
#if GPS_AIRBORNE
unsigned char UBX_CFG_NAV5[45] = {GPS_ADDR, 0xb5, 0x62, 0x06, 0x24, 0x24, 0x00, 0x09, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5E, 0x11 }; // CFG-NAV5 Navigation engine settings: set the dynamic model to Airborne<1g and dead reckoning time to 1s
#endif
I2CInit(100);
Delay(100);
I2CMaster(UBX_CFG_RST, 13, 0, 0); // Send the reset configs
I2CMaster(UBX_CFG_PRT, 29, 0, 0); // Send the port configs
I2CMaster(UBX_CFG_TPS, 41, 0, 0); // Send the Timepulse settings (otherwise the LED don't flash)
I2CMaster(UBX_CFG_RATE, 15, 0, 0); // Send the Rate settings
#if GPS_AIRBORNE
I2CMaster(UBX_CFG_NAV5, 45, 0, 0); // Send the Nav settings (to put in Airborne<1g dynamic model)
#endif
#if GPS_METHOD == 1
FUNCGPSState = 0;
#endif
}
void GPSHotstart(void) {
unsigned char UBX_CFG_RST[13] = { GPS_ADDR, 0xb5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x17, 0x76}; // CFG-PM2 Power management config: set wake up
I2CMaster(UBX_CFG_RST, 13, 0, 0); // Send the reset configs
}
void GPSSleep(void) {
unsigned char UBX_CFG_RST[13] = {GPS_ADDR, 0xb5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x16, 0x74}; // CFG-PM2 Power management config: set shutdown
I2CMaster(UBX_CFG_RST, 13, 0, 0); // Send the power management configs
}
void GPSPoll(unsigned short id) {
unsigned char id1, id2;
unsigned char UBX_POLL[9] = {GPS_ADDR, 0xb5, 0x62, 0, 0, 0x00, 0x00, 0, 0};
id1 = id >> 8;
id2 = id & 0xff;
UBX_POLL[3] = id1; // ID
UBX_POLL[4] = id2; // ID
UBX_POLL[7] = id1 + id2; // checksum A
UBX_POLL[8] = id1*4 + id2*3; // checksum B
I2CMaster(UBX_POLL, 9, 0, 0);
}
#if GPS_METHOD == 0
unsigned short GPSGetMessage(unsigned short id, unsigned char * buffer) {
unsigned char data[GPS_BUFFER_SIZE], character, tries, state, id1=0, id2=0, chkA=0, chkB=0;
unsigned short length, request, payloadlength=0, i, packetcounter=0;
tries = GPS_TRIES_MAX;
while(tries > 0) {
data[0] = GPS_ADDR;
data[1] = 0xfd; // Contains the number of valid bytes
data[2] = GPS_ADDR | 1;
if(I2CMaster(data, 2, data, 2)) length = data[1] + (data[0] << 8);
else length = 0;
state = 0;
if(length > 0) {
if(length > GPS_BUFFER_SIZE) { // prevent overflow
request = GPS_BUFFER_SIZE;
length -= GPS_BUFFER_SIZE;
}
else {
request = length;
length = 0;
}
data[0] = GPS_ADDR;
data[1] = 0xff; // Contains the message stream
data[2] = GPS_ADDR | 1;
if(I2CMaster(data, 2, data, request)) {
for(i=0; i<request; i++) {
character = data[i];
switch(state) {
default: // fall through to case 0
case 0: // search for 0xB5 first start header
if(character == 0xB5) {state = 1; }
break;
case 1: // search for 0x62 second start header
if(character == 0x62) {state = 2;}
else state = 0;
break;
case 2: // read the first ID
id1 = character;
chkA = character;
chkB = chkA;
state = 3;
break;
case 3: // read the second ID
id2 = character;
chkA += character;
chkB += chkA;
state = 4;
break;
case 4: // read the first byte of length
payloadlength = character;
chkA += character;
chkB += chkA;
state = 5;
break;
case 5: // read the second byte of length
payloadlength += character << 8;
chkA += character;
chkB += chkA;
if(((id1 << 8) | id2) != id) { // check for the ID we want
state = 0;
if(i+payloadlength+2 > request) { // don't bother processing the packet if it's not the right message (dont' exceed requested data size)
i = request;
}
else {
i += payloadlength + 2;
}
}
else {
if(payloadlength > 0) state = 6; // zero-length messages go direct to checksum
else state = 7;
}
packetcounter = 0;
break;
case 6: // read a byte of payload
buffer[packetcounter] = character;
packetcounter++;
if(packetcounter >= payloadlength) state = 7;
chkA += character;
chkB += chkA;
break;
case 7: // check first checksum
if(character == chkA) state = 8;
else state = 0;
break;
case 8: // check second checksum
if(character == chkB) {
// data valid
return payloadlength;
}
else {
// data invalid
return 0;
}
state = 0;
break;
}
}
}
}
else {
Delay(GPS_TRIES_DELAY);
tries--;
}
}
return 0;
}
void GPSClearBuffer(void) {
unsigned char data[GPS_BUFFER_SIZE];
unsigned short length, request;
data[0] = GPS_ADDR;
data[1] = 0xfd; // Contains the number of valid bytes
data[2] = GPS_ADDR | 1;
if(I2CMaster(data, 2, data, 2)) length = data[1] + (data[0] << 8);
else length = 0;
while(length > 0) {
if(length > GPS_BUFFER_SIZE) { // prevent overflow
request = GPS_BUFFER_SIZE;
length -= GPS_BUFFER_SIZE;
}
else {
request = length;
length = 0;
}
data[0] = GPS_ADDR;
data[1] = 0xff; // Contains the message stream
data[2] = GPS_ADDR | 1;
I2CMaster(data, 2, data, request);
}
}
unsigned char GPSGetLocation(signed int * location) {
unsigned char payload[28];
unsigned char i;
unsigned char * ptr; // mess with pointers to shoehorn chars into int array
ptr = (unsigned char *) location;
GPSPoll(ID_NAV_POSLLH);
if(GPSGetMessage(ID_NAV_POSLLH, payload)) {
GPSClearBuffer();
for(i=0; i<8; i++) {
ptr[i] = payload[i+4];
}
for(; i<12; i++) {
ptr[i] = payload[i+8];
}
return 1;
}
return 0;
}
unsigned char GPSGetFix(void) {
unsigned char payload[16];
GPSPoll(ID_NAV_STATUS);
if(GPSGetMessage(ID_NAV_STATUS, payload)) {
GPSClearBuffer();
if(payload[5] & 0x01) { // first bit of this byte is "gpsFixOk"
return payload[4]; // this contains gpsFix information
}
}
return 0;
}
#endif
#if GPS_METHOD == 1
volatile unsigned char FUNCGPSState, FUNCGPSChecksumA, FUNCGPSChecksumB, FUNCGPSID1, FUNCGPSID2;
volatile unsigned short FUNCGPSLength, FUNCGPSPacket, FUNCGPSID;
unsigned char FUNCGPSBuffer[GPS_BUFFER_SIZE];
void GPSSetRate(unsigned short id, unsigned char rate) {
unsigned char id1, id2;
unsigned char UBX_POLL[17] = {GPS_ADDR, 0xb5, 0x62, 0x06, 0x01, 0x08, 0x00, 0, 0, 0, 0x00, 0x00, 0x00, 0x00, 0x00, 0, 0 };
id1 = id >> 8;
id2 = id & 0xff;
UBX_POLL[7] = id1; // ID
UBX_POLL[8] = id2; // ID
UBX_POLL[9] = rate; // rate
UBX_POLL[15] = 15 + id1 + id2 + rate; // checksum A
UBX_POLL[16] = 163 + id1*8 + id2*7 + rate*6; // checksum B
I2CMaster(UBX_POLL, 17, 0, 0);
}
void GPSFetchData(void) {
unsigned char data[GPS_BUFFER_SIZE], character;
unsigned short length=0, request, i;
data[0] = GPS_ADDR;
data[1] = 0xfd; // Contains the number of valid bytes
data[2] = GPS_ADDR | 1;
if(I2CMaster(data, 2, data, 2)) length = data[1] + (data[0] << 8);
else length = 0;
while(length > 0) {
if(length > I2C_DATA_SIZE) { // prevent overflow
request = I2C_DATA_SIZE;
length -= I2C_DATA_SIZE;
}
else {
request = length;
length = 0;
}
data[0] = GPS_ADDR;
data[1] = 0xff; // Contains the message stream
data[2] = GPS_ADDR | 1;
if(I2CMaster(data, 2, data, request)) {
for(i=0; i<request; i++) {
character = data[i];
switch(FUNCGPSState) {
default: // fall through to case 0
case 0: // search for 0xB5 first start header
if(character == 0xB5) FUNCGPSState = 1;
break;
case 1: // search for 0x62 second start header
if(character == 0x62) FUNCGPSState = 2;
else FUNCGPSState = 0;
break;
case 2: // read the first ID
FUNCGPSID1 = character;
FUNCGPSChecksumA = character;
FUNCGPSChecksumB = FUNCGPSChecksumA;
FUNCGPSState = 3;
break;
case 3: // read the second ID
FUNCGPSID2 = character;
FUNCGPSChecksumA += character;
FUNCGPSChecksumB += FUNCGPSChecksumA;
FUNCGPSState = 4;
break;
case 4: // read the first byte of length
FUNCGPSLength = character;
FUNCGPSChecksumA += character;
FUNCGPSChecksumB += FUNCGPSChecksumA;
FUNCGPSState = 5;
break;
case 5: // read the second byte of length
FUNCGPSLength += character << 8;
FUNCGPSChecksumA += character;
FUNCGPSChecksumB += FUNCGPSChecksumA;
if(FUNCGPSLength > 0) FUNCGPSState = 6;
else FUNCGPSState = 7;
FUNCGPSPacket = 0;
break;
case 6: // read a byte of payload
if(FUNCGPSPacket < GPS_BUFFER_SIZE) {
FUNCGPSBuffer[FUNCGPSPacket] = character;
}
FUNCGPSPacket++;
if(FUNCGPSPacket >= FUNCGPSLength) FUNCGPSState = 7;
FUNCGPSChecksumA += character;
FUNCGPSChecksumB += FUNCGPSChecksumA;
break;
case 7: // check first checksum
if(character == FUNCGPSChecksumA) FUNCGPSState = 8;
else FUNCGPSState = 0;
break;
case 8: // check second checksum
if(character == FUNCGPSChecksumB) {
// data valid
FUNCGPSID = (FUNCGPSID1 << 8) | FUNCGPSID2;
if(GPSMessage) GPSMessage(FUNCGPSID, FUNCGPSBuffer, FUNCGPSLength);
}
FUNCGPSState = 0;
break;
}
}
}
}
}
#endif
#endif
// ****************************************************************************
// *** Flash Functions
// ****************************************************************************
#if SSP1_EN
#if FLASH_EN
volatile unsigned int FUNCFlashCR0Reset, FUNCFlashCPSRReset;
volatile unsigned int FUNCFlashCurrentSector;
unsigned char FUNCFlashSectorBuffer[4096];
volatile unsigned char FUNCFlashBufferChanged;
void FlashInit(void) {
SSP1Init(12000); // Init SPI port at 12MHz
Port0Init(PIN23); // Init CS for flash chip
Port0SetOut(PIN23);
FlashStart();
FlashCLR();
// This flash chip boots up with write protection enabled everywhere, we need to disable it
FlashSEL();
SSP1WriteByte(0x50); // Enable Write to status register
FlashCLR();
FlashSEL();
SSP1WriteByte(0x01); // Write to Write Status Register
SSP1WriteByte(0x00); // - disables all protection
FlashCLR();
FlashEnd();
FUNCFlashCurrentSector = 0xffffffff;
FUNCFlashBufferChanged = 0;
}
void FlashStart(void) {
FUNCFlashCR0Reset = LPC_SSP1->CR0; // store old config
FUNCFlashCPSRReset = LPC_SSP1->CPSR; // store old clock speed
LPC_SSP1->CR0 = 7; // Switch to Phase = 0, Polarity = 0, Format = 0, Frame = 8-bit;
LPC_SSP1->CPSR = 6; // run at highest speed possible (last reliable test was at 12Mhz)
}
void FlashEnd(void) {
LPC_SSP1->CR0 = FUNCFlashCR0Reset;
LPC_SSP1->CPSR = FUNCFlashCPSRReset;
}
void FlashWait(void) {
FlashSEL();
SSP1WriteByte(0x05); // Read status register
while(SSP1ReadByte() & 0x1); // check busy status
FlashCLR();
}
void FlashWrEn(void) {
FlashSEL();
SSP1WriteByte(0x06); // enables write access
FlashCLR();
}
unsigned int FlashGetID(void) {
unsigned char ManID, Type, Capacity;
FlashStart();
FlashSEL();
SSP1WriteByte(0x9f); // grabs JEDEC ID
ManID = SSP1ReadByte();
Type = SSP1ReadByte();
Capacity = SSP1ReadByte();
FlashCLR();
FlashEnd();
return (ManID << 16) | (Type << 8) | Capacity;
}
unsigned char FlashGetMan(void) {
return FlashGetID() >> 16;
}
unsigned char FlashGetType(void) {
return FlashGetID() >> 8;
}
unsigned char FlashGetCapacity(void) {
// TODO: translate emory capacity codes
return FlashGetID() >> 0;
}
void FlashEraseChip(void) {
FlashStart();
FlashWait(); // Wait for busy
FlashWrEn(); // Enable write
// Erase the whole chip
FlashSEL();
SSP1WriteByte(0x60);
FlashCLR();
FlashEnd();
}
void FlashErase4k(unsigned int address) {
FlashStart();
FlashWait(); // Wait for busy
FlashWrEn(); // Enable write
// Erase 4k sector beginning at address & 0xfffff000
FlashSEL();
SSP1WriteByte(0x20);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
FlashCLR();
FlashEnd();
}
void FlashErase32k(unsigned int address) {
FlashStart();
FlashWait(); // Wait for busy
FlashWrEn(); // Enable write
// Erase 32k sector beginning at address & 0xffff8000
FlashSEL();
SSP1WriteByte(0x52);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
FlashCLR();
FlashEnd();
}
void FlashErase64k(unsigned int address) {
FlashStart();
FlashWait(); // Wait for busy
FlashWrEn(); // Enable write
// Erase 64k sector beginning at address & 0xffff0000
FlashSEL();
SSP1WriteByte(0xd8);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
FlashCLR();
FlashEnd();
}
void FlashRawWriteByte(unsigned int address, unsigned char data) {
FlashStart();
FlashWait(); // Wait for busy
FlashWrEn(); // Enable write
// Send byte
FlashSEL();
SSP1WriteByte(0x02);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
SSP1WriteByte(data);
FlashCLR();
FlashEnd();
}
unsigned char FlashRawReadByte(unsigned int address) {
unsigned char data;
FlashStart();
FlashWait(); // Wait for busy
// Read byte
FlashSEL();
SSP1WriteByte(0x03);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
//SSP1WriteByte(0); // dummy byte if using fast read 0x0b, do not use if using regular read 0x03
data = SSP1ReadByte();
FlashCLR();
FlashEnd();
return data;
}
unsigned char FlashVerify(unsigned int address, unsigned char * data, unsigned int length) {
unsigned int i;
FlashStart();
FlashWait(); // Wait for busy
// Read byte
FlashSEL();
SSP1WriteByte(0x03);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
//SSP1WriteByte(0); // dummy byte if using fast read 0x0b, do not use if using regular read 0x03
for(i=0; i<length; i++) {
if(SSP1ReadByte() != data[i]) {
FlashCLR();
FlashEnd();
return 0;
}
}
FlashCLR();
FlashEnd();
return 1;
}
void FlashRawWrite(unsigned int address, unsigned char * data, unsigned int length) {
unsigned char odd;
// because the flash chip's auto increment write feature writes two bytes at a time,
// if the address is an odd number, we need to do a single byte write
if((address & 0x1) && length > 0) { // check if address is odd number
FlashRawWriteByte(address, data[0]);
address++;
data++;
length--;
}
// now that the address is even, check if the length is odd, if it is then there's
// one more byte at the end that needs to be written using a single byte write
if(length & 0x1) {
odd = 1;
length--; // make length even again
}
else odd = 0;
if(length > 0) {
FlashStart();
FlashWait(); // Wait for busy
FlashWrEn(); // Enable write
// Start auto address increment programming
FlashSEL();
SSP1WriteByte(0xad);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
SSP1WriteByte(data[0]);
SSP1WriteByte(data[1]);
FlashCLR();
address+=2;
data+=2;
length-=2;
// write even length of bytes, ensure that if length is odd, the last byte is not written
while(length) {
// Poll for Busy
// TODO: replace with hardware end of write detection
FlashWait();
// Write bytes
FlashSEL();
SSP1WriteByte(0xad);
SSP1WriteByte(data[0]);
SSP1WriteByte(data[1]);
FlashCLR();
address+=2;
data+=2;
length-=2;
}
// Poll for Busy
FlashWait();
// Send Write disable to end auto address increment programming
FlashSEL();
SSP1WriteByte(0x04);
FlashCLR();
FlashEnd();
}
// if there was one more byte left over to write, deal with this using FlashWriteByte
if(odd) { // check if length is odd number
FlashRawWriteByte(address, data[0]);
}
}
void FlashRawRead(unsigned int address, unsigned char * data, unsigned int length) {
unsigned int i;
if(length > 0) {
FlashStart();
FlashWait(); // Wait for busy
// Read byte
FlashSEL();
SSP1WriteByte(0x03);
SSP1WriteByte(address >> 16);
SSP1WriteByte(address >> 8);
SSP1WriteByte(address >> 0);
//SSP1WriteByte(0); // dummy byte if using fast read 0x0b, do not use if using regular read 0x03
for(i=0; i<length; i++) {
data[i] = SSP1ReadByte();
}
FlashCLR();
FlashEnd();
}
}
void FlashBufferSector(unsigned int address) {
FlashFlushBuffer(); // FUNCFlashBufferChanged = 0 is in here
if((address & 0xfffff000) != FUNCFlashCurrentSector) {
FUNCFlashCurrentSector = address & 0xfffff000;
FlashRawRead(FUNCFlashCurrentSector, FUNCFlashSectorBuffer, 4096);
}
}
void FlashFlushBuffer(void) {
if(FUNCFlashCurrentSector != 0xffffffff) {
if(FUNCFlashBufferChanged) { // only need to write if buffer was changed
FlashErase4k(FUNCFlashCurrentSector);
FlashRawWrite(FUNCFlashCurrentSector, FUNCFlashSectorBuffer, 4096);
FUNCFlashBufferChanged = 0; // after flushing, there is now no difference between the buffer and the flash
}
}
}
void FlashWriteByte(unsigned int address, unsigned char data) {
// check conditions under which we'd need to buffer a new sector (if there is an invalid buffer, or buffer contains wrong sector)
if((FUNCFlashCurrentSector == 0xffffffff) || ((address & 0xfffff000) != FUNCFlashCurrentSector)) {
FlashBufferSector(address);
}
FUNCFlashBufferChanged = 1;
FUNCFlashSectorBuffer[address & 0xfff] = data; // save the byte to the buffer
}
void FlashWrite(unsigned int address, unsigned char * data, unsigned int length) {
unsigned int writeLength, i;
while(length) {
// check conditions under which we'd need to buffer a new sector (if there is an invalid buffer, or buffer contains wrong sector)
if((FUNCFlashCurrentSector == 0xffffffff) || ((address & 0xfffff000) != FUNCFlashCurrentSector)) {
FlashBufferSector(address);
}
writeLength = (0x1000 - (address & 0xfff)); // this is the writable bytes in this sector starting from the address
for(i=0; i<length && i<writeLength; i++) { // write into buffer
FUNCFlashSectorBuffer[(address & 0xfff) + i] = data[i];
}
FUNCFlashBufferChanged = 1;
address += i;
length -= i;
data += i;
}
}
unsigned char FlashReadByte(unsigned int address) {
// see if there's a valid sector in buffer, and that the sector is the one we want
if((FUNCFlashCurrentSector != 0xffffffff) && ((address & 0xfffff000) == FUNCFlashCurrentSector)) {
return FUNCFlashSectorBuffer[address & 0xfff]; // return the byte from the buffer
}
else {
return FlashRawReadByte(address); // otherwise get it from flash
}
}
void FlashRead(unsigned int address, unsigned char * data, unsigned int length) {
unsigned int readLength, i;
while(length) {
// see if there's a valid sector in buffer, and that the sector is the one we want
if((FUNCFlashCurrentSector != 0xffffffff) && ((address & 0xfffff000) == FUNCFlashCurrentSector)) {
readLength = (0x1000 - (address & 0xfff)); // this is the readable bytes in this sector starting from the address
for(i=0; i<length && i<readLength; i++) { // read it all out
data[i] = FUNCFlashSectorBuffer[(address & 0xfff) + i];
}
address += i;
length -= i;
data += i;
}
else {
FlashRawRead(address, data, length); // otherwise get it from flash
break;
}
}
}
#endif
#endif
#endif
#if WHO_AM_I == I_AM_HYPO || WHO_AM_I == I_AM_HYPX
// ****************************************************************************
// *** XBee Functions
// ****************************************************************************
#if UART_EN && SYSTICK_EN && XBEE_EN
unsigned char FUNCXBeetBuf[TBUF_LEN];
volatile unsigned char FUNCXBeetBufCount;
volatile unsigned int FUNCXBeeState;
volatile unsigned short FUNCXBeeLength, FUNCXBeeID, FUNCXBeePacket;
volatile unsigned char FUNCXBeeChecksum;
unsigned char FUNCXBeeBuffer[XBEE_BUFFER_SIZE];
unsigned char XBeeSendATCommand(void) {
xbee_at_command.frameID = Random() | 0x1;
XBeeSendFrame(ID_XBEE_ATCOMMAND, (unsigned char *)&xbee_at_command, sizeof(xbee_at_command)-2-16+xbee_at_command.varLen);
// check status
xbee_at_response.isNew = 0;
FUNCTimeout = 1000;
while(FUNCTimeout > 0 && xbee_at_response.isNew == 0);
if(xbee_at_response.frameID == xbee_at_command.frameID && xbee_at_response.commandStatus == 0) {
return 1;
}
return 0;
}
unsigned char XBeeWriteBroadcast(unsigned char * buffer, unsigned short length) {
unsigned int i;
for(i=0; i<length; i++) {
xbee_transmit_request.RFData[i] = buffer[i];
}
xbee_transmit_request.varLen = length;
xbee_transmit_request.destinationAddress = 0xffff000000000000ULL; //broadcast (big-endian)
xbee_transmit_request.networkAddress = 0xfeff;
XBeeSendPacket();
return 1;
}
unsigned char XBeeWriteCoordinator(unsigned char * buffer, unsigned short length) {
unsigned int i;
for(i=0; i<length; i++) {
xbee_transmit_request.RFData[i] = buffer[i];
}
xbee_transmit_request.varLen = length;
xbee_transmit_request.destinationAddress = 0x0000000000000000ULL; //to coordinator (big-endian)
xbee_transmit_request.networkAddress = 0xfeff;
XBeeSendPacket();
return 1;
}
unsigned char XBeeSendPacket(void) {
xbee_transmit_request.frameID = Random() | 0x01;
xbee_transmit_request.broadcastRadius = 0;
xbee_transmit_request.options = 0x01; // disable ACK;
XBeeSendFrame(ID_XBEE_TRANSMITREQUEST, (unsigned char *)&xbee_transmit_request, sizeof(xbee_transmit_request)-2-255+xbee_transmit_request.varLen);
return 1;
}
void XBeeAllowJoin() {
XBeeStopJoin();
// set NJ
xbee_at_command.frameID = Random() | 0x1;
xbee_at_command.ATCommand1 = 'N';
xbee_at_command.ATCommand2 = 'J';
xbee_at_command.parameterValue[0] = XBEE_JOINPERIOD;
xbee_at_command.varLen = 1;
XBeeSendATCommand();
}
void XBeeStopJoin() {
// set NJ
xbee_at_command.ATCommand1 = 'N';
xbee_at_command.ATCommand2 = 'J';
xbee_at_command.parameterValue[0] = 0x00;
xbee_at_command.varLen = 1;
XBeeSendATCommand();
}
void XBeeJoin() {
xbee_at_response.isNew = 0;
// NR to network reset
xbee_at_command.ATCommand1 = 'N';
xbee_at_command.ATCommand2 = 'R';
xbee_at_command.varLen = 0;
if(!XBeeSendATCommand()) XBeeCommFail();
// NJ0 to prevent others joining
XBeeStopJoin();
// PL# to set power level
xbee_at_command.ATCommand1 = 'P';
xbee_at_command.ATCommand2 = 'L';
xbee_at_command.parameterValue[0] = XBEE_POWER_LEVEL;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// JN1 to enable join notification
xbee_at_command.ATCommand1 = 'J';
xbee_at_command.ATCommand2 = 'N';
xbee_at_command.parameterValue[0] = 1;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// CE0 to disable coordinator mode
xbee_at_command.ATCommand1 = 'C';
xbee_at_command.ATCommand2 = 'E';
xbee_at_command.parameterValue[0] = 0;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// ID0 to set PAN ID to 0 (autofind network)
xbee_at_command.ATCommand1 = 'I';
xbee_at_command.ATCommand2 = 'D';
xbee_at_command.parameterValue[0] = 0;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// EE1 for encryption enable
xbee_at_command.ATCommand1 = 'E';
xbee_at_command.ATCommand2 = 'E';
xbee_at_command.parameterValue[0] = 1;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// KY### to set link key
xbee_at_command.ATCommand1 = 'K';
xbee_at_command.ATCommand2 = 'Y';
xbee_at_command.parameterValue[0] = 'U';
xbee_at_command.parameterValue[1] = 'N';
xbee_at_command.parameterValue[2] = 'I';
xbee_at_command.parameterValue[3] = 'V';
xbee_at_command.parameterValue[4] = 'E';
xbee_at_command.parameterValue[5] = 'R';
xbee_at_command.parameterValue[6] = 'S';
xbee_at_command.parameterValue[7] = 'A';
xbee_at_command.parameterValue[8] = 'L';
xbee_at_command.parameterValue[9] = '_';
xbee_at_command.parameterValue[10] = 'A';
xbee_at_command.parameterValue[11] = 'I';
xbee_at_command.parameterValue[12] = 'R';
xbee_at_command.parameterValue[13] = '1';
xbee_at_command.parameterValue[14] = '2';
xbee_at_command.parameterValue[15] = '3';
xbee_at_command.varLen = 16;
if(!XBeeSendATCommand()) XBeeCommFail();
// AC to apply
xbee_at_command.ATCommand1 = 'A';
xbee_at_command.ATCommand2 = 'C';
xbee_at_command.varLen = 0;
if(!XBeeSendATCommand()) XBeeCommFail();
while(1) {
Delay(100);
// AI0 to get association information
xbee_at_command.frameID = Random() | 0x1;
xbee_at_command.ATCommand1 = 'A';
xbee_at_command.ATCommand2 = 'I';
xbee_at_command.varLen = 0;
//if(!XBeeSendATCommand()) XBeeCommFail();
if(!XBeeSendATCommand()) Delay(1000);
if(xbee_at_response.commandData[0] == 0) break;
}
// WR to write changes
xbee_at_command.ATCommand1 = 'W';
xbee_at_command.ATCommand2 = 'R';
xbee_at_command.varLen = 0;
if(!XBeeSendATCommand()) XBeeCommFail();
}
void XBeeCoordinatorJoin() {
xbee_at_response.isNew = 0;
// NR to network reset
xbee_at_command.ATCommand1 = 'N';
xbee_at_command.ATCommand2 = 'R';
xbee_at_command.varLen = 0;
if(!XBeeSendATCommand()) XBeeCommFail();
// set Powerlevel
xbee_at_command.ATCommand1 = 'P';
xbee_at_command.ATCommand2 = 'L';
xbee_at_command.parameterValue[0] = XBEE_POWER_LEVEL;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// set CE mode
xbee_at_command.ATCommand1 = 'C';
xbee_at_command.ATCommand2 = 'E';
xbee_at_command.parameterValue[0] = 1;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// set PAN ID
xbee_at_command.ATCommand1 = 'I';
xbee_at_command.ATCommand2 = 'D';
xbee_at_command.parameterValue[0] = 0;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// encryption enable
xbee_at_command.ATCommand1 = 'E';
xbee_at_command.ATCommand2 = 'E';
xbee_at_command.parameterValue[0] = 1;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// encryption options
xbee_at_command.ATCommand1 = 'E';
xbee_at_command.ATCommand2 = 'O';
xbee_at_command.parameterValue[0] = 0x02;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// set network key to zero
xbee_at_command.ATCommand1 = 'N';
xbee_at_command.ATCommand2 = 'K';
xbee_at_command.parameterValue[0] = 0;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// set link key
xbee_at_command.ATCommand1 = 'K';
xbee_at_command.ATCommand2 = 'Y';
xbee_at_command.parameterValue[0] = 'U';
xbee_at_command.parameterValue[1] = 'N';
xbee_at_command.parameterValue[2] = 'I';
xbee_at_command.parameterValue[3] = 'V';
xbee_at_command.parameterValue[4] = 'E';
xbee_at_command.parameterValue[5] = 'R';
xbee_at_command.parameterValue[6] = 'S';
xbee_at_command.parameterValue[7] = 'A';
xbee_at_command.parameterValue[8] = 'L';
xbee_at_command.parameterValue[9] = '_';
xbee_at_command.parameterValue[10] = 'A';
xbee_at_command.parameterValue[11] = 'I';
xbee_at_command.parameterValue[12] = 'R';
xbee_at_command.parameterValue[13] = '1';
xbee_at_command.parameterValue[14] = '2';
xbee_at_command.parameterValue[15] = '3';
xbee_at_command.varLen = 16;
if(!XBeeSendATCommand()) XBeeCommFail();
// set NJ
xbee_at_command.ATCommand1 = 'N';
xbee_at_command.ATCommand2 = 'J';
xbee_at_command.parameterValue[0] = 0x00;
xbee_at_command.varLen = 1;
if(!XBeeSendATCommand()) XBeeCommFail();
// WR to write changes
xbee_at_command.ATCommand1 = 'W';
xbee_at_command.ATCommand2 = 'R';
xbee_at_command.varLen = 0;
if(!XBeeSendATCommand()) XBeeCommFail();
while(1) {
Delay(100);
// AI0 to get association information
xbee_at_command.frameID = Random() | 0x1;
xbee_at_command.ATCommand1 = 'A';
xbee_at_command.ATCommand2 = 'I';
xbee_at_command.varLen = 0;
if(XBeeSendATCommand()) break;
}
XBeeAllowJoin();
}
void XBeeSendFrame(unsigned char id, unsigned char * buffer, unsigned short length) {
unsigned int i;
unsigned char chksum;
UARTWriteByte(0x7E); // Start byte
UARTWriteByte(length >> 8); // length MSB
UARTWriteByte(length & 0xff); // length LSB
UARTWriteByte(id);
chksum = id;
for(i=0; i<length-1; i++) {
UARTWriteByte(buffer[i]);
chksum += buffer[i];
}
UARTWriteByte(0xff - chksum);
}
void XBeeSetDefaults(void) {
unsigned char changes = 0;
// Try to enter AT mode at 115200 baud
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
UARTWrite((unsigned char *)"+++", 3);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 1 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) {
// if timed out or didn't receive OK, maybe we're at the wrong baud?
// Try to enter AT mode at 9600 baud
UARTInit(9600);
Delay(100);
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
UARTWrite((unsigned char *)"+++", 3);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 1 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) {
// If timed out or did not receive OK, don't know what to do, fail.
XBeeCommFail();
}
// assuming successfully entered AT mode at 9600 baud, set baud rate to 115200 for next time
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
UARTWrite((unsigned char *)"ATBD7\r", 6);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 1 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) {
// If timed out or didn't receive OK, don't know what to do, fail.
XBeeCommFail();
}
changes+=10;
}
// assuming successfully entered AT mode, procede to check settings
// Check API mode
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
UARTWrite((unsigned char *)"ATAP\r", 5);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 2); // wait for 1 second or until 1 characters received
if(XBeetBufCompare((unsigned char *)"1\r", 2) == 0) {
// if API mode was not already on, set it
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
UARTWrite((unsigned char *)"ATAP1\r", 6);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 1 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) {
// If timed out or didn't receive OK, don't know what to do, fail.
XBeeCommFail();
}
changes++;
}
// If any changes, write them
if(changes > 0) {
FUNCXBeetBufCount = 0;
FUNCTimeout = 3000;
UARTWrite((unsigned char *)"ATWR\r", 5);
while(FUNCTimeout < 0 && FUNCXBeetBufCount < 3); // wait for 4 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) {
// If timed out or didn't receive OK, don't know what to do, fail.
//XBeeCommFail();
// For some reason this isn't always detected, disable this catch for now
}
}
// Close ATCN mode
UARTWrite((unsigned char *)"ATCN\r", 5);
if(changes > 10) {
// this signifies that the UART baud was changed, switch baud back up
Delay(100); // either a delay or wait for UART FIFO to clear
UARTInit(115200);
}
}
void XBeeFactoryReset(void) {
//Xbee can be factory reset by restarting XBee with TX held low (BREAK signal), afterwards it'll be on 9600 baud
UARTInit(9600);
Port0Init(PIN19);
Port0SetOut(PIN19);
Port0Write(PIN19, 0);
XBeeReset();
Delay(50);
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
XBeeRelease();
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 1 second or until 3 characters received: "OK\r"a
Delay(100);
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) return;
UARTInit(9600);
// issue restore defaults command
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
UARTWrite((unsigned char *)"ATRE\r", 5);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 1 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) return;
// issue save settings command
FUNCXBeetBufCount = 0;
FUNCTimeout = 3000;
UARTWrite((unsigned char *)"ATWR\r", 5);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 3 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) return;
// now restart
FUNCXBeetBufCount = 0;
FUNCTimeout = 1000;
UARTWrite((unsigned char *)"ATFR\r", 5);
while(FUNCTimeout > 0 && FUNCXBeetBufCount < 3); // wait for 1 second or until 3 characters received: "OK\r"a
if(XBeetBufCompare((unsigned char *)"OK\r", 3) == 0) return;
}
void XBeeCommFail() {
while(1);
}
unsigned int XBeetBufCompare(unsigned char * compare, unsigned int length) {
unsigned int i;
if(FUNCXBeetBufCount < length) return 0;
for(i=0; i<length; i++) {
if(compare[i] != FUNCXBeetBuf[FUNCXBeetBufCount-length+i]) return 0;
}
return 1;
}
void XBeeInit(void) {
FUNCXBeeState = 0;
UARTInit(115200);
FUNCXBeetBufCount = 0;
Port0Init(PIN20 | PIN17);
Port0SetOut(PIN20 | PIN17);
XBeeReset();
Delay(50);
XBeeRelease();
XBeeAllow();
// Start timeout and wait to see if XBee is already configured (should receive modem_status API frame)
FUNCTimeout = 1000;
xbee_modem_status.isNew = 0;
while(FUNCTimeout > 0 && xbee_modem_status.isNew == 0);
if(xbee_modem_status.isNew == 0) {
XBeeSetDefaults();
}
}
void UARTInterrupt(unsigned char byte) {
// insert into buffer
if(FUNCXBeetBufCount < TBUF_LEN) FUNCXBeetBuf[FUNCXBeetBufCount++] = byte;
switch(FUNCXBeeState) {
default: // fall through to 0
case 0: // find start character 0x7e
if(byte == 0x7e) FUNCXBeeState++;
break;
case 1: // length MSB
FUNCXBeeLength = byte << 8;
FUNCXBeeState++;
break;
case 2: // length LSB
FUNCXBeeLength |= byte;
if(FUNCXBeeLength > 1) FUNCXBeeState++;
else FUNCXBeeState = 0;
FUNCXBeePacket = 0;
FUNCXBeeChecksum = 0;
break;
case 3: // cmd frame
FUNCXBeeID = byte;
FUNCXBeeLength--; // length value includes ID, we need length in terms of payload size
FUNCXBeeState++;
FUNCXBeeChecksum += byte;
break;
case 4: // cmd data
if(FUNCXBeePacket < XBEE_BUFFER_SIZE) {
FUNCXBeeBuffer[FUNCXBeePacket] = byte;
}
FUNCXBeePacket++;
if(FUNCXBeePacket >= FUNCXBeeLength) FUNCXBeeState++;
FUNCXBeeChecksum += byte;
break;
case 5: // checksum
if(0xff - FUNCXBeeChecksum == byte) {
if(XBeeMessage) XBeeMessage(FUNCXBeeID, FUNCXBeeBuffer, FUNCXBeeLength);
}
else {
}
FUNCXBeeState = 0;
break;
case 0xff: // bypass mode
if(XBeeMessage) XBeeMessage(0, &byte, 1);
break;
}
}
#endif
#endif
#ifdef __cplusplus
}
#endif <file_sep>#ifndef __T_MAVLINK_H__
#define __T_MAVLINK_H__
#include "mavlink/common/mavlink.h"
#define MAVLINK_SENSOR_GYRO (0x1 << 0)
#define MAVLINK_SENSOR_ACCEL (0x1 << 1)
#define MAVLINK_SENSOR_MAGNETO (0x1 << 2)
#define MAVLINK_SENSOR_BARO (0x1 << 3)
#define MAVLINK_SENSOR_DIFPRESS (0x1 << 4)
#define MAVLINK_SENSOR_GPS (0x1 << 5)
#define MAVLINK_SENSOR_OPFLOW (0x1 << 6)
#define MAVLINK_SENSOR_VISION (0x1 << 7)
#define MAVLINK_SENSOR_LASER (0x1 << 8)
#define MAVLINK_SENSOR_EXTGND (0x1 << 9)
#define MAVLINK_CONTROL_ANGLERATE (0x1 << 10)
#define MAVLINK_CONTROL_ATTITUDE (0x1 << 11)
#define MAVLINK_CONTROL_YAW (0x1 << 12)
#define MAVLINK_CONTROL_Z (0x1 << 13)
#define MAVLINK_CONTROL_XY (0x1 << 14)
#define MAVLINK_CONTROL_MOTOR (0x1 << 15)
#endif<file_sep>// ****************************************************************************
// *** EEPROM Functions
// ****************************************************************************
// *** This function loads all parameters from EEPROM. First it loads the
// parameters into temporary storage to verify the checksum. Only if the
// checksums are correct will the function update the parameters in RAM.
void EEPROMLoadAll(void) {
unsigned char chkA, chkB;
unsigned int i;
unsigned char * ptr;
float tempStorage[EEPROM_MAX_PARAMS+1];
// Read EEPROM into some temporarily allocated space
EEPROMRead(EEPROM_OFFSET, (unsigned char *)&tempStorage, paramCount * 4 + 2);
// Calculate the Fletcher-16 checksum
chkA=EEPROM_VERSION;
chkB=EEPROM_VERSION;
ptr = (unsigned char *)&tempStorage;
for(i=0; i<paramCount*4; i++) {
chkA += ptr[i];
chkB += chkA;
}
// Verify the checksum is valid (at this point i points to the correct elements for chkA and chkB)
if(chkA == ptr[i] && chkB == ptr[i+1]) {
// For valid data, load into parameters in RAM
for(i=0; i<paramCount; i++) {
paramStorage[i].value = tempStorage[i];
}
}
}
// *** This function saves all parameters to EEPROM.
void EEPROMSaveAll(void) {
unsigned char chkA, chkB;
unsigned int i;
unsigned char * ptr;
float tempStorage[EEPROM_MAX_PARAMS+1];
// Save parameters into temporary space
chkA=EEPROM_VERSION;
chkB=EEPROM_VERSION;
for(i=0; i<paramCount && i<EEPROM_MAX_PARAMS; i++) {
tempStorage[i] = paramStorage[i].value;
ptr = (unsigned char *)&(tempStorage[i]);
chkA += ptr[0];
chkB += chkA;
chkA += ptr[1];
chkB += chkA;
chkA += ptr[2];
chkB += chkA;
chkA += ptr[3];
chkB += chkA;
}
ptr = (unsigned char *)&(tempStorage[i]);
ptr[0] = chkA;
ptr[1] = chkB;
EEPROMWrite(EEPROM_OFFSET, (unsigned char *)&tempStorage, paramCount * 4 + 2);
}<file_sep>Copyright (c) 2011, Universal Air Ltd. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the organization nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This is the template project containing the Thalamus Function Set which allows
allows users to easily make use of the LPC1347's hardware featuress. As well as
Thalamus-specific hardware features.
This function set is designed for use with the Thalamus boards, but all the base
functions can be used with any LPC1347-based boards.
The library is branched from the Forebrain LPC1343 library.
This document pertains to the library files dealing with LPC1347's hardware
features. This set of functions allows users to easily make use of the
LPC1347's hardware features used in the Thalamus family of boards. It can
generally be used with any LPC1347 project.
This library was branched from the Forebrain LPC1343 library.
.cproject Eclipse project file
.project Eclipse project file
config.h Configurations for hardware
main.c Your code here!
readme_thalamus.txt This file
build/linker.ld Linker script
build/LPC1347.h Core LPC1347 file
build/Makefile Compiler script
build/startup.c Core LPC1347 file
build/thalfunc.c Thalamus family function set
build/thalfunc.h Thalamus family function set
build/thalamus.c Functions specific to Thalamus board
build/thalamus.h Functions specific to Thalamus board
TODO:
- Misc functions
- Power management
- GPIO
- USB
- USART
- SPI
- I2C
- Timers
- WDT
- Systick
- RIT
- ADC
- EEPROM
- Flashing
- Debug
- Power/Clock management - PMU
Known issues:
- Reprogram function can only enter serial programming mode
Changelog:
Revision 18
- Branched Thalamus MK5 (LPC1347) version
- Significantly simplified startup routine
- Added Mersenne Twister random number generator
Revision 17 (2012-09-19)
- Branched Thalamus MK2 (LPC1343) version
Revision 16 (2012-04-22)
- Added Thalamus support
- Added ReadPID and ReadUID and ReadUIDHash functions
Revision 15 (2012-01-18)
- Changed this readme file name
- Combined config files, and moved back to root folder (better this way, yes?)
- Added Port#GetInterrupt()
- Fixed WDT interrupt
- Added Startup timer settings
- Added SysTickTimer startup settings
- Copied startup timer code to startup.c to reduce flash usage in most situations
- Added ability to disable boot-up port initialisation, reduces flash usage in some situations
- Added Timer#EnableInterrupt() and Timer#DisableInterrupt() functions
- Added option to turn off fractional baud rate calculations
- Fixed bug in WriteBootData4()
Revision 14 (2012-12-18)
- Combined Seraphim, Hivebrain and Forebrain Function Sets into one template
- Added SD card functions
- Added ChaN's FatFS library
- Reordered SSPInit() to work for SD cards
- Added SDTimer() function to System tick timer for use with SD cards
- Added better TRUE/FALSE and NULL definitions
- Moved all config files into /build folder
- Changed ADCInit to accept unsigned short type
Seraphim Function Set Revision 5 (2011-12-16)
- Changed BaroConvAlt() to return altitude in millimeters!
- Fixed GPSPoll to prevent return on fail due to left over data in array
- Changed axes to convention (x: forward, y: starboard, z: down)
Seraphim Function Set Revision 4 (2011-11-29)
- Changed GPSChecksum to add start argument
Seraphim Function Set Revision 3 (2011-11-28)
- Removed redundant GPS_EN definition
- Removed GPSDisable() function
- Added GPSSleep() function
- Added GPS startup command to GPSInit() function
Revision 13 (2011-11-28)
- Fixed bug in Timer1Reset(), Timer2Reset() and Timer3Reset()
- Changed UART code to use unsigned char instead of char
- Commented out a couple of lines the UARTWrite functions relating to loopback fixes
Seraphim Function Set Revision 2 (2011-11-27)
- Added GPSDisable() function
- Moved GPS precalulated messages to local scope within GPSInit()
Seraphim Function Set Revision 1 (2011-11-24)
- Added GPS functions
- Added Gyro functions
- Added Accelerometer functions
- Added Magneto functions
- Added Barometer functions
Original version
Revision 12 (2011-11-02)
- Changed definitions in uafunc.h to declarations, thanks <NAME>
Revision 11 (2011-09-23)
- Fixed bug in UART on-demand mode
- Changed order of arguments on UARTSetInterrupt
Revision 10 (2011-09-16)
- Changed version numbering format (retroactive), thanks <NAME>!
- Added comments and annotations
- Removed set data line of Port#Init functions
- Changed PULL_UP and PULL_DOWN definitions to PULLUP and PULLDOWN
- Changed OUTPUT_HIGH, etc. to OUTPUTHIGH, etc.
- Fixed bug in timer match and interrupt functions for all timers
- Fixed bug in hardware PWM
- Added Timer#SetStatus functions
Revision 9 (2011-09-11)
- Added UART auto-flow control option in config.h
- Fixed bug in UART fractional buad generator presets at 9600 baud on 12MHz clock
- Added SSP functions for SPI mode
Revision 8 (2011-09-10)
- Added Brownout functions
- DeepSleep() timed wakeup
- Added ClockMode() function
- Added 12MHz and 72MHz clock modes
- Added fractional baud rate calibrations for UART in 12MHz mode
- Added Boot-up clock mode selection in config.h
- Added ResetStatus() function
- Changed WDTInit() to accept WDT period in ms and interrupt/reset mode
- Added WDTStop()
Revision 7 (2011-09-07)
- Added CRP definitions
- Added condition to Delay() to not use SysTick when it is enabled but stopped
- Added Sleep(), DeepSleep() and PowerDown() (and Read/Write Boot Data()) functions
- Added ClockOut() function
Revision 6 (2011-08-30)
- Prefixed all global vars used by Forebrain Function Set (FFS) with "FBR" to avoid potential collision with user code
- Fixed bug in EEPROMRead() function
- Fixed bug in MakeInt() function
- Removed Soft PWM functions (these will be available in a separate library)
- Added GPIO Interrupts
- Added Timer and PWM functions (should work but not extensively tested)
Revision 5 (2011-08-28)
- Added USB MSC built-in functions
- Changed USB HID functions to accept sample rate
- Changed EEPROMRead to EEPROMReadByte and EEPROMPageRead to EEPROMRead (similarly for EEPROMWrite) for consistency
- Added Port#Data() functions
- Added LEDWrite() function
Revision 4 (2011-08-27)
- Changed versioning numbers
- Added UART functions
- Added UART autobaud and fractional baud
Revision 3 (2011-08-26)
- Changed some variable names in the byte manipulation functions
- Added ResetInit()
- Added Random functions
- Added EEPROM functions
Revision 2 (2011-08-26)
- Simplified I2C functions
- Added some stuff I can't quite remember...
Revision 1 (2011-08-01)
Original version<file_sep>
void ReadBaroSensors(void) {
// Get raw barometric pressure reading in Pascals, when it reads 0
float baro = GetBaroPressure();
// There is an I2C or sensor error if 0 is returned, so only update altitude when pressure is greater than 0
if(baro > 0) {
// Run an LPF filter on the barometer data
alt.baro *= LPF_BARO;
alt.baro += (1-LPF_BARO) * baro;
// Linearise around Sea Level
//Scale to Metres
alt.baro = alt.baro/1.0;
// Output processed data over telemetry
ilink_altitude.baro = alt.baro;
}
}
void ReadUltrasound(void) {
// Get ultrasound data and scale to mm??
// TODO: Scale to m (everywhere should use SI units)
ultra = (UltraGetNewRawData()) * 0.17;
if(ultra > 0) {
ultraLoss = 0;
// We run an LPF filter on the ultrasound readings
alt.ultra *= LPF_ULTRA;
alt.ultra += (1-LPF_ULTRA) * ultra;
// Output the ultrasound altitude
ilink_altitude.ultra = alt.ultra;
}
// if ultra = 0 then there isn't valid data
// TODO: Improve ultrasound confidence estimator
else {
ultraLoss++;
if(ultraLoss > ULTRA_OVTH) ultraLoss = ULTRA_OVTH;
}
}
void ReadBattVoltage(void) {
// Because the factor is 6325/1024, we can do this in integer maths by right-shifting 10 bits instead of dividing by 1024.
unsigned short battV = (ADCGet() * 6325) >> 10;
// battVoltage in milivolts
batteryVoltage *= 0.99f;
batteryVoltage += 0.01f * (float)battV;
ilink_thalstat.battVoltage = battV;
ADCTrigger(CHN7);
}
void ReadGyroSensors(void) {
signed short data[4];
if(GetGyro(data)) {
// Read raw Gyro data
Gyro.X.raw = data[0];
Gyro.Y.raw = data[2];
Gyro.Z.raw = -data[1];
// Output raw data over telemetry
ilink_rawimu.xGyro = Gyro.X.raw;
ilink_rawimu.yGyro = Gyro.Y.raw;
ilink_rawimu.zGyro = Gyro.Z.raw;
// Perform running average
Gyro.X.total -= Gyro.X.history[Gyro.count];
Gyro.Y.total -= Gyro.Y.history[Gyro.count];
Gyro.Z.total -= Gyro.Z.history[Gyro.count];
Gyro.X.total += Gyro.X.raw;
Gyro.Y.total += Gyro.Y.raw;
Gyro.Z.total += Gyro.Z.raw;
Gyro.X.history[Gyro.count] = Gyro.X.raw;
Gyro.Y.history[Gyro.count] = Gyro.Y.raw;
Gyro.Z.history[Gyro.count] = Gyro.Z.raw;
Gyro.X.av = (float)Gyro.X.total/(float)GAV_LEN;
Gyro.Y.av = (float)Gyro.Y.total/(float)GAV_LEN;
Gyro.Z.av = (float)Gyro.Z.total/(float)GAV_LEN;
if(++Gyro.count >= GAV_LEN) Gyro.count = 0;
// Add the offset calculated on calibration (to set no rotational movement to 0 corresponding output)
// and scale to radians/s
Gyro.X.value = (Gyro.X.av - Gyro.X.offset)/818.51113590117601252569f;
Gyro.Y.value = (Gyro.Y.av - Gyro.Y.offset)/818.51113590117601252569f;
Gyro.Z.value = (Gyro.Z.av - Gyro.Z.offset)/818.51113590117601252569f;
// Send processed values over telemetry
ilink_scaledimu.xGyro = Gyro.X.value * 1000;
ilink_scaledimu.yGyro = Gyro.Y.value * 1000;
ilink_scaledimu.zGyro = Gyro.Z.value * 1000;
}
}
void ReadAccelSensors(void) {
float sumsqu;
signed short data[4];
if(GetAccel(data)) {
// Get raw Accelerometer data
Accel.X.raw = data[0];
Accel.Y.raw = data[2];
Accel.Z.raw = -data[1];
// Perform Running Average
Accel.X.total -= Accel.X.history[Accel.count];
Accel.Y.total -= Accel.Y.history[Accel.count];
Accel.Z.total -= Accel.Z.history[Accel.count];
Accel.X.total += Accel.X.raw;
Accel.Y.total += Accel.Y.raw;
Accel.Z.total += Accel.Z.raw;
Accel.X.history[Accel.count] = Accel.X.raw;
Accel.Y.history[Accel.count] = Accel.Y.raw;
Accel.Z.history[Accel.count] = Accel.Z.raw;
// Output raw data over telemetry (this is just the last value used)
ilink_rawimu.xAcc = Accel.X.raw;
ilink_rawimu.yAcc = Accel.Y.raw;
ilink_rawimu.zAcc = Accel.Z.raw;
// Get average
Accel.X.av = (float)Accel.X.total/(float)AAV_LEN;
Accel.Y.av = (float)Accel.Y.total/(float)AAV_LEN;
Accel.Z.av = (float)Accel.Z.total/(float)AAV_LEN;
if(++Accel.count >= AAV_LEN) Accel.count = 0;
// Normalise accelerometer so it is a unit vector
sumsqu = finvSqrt((float)Accel.X.av*(float)Accel.X.av + (float)Accel.Y.av*(float)Accel.Y.av + (float)Accel.Z.av*(float)Accel.Z.av); // Accelerometr data is normalised so no need to convert units.
Accel.X.value = (float)Accel.X.av * sumsqu;
Accel.Y.value = (float)Accel.Y.av * sumsqu;
Accel.Z.value = (float)Accel.Z.av * sumsqu;
//Output processed values over telemetry
ilink_scaledimu.xAcc = Accel.X.value * 1000;
ilink_scaledimu.yAcc = Accel.Y.value * 1000;
ilink_scaledimu.zAcc = Accel.Z.value * 1000;
}
}
void ReadMagSensors(void) {
float sumsqu, temp1, temp2, temp3;
signed short data[4];
if(GetMagneto(data)) {
// Get raw magnetometer data
Mag.X.raw = data[0];
Mag.Y.raw = data[2];
Mag.Z.raw = -data[1];
// Output raw data over telemetry
ilink_rawimu.xMag = Mag.X.raw;
ilink_rawimu.yMag = Mag.Y.raw;
ilink_rawimu.zMag = Mag.Z.raw;
// Perform running average
Mag.X.total -= Mag.X.history[Mag.count];
Mag.Y.total -= Mag.Y.history[Mag.count];
Mag.Z.total -= Mag.Z.history[Mag.count];
Mag.X.total += Mag.X.raw;
Mag.Y.total += Mag.Y.raw;
Mag.Z.total += Mag.Z.raw;
Mag.X.history[Mag.count] = Mag.X.raw;
Mag.Y.history[Mag.count] = Mag.Y.raw;
Mag.Z.history[Mag.count] = Mag.Z.raw;
Mag.X.av = (float)Mag.X.total/(float)MAV_LEN;
Mag.Y.av = (float)Mag.Y.total/(float)MAV_LEN;
Mag.Z.av = (float)Mag.Z.total/(float)MAV_LEN;
if(++Mag.count >= MAV_LEN) Mag.count = 0;
// Correcting Elipsoid Centre Point (These values are found during Magneto Calibration)
temp1 = Mag.X.av - MAGCOR_M1;
temp2 = Mag.Y.av - MAGCOR_M2;
temp3 = Mag.Z.av - MAGCOR_M3;
// Reshaping Elipsoid to Sphere (These values are set the same for all Thalamus Units)
temp1 = MAGCOR_N1 * temp1 + MAGCOR_N2 * temp2 + MAGCOR_N3 * temp3;
temp2 = MAGCOR_N5 * temp2 + MAGCOR_N6 * temp3;
temp3 = MAGCOR_N9 * temp3;
// Normalize magneto into unit vector
sumsqu = finvSqrt((float)temp1*(float)temp1 + (float)temp2*(float)temp2 + (float)temp3*(float)temp3); // Magnetoerometr data is normalised so no need to convert units.
Mag.X.value = (float)temp1 * sumsqu;
Mag.Y.value = (float)temp2 * sumsqu;
Mag.Z.value = (float)temp3 * sumsqu;
// Output processed data over telemetry
ilink_scaledimu.xMag = Mag.X.value * 1000;
ilink_scaledimu.yMag = Mag.Y.value * 1000;
ilink_scaledimu.zMag = Mag.Z.value * 1000;
}
}
// TODO: Simplify the calibration routines, there seems to be a lot of overlap and unnecessary/ unused code
void CalibrateMagneto(void) {
unsigned int i;
unsigned int good;
float Xav, Yav, Zav;
float distance;
signed short Xmax, Xmin, Ymax, Ymin, Zmax, Zmin;
unsigned int started;
if(armed == 0) {
ilink_thalstat.sensorStatus = 2; // calibrating
started = 0;
Xav = 0;
Yav = 0;
Zav = 0;
flashVLED = 1;
good = 0;
ReadMagSensors();
Xmax = Mag.X.raw;
Xmin = Xmax;
Ymax = Mag.Y.raw;
Ymin = Ymax;
Zmax = Mag.Z.raw;
Zmin = Zmax;
// Calibrate for 70 seconds or until still for 2.8 seconds.
//TODO: filter out spikes
for(i=0; i<5000; i++) {
ReadGyroSensors();
// calculate distance of data from running average
distance = (Xav - (float)Gyro.X.raw)*(Xav - (float)Gyro.X.raw);
distance += (Yav - (float)Gyro.Y.raw)*(Yav - (float)Gyro.Y.raw);
distance += (Zav - (float)Gyro.Z.raw)*(Zav - (float)Gyro.Z.raw);
if(started == 0) {
// before starting, wait for gyro to move around
if(distance > 2000) {
// high-movement, increment good counter and add average value.
good++;
if(good >= 10) {
started = 1; // if enough movement readings, escape loop
good = 0;
flashVLED = 2;
}
}
else {
good = 0;
}
}
else {
ReadMagSensors();
if(Mag.X.raw > Xmax) Xmax = Mag.X.raw;
else if(Mag.X.raw < Xmin) Xmin = Mag.X.raw;
if(Mag.Y.raw > Ymax) Ymax = Mag.Y.raw;
else if(Mag.Y.raw < Ymin) Ymin = Mag.Y.raw;
if(Mag.Z.raw > Zmax) Zmax = Mag.Z.raw;
else if(Mag.Z.raw < Zmin) Zmin = Mag.Z.raw;
if(distance < 2000) {
// high-movement, increment good counter and add average value.
good++;
if(good >= 200) break; // if enough movement readings, escape loop
}
else {
good = 0;
}
}
Xav *= 0.95f;
Xav += 0.05f * (float)Gyro.X.raw;
Yav *= 0.95f;
Yav += 0.05f * (float)Gyro.Y.raw;
Zav *= 0.95f;
Zav += 0.05f * (float)Gyro.Z.raw;
//TODO: Inline delay
Delay(14);
}
MAGCOR_M1 = (Xmax + Xmin)/2;
MAGCOR_M2 = (Ymax + Ymin)/2;
MAGCOR_M3 = (Zmax + Zmin)/2;
EEPROMSaveAll();
flashPLED = 0;
LEDOff(PLED);
ilink_thalstat.sensorStatus &= ~(0x7); // mask status
ilink_thalstat.sensorStatus |= 3; // standby
}
}
void SensorZero(void) {
unsigned int i;
signed short data[4];
if(!GetGyro(data) || !GetMagneto(data) || !GetAccel(data)/* || GetBaro() == 0*/) {
LEDInit(PLED | VLED);
LEDOn(PLED);
LEDOff(VLED);
flashPLED = 2;
flashVLED = 2;
while(1);
}
// *** Zero totals
Gyro.X.total = 0;
Gyro.Y.total = 0;
Gyro.Z.total = 0;
Accel.X.total = 0;
Accel.Y.total = 0;
Accel.Z.total = 0;
Mag.X.total = 0;
Mag.Y.total = 0;
Mag.Z.total = 0;
for(i=0; (i<GAV_LEN); i++) {
Gyro.X.history[i] = 0;
Gyro.Y.history[i] = 0;
Gyro.Z.history[i] = 0;
}
for(i=0; (i<AAV_LEN); i++) {
Accel.X.history[i] = 0;
Accel.Y.history[i] = 0;
Accel.Z.history[i] = 0;
}
for(i=0; (i<MAV_LEN); i++) {
Mag.X.history[i] = 0;
Mag.Y.history[i] = 0;
Mag.Z.history[i] = 0;
}
Gyro.X.offset = 0;
Gyro.Y.offset = 0;
Gyro.Z.offset = 0;
// pre-seed averages
for(i=0; (i<GAV_LEN); i++) {
ReadGyroSensors();
}
for(i=0; (i<AAV_LEN); i++) {
ReadAccelSensors();
}
for(i=0; (i<MAV_LEN); i++) {
ReadMagSensors();
}
ilink_thalstat.sensorStatus |= (0xf << 3);
}
void CalibrateGyro(void) {
CalibrateGyroTemp(6);
CAL_GYROX = Gyro.X.offset;
CAL_GYROY = Gyro.Y.offset;
CAL_GYROZ = Gyro.Z.offset;
EEPROMSaveAll();
}
void CalibrateGyroTemp(unsigned int seconds) {
unsigned int i;
// *** Calibrate Gyro
unsigned int good;
float Xav, Yav, Zav;
signed int Xtotal, Ytotal, Ztotal;
float distance;
if(armed == 0) {
ReadGyroSensors();
Xtotal = 0;
Ytotal = 0;
Ztotal = 0;
Xav = Gyro.X.raw;
Yav = Gyro.Y.raw;
Zav = Gyro.Z.raw;
flashPLED = 1;
good = 0;
// Wait for Gyro to be steady or 20 seconds
for(i=0; i<5000; i++) {
ReadGyroSensors();
// calculate distance of data from running average
distance = (Xav - (float)Gyro.X.raw)*(Xav - (float)Gyro.X.raw);
distance += (Yav - (float)Gyro.Y.raw)*(Yav - (float)Gyro.Y.raw);
distance += (Zav - (float)Gyro.Z.raw)*(Zav - (float)Gyro.Z.raw);
// LPF for above
Xav *= 0.95f;
Xav += 0.05f * (float)Gyro.X.raw;
Yav *= 0.95f;
Yav += 0.05f * (float)Gyro.Y.raw;
Zav *= 0.95f;
Zav += 0.05f * (float)Gyro.Z.raw;
//TODO: This distnace was never small enough on the ICRS Quad. Double check
if(distance < 2000) {
// low-movement, increment good counter and add average value.
good++;
if(good >= 333) break; // if enough good readings, escape loop
}
else {
// high movement, zero good counter, and average values.
good = 0;
}
Delay(3);
}
ilink_thalstat.sensorStatus &= ~(0x7); // mask status
ilink_thalstat.sensorStatus |= 2; // calibrating
flashPLED=2;
LEDOn(PLED);
// at this point should have at least 200 good Gyro readings, take some more
for(i=0; i<seconds*333; i++) {
ReadGyroSensors();
Xtotal += Gyro.X.raw;
Ytotal += Gyro.Y.raw;
Ztotal += Gyro.Z.raw;
Delay(3);
}
Gyro.X.offset = (float)Xtotal/(float)(seconds * 333);
Gyro.Y.offset = (float)Ytotal/(float)(seconds * 333);
Gyro.Z.offset = (float)Ztotal/(float)(seconds * 333);
flashPLED = 0;
LEDOff(PLED);
ilink_thalstat.sensorStatus &= ~(0x7); // mask status
ilink_thalstat.sensorStatus |= 3; // standby
}
} | a83225cfcff4557900da0c0a42ff7537c5121f16 | [
"Markdown",
"C",
"Text"
] | 18 | C | adpoliak/Mavrx-firmware | d45533b4e2429c9f9467acfb1e6f0b1b33dd739c | 377c2de442a00c70c89a09a9e2680008927c5543 |
refs/heads/main | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Notes;
class NotesController extends Controller
{
//
public function storeNote(Request $request) {
$note = new Notes();
$note->title = $request->title;
$note->note = $request->note;
$note->save();
return $note;
}
public function getNotes(Request $request) {
$notes = Notes::all();
return $notes;
}
public function editNote(Request $request, $id){
$note = Notes::where('id',$id)->first();
$note->title = $request->get('val_1');
$note->note = $request->get('val_2');
$note->save();
return $note;
}
public function deleteNote(Request $request){
$note = Notes::find($request->id)->delete();
}
}
<file_sep>## Very simple Laravel & Vue App
| f3050914d3e6a1396f3f4f3705f41117c1396bc0 | [
"Markdown",
"PHP"
] | 2 | PHP | maskeddeveloper/simple_laravel_vue_app | 738d98944d34230ad0569d2348ac4e20427f52c5 | 7aa2a504eff8f42aea92952e5cf110d1d3e0d6c9 |
refs/heads/master | <repo_name>Ph3bian/ng-tacos<file_sep>/src/app/pages/home/home.component.ts
import { Component, OnInit } from "@angular/core";
import { eventDispatcher, store } from "../../store";
import { ActionTypes } from "../../store/actions";
import { HomeService } from "./home.service";
import { Observable } from "rxjs";
@Component({
selector: "app-home",
templateUrl: "./home.component.html",
styleUrls: ["./home.component.scss"],
})
export class HomeComponent implements OnInit {
recipes: Array<object> = [];
loading: boolean = true;
loadingMore: boolean = false;
error: string = "";
constructor(private homeService: HomeService) {
store.subscribe((state) => {
const { recipes } = state;
this.recipes = recipes;
});
}
ngOnInit() {
this.fetchRandom();
}
fetchRandom() {
this.homeService.getRecipe().subscribe((response) => {
this.loading = false;
console.log(response);
eventDispatcher.next({
type: ActionTypes.GET_RECIPE,
payload: response.recipe,
});
});
}
loadMore() {
this.loadingMore = true;
this.homeService.getRecipe().subscribe(
(response) => {
eventDispatcher.next({
type: ActionTypes.GET_RECIPE,
payload: response.recipe,
});
return (this.loadingMore = false);
},
(err) => {
this.error = err.message;
this.loadingMore = false;
}
);
}
}
<file_sep>/src/app/store/actions.ts
export enum ActionTypes {
GET_RECIPE = '[HOME] Fetch recipe',
UPDATE_RECIPE = '[HOME] Fetch recipe',
}<file_sep>/src/app/shared/services/api/index.ts
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root",
})
export class ApiService {
constructor() {}
baseUrl = "http://taco-randomizer.herokuapp.com";
random = () => `${this.baseUrl}/random/?full-taco=true`;
contributors = ({ recipe_type, recipe_slug }) =>
`/${this.baseUrl}/contributors/${recipe_type}/${recipe_slug}`;
}
<file_sep>/src/app/components/header/header.component.ts
import { Component, OnInit } from "@angular/core";
import { Location } from "@angular/common";
@Component({
selector: "app-header",
templateUrl: "./header.component.html",
styleUrls: ["./header.component.scss"],
})
export class HeaderComponent implements OnInit {
location: Location;
constructor(location: Location) {
this.location = location;
}
ngOnInit() {}
getTitle() {
let title = this.location.prepareExternalUrl(this.location.path());
title = title.split("/").pop();
return title;
}
}
| 1a55f1be37b9e7ed706b9549deffc5c51eced0a5 | [
"TypeScript"
] | 4 | TypeScript | Ph3bian/ng-tacos | 6a7ac3ccd3a8bab078c1099a91351d5681281dc3 | 22bf5f7af6834b2ae7a010b69883d813d7f3938f |
refs/heads/master | <repo_name>the-cc-dev/ccd3vtheme<file_sep>/templates/feet.php
</main>
<?php get_template_part('templates/footer'); ?>
</body>
</html><file_sep>/page-home.php
<?php while (have_posts()) : the_post(); get_template_part('templates/head'); ?>
<?php get_template_part('templates/feet'); endwhile; ?>
<file_sep>/templates/header.php
<header id="theHeader" class="the-header">
<nav id="theNav" class="the-nav">
<ul id="navList" class="nav-list">
<li id="homeNav" class="nav-item">
<a id="homeLink" class="nav-link" href="index.php">
<i id="homeIcon" class="nav-icon fa fa-fort-awesome"></i>
<span id="homeText" class="nav-text">Home</span>
</a>
</li>
<li id="aboutNav" class="nav-item">
<a id="aboutLink" class="nav-link" href="about.php">
<i id="aboutIcon" class="nav-icon fa fa-info"></i>
<span id="aboutText" class="nav-text">About</span>
</a>
</li>
<li id="contactNav" class="nav-item">
<a id="contactLink" class="nav-link" href="contact.php">
<i id="contactIcon" class="nav-icon fa fa-phone"></i>
<span id="contactText" class="nav-text">Contact</span>
</a>
</li>
<li id="folioNav" class="nav-item">
<a id="folioLink" class="nav-link" href="portfolio.php">
<i id="folioIcon" class="nav-icon fa fa-briefcase"></i>
<span id="folioText" class="nav-text">Portfolio</span>
</a>
</li>
<li id="etcNav" class="nav-item">
<a id="etcLink" class="nav-link" href="etc.php">
<i id="etcIcon" class="nav-icon fa fa-ellipsis-h"></i>
<span id="etcText" class="nav-text">Etc</span>
</a>
</li>
</ul>
</nav>
</header>
<?php get_template_part('templates/head-letters'); ?><file_sep>/templates/head.php
<!doctype html>
<html>
<head>
<title>ccD3V</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="dist/javascripts/scripts.js"></script>
<link rel="stylesheet" type="text/css" href="dist/stylesheets/styles.min.css">
</head>
<body>
<?php get_template_part('templates/header'); ?>
<main id="theMain" class="the-main"><file_sep>/assets/js/main.js
$(document).ready(function() {
var navData = {
navList: [
{ id: 'home', link: 'index.php', icon: 'fort-awesome', text: 'Home' },
{ id: 'about', link: 'about.php', icon: 'info', text: 'About' },
{ id: 'contact', link: 'contact.php', icon: 'phone', text: 'Contact' },
{ id: 'folio', link: 'portfolio.php', icon: 'briefcase', text: 'Portfolio' },
{ id: 'etc', link: 'etc.php', icon: 'ellipsis-h', text: 'Etc'}
]
};
var footerData = {},
homeData = {},
aboutData = {},
contactData = {},
folioData = {},
etcData = {};
var header = new Vue({
el: '#theHeader',
data: navData
});
var footer = new Vue({
el: '#theFooter',
data: footerData
});
}); | ba8ac670c1075d3ac11327cdf4e020837c40999c | [
"JavaScript",
"PHP"
] | 5 | PHP | the-cc-dev/ccd3vtheme | 62f4f5d0c3f15b13ce05a5f55219ac583c7d4ab9 | b08fe6d85b93282a0d80a8309f3dbb2caa4bc84e |
refs/heads/master | <repo_name>titrabui/facebook_ads<file_sep>/fuel/app/modules/api/classes/controller/base.php
<?php
namespace Api;
require_once (APPPATH.'vendor'.DS.'jwt'.DS.'JWT.php');
use \Firebase\JWT\JWT;
class Controller_Base extends \Controller_Rest
{
// default format
protected $format = 'json';
protected $key = '<KEY>';
protected $algorithm = array('HS256');
public function before()
{
parent::before();
}
/**
* The checking authorization token function
*
* @access protected
* @return success: true | fail: false
*/
protected function check_authorization_token()
{
if ( ! $token = $this->get_bearer_token()) return null;
try
{
JWT::$leeway = 60; // $leeway in seconds
$jwt_decode = JWT::decode($token, $this->key, $this->algorithm);
$jwt_data = $jwt_decode->data;
}
catch (\Exception $e)
{
return null;
}
catch (SignatureInvalidException $s)
{
return null;
}
catch (BeforeValidException $b)
{
return null;
}
catch (ExpiredException $exp)
{
return null;
}
if (!isset($jwt_data->username) or !isset($jwt_data->password)) return null;
if ($user = \Auth::validate_user($jwt_data->username, $jwt_data->password))
{
return $user;
}
else
{
return null;
}
}
/**
* The error response function
*
* @access protected
* @return Http code
*/
protected function error_response($response_data = [])
{
return $this->response(array(
'status' => 'Error',
'error' => $response_data
), 401);
}
/**
* The success response function
*
* @access protected
* @return Http code
*/
protected function success_response($response_data = [])
{
return $this->response(array(
'status' => 'Success',
'data' => is_array($response_data) ? array_values($response_data) : $response_data
), 200);
}
/**
* The bearer token getting function
*
* @access protected
* @return Token | null
*/
private function get_bearer_token()
{
$header = apache_request_headers();
if (!isset($header['Authorization'])) return null;
if (preg_match('/Bearer\s(\S+)/', $header['Authorization'], $matches))
{
return $matches[1];
}
}
}
<file_sep>/fuel/app/modules/api/classes/controller/campaigns.php
<?php
namespace Api;
use FacebookAds\Api;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
class Controller_Campaigns extends Controller_Base {
public function before()
{
parent::before();
}
/**
* The campaign creation post.
*
* @access public
* @return Http code
*/
public function post_create()
{
// $account_ids = ['619728524764102', '144135033007233', '102209717222621', '105291676913638', '111306649643951'];
$account_ids = ['619728524764102'];
$campaigns = [];
Api::init(
\Constants::$facebook_ads_configurations['app_id'],
\Constants::$facebook_ads_configurations['app_secret'],
\Constants::$facebook_ads_configurations['access_token']
);
try
{
foreach ($account_ids as $account_id) {
$account = (new AdAccount('act_'.$account_id))->read(array(
AdAccountFields::ID,
AdAccountFields::NAME,
AdAccountFields::ACCOUNT_STATUS,
));
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1)
throw new \Exception('This account is not active');
$campaign = new Campaign(null, $account->id);
$campaign->setData(array(
CampaignFields::NAME => 'KTLV Campaign',
CampaignFields::OBJECTIVE => 'LINK_CLICKS',
));
$campaign->validate()->create(array(
Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
array_push($campaigns, $campaign->id);
}
return $this->success_response($campaigns);
// return $this->success_response();
}
catch (\Exception $e)
{
return $this->error_response($e->getMessage());
}
}
}
<file_sep>/fuel/app/classes/model/user.php
<?php
class Model_User extends \Orm\Model
{
protected static $_properties = array(
'id',
'username',
'password',
'group',
'status',
'email',
'last_login',
'login_hash',
'balance',
'profile_fields',
'created_at',
'updated_at',
'deleted_at',
);
protected static $_observers = array(
'Orm\Observer_CreatedAt' => array(
'events' => array('before_insert'),
'mysql_timestamp' => false,
),
'Orm\Observer_UpdatedAt' => array(
'events' => array('before_update'),
'mysql_timestamp' => false,
),
);
protected static $_table_name = 'users';
public static function validate($factory , $param = array())
{
$val = Validation::forge($factory);
switch ($factory) {
case 'MasterLogin': // Administrator user login
// Validate rule setting
$val->add_field('username', 'username', 'required');
$val->add_field('password', '<PASSWORD>', '<PASSWORD>');
break;
case 'MasterCreate': // Create an administrator user
// Validate rule setting
$val->add_field('username', 'username', 'required|max_length[50]');
$val->add_field('password', '<PASSWORD>', '<PASSWORD>]');
$val->add_field('email', 'email', 'required|valid_email|max_length[255]');
$val->add_field('group', 'group', 'valid_string[numeric]');
$val->add_field('fullname', 'fullname', 'max_length[256]');
$val->add_field('phone', 'phone', 'valid_string[numeric]');
$val->add_field('address', 'address', 'max_length[512]');
break;
case 'MasterModify': // Change administrator user
$val->add_callable('Validate_user');
$val->add('old_password', '<PASSWORD>')
->add_rule('required_with', 'password')
->add_rule('oldpasscheck', $param['username'])
->add_rule('max_length',255);
$val->add('password', '<PASSWORD>')
->add_rule('required_with', 'old_password')
->add_rule('valid_string',array('alpha','numeric'))
->add_rule('match_value', \Input::post('password2'), true)
->add_rule('max_length',255);
$val->add('email', 'email')
->add_rule('match_value', \Input::post('email2'), true)
->add_rule('valid_email')
->add_rule('max_length',255);
$val->set_message('oldpasscheck', \Constants::$error_message['bad_old_password']);
break;
case 'UserLogin':
$val->add_field('username', 'username', 'required');
$val->add_field('password', '<PASSWORD>', '<PASSWORD>');
break;
case 'UserModifyMail':
$val->add('email', 'email')
->add_rule('match_value', \Input::post('email2'), true)
->add_rule('valid_email')
->add_rule('max_length',255);
break;
case 'UserModifyPass':
$val->add_callable('Validate_user');
$val->add('old_password', '<PASSWORD>')
->add_rule('required_with', 'password')
->add_rule('oldpasscheck', $param['username'])
->add_rule('max_length',255);
$val->add('password', '<PASSWORD>')
->add_rule('required_with', 'old_password')
->add_rule('valid_string',array('alpha','numeric'))
->add_rule('match_value', \Input::post('password2'), true)
->add_rule('max_length',255);
$val->set_message('oldpasscheck', \Constants::$error_message['bad_old_password']);
break;
case 'ApiUserModifyPass':
$val->add('old_password', '<PASSWORD>')
->add_rule('required_with', 'password')
->add_rule('max_length', 255);
$val->add('password', '<PASSWORD>')
->add_rule('required_with', 'old_password')
->add_rule('valid_string', array('alpha','numeric'))
->add_rule('match_value', \Input::post('password2'), true)
->add_rule('max_length', 255);
break;
default:
break;
}
return $val;
}
}<file_sep>/fuel/app/config/crypt.php
<?php
return array (
'crypto_key' => '-toq9U5HsDm0nvEu24Rp0OoI',
'crypto_iv' => 'c6Maw0UGsrg0ZmI25wnB0kG4',
'crypto_hmac' => 'xzoE0AI20ivIR94vGkOqAD2w',
);
<file_sep>/fuel/app/modules/api/classes/controller/login.php
<?php
namespace Api;
require_once (APPPATH.'vendor'.DS.'jwt'.DS.'JWT.php');
use \Firebase\JWT\JWT;
class Controller_Login extends Controller_Base
{
private $TWO_HOURS = 7200;
private $TEN_SECONDS = 10;
public function before()
{
parent::before();
}
/**
* The Login Authenication function
*
* @access public
* @return true: authenicate success | false: authenicate error
*/
public function post_index()
{
// Acquire validate rule for login
$val = \Model_User::validate('MasterLogin');
if ( ! $val->run()) return $this->error_response($val->error());
if ($user = \Auth::validate_user(\Input::post('username'), \Input::post('password')))
{
$issue_time = time();
$token = array(
"iss" => 'http://sgtvt-bkdn.com',
"aud" => 'titrabui',
"iat" => $issue_time,
"nbf" => $issue_time + $this->TEN_SECONDS,
"exp" => $issue_time + ($this->TEN_SECONDS + $this->TWO_HOURS),
"data" => [
"id" => $user['id'],
"username" => $user['username'],
"password" => \Input::post('<PASSWORD>')
]
);
try
{
$jwt = JWT::encode($token, $this->key);
}
catch (\Exception $e)
{
return $this->error_response('User name or password is invalid. Login failed');
}
return $this->response(array(
'status' => 'Success',
'token' => $jwt
), 200);
}
else
{
return $this->error_response('User name or password wrong. Login failed');
}
}
}
<file_sep>/fuel/app/vendor/excel/export.php
<?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
if (PHP_SAPI == 'cli') die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/../excel/PHPExcel.php';
Class Excel {
public static function export($measuring_values, $month_selected)
{
try
{
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()
->setCreator("Sở giao thông vận tải Đà Nẵng")
->setLastModifiedBy("Sở giao thông vận tải Đà Nẵng")
->setTitle("Báo cáo giá trị đo");
// Set title header
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'STT')
->setCellValue('B1', 'Ngày')
->setCellValue('C1', 'Thời gian')
->setCellValue('D1', 'Tổng thời gian khảo sát (ngày)')
->setCellValue('E1', 'Nhiệt độ bên ngoài (℃)')
->setCellValue('F1', 'Nhiệt độ vị trí 1 dưới kết cấu (℃)')
->setCellValue('G1', 'Nhiệt độ vị trí 2 dưới kết cấu (℃)');
// Add excel data
$index = 1;
$row = 2;
foreach ($measuring_values as $item)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$row, $index++)
->setCellValue('B'.$row, Date::forge($item['created_at'])->format("%d - %m - %Y"))
->setCellValue('C'.$row, Date::forge($item['created_at'])->format("%H : %M : %S"))
->setCellValue('D'.$row, $item['total_time_surveying'])
->setCellValue('E'.$row, $item['value1'])
->setCellValue('F'.$row, $item['value2'])
->setCellValue('G'.$row, $item['value3']);
$row++;
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle($month_selected);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Báo cáo tháng '.$month_selected.'".xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
catch (\Exception $e)
{
// redirect to error page
Session::set_flash('error', array('message' => $e->getMessage()));
Response::redirect('admin/error');
}
}
}
<file_sep>/fuel/app/classes/controller/login.php
<?php
class Controller_Login extends Controller_Base
{
/**
* Preprocessing
*/
public function before() {
// Set fields handled in input form as array
parent::before();
}
/**
* The login function
*
* @access public
* @return Response view
*/
public function action_index()
{
// Call view template
$view = View::forge('login/index');
return $view;
}
}<file_sep>/fuel/app/classes/controller/base.php
<?php
class Controller_Base extends \Fuel\Core\Controller_Template
{
// Template name
public $referrer;
public $modules;
public $controller;
public $action;
public function before()
{
$this->current_user = null;
$this->userprofile = null;
$this->set_init();
// Confirm whether simpleauth driver is certified
$driver = Auth::verified('simpleauth');
$logined = 0;
if (($id = Auth::get_user_id()) !== false)
{
$this->current_user = Model\Auth_User::find($id[1]);
}
if (\Auth::check())
{
$logined = 1;
}
// Set a global variable so views can use it
// View::set_global('current_user', $this->current_user);
Session::set('current_user', $this->current_user);
View::set_global('current_userprofile', $this->userprofile);
/* if ( ! $this->is_restful())
{
$this->template->logined_flag = $logined;
// Also set it for view
$this->template->title = \Constants::$site_title;
$this->template->pagetitle = \Constants::$page_title['normal'];
}*/
return parent::before();
}
/**
* set init
*/
private function set_init() {
$this->modules = Request::main()->module;
$controller = strtolower(str_replace("Controller_", "", Request::main()->controller));
$controller = str_replace($this->modules . "\\", "", $controller);
$controller = str_replace("_", "/", $controller);
$this->controller = $controller;
$this->action = Request::main()->action;
if (!empty($this->template) and !is_string($this->template)) {
$this->template->modeuls = Request::main()->module;
$this->template->controller = $controller;
$this->template->action = Request::main()->action;
}
}
}
<file_sep>/fuel/app/classes/constants.php
<?php
class Constants
{
public static $site_title = '';
public static $page_title = array(
'normal' => '',
'login' => 'Đăng nhập',
'mainmenu' => '',
'photoedit' => '',
'photolist' => '',
'photomap' => '',
'changemail' => '',
'changepass' => '',
);
public static $error_message = array(
'login_error' => 'Đăng nhập thất bại',
'already_logged_in' => 'Tài khoản đã đăng nhập rồi',
'expired_csrf_token' => 'There is no valid session.',
'bad_old_password' => '<PASSWORD>',
'not_change_mail' => 'Địa chỉ email không thể thay đổi',
'not_change_user_profile' => 'Thông tin người dùng không thể thêm hoặc thay đổi',
'not_change_user_id_pass' => '<PASSWORD>',
'already_exist_user' => 'Tài khoản người dùng đã được đăng ký rồi',
'bad_route' => 'Đường dẫn không hợp lệ',
'not_exist_date' => ':label Ngày không hợp lệ',
);
public static $user_group = array(
'Administrators' => '100',
'Moderators' => '50',
'Users' => '1',
);
public static $facebook_ads_configurations = array(
'access_token' => '<KEY>',
'app_id' => '1514996251856617',
'app_secret' => '<KEY>'
);
}
<file_sep>/fuel/app/modules/api/classes/controller/users.php
<?php
namespace Api;
class Controller_Users extends Controller_Base {
public function before()
{
parent::before();
}
/**
* The get user post.
*
* @access public
* @return Http code
*/
public function post_get($id = null)
{
if ( ! $current_user = $this->check_authorization_token())
return $this->error_response('The access token could not be decrypted');
if ($current_user['group'] != \Constants::$user_group['Administrators'])
return $this->error_response('Access denied for user');
try
{
if (is_null($id))
{
$users = \Model_User::query()
->select('id', 'username', 'group', 'email', 'profile_fields', 'last_login')
->from_cache(false)
->get();
}
else
{
if ( ! \Model_User::find($id))
return $this->error_response("User #.$id. is not exist");
$users = \Model_User::query()
->select('id', 'username', 'group', 'email', 'profile_fields', 'last_login')
->where('id', $id)
->from_cache(false)
->get();
}
return $this->success_response($users);
}
catch (\Exception $e)
{
return $this->error_response($e->getMessage());
}
}
/**
* The user infor post.
*
* @access public
* @return Http code
*/
public function post_infor()
{
if ( ! $current_user = $this->check_authorization_token())
return $this->error_response('The access token could not be decrypted');
return $this->success_response($current_user);
}
/**
* The register post.
*
* @access public
* @return Http code
*/
public function post_register()
{
if ( ! $user = $this->check_authorization_token())
return $this->error_response('The access token could not be decrypted');
if ($user['group'] != \Constants::$user_group['Administrators'])
return $this->error_response('Access denied for user');
try
{
$val = \Model_User::validate('MasterCreate');
if ( ! $val->run()) return $this->error_response($val->error());
if (\Auth::create_user(
\Input::post('username'),
\Input::post('password'),
\Input::post('email'),
\Input::post('group') ? \Input::post('group') : 1,
array(
'fullname' => \Input::post('fullname') ? \Input::post('fullname') : '',
'phone' => \Input::post('phone') ? \Input::post('phone') : '',
'address' => \Input::post('address') ? \Input::post('address') : ''
)
))
{
return $this->success_response();
}
else
{
return $this->error_response('Create user failed');
}
}
catch (\Exception $e)
{
return $this->error_response($e->getMessage());
}
}
/**
* The change_password post.
*
* @access public
* @return Http code
*/
public function post_change_password()
{
if ( ! $user = $this->check_authorization_token())
return $this->error_response('The access token could not be decrypted');
try
{
$val = \Model_User::validate('ApiUserModifyPass');
if ( ! $val->run()) return $this->error_response($val->error());
if (\Input::post('old_password') == \Input::post('password'))
return $this->error_response('new_password and old_password must be different');
if (\Auth::validate_user($user['username'], \Input::post('old_password')))
{
if (\Auth::change_password(
\Input::post('old_password'),
\Input::post('password'),
$user['username']))
{
return $this->success_response();
}
else
{
return $this->error_response('Change password failed');
}
}
else
{
return $this->error_response('old_password is wrong');
}
}
catch (\Exception $e)
{
return $this->error_response($e->getMessage());
}
}
/**
* The delete post.
*
* @access public
* @return Http code
*/
public function post_delete($id = null)
{
if ( ! $user = $this->check_authorization_token())
return $this->error_response('The access token could not be decrypted');
if ($user['group'] != \Constants::$user_group['Administrators'])
return $this->error_response('Access denied for user');
try
{
if (is_null($id)) return $this->error_response('Request format is not valid');
if ( ! $delete_user = \Model_User::find($id))
return $this->error_response('User #'.$id.' is not exist');
if ($delete_user['username'] == $user['username'])
return $this->error_response('Could not deleted current user');
if ( ! \Auth::delete_user($delete_user['username']))
return $this->error_response('Could not deleted user');
return $this->success_response();
}
catch (\Exception $e)
{
return $this->error_response($e->getMessage());
}
}
}
<file_sep>/fuel/app/views/login/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>HỆ THỐNG QUẢN LÝ DỮ LIỆU NHIỆT ĐỘ BÊ TÔNG NHỰA | Đăng nhập</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<?php echo Asset::css('bootstrap/bootstrap.min.css'); ?>
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<?php echo Asset::css('dist/AdminLTE.min.css'); ?>
<!-- iCheck -->
<?php echo Asset::css('plugins/iCheck/square/blue.css'); ?>
<?php echo Asset::css('style.css'); ?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition login-page" style="background: url('<?php echo Asset::get_file('login_bg.jpg', 'img');?>');">
<div class="row">
<div class="login-logo" style="margin-top: 40px;">
<div class="row">
<div class="col-sm-6">
<!-- So GTVT -->
<a target="_blank" href="http://www.sgtvt.danang.gov.vn"><?php echo Asset::img('logo-danang.png', array('class' => 'investor-logo')); ?></a>
<!-- BkECC -->
<a target="_blank" href="http://www.bk-ecc.com.vn"><?php echo Asset::img('Bk-ecc.jpg', array('class' => 'investor-logo')); ?></a>
<!-- BKDN -->
<a target="_blank" href="http://www.dut.udn.vn"><?php echo Asset::img('logo-bkdn.jpg', array('class' => 'investor-logo')); ?></a>
</div>
<div class="col-sm-6">
<!-- Khoa cau duong -->
<a target="_blank" href="http://cauduongbkdn.com"><?php echo Asset::img('logo-cauduongbkdn.jpeg', array('class' => 'investor-logo')); ?></a>
<!-- BK-ITEC -->
<a target="_blank" href="#"><?php echo Asset::img('BK-ITEC_Logo.png', array('class' => 'investor-logo')); ?></a>
<!-- CEI -->
<a target="_blank" href="#"><?php echo Asset::img('CEI_logo_1.png', array('class' => 'investor-logo')); ?></a>
</div>
</div>
<div class="row text-center">
<div class="col-xs-12">
<a class="web-name" href="<?php echo Uri::create('/') ?>"><b><NAME><br>DỮ LIỆU NHIỆT ĐỘ BÊ TÔNG NHỰA</b></a>
</div>
</div>
</div>
</div>
<div class="login-box">
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">ĐĂNG NHẬP HỆ THỐNG</p>
<?php
if (Session::get_flash('error')) {
$error = Session::get_flash('error'); ?>
<div class="row text-center">
<div class="col-md-12">
<div class="alert alert-danger alert-dismissable">
<?php echo $error; ?>
</div>
</div>
</div>
<?php } ?>
<form action="<?php echo \Uri::create('/login'); ?>" method="post">
<div class="form-group has-feedback">
<input type="text" name="username" class="form-control" placeholder="<NAME>">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="<PASSWORD>">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12">
<button type="submit" class="btn btn-primary btn-block btn-flat">Đăng nhập</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 2.2.3 -->
<?php echo Asset::js('plugins/jQuery/jquery-2.2.3.min.js'); ?>
<!-- Bootstrap 3.3.6 -->
<?php echo Asset::js('bootstrap/js/bootstrap.min.js'); ?>
<!-- iCheck -->
<?php echo Asset::js('plugins/iCheck/icheck.min.js'); ?>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
</body>
</html>
<file_sep>/fuel/app/classes/controller/index.php
<?php
class Controller_Index extends Controller_Base
{
public $page;
/**
* Preprocessing
*/
public function before() {
// Set fields handled in input form as array
parent::before();
}
/**
*
* @throws Exception
*/
public function action_index()
{
if (Auth::check())
{
Auth::member(\Constants::$user_group['Administrators']) and \Response::redirect('admin/projects');
Auth::member(\Constants::$user_group['Moderators']) and \Response::redirect('moderator/projects');
Auth::member(\Constants::$user_group['Users']) and \Response::redirect('user/projects');
\Auth::logout();
}
Response::redirect('login');
}
}<file_sep>/fuel/app/views/template.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hệ thống quản lý nhiệt độ bê tông nhựa | Quản lý</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<?php echo Asset::css('bootstrap/bootstrap.min.css'); ?>
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<?php echo Asset::css('dist/AdminLTE.min.css'); ?>
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<?php echo Asset::css('dist/skins/_all-skins.min.css'); ?>
<!-- iCheck -->
<?php echo Asset::css('plugins/iCheck/flat/blue.css'); ?>
<!-- Date Picker -->
<?php echo Asset::css('plugins/datepicker/datepicker3.css'); ?>
<!-- Daterange picker -->
<?php echo Asset::css('plugins/daterangepicker/daterangepicker.css'); ?>
<?php echo Asset::css('style.css'); ?>
<!-- jQuery 2.2.3 -->
<?php echo Asset::js('plugins/jQuery/jquery-2.2.3.min.js'); ?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="<?php echo Uri::create('/') ?>" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini">...</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg">HỆ THỐNG QUẢN LÝ</span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="hidden-xs">
<i class="fa fa-user-circle"></i>
<?php
if (\Session::get('current_user'))
{
$current_user = \Session::get('current_user');
echo $current_user['username'];
}
else
{
echo 'Anonymous';
}
?>
</span>
</a>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="<?php echo Uri::create('logout') ?>">
<span>
<i class="fa fa-sign-out"></i>
Đăng xuất
</span>
</a>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="header">MENU CHÍNH</li>
<li class="active treeview">
<a href="<?php echo Uri::create('/') ?>">
<i class="fa fa-dashboard"></i> <span>Dự án</span>
</a>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Main content -->
<section class="content">
<?php echo $content; ?>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 1.0
</div>
<!--<strong>Copyright © 2017 <a href="http://ktlv.com.vn">KTLV</a>.</strong> All rights
reserved.-->
<strong>Designed by <a href="http://ktlv.com.vn">KTLV</a>.</strong>
</footer>
</div>
<!-- ./wrapper -->
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<?php echo Asset::js('bootstrap/js/bootstrap.min.js'); ?>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<!-- datepicker -->
<?php echo Asset::js('plugins/daterangepicker/daterangepicker.js'); ?>
<!-- datepicker -->
<?php echo Asset::js('plugins/datepicker/bootstrap-datepicker.js'); ?>
<!-- ChartJS 1.0.1 -->
<?php echo Asset::js('plugins/chartjs/Chart.min.js'); ?>
<!-- FastClick -->
<?php echo Asset::js('plugins/fastclick/fastclick.js'); ?>
<!-- AdminLTE App -->
<?php echo Asset::js('dist/js/app.min.js'); ?>
</body>
</html>
<file_sep>/fuel/app/classes/controller/logout.php
<?php
class Controller_Logout extends Controller
{
/**
* Preprocessing
*/
public function before() {
// Set fields handled in input form as array
parent::before();
}
/**
* The logout function
*
* @access public
* @return none
*/
public function action_index()
{
// Object generation for login
$auth = Auth::instance();
$auth->logout();
Response::redirect('/');
}
} | dc93c6bdc8a7b86f0d8b28dba470edb677c6c843 | [
"PHP"
] | 14 | PHP | titrabui/facebook_ads | 6f37a1fc710b134c3904efd1dfa1e2ded5be1e81 | d52d2bbe172f171b26f7bca391704637b359f0e9 |
refs/heads/master | <repo_name>juliarodriguess/api-postits_reprograma<file_sep>/users.js
const users = [
{
id: 1,
name: "Luana",
email: "<EMAIL>"
},
{
id: 2,
name: "Marcia",
email: "<EMAIL>"
},
{
id: 3,
name: "Mariana",
email: "<EMAIL>"
}
]
module.exports = users<file_sep>/index.js
const express = require('express');
const Joi = require('joi');
const postits = require('./post-its.js');
const app = express();
app.use(express.json());
//mostra os post-its
app.get('/', (req, res) => res.send('Hello world!'));
app.get('/api/postits', (req, res) => res.send(postits));
app.get('/api/postits/:id', (req, res) => {
const foundPostIt = postits.find(postit => postit.id === parseInt(req.params.id));
if(!foundPostIt) {
return res.status(404).send('Deu Merda');
}
res.send(foundPostIt);
});
//cadastra novo post-it
app.post('/api/postits', (req, res) => {
const id = Math.max(...postits.map(postit => postit.id)) + 1;
const newPostIt = {
id,
title: req.body.title,
text: req.body.text
};
const schema = {
title: Joi.string().min(1).required(),
text: Joi.string().min(1).required()
}
const validation = Joi.validate(req.body, schema);
if(validation.error){
return res.status(400).send(validation.error.details[0].message);
}
postits.push(newPostIt);
res.send(newPostIt);
});
//modifica o post-it
app.put('/api/postits/:id', (req, res) => {
const updatePostIt = postits.find(postit => postit.id === parseInt(req.params.id));
const schema = {
title: Joi.string().min(1).required(),
text: Joi.string().min(1).required()
}
const validation = Joi.validate(req.body, schema);
if(!updatePostIt) {
return res.status(404).send('Não encontramos esse post-it :(');
}
if(validation.error){
return res.status(400).send(validation.error.details[0].message);
}
updatePostIt.title = req.body.title;
updatePostIt.text = req.body.text;
res.send(updatePostIt);
})
//deleta o post-it
app.delete('/api/postits/:id', (req, res) => {
const deletePostIt = postits.find(user => user.id === parseInt(req.params.id));
const index = postits.indexOf(deletePostIt);
if(index > -1){
postits.splice(index, 1);
res.send(deletePostIt);
}
})
app.listen(3001, () => console.log('Ouvindo na porta 3001.............')); | fab018f48b5c45f27a3cc8751d517f9cbd6c7a21 | [
"JavaScript"
] | 2 | JavaScript | juliarodriguess/api-postits_reprograma | ec10a947191b5507386efdd7d317834dd3828d5d | e13795d11cdb8bec2b68535d181b3ebc9ac272ee |
refs/heads/master | <file_sep>//
// ViewController.swift
// Tapper
//
// Created by <NAME> on 6/29/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// scene 1 elements
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var howManyTaps: UITextField!
@IBOutlet weak var logoImg: UIImageView!
//scene 2 elements
@IBOutlet weak var tapsButton: UIImageView!
@IBOutlet weak var tapsTxt: UILabel!
@IBAction func onPlayBtnPressed(sender: UIButton!) {
logoImg.isHidden = true
playButton.isHidden = true
howManyTaps.isHidden = true
tapsTxt.isHidden = false
tapsButton.isHidden = false
}
}
| a73d38d0336e1cf678d764e03613bdabde90a034 | [
"Swift"
] | 1 | Swift | rmwilson79/Tapper | c74f70322ec7743f10560c3f8a26473864f9c4ab | 1772c0542d73a0dff4980a227a94fd351e135493 |
refs/heads/master | <file_sep>class LinkedList():
""" Python class representing a Linked List """
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def _make_node(value):
node = {}
node["value"] = value
node["next"] = None
return node
def add_to_tail(self, value):
new_node = self._make_node(value)
if self.head == None:
self.head = new_node
self.tail = new_node
self.size = self.size + 1
else:
self.tail["next"] = new_node
self.tail = new_node
self.size = self.size + 1
def remove_head(self):
if self.size != 0:
self.size = self.size - 1
removed = self.head
if self.head == self.tail:
self.tail = None
self.head = self.head["next"]
return removed["value"]
else:
raise Exception("Cannot remove head of empty list")
def contains(self, value):
target_node = self.head
found = False
while (target_node != None) and (found == False):
if target_node["value"] == value:
found = True
else:
target_node = target_node["next"]
return found<file_sep># pyDataStructures
Common data structures available as Python classes
| 7ce62e5d6ff3d11db9ddb2e01a9ebbd12ee3a8dd | [
"Markdown",
"Python"
] | 2 | Python | rohanagrawal/pyDataStructures | 5a63bf111cfd99754c39ef15d722b4af2f468fb4 | 34bc670393ffa75dd8f9c30c9165fbe798b38e20 |
refs/heads/master | <repo_name>eslafur/ESP32-8-Octave-Audio-Spectrum-WS2812-test<file_sep>/ESP32_Stereo_8Band_Spectrum_Analyzer.ino
#include <Wire.h>
#include "arduinoFFT.h" // Standard Arduino FFT library https://github.com/kosme/arduinoFFT
arduinoFFT FFT = arduinoFFT();
#define SAMPLES 2048 // Must be a power of 2
#define SAMPLING_FREQUENCY 40000 // Hz, must be 40000 or less due to ADC conversion time. Determines maximum frequency that can be analysed by the FFT Fmax=sampleF/2.
#define amplitude 150 // Depending on your audio source level, you may need to increase this value
#define Left true
#define Right false
unsigned int sampling_period_us;
unsigned long microseconds;
byte Lpeak[] = {0,0,0,0,0,0,0,0};
byte Rpeak[] = {0,0,0,0,0,0,0,0};
double LvReal[SAMPLES];
double LvImag[SAMPLES];
double RvReal[SAMPLES];
double RvImag[SAMPLES];
unsigned long newTime, oldTime;
/////////////////////////////////////////////////////////////////////////
void setup() {
Serial.begin(115200);
sampling_period_us = round(1000000 * (1.0 / SAMPLING_FREQUENCY));
}
void loop() {
display.clear();
display.drawString(0,0,"125 250 500 1K 2K 4K 8K 16K");
for (int i = 0; i < SAMPLES; i++) {
newTime = micros()-oldTime;
oldTime = newTime;
//VP input = Left, VN = Right
LvReal[i] = analogRead(36); // Using Arduino ADC nomenclature. A conversion takes about 1uS on an ESP32
LvImag[i] = 0;
RvReal[i] = analogRead(39); // Using Arduino ADC nomenclature. A conversion takes about 1uS on an ESP32
RvImag[i] = 0;
while (micros() < (newTime + sampling_period_us)) { /* do nothing to wait */ }
}
FFT.Windowing(LvReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(LvReal, LvImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(LvReal, LvImag, SAMPLES);
FFT.Windowing(RvReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(RvReal, RvImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(RvReal, RvImag, SAMPLES);
for (int i = 2; i < (SAMPLES/2); i++){ // Don't use sample 0 and only the first SAMPLES/2 are usable.
// Each array element represents a frequency and its value, is the amplitude. Note the frequencies are not discrete.
if (LvReal[i] > 1500 || RvReal[i] > 1500) { // Add a crude noise filter, 10 x amplitude or more
if (i<=2 ) {
displayBand(Left,0,(int)LvReal[i]); // 125Hz
displayBand(Right,0,(int)RvReal[i]); // 125Hz
}
if (i >2 && i<=4 ) {
displayBand(Left,1,(int)LvReal[i]); // 250Hz
displayBand(Right,1,(int)RvReal[i]); // 250Hz
}
if (i >4 && i<=7 ) {
displayBand(Left,2,(int)LvReal[i]); // 500Hz
displayBand(Right,2,(int)RvReal[i]); // 500Hz
}
if (i >7 && i<=15 ) {
displayBand(Left,3,(int)LvReal[i]); // 1000Hz
displayBand(Right,3,(int)RvReal[i]); // 1000Hz
}
if (i >15 && i<=40 ) {
displayBand(Left,4,(int)LvReal[i]); // 2000Hz
displayBand(Right,4,(int)RvReal[i]); // 2000Hz
}
if (i >40 && i<=70 ) {
displayBand(Left,5,(int)LvReal[i]); // 4000Hz
displayBand(Right,5,(int)RvReal[i]); // 4000Hz
}
if (i >70 && i<=288 ) {
displayBand(Left,6,(int)LvReal[i]); // 8000Hz
displayBand(Right,6,(int)RvReal[i]); // 8000Hz
}
if (i >288 ) {
displayBand(Left,7,(int)LvReal[i]); // 16000Hz
displayBand(Right,7,(int)RvReal[i]); // 16000Hz
}
//Serial.println(i);
}
}
}
void displayBand(bool channel, int band, int dsize){
//output to ws
}
| ff3353edc811b1d485b71f8486f8c3db2edda024 | [
"C++"
] | 1 | C++ | eslafur/ESP32-8-Octave-Audio-Spectrum-WS2812-test | 4678d2d3ff66263800755fefbc87feadb6e652f3 | 74348141dd6c797cef721f656f216633c76b7461 |
refs/heads/master | <repo_name>chips001/Swift_ToDoApp2<file_sep>/Swift_ToDoApp2/Scenes/ContentsKind.swift
//
// MainContentsKind.swift
// Swift_ToDoApp2
//
// Created by <NAME> on 2019/02/26.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
enum ContentsKind {
case toDo
var description: String {
switch self {
case .toDo: return "ToDoList"
}
}
}
<file_sep>/Swift_ToDoApp2/Scenes/TopLevelMenuKind.swift
//
// TopLevelMenuKind.swift
// Swift_ToDoApp2
//
// Created by <NAME> on 2019/02/26.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
enum TopLevelMenuKind: Equatable {
case main(ContentsKind)
var controllerType: UIViewController.Type {
switch self {
case .main: return MainListViewController.self
}
}
var title: String {
switch self {
case .main: return "MainList"
}
}
}
<file_sep>/Swift_ToDoApp2/Scenes/ContainerViewController.swift
//
// ContainerViewController.swift
// Swift_ToDoApp2
//
// Created by <NAME> on 2019/02/26.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ContainerViewController: UIViewController {
var didTapBarButtonHandler: (() -> Void)?
private var controllerList:[TopLevelMenuKind] = [
.main(.toDo)
]
private var currentNavigationController: UINavigationController?
override func viewDidLoad() {
super.viewDidLoad()
self.setupFirstViewController()
}
private func setupFirstViewController() {
let firstViewController = self.instantiateToViewController(kind: self.controllerList[0])
let firstNavigationController = UINavigationController(rootViewController: firstViewController)
self.currentNavigationController = firstNavigationController
self.addChild(firstNavigationController)
self.view.insertSubview(firstNavigationController.view, at: 0)
firstNavigationController.didMove(toParent: self)
}
private func instantiateToViewController(kind: TopLevelMenuKind) -> UIViewController {
let toViewController: UIViewController
switch kind {
case .main(let kind):
let viewController = MainListViewController.instantiateFromStoryboard()
viewController.contentsKind = kind
toViewController = viewController
}
return toViewController
}
func showChildViewController(kind: TopLevelMenuKind) {
guard let fromNavigationController = self.currentNavigationController else { return }
let toViewController = self.instantiateToViewController(kind: kind)
let toNavigationController = UINavigationController(rootViewController: toViewController)
fromNavigationController.willMove(toParent: nil)
self.addChild(toNavigationController)
self.transition(
from: fromNavigationController,
to: toNavigationController,
duration: 0,
options: [],
animations: nil,
completion: { [weak self] _ in
guard let `self` = self else { return }
fromNavigationController.removeFromParent()
toNavigationController.didMove(toParent: self)
self.currentNavigationController = toNavigationController
})
}
}
<file_sep>/Swift_ToDoApp2/Scenes/ToDoList/MainListViewController.swift
//
// ToDoListViewController.swift
// Swift_ToDoApp2
//
// Created by <NAME> on 2019/02/25.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class MainListViewController: UIViewController {
var contentsKind: ContentsKind?
var todoList = [Todo]()
override func viewDidLoad() {
super.viewDidLoad()
self.setupBarButtonItem(viewController: self)
let userDefaults = UserDefaults.standard
if let storedToDoList = userDefaults.object(forKey: "todolist") as? Data,
let unarchiveTodoList = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(storedToDoList) as? [Todo],
let unarchivedTodoList = unarchiveTodoList {
self.todoList.append(contentsOf: unarchivedTodoList)
}
}
private func setupBarButtonItem(viewController : UIViewController) {
let barButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonClicked(sender:)))
viewController.navigationItem.rightBarButtonItem = barButtonItem
}
@objc private func addButtonClicked(sender: UIBarButtonItem) {
let arertViewController = UIAlertController(
title: "TODO追加",
message: "TODOを入力して下さい",
preferredStyle: .alert
)
arertViewController.addTextField(configurationHandler: nil)
let okAction = UIAlertAction(
title: "OK",
style: .default
) { action in
if let textField = arertViewController.textFields?.first, let text = textField.text {
let todo = Todo()
todo.todoTitle = text
self.todoList.insert(todo, at: 0)
self.toDoListTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .right)
self.saveToUserDefaultsWithTodolist()
}
}
arertViewController.addAction(okAction)
let cancelAction = UIAlertAction(
title: "CANCEL",
style: .cancel,
handler: nil
)
arertViewController.addAction(cancelAction)
self.present(arertViewController, animated: true, completion: nil)
}
private func saveToUserDefaultsWithTodolist() {
let userDefaults = UserDefaults.standard
if let data = try? NSKeyedArchiver.archivedData(withRootObject: self.todoList, requiringSecureCoding: false) {
userDefaults.set(data, forKey: "todolist")
userDefaults.synchronize()
}
}
@IBOutlet weak var toDoListTableView: UITableView!
}
extension MainListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return ToDoCell.heightForRow
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todoList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withClass: ToDoCell.self, for: indexPath)
let todo = self.todoList[indexPath.row]
cell.toDoLabel.text = todo.todoTitle
if todo.todoDone {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let todo = self.todoList[indexPath.row]
if todo.todoDone {
todo.todoDone = false
} else {
todo.todoDone = true
}
tableView.reloadRows(at: [indexPath], with: .fade)
self.saveToUserDefaultsWithTodolist()
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
self.todoList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
self.saveToUserDefaultsWithTodolist()
}
}
}
final class ToDoCell: UITableViewCell {
static let heightForRow: CGFloat = 50
@IBOutlet weak var toDoLabel: UILabel!
}
class Todo: NSObject, NSCoding {
func encode(with aCoder: NSCoder) {
aCoder.encode(self.todoTitle, forKey: "todotitle")
aCoder.encode(self.todoDone, forKey: "tododone")
}
required init?(coder aDecoder: NSCoder) {
todoTitle = aDecoder.decodeObject(forKey: "todotitle") as? String
todoDone = aDecoder.decodeBool(forKey: "tododone")
}
var todoTitle: String?
var todoDone: Bool = false
override init() { }
}
<file_sep>/Swift_ToDoApp2/AppDelegate.swift
//
// AppDelegate.swift
// Swift_ToDoApp2
//
// Created by <NAME> on 2019/02/25.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window?.rootViewController = ContainerViewController()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
<file_sep>/Swift_ToDoApp2/Extensions/UITableView+Util.swift
//
// UITableView+Util.swift
// Swift_ToDoApp2
//
// Created by <NAME> on 2019/03/02.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UITableView {
// func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell
func dequeueReusableCell<T: UITableViewCell>(withClass type: T.Type, for indexPath: IndexPath) -> T {
return self.dequeueReusableCell(withIdentifier: String(describing: type), for: indexPath) as! T
}
func dequeueReusableCell<T: UITableViewCell>(withClass type: T.Type) -> T {
return self.dequeueReusableCell(withIdentifier: String(describing: type)) as! T
}
}
| e2368b38d9d8a4b399ca8204effe607595d8c15c | [
"Swift"
] | 6 | Swift | chips001/Swift_ToDoApp2 | 7f0e0d867071dad480f06bd03f9f378fcacd04f4 | 58613a6ca8c034f37d78665dd785fed3a8033447 |
refs/heads/master | <repo_name>dmarshall83/coursera-getting-and-cleaning-data-project<file_sep>/CodeBook.md
#Code Book
This code book is for the uci-har-means-tidy.txt dataset
##Original Data Source
The original source for the data in this dataset came from the study "Human Activity Recognition Using Smartphones Data Set". A description of the study and relevant files can be found at: http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
##Identifying Fields
* subject - An ID number identifying the test subject performing the activities.
* activity - A description of the activities performed by the subject (activity labels have been converted to lowercase and underscores have been removed to make them more tidy):
* walking
* walkingupstairs
* walkingdownstairs
* sitting
* standing
* laying
##Measurement Fields
All of the measurement fields are derived from the measurement of the similar field in the original dataset (see below for name conversion). The measurements are the means of the original values grouped by subject and activity. In order to make the field names more tidy, the hyphens and parenthesis have been removed and camel case has been applied to adjoining words.
|Tidy.Data.Name|Original.Data.Name|
|--------------------------------------|--------------------------------------|
|`tBodyAccMeanX`|`tBodyAcc-mean()-X`|
|`tBodyAccMeanY`|`tBodyAcc-mean()-Y`|
|`tBodyAccMeanZ`|`tBodyAcc-mean()-Z`|
|`tBodyAccStdX`|`tBodyAcc-std()-X`|
|`tBodyAccStdY`|`tBodyAcc-std()-Y`|
|`tBodyAccStdZ`|`tBodyAcc-std()-Z`|
|`tGravityAccMeanX`|`tGravityAcc-mean()-X`|
|`tGravityAccMeanY`|`tGravityAcc-mean()-Y`|
|`tGravityAccMeanZ`|`tGravityAcc-mean()-Z`|
|`tGravityAccStdX`|`tGravityAcc-std()-X`|
|`tGravityAccStdY`|`tGravityAcc-std()-Y`|
|`tGravityAccStdZ`|`tGravityAcc-std()-Z`|
|`tBodyAccJerkMeanX`|`tBodyAccJerk-mean()-X`|
|`tBodyAccJerkMeanY`|`tBodyAccJerk-mean()-Y`|
|`tBodyAccJerkMeanZ`|`tBodyAccJerk-mean()-Z`|
|`tBodyAccJerkStdX`|`tBodyAccJerk-std()-X`|
|`tBodyAccJerkStdY`|`tBodyAccJerk-std()-Y`|
|`tBodyAccJerkStdZ`|`tBodyAccJerk-std()-Z`|
|`tBodyGyroMeanX`|`tBodyGyro-mean()-X`|
|`tBodyGyroMeanY`|`tBodyGyro-mean()-Y`|
|`tBodyGyroMeanZ`|`tBodyGyro-mean()-Z`|
|`tBodyGyroStdX`|`tBodyGyro-std()-X`|
|`tBodyGyroStdY`|`tBodyGyro-std()-Y`|
|`tBodyGyroStdZ`|`tBodyGyro-std()-Z`|
|`tBodyGyroJerkMeanX`|`tBodyGyroJerk-mean()-X`|
|`tBodyGyroJerkMeanY`|`tBodyGyroJerk-mean()-Y`|
|`tBodyGyroJerkMeanZ`|`tBodyGyroJerk-mean()-Z`|
|`tBodyGyroJerkStdX`|`tBodyGyroJerk-std()-X`|
|`tBodyGyroJerkStdY`|`tBodyGyroJerk-std()-Y`|
|`tBodyGyroJerkStdZ`|`tBodyGyroJerk-std()-Z`|
|`tBodyAccMagMean`|`tBodyAccMag-mean()`|
|`tBodyAccMagStd`|`tBodyAccMag-std()`|
|`tGravityAccMagMean`|`tGravityAccMag-mean()`|
|`tGravityAccMagStd`|`tGravityAccMag-std()`|
|`tBodyAccJerkMagMean`|`tBodyAccJerkMag-mean()`|
|`tBodyAccJerkMagStd`|`tBodyAccJerkMag-std()`|
|`tBodyGyroMagMean`|`tBodyGyroMag-mean()`|
|`tBodyGyroMagStd`|`tBodyGyroMag-std()`|
|`tBodyGyroJerkMagMean`|`tBodyGyroJerkMag-mean()`|
|`tBodyGyroJerkMagStd`|`tBodyGyroJerkMag-std()`|
|`fBodyAccMeanX`|`fBodyAcc-mean()-X`|
|`fBodyAccMeanY`|`fBodyAcc-mean()-Y`|
|`fBodyAccMeanZ`|`fBodyAcc-mean()-Z`|
|`fBodyAccStdX`|`fBodyAcc-std()-X`|
|`fBodyAccStdY`|`fBodyAcc-std()-Y`|
|`fBodyAccStdZ`|`fBodyAcc-std()-Z`|
|`fBodyAccMeanFreqX`|`fBodyAcc-meanFreq()-X`|
|`fBodyAccMeanFreqY`|`fBodyAcc-meanFreq()-Y`|
|`fBodyAccMeanFreqZ`|`fBodyAcc-meanFreq()-Z`|
|`fBodyAccJerkMeanX`|`fBodyAccJerk-mean()-X`|
|`fBodyAccJerkMeanY`|`fBodyAccJerk-mean()-Y`|
|`fBodyAccJerkMeanZ`|`fBodyAccJerk-mean()-Z`|
|`fBodyAccJerkStdX`|`fBodyAccJerk-std()-X`|
|`fBodyAccJerkStdY`|`fBodyAccJerk-std()-Y`|
|`fBodyAccJerkStdZ`|`fBodyAccJerk-std()-Z`|
|`fBodyAccJerkMeanFreqX`|`fBodyAccJerk-meanFreq()-X`|
|`fBodyAccJerkMeanFreqY`|`fBodyAccJerk-meanFreq()-Y`|
|`fBodyAccJerkMeanFreqZ`|`fBodyAccJerk-meanFreq()-Z`|
|`fBodyGyroMeanX`|`fBodyGyro-mean()-X`|
|`fBodyGyroMeanY`|`fBodyGyro-mean()-Y`|
|`fBodyGyroMeanZ`|`fBodyGyro-mean()-Z`|
|`fBodyGyroStdX`|`fBodyGyro-std()-X`|
|`fBodyGyroStdY`|`fBodyGyro-std()-Y`|
|`fBodyGyroStdZ`|`fBodyGyro-std()-Z`|
|`fBodyGyroMeanFreqX`|`fBodyGyro-meanFreq()-X`|
|`fBodyGyroMeanFreqY`|`fBodyGyro-meanFreq()-Y`|
|`fBodyGyroMeanFreqZ`|`fBodyGyro-meanFreq()-Z`|
|`fBodyAccMagMean`|`fBodyAccMag-mean()`|
|`fBodyAccMagStd`|`fBodyAccMag-std()`|
|`fBodyAccMagMeanFreq`|`fBodyAccMag-meanFreq()`|
|`fBodyAccJerkMagMean`|`fBodyBodyAccJerkMag-mean()`|
|`fBodyAccJerkMagStd`|`fBodyBodyAccJerkMag-std()`|
|`fBodyAccJerkMagMeanFreq`|`fBodyBodyAccJerkMag-meanFreq()`|
|`fBodyGyroMagMean`|`fBodyBodyGyroMag-mean()`|
|`fBodyGyroMagStd`|`fBodyBodyGyroMag-std()`|
|`fBodyGyroMagMeanFreq`|`fBodyBodyGyroMag-meanFreq()`|
|`fBodyGyroJerkMagMean`|`fBodyBodyGyroJerkMag-mean()`|
|`fBodyGyroJerkMagStd`|`fBodyBodyGyroJerkMag-std()`|
|`fBodyGyroJerkMagMeanFreq`|`fBodyBodyGyroJerkMag-meanFreq()`|
|`angle(tBodyAccMean,gravity)`|`angle(tBodyAccMean,gravity)`|
|`angle(tBodyAccJerkMean),gravityMean)`|`angle(tBodyAccJerkMean),gravityMean)`|
|`angle(tBodyGyroMean,gravityMean)`|`angle(tBodyGyroMean,gravityMean)`|
|`angle(tBodyGyroJerkMean,gravityMean)`|`angle(tBodyGyroJerkMean,gravityMean)`|
|`angle(X,gravityMean)`|`angle(X,gravityMean)`|
|`angle(Y,gravityMean)`|`angle(Y,gravityMean)`|
|`angle(Z,gravityMean)`|`angle(Z,gravityMean)`|
##Feature Selection (notes from orignial data ReadMe)
The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals tAcc-XYZ and tGyro-XYZ. These time domain signals (prefix 't' to denote time) were captured at a constant rate of 50 Hz. Then they were filtered using a median filter and a 3rd order low pass Butterworth filter with a corner frequency of 20 Hz to remove noise. Similarly, the acceleration signal was then separated into body and gravity acceleration signals (tBodyAcc-XYZ and tGravityAcc-XYZ) using another low pass Butterworth filter with a corner frequency of 0.3 Hz.
Subsequently, the body linear acceleration and angular velocity were derived in time to obtain Jerk signals (tBodyAccJerk-XYZ and tBodyGyroJerk-XYZ). Also the magnitude of these three-dimensional signals were calculated using the Euclidean norm (tBodyAccMag, tGravityAccMag, tBodyAccJerkMag, tBodyGyroMag, tBodyGyroJerkMag).
Finally a Fast Fourier Transform (FFT) was applied to some of these signals producing fBodyAcc-XYZ, fBodyAccJerk-XYZ, fBodyGyro-XYZ, fBodyAccJerkMag, fBodyGyroMag, fBodyGyroJerkMag. (Note the 'f' to indicate frequency domain signals).
These signals were used to estimate variables of the feature vector for each pattern:
'-XYZ' is used to denote 3-axial signals in the X, Y and Z directions.
* tBodyAcc-XYZ
* tGravityAcc-XYZ
* tBodyAccJerk-XYZ
* tBodyGyro-XYZ
* tBodyGyroJerk-XYZ
* tBodyAccMag
* tGravityAccMag
* tBodyAccJerkMag
* tBodyGyroMag
* tBodyGyroJerkMag
* fBodyAcc-XYZ
* fBodyAccJerk-XYZ
* fBodyGyro-XYZ
* fBodyAccMag
* fBodyAccJerkMag
* fBodyGyroMag
* fBodyGyroJerkMag
The set of variables that were estimated from these signals are:
* mean(): Mean value
* std(): Standard deviation
* \* additional measurements were created in original dataset that do not appear in this tidy dataset
Additional vectors obtained by averaging the signals in a signal window sample. These are used on the angle() variable:
* gravityMean
* tBodyAccMean
* tBodyAccJerkMean
* tBodyGyroMean
* tBodyGyroJerkMean
<file_sep>/run_analysis.R
##This collection of function will download the UCI HAR Dataset process the
##data into a complete and tidy dataset. Then it will summarize the dataset by
##subject, activity, and mean of selected measures. This new dataset will get
##written to uci-har-means-tidy.csv in the working directory. The runAnalysis
##is a wrapper and will run all needed support functions.
runAnalysis <- function(){
# Prepare Libraries
getLibraries()
# Get the data
getData()
# Combine data into a unified dataset
writeLines("Combining the data.")
combinedDataset <- createCombinedDataset()
#Create the Tidy summary dataset
writeLines("Summarizing the data.")
tidySummaryData <- createSummaryDataset(combinedDataset)
#write the file to uci-har-means-tidy.txt
write.table(summary, "uci-har-means-tidy.txt", row.names = FALSE)
writeLines(paste0("Tidy summary file has been saved to ", getwd(), "/uci-har-means-tidy.txt"))
writeLines("To view the file run: \ndata <- read.table('uci-har-means-tidy.txt', header = TRUE)\nView(data)")
}
createSummaryDataset <- function(dataset){
#select only the mean and std columns
subset <- select(dataset, subject, activity, grep("[Mm]ean|[Ss]td", names(dataset)))
#create the mean file
summary <- subset %>% group_by(subject, activity) %>% summarise_each(funs(mean))
#make tidy names
tidynames <- names(summary)
tidynames <- gsub("-mean", "Mean",tidynames)
tidynames <- gsub("-std", "Std",tidynames)
tidynames <- gsub("\\(\\)-|\\(\\)", "",tidynames)
tidynames <- gsub("BodyBody", "Body",tidynames)
names(summary) <- tidynames
return(summary)
}
createCombinedDataset <- function(){
#Combine the training and test dataset applying the appropriate labels and headers
#read in all necessary files
xtrain <- read.table("./UCI HAR Dataset/train/x_train.txt")
ytrain <- read.table("./UCI HAR Dataset/train/y_train.txt")
subtrain <- read.table("./UCI HAR Dataset/train/subject_train.txt")
subtest <- read.table("./UCI HAR Dataset/test/subject_test.txt")
features <- read.table("./UCI HAR Dataset/features.txt", stringsAsFactors = FALSE)
xtest <- read.table("./UCI HAR Dataset/test/X_test.txt")
ytest <- read.table("./UCI HAR Dataset/test/y_test.txt")
activitylabels <- read.table("./UCI HAR Dataset/activity_labels.txt")
#make the names unique
featurelabels <- make.unique(features$V2)
#add the column labels
names(xtrain) <- featurelabels
names(xtest) <- featurelabels
#cbind the xy for each
xytrain <- cbind(activity = ytrain$V1, xtrain)
xytest <- cbind(activity = ytest$V1, xtest)
#cbind the subject
xytrain <- cbind(subject = subtrain$V1, xytrain)
xytest <- cbind(subject = subtest$V1, xytest)
#add the data tables together
xycombined <- rbind(xytrain, xytest)
#change the levels of activityif to be the activity name
xycombined$activity <- as.factor(xycombined$activity)
#make the activity name lowercase and remove the underscore
activities <- gsub("_", "", tolower(activitylabels$V2))
levels(xycombined$activity) <- activities
return(xycombined)
}
getData <- function(){
#check to see if the file already exists and exit download
if(file.exists("UCI HAR Dataset")){
writeLines("UCI HAR Dataset located in working directory.")
}else{
download.file("https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip", "dataset.zip")
unzip("dataset.zip")
file.remove("dataset.zip")
writeLines(paste0("UCI HAR Dataset downloaded and saved to ", getwd(), "/UCI HAR Dataset"))
}
}
getLibraries <- function(){
#Checks for the required dplyr library and installs it if necessary
if(require("dplyr")){
writeLines("dplyr is loaded")
} else {
writeLines("attempting to install dplyr")
install.packages("dplyr")
if(require(dplyr)){
writeLines("dplyr was installed and loaded correctly")
} else {
stop("could not install required packages (dplyr)")
}
}
}<file_sep>/README.md
# Getting and Cleaning Data - Course Project
The R script `run_analysis.R` was created to gather data, clean data, and created a tidy summary dataset of the UCI HAR Dataset. `run_analysis.R` contians the following functions:
* ###runAnalysis
This function is a wrapper to run all necessary functions start to finish and write the tidy summary dataset to uci-har-means-tidy.txt. To view the output run the following code:
`data <- read.table('uci-har-means-tidy.txt', header = TRUE)`
`View(data)`
* ###getLibraries
This script requires the dplyr library. This function will check for this library and download and/or load if necessary.
* ###getData
This function checks the working directory for the `UCI HAR Dataset`. If the folder does not exist the data is downloaded, unziped, and the zipped file is removed. The unziped folder location is reported to the user.
* ###createCombinedDataset
This function does the following:
1. Reads all necessary tables into R.
2. Makes a unique feature list to avoid duplicate label issues with dplyr select.
3. Relabels the columns in both test and train data to the features.
4. Adds the y for each test and train dataset and labels is `activity`.
5. Adds the `subject` to each test and train dataset.
6. Combines the test and train data into one dataset.
7. Changes `activity` to a factor and resets the levels to the tidy activity labels.
8. Returns the combined labeled dataset.
* ###createSummaryDataset
This functions takes the output of the createCombinedDataset function and does the following:
1. Selects a subset of columns that contain: `subject`, `activity`, and any field containing the word `mean` or `std` in the label.
2. Groups the data by `subject` and `activity` then summarizes all measurement fields by the mean.
3. Creates tidy column labels by the following:
a. removing hypens.
b. removing parenthesis.
c. applying camel case.
d. changes `BodyBody` to `Body`.
4. returns the tidy summary dataset. | edffb48826d5ebaedbb46cc6e985da254debe4a8 | [
"Markdown",
"R"
] | 3 | Markdown | dmarshall83/coursera-getting-and-cleaning-data-project | 1b46c6763bc5dc46b1d3f9a599656ceafd1335b1 | 2e0135f58b036bffba865739c502b1e687beb18c |
refs/heads/master | <repo_name>PoojaSinha1998/SalesAppOnWheels<file_sep>/android/app/src/main/kotlin/com/example/onwheelssales/MainActivity.kt
package com.example.onwheelssales
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 865b9e4598089c562c5ed4814b565bd1c005bf90 | [
"Kotlin"
] | 1 | Kotlin | PoojaSinha1998/SalesAppOnWheels | 5b9df758391a6fca962994b69f45ee55c1a1763a | 7b567440a48379c4e04d03313aa36f3d51cf4c1a |
refs/heads/master | <repo_name>hakeemsyd/segmentnext<file_sep>/app/router.ts
'use strict'
// import React from 'react';
// import { Platform, StatusBar } from 'react-native';
import { StackNavigator } from 'react-navigation';
// import { FontAwesome } from 'react-native-vector-icons';
import { Home } from './layout/Home';
import { Post } from './layout/Post';
// import { NavigationActions } from 'react-navigation';
// import { PostsListStore } from './stores/PostsListStore';
export class Router {
private constructor() {
}
static Main = StackNavigator({
Home: {
screen: Home,
navigationOptions: {
title: 'Segmentnext'
}
},
Post: {
screen: Post,
}
});
/*static SignedOut = StackNavigator({
UserHome: {
screen: Router.SignedIn
}
});*/
};
<file_sep>/README.md
A react native app which fetches list of posts from a remote URL and displays them in a list. The articles can be viewed in detail by clicking on each article.
<file_sep>/android/settings.gradle
rootProject.name = 'segmentnext'
include ':app'
<file_sep>/app/index.ts
'use strict';
import { Router } from './router';
import { AppRegistry } from 'react-native';
import { Constants } from './utils/constants';
import * as firebase from 'firebase';
export const firebaseApp = firebase.initializeApp(Constants.config);
AppRegistry.registerComponent('segmentnext', () => Router.Main);
<file_sep>/app/stores/PostsListStore.ts
'use strict';
import { observable } from 'mobx';
// import { Router } from '../router';
// import { Constants } from '../utils/constants';
export class PostsListStore {
@observable
posts: Array<{id: number, title: string, body: string, image: string, url: string}>;
constructor() {
const p = [
{
id: 1,
title: '<NAME>',
body: 'Some post 1',
image: '',
url: 'https://unsplash.com/photos/C9t94JC4_L8'
},
{
id: 2,
title: '<NAME>',
body: 'some post 2',
image: '',
url: 'https://unsplash.com/photos/waZEHLRP98s'
},
{
id: 3,
title: '<NAME>',
body: 'some post 3',
image: '',
url: 'https://unsplash.com/photos/cFplR9ZGnAk'
},
{
id: 4,
title: '<NAME>',
body: 'SOme post 4',
image: '',
url: 'https://unsplash.com/photos/89PFnHKg8HE'
}
]
this.posts = p;
}
addPost(id: number, title: string, body: string): void {
this.posts.push({
id: id,
title: title,
body: body,
image: '',
url: ''
});
}
}
<file_sep>/app/utils/constants.ts
'use strict';
export class Constants {
private constructor() {
}
public static config = {
apiKey: "<KEY>",
authDomain: "gossip-bbb74.firebaseapp.com",
databaseURL: "https://gossip-bbb74.firebaseio.com",
projectId: "gossip-bbb74",
storageBucket: "gossip-bbb74.appspot.com",
messagingSenderId: "298354551253"
};
public static KEY_TOKEN = 'auth_token';
}<file_sep>/gulpfile.js
var gulp = require('gulp');
var ts = require('gulp-typescript');
var clean = require('gulp-clean');
// Grab settings from tsconfig.json
var tsProject = ts.createProject('tsconfig.json');
gulp.task('clean', function () {
return gulp.src('./bin', { read: false })
.pipe(clean());
});
gulp.task('build', ['assets'], function () {
var tsResult = tsProject.src().pipe(tsProject());
return tsResult.js.pipe(gulp.dest('bin'));
});
gulp.task('assets', ['clean'], function () {
//gulp.src("./app/images/**.*")
// .pipe(gulp.dest('bin/app/images/'));
});
gulp.task('watch', ['build'], function () {
gulp.watch('./**/*.ts', ['clean','build']);
gulp.watch('./**/*.tsx', ['clean','build']);
});
gulp.task('default', ['build']);
| 331e7861ca76c9557ed36943484479235fe2a451 | [
"Markdown",
"TypeScript",
"JavaScript",
"Gradle"
] | 7 | TypeScript | hakeemsyd/segmentnext | 8fd2da50bcfc5e1ddd950177dd8fcc81597728e0 | 71490ec870b912074079c31527f5dfdf8d37fbdd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.