repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
arnosthavelka/lambdas-poc | src/main/java/com/github/aha/poc/lambdas/enums/OperationStrategy.java | 136 | package com.github.aha.poc.lambdas.enums;
@FunctionalInterface
public interface OperationStrategy<T> {
T compute(T x, T y);
}
| mit |
zalando/intellij-swagger | src/main/java/org/zalando/intellij/swagger/completion/value/completion/openapi/StyleValueCompletion.java | 679 | package org.zalando.intellij.swagger.completion.value.completion.openapi;
import com.intellij.codeInsight.completion.CompletionResultSet;
import org.zalando.intellij.swagger.completion.CompletionHelper;
import org.zalando.intellij.swagger.completion.value.ValueCompletion;
import org.zalando.intellij.swagger.completion.value.model.openapi.OpenApiValues;
class StyleValueCompletion extends ValueCompletion {
StyleValueCompletion(
final CompletionHelper completionHelper, final CompletionResultSet completionResultSet) {
super(completionHelper, completionResultSet);
}
@Override
public void fill() {
OpenApiValues.styles().forEach(this::addValue);
}
}
| mit |
stojanovic/scottyjs | bin/scotty.js | 8152 | #!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const minimist = require('minimist')
const AWS = require('aws-sdk')
const scotty = require('../index')
const inquirer = require('inquirer')
const colors = require('colors')
const clipboardy = require('clipboardy')
const configFilePath = path.join(__dirname, '..', '.scotty-config.json')
// Supported regions from http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
const AWS_REGIONS = [
'eu-central-1',
'eu-west-1',
'eu-west-2',
'us-east-2',
'us-east-1',
'us-west-1',
'us-west-2',
'ca-central-1',
'ap-south-1',
'ap-northeast-2',
'ap-southeast-1',
'ap-southeast-2',
'ap-northeast-1',
'sa-east-1',
'cn-north-1'
]
function showHelp() {
return console.log(`
${colors.magenta('Scotty')} ✤ ${colors.cyan('deploy static websites or folders to AWS S3 with a single command')}
${colors.magenta('Version:')} ${colors.cyan(require(path.join(__dirname, '..', 'package.json')).version)}
✤ ✤ ✤
USAGE:
${colors.magenta('scotty {options}')} ${colors.cyan('or')} ${colors.magenta('beam-me-up {options}')}
AVAILABLE OPTIONS:
${colors.magenta('--help')} ${colors.cyan('or')} ${colors.magenta('-h')} Print this help
${colors.magenta('--version')} ${colors.cyan('or')} ${colors.magenta('-v')} Print the current version
${colors.magenta('--quiet')} ${colors.cyan('or')} ${colors.magenta('-q')} Suppress output when executing commands ${colors.cyan('| default: false')}
${colors.magenta('--noclipboard')} ${colors.cyan('or')} ${colors.magenta('-n')} Do not copy the URL to clipboard ${colors.cyan('| default: false')}
${colors.magenta('--website')} ${colors.cyan('or')} ${colors.magenta('-w')} Set uploaded folder as a static website ${colors.cyan('| default: false')}
${colors.magenta('--spa')} Set uploaded folder as a single page app and redirect all non-existing pages to index.html ${colors.cyan('| default: false')}
${colors.magenta('--source')} ${colors.cyan('or')} ${colors.magenta('-s')} Source of the folder that will be uploaded ${colors.cyan('| default: current folder')}
${colors.magenta('--bucket')} ${colors.cyan('or')} ${colors.magenta('-b')} Name of the S3 bucket ${colors.cyan('| default: name of the current folder')}
${colors.magenta('--prefix')} ${colors.cyan('or')} ${colors.magenta('-p')} Prefix on the S3 bucket ${colors.cyan('| default: the root of the bucket')}
${colors.magenta('--region')} ${colors.cyan('or')} ${colors.magenta('-r')} AWS region where the files will be uploaded ${colors.cyan('| default: saved region if exists or a list to choose one if it is not saved yet')}
${colors.magenta('--force')} ${colors.cyan('or')} ${colors.magenta('-f')} Update the bucket without asking, region can be overridden with ${colors.magenta('-r')} ${colors.cyan('| default: false')}
${colors.magenta('--update')} ${colors.cyan('or')} ${colors.magenta('-u')} Update existing bucket ${colors.cyan('| default: false')}
${colors.magenta('--delete')} ${colors.cyan('or')} ${colors.magenta('-d')} Delete existing bucket ${colors.cyan('| default: false')}
${colors.magenta('--nocdn')} ${colors.cyan('or')} ${colors.magenta('-c')} Disable Cloudfront handling ${colors.cyan('| default: false')}
${colors.magenta('--urlonly')} ${colors.cyan('or')} ${colors.magenta('-o')} Only output the resulting URL, CDN or S3 according to options ${colors.cyan('| default: false')}
${colors.magenta('--expire')} ${colors.cyan('or')} ${colors.magenta('-e')} Delete objects on bucket older than n days ${colors.cyan('| default: no expiration')}
${colors.magenta('--profile')} ${colors.cyan('or')} ${colors.magenta('-a')} AWS profile to be used ${colors.cyan('| default: default')}
${colors.magenta('--empty')} ${colors.cyan('or')} ${colors.magenta('-y')} Empty the bucket (Delete all objects before upload files) ${colors.cyan('| default: false')}
✤ ✤ ✤
${colors.magenta('Beam me up, Scotty!')}
More info: ${colors.cyan('https://github.com/stojanovic/scottyjs')}
Changelog/release history: ${colors.cyan('https://github.com/stojanovic/scottyjs/releases')}
`)
}
function readArgs() {
return minimist(process.argv.slice(2), {
alias: {
h: 'help',
v: 'version',
q: 'quiet',
n: 'noclipboard',
w: 'website',
s: 'source',
b: 'bucket',
p: 'prefix',
r: 'region',
f: 'force',
u: 'update',
d: 'delete',
c: 'nocdn',
o: 'urlonly',
e: 'expire',
a: 'profile',
y: 'empty'
},
string: ['source', 'bucket', 'prefix', 'region', 'profile'],
boolean: ['quiet', 'website', 'spa', 'force', 'update', 'delete', 'empty'],
default: {
source: process.cwd(),
bucket: path.parse(process.cwd()).name,
prefix: ''
}
})
}
function getConfigFile() {
try {
return require(configFilePath)
} catch(e) {
return {}
}
}
function getDefaultRegion() {
return new Promise((resolve, reject) => {
fs.readFile(configFilePath, (err, data) => {
if (err && err.code === 'ENOENT') {
fs.readFile(configFilePath, (err, data) => {
if (data) {
const region = JSON.parse(data.toString('utf8')).region
if (region)
return resolve(region)
}
reject('No default region')
})
}
if (data) {
const region = JSON.parse(data.toString('utf8')).region
if (region)
return resolve(region)
}
reject('No default region')
})
})
}
function saveDefaultRegion(region) {
return new Promise((resolve) => {
fs.writeFile(configFilePath, `{"region":"${region}"}`, 'utf8', err => {
if (err) {
fs.writeFile(configFilePath, `{"region":"${region}"}`, 'utf8', () => {
resolve(region)
})
}
resolve(region)
})
})
}
function setAWSProfile(profile) {
const options = {}
// Replace the file value for the CLI one if exist
if (profile) {
options.profile = profile
// update the Credentials for the current value or the default value which is 'default'
AWS.config.credentials = new AWS.SharedIniFileCredentials(options)
}
}
function cmd(console) {
const args = readArgs()
if (args.version)
return console.log(require(path.join(__dirname, '..', 'package.json')).version)
if (args.help)
return showHelp()
setAWSProfile(args.profile)
// if a non-existent profile is set AWS.config.credentials.accessKeyId will be undefined
if (!AWS.config.credentials || !AWS.config.credentials.accessKeyId)
return console.log(`Set AWS credentials first. Guide is available here: http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html`)
if (!args.region) {
return getDefaultRegion()
.catch(() => {
if (args.force)
return 'us-east-1'
return inquirer.prompt([{
type: 'list',
name: 'region',
message: `Where do you want me to beam you up to?`,
choices: AWS_REGIONS,
default: 'us-east-1'
}])
.then(result => result.region)
.then(saveDefaultRegion)
})
.then(region => beamUp(args, region, console))
}
return saveDefaultRegion(args.region)
.then(() => beamUp(args, args.region, console))
}
function beamUp (args, region, console) {
const s3 = new AWS.S3({
region: region
})
const promise = scotty(args.source, args.bucket, args.prefix, region, args.website, args.spa, args.update, args.delete, args.nocdn, args.urlonly, args.expire, args.force, args.empty, args.quiet, !args.noclipboard, console, s3)
if (!args.noclipboard) {
promise.then(endpoint => clipboardy.write(endpoint))
}
return promise
.then(() => process.exit(0))
.catch(() => process.exit(1))
}
if (require.main === module)
cmd(console)
module.exports = cmd
| mit |
vondrejc/FFTHomPy | ffthompy/applications.py | 5815 | import numpy as np
import ffthompy.projections as proj
from ffthompy.materials import Material
from ffthompy.postprocess import postprocess, add_macro2minimizer
from ffthompy.general.solver import linear_solver
from ffthompy.general.solver_pp import CallBack, CallBack_GA
from ffthompy.general.base import Timer
from ffthompy.tensors import Tensor, DFT, Operator
def scalar(problem):
"""
Homogenization of scalar elliptic problem.
Parameters
----------
problem : object
"""
print(' ')
pb = problem
print(pb)
# Fourier projections
_, hG1N, hG2N = proj.scalar(pb.solve['N'], pb.Y, NyqNul=True, tensor=True)
if pb.solve['kind'] is 'GaNi':
Nbar = pb.solve['N']
elif pb.solve['kind'] is 'Ga':
Nbar = 2*pb.solve['N'] - 1
hG1N = hG1N.enlarge(Nbar)
hG2N = hG2N.enlarge(Nbar)
FN = DFT(name='FN', inverse=False, N=Nbar)
FiN = DFT(name='FiN', inverse=True, N=Nbar)
G1N = Operator(name='G1', mat=[[FiN, hG1N, FN]])
G2N = Operator(name='G2', mat=[[FiN, hG2N, FN]])
for primaldual in pb.solve['primaldual']:
tim = Timer(name='primal-dual')
print(('\nproblem: ' + primaldual))
solutions = np.zeros(pb.shape).tolist()
results = np.zeros(pb.shape).tolist()
# material coefficients
mat = Material(pb.material)
if pb.solve['kind'] is 'GaNi':
A = mat.get_A_GaNi(pb.solve['N'], primaldual)
elif pb.solve['kind'] is 'Ga':
A = mat.get_A_Ga(Nbar=Nbar, primaldual=primaldual)
if primaldual is 'primal':
GN = G1N
else:
GN = G2N
Afun = Operator(name='FiGFA', mat=[[GN, A]])
for iL in np.arange(pb.dim): # iteration over unitary loads
E = np.zeros(pb.dim)
E[iL] = 1
print(('macroscopic load E = ' + str(E)))
EN = Tensor(name='EN', N=Nbar, shape=(pb.dim,), Fourier=False)
EN.set_mean(E)
# initial approximation for solvers
x0 = Tensor(name='x0', N=Nbar, shape=(pb.dim,), Fourier=False)
B = Afun(-EN) # RHS
if not hasattr(pb.solver, 'callback'):
cb = CallBack(A=Afun, B=B)
elif pb.solver['callback'] == 'detailed':
cb = CallBack_GA(A=Afun, B=B, EN=EN, A_Ga=A, GN=GN)
else:
raise NotImplementedError("The solver callback (%s) is not \
implemented" % (pb.solver['callback']))
print(('solver : {}'.format(pb.solver['kind'])))
X, info = linear_solver(solver=pb.solver['kind'], Afun=Afun, B=B,
x0=x0, par=pb.solver, callback=cb)
solutions[iL] = add_macro2minimizer(X, E)
results[iL] = {'cb': cb, 'info': info}
print(cb)
tim.measure()
# POSTPROCESSING
del Afun, B, E, EN, GN, X
postprocess(pb, A, mat, solutions, results, primaldual)
def elasticity(problem):
"""
Homogenization of linear elasticity.
Parameters
----------
problem : object
"""
print(' ')
pb = problem
print(pb)
# Fourier projections
_, hG1hN, hG1sN, hG2hN, hG2sN = proj.elasticity(pb.solve['N'], pb.Y, NyqNul=True)
del _
if pb.solve['kind'] is 'GaNi':
Nbar = pb.solve['N']
elif pb.solve['kind'] is 'Ga':
Nbar = 2*pb.solve['N'] - 1
hG1hN = hG1hN.enlarge(Nbar)
hG1sN = hG1sN.enlarge(Nbar)
hG2hN = hG2hN.enlarge(Nbar)
hG2sN = hG2sN.enlarge(Nbar)
FN = DFT(name='FN', inverse=False, N=Nbar)
FiN = DFT(name='FiN', inverse=True, N=Nbar)
G1N = Operator(name='G1', mat=[[FiN, hG1hN + hG1sN, FN]])
G2N = Operator(name='G2', mat=[[FiN, hG2hN + hG2sN, FN]])
for primaldual in pb.solve['primaldual']:
tim = Timer(name='primal-dual')
print(('\nproblem: ' + primaldual))
solutions = np.zeros(pb.shape).tolist()
results = np.zeros(pb.shape).tolist()
# material coefficients
mat = Material(pb.material)
if pb.solve['kind'] is 'GaNi':
A = mat.get_A_GaNi(pb.solve['N'], primaldual)
elif pb.solve['kind'] is 'Ga':
A = mat.get_A_Ga(Nbar=Nbar, primaldual=primaldual)
if primaldual is 'primal':
GN = G1N
else:
GN = G2N
Afun = Operator(name='FiGFA', mat=[[GN, A]])
D = int(pb.dim*(pb.dim+1)/2)
for iL in range(D): # iteration over unitary loads
E = np.zeros(D)
E[iL] = 1
print(('macroscopic load E = ' + str(E)))
EN = Tensor(name='EN', N=Nbar, shape=(D,), Fourier=False)
EN.set_mean(E)
# initial approximation for solvers
x0 = EN.zeros_like(name='x0')
B = Afun(-EN) # RHS
if not hasattr(pb.solver, 'callback'):
cb = CallBack(A=Afun, B=B)
elif pb.solver['callback'] == 'detailed':
cb = CallBack_GA(A=Afun, B=B, EN=EN, A_Ga=A, GN=GN)
else:
raise NotImplementedError("The solver callback (%s) is not \
implemented" % (pb.solver['callback']))
print(('solver : %s' % pb.solver['kind']))
X, info = linear_solver(solver=pb.solver['kind'], Afun=Afun, B=B,
x0=x0, par=pb.solver, callback=cb)
solutions[iL] = add_macro2minimizer(X, E)
results[iL] = {'cb': cb, 'info': info}
print(cb)
tim.measure()
# POSTPROCESSING
del Afun, B, E, EN, GN, X
postprocess(pb, A, mat, solutions, results, primaldual)
if __name__ == '__main__':
exec(compile(open('../main_test.py').read(), '../main_test.py', 'exec'))
| mit |
HaozheGuAsh/Leet_Code | [70] [Climbing Stairs] [Easy] [Dynamic Programming] [Adobe Apple ] [].cpp | 1741 | /*
Question# + Difficulty + Topic + Company + Similar_Question
[70] [Climbing Stairs] [Easy] [Dynamic Programming]
[Adobe Apple ]
[].cpp
*/
/*
The problem seems to be a dynamic programming one. Hint: the tag also suggests that!
Here are the steps to get the solution incrementally.
Base cases:
if n <= 0, then the number of ways should be zero.
if n == 1, then there is only way to climb the stair.
if n == 2, then there are two ways to climb the stairs. One solution is one step by another; the other one is two steps at one time.
The key intuition to solve the problem is that given a number of stairs n, if we know the number ways to get to the points [n-1] and [n-2] respectively, denoted as n1 and n2 , then the total ways to get to the point [n] is n1 + n2. Because from the [n-1] point, we can take one single step to reach [n]. And from the [n-2] point, we could take two steps to get there. There is NO overlapping between these two solution sets, because we differ in the final step.
Now given the above intuition, one can construct an array where each node stores the solution for each number n. Or if we look at it closer, it is clear that this is basically a fibonacci number, with the starting numbers as 1 and 2, instead of 1 and 1.
*/
/* Fisrt Attemp Simple Recursion, Too Slow - -... */
class Solution {
public:
int climbStairs(int n) {
// base cases
if(n <= 0) return 0;
if(n == 1) return 1;
if(n == 2) return 2;
int one_step_before = 2;
int two_steps_before = 1;
int all_ways = 0;
for(int i=2; i<n; i++){
all_ways = one_step_before + two_steps_before;
two_steps_before = one_step_before;
one_step_before = all_ways;
}
return all_ways;
}
};
| mit |
chrisnankam24/SGP | application/models/Rollbackrejectionabandon_model.php | 2009 | <?php
/*
* Generated by CRUDigniter v2.3 Beta
* www.crudigniter.com
*/
class Rollbackrejectionabandon_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
/*
* Get rollbackrejectionabandon by rollbackRejectionAbandoned
*/
function get_rollbackrejectionabandon($rollbackRejectionAbandoned)
{
return $this->db->get_where('rollbackrejectionabandon',array('rollbackRejectionAbandoned'=>$rollbackRejectionAbandoned))->row_array();
}
/*
* Get all rollbackrejectionabandon
*/
function get_all_rollbackrejectionabandon()
{
return $this->db->get('rollbackrejectionabandon')->result_array();
}
/*
* function to add new rollbackrejectionabandon
*/
function add_rollbackrejectionabandon($params)
{
$this->db->insert('rollbackrejectionabandon',$params);
return $this->db->insert_id();
}
/*
* function to update rollbackrejectionabandon
*/
function update_rollbackrejectionabandon($rollbackRejectionAbandonedId,$params)
{
$this->db->where('rollbackRejectionAbandonedId',$rollbackRejectionAbandonedId);
$response = $this->db->update('rollbackrejectionabandon',$params);
if($response)
{
return "rollbackrejectionabandon updated successfully";
}
else
{
return "Error occuring while updating rollbackrejectionabandon";
}
}
/*
* function to delete rollbackrejectionabandon
*/
function delete_rollbackrejectionabandon($rollbackRejectionAbandoned)
{
$response = $this->db->delete('rollbackrejectionabandon',array('rollbackRejectionAbandoned'=>$rollbackRejectionAbandoned));
if($response)
{
return "rollbackrejectionabandon deleted successfully";
}
else
{
return "Error occuring while deleting rollbackrejectionabandon";
}
}
}
| mit |
svlcode/HomeManager | sources/HomeManager/HomeManager.GUI/Forms/MainForm.Designer.cs | 21912 | namespace HomeManager.GUI.Forms
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.navBarControl1 = new DevExpress.XtraNavBar.NavBarControl();
this.navBarGroup1 = new DevExpress.XtraNavBar.NavBarGroup();
this.navBarItemVenituriLunare = new DevExpress.XtraNavBar.NavBarItem();
this.navBarItemAlteVenituri = new DevExpress.XtraNavBar.NavBarItem();
this.navBarGroup2 = new DevExpress.XtraNavBar.NavBarGroup();
this.navBarItemMonthlyPayments = new DevExpress.XtraNavBar.NavBarItem();
this.navBarItemPayments = new DevExpress.XtraNavBar.NavBarItem();
this.navBarItemCheltuieli = new DevExpress.XtraNavBar.NavBarItem();
this.navBarItemReceipts = new DevExpress.XtraNavBar.NavBarItem();
this.navBarGroupPawnShop = new DevExpress.XtraNavBar.NavBarGroup();
this.navBarItemJewelry = new DevExpress.XtraNavBar.NavBarItem();
this.navBarItem1 = new DevExpress.XtraNavBar.NavBarItem();
this.navBarItem3 = new DevExpress.XtraNavBar.NavBarItem();
this.navBarGroupRapoarte = new DevExpress.XtraNavBar.NavBarGroup();
this.navBarGroupGeneral = new DevExpress.XtraNavBar.NavBarGroup();
this.dockManager1 = new DevExpress.XtraBars.Docking.DockManager(this.components);
this.barManager1 = new DevExpress.XtraBars.BarManager(this.components);
this.bar2 = new DevExpress.XtraBars.Bar();
this.barSubItem1 = new DevExpress.XtraBars.BarSubItem();
this.barButtonItemExit = new DevExpress.XtraBars.BarButtonItem();
this.barSubItem2 = new DevExpress.XtraBars.BarSubItem();
this.barButtonItemAbout = new DevExpress.XtraBars.BarButtonItem();
this.bar3 = new DevExpress.XtraBars.Bar();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.dockPanelNavigation = new DevExpress.XtraBars.Docking.DockPanel();
this.dockPanel1_Container = new DevExpress.XtraBars.Docking.ControlContainer();
this.xtraTabControl1 = new DevExpress.XtraTab.XtraTabControl();
this.defaultLookAndFeel1 = new DevExpress.LookAndFeel.DefaultLookAndFeel(this.components);
this.navBarItemContacts = new DevExpress.XtraNavBar.NavBarItem();
((System.ComponentModel.ISupportInitialize)(this.navBarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dockManager1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
this.dockPanelNavigation.SuspendLayout();
this.dockPanel1_Container.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).BeginInit();
this.SuspendLayout();
//
// navBarControl1
//
this.navBarControl1.ActiveGroup = this.navBarGroup1;
this.navBarControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.navBarControl1.Groups.AddRange(new DevExpress.XtraNavBar.NavBarGroup[] {
this.navBarGroup1,
this.navBarGroup2,
this.navBarGroupPawnShop,
this.navBarGroupRapoarte,
this.navBarGroupGeneral});
this.navBarControl1.Items.AddRange(new DevExpress.XtraNavBar.NavBarItem[] {
this.navBarItemVenituriLunare,
this.navBarItemMonthlyPayments,
this.navBarItemCheltuieli,
this.navBarItemReceipts,
this.navBarItemAlteVenituri,
this.navBarItemJewelry,
this.navBarItemPayments,
this.navBarItem1,
this.navBarItem3,
this.navBarItemContacts});
this.navBarControl1.Location = new System.Drawing.Point(0, 0);
this.navBarControl1.Name = "navBarControl1";
this.navBarControl1.OptionsNavPane.ExpandedWidth = 194;
this.navBarControl1.Size = new System.Drawing.Size(194, 461);
this.navBarControl1.TabIndex = 0;
this.navBarControl1.Text = "navBarControl1";
//
// navBarGroup1
//
this.navBarGroup1.Caption = "Venituri";
this.navBarGroup1.Expanded = true;
this.navBarGroup1.ItemLinks.AddRange(new DevExpress.XtraNavBar.NavBarItemLink[] {
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemVenituriLunare),
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemAlteVenituri)});
this.navBarGroup1.Name = "navBarGroup1";
//
// navBarItemVenituriLunare
//
this.navBarItemVenituriLunare.Caption = "Venituri lunare";
this.navBarItemVenituriLunare.Name = "navBarItemVenituriLunare";
this.navBarItemVenituriLunare.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(this.navBarItemVenituriLunare_LinkClicked);
//
// navBarItemAlteVenituri
//
this.navBarItemAlteVenituri.Caption = "Alte venituri";
this.navBarItemAlteVenituri.Name = "navBarItemAlteVenituri";
//
// navBarGroup2
//
this.navBarGroup2.Caption = "Cheltuieli";
this.navBarGroup2.Expanded = true;
this.navBarGroup2.ItemLinks.AddRange(new DevExpress.XtraNavBar.NavBarItemLink[] {
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemMonthlyPayments),
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemPayments),
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemCheltuieli),
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemReceipts)});
this.navBarGroup2.Name = "navBarGroup2";
//
// navBarItemMonthlyPayments
//
this.navBarItemMonthlyPayments.Caption = "Plati lunare";
this.navBarItemMonthlyPayments.Name = "navBarItemMonthlyPayments";
this.navBarItemMonthlyPayments.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(this.navBarItemMonthlyPayments_LinkClicked);
//
// navBarItemPayments
//
this.navBarItemPayments.Caption = "Plati";
this.navBarItemPayments.Name = "navBarItemPayments";
this.navBarItemPayments.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(this.navBarItemPayments_LinkClicked);
//
// navBarItemCheltuieli
//
this.navBarItemCheltuieli.Caption = "Cheltuieli";
this.navBarItemCheltuieli.Name = "navBarItemCheltuieli";
this.navBarItemCheltuieli.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(this.navBarItemCheltuieli_LinkClicked);
//
// navBarItemReceipts
//
this.navBarItemReceipts.Caption = "Bonuri";
this.navBarItemReceipts.Name = "navBarItemReceipts";
this.navBarItemReceipts.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(this.navBarItemReceipts_LinkClicked);
//
// navBarGroupPawnShop
//
this.navBarGroupPawnShop.Caption = "Datorii";
this.navBarGroupPawnShop.Expanded = true;
this.navBarGroupPawnShop.ItemLinks.AddRange(new DevExpress.XtraNavBar.NavBarItemLink[] {
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemJewelry),
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItem1),
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItem3)});
this.navBarGroupPawnShop.Name = "navBarGroupPawnShop";
//
// navBarItemJewelry
//
this.navBarItemJewelry.Caption = "Amanet";
this.navBarItemJewelry.Name = "navBarItemJewelry";
//
// navBarItem1
//
this.navBarItem1.Caption = "Banci";
this.navBarItem1.Name = "navBarItem1";
//
// navBarItem3
//
this.navBarItem3.Caption = "Datorii";
this.navBarItem3.Name = "navBarItem3";
//
// navBarGroupRapoarte
//
this.navBarGroupRapoarte.Caption = "Rapoarte";
this.navBarGroupRapoarte.Name = "navBarGroupRapoarte";
//
// navBarGroupGeneral
//
this.navBarGroupGeneral.Caption = "General";
this.navBarGroupGeneral.Expanded = true;
this.navBarGroupGeneral.ItemLinks.AddRange(new DevExpress.XtraNavBar.NavBarItemLink[] {
new DevExpress.XtraNavBar.NavBarItemLink(this.navBarItemContacts)});
this.navBarGroupGeneral.Name = "navBarGroupGeneral";
//
// dockManager1
//
this.dockManager1.Form = this;
this.dockManager1.MenuManager = this.barManager1;
this.dockManager1.RootPanels.AddRange(new DevExpress.XtraBars.Docking.DockPanel[] {
this.dockPanelNavigation});
this.dockManager1.TopZIndexControls.AddRange(new string[] {
"DevExpress.XtraBars.BarDockControl",
"DevExpress.XtraBars.StandaloneBarDockControl",
"System.Windows.Forms.StatusBar",
"System.Windows.Forms.MenuStrip",
"System.Windows.Forms.StatusStrip",
"DevExpress.XtraBars.Ribbon.RibbonStatusBar",
"DevExpress.XtraBars.Ribbon.RibbonControl"});
//
// barManager1
//
this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.bar2,
this.bar3});
this.barManager1.DockControls.Add(this.barDockControlTop);
this.barManager1.DockControls.Add(this.barDockControlBottom);
this.barManager1.DockControls.Add(this.barDockControlLeft);
this.barManager1.DockControls.Add(this.barDockControlRight);
this.barManager1.DockManager = this.dockManager1;
this.barManager1.Form = this;
this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.barSubItem1,
this.barSubItem2,
this.barButtonItemAbout,
this.barButtonItemExit});
this.barManager1.MainMenu = this.bar2;
this.barManager1.MaxItemId = 5;
this.barManager1.StatusBar = this.bar3;
//
// bar2
//
this.bar2.BarName = "Main menu";
this.bar2.DockCol = 0;
this.bar2.DockRow = 0;
this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem2)});
this.bar2.OptionsBar.AllowQuickCustomization = false;
this.bar2.OptionsBar.DrawBorder = false;
this.bar2.OptionsBar.MultiLine = true;
this.bar2.OptionsBar.UseWholeRow = true;
this.bar2.Text = "Main menu";
//
// barSubItem1
//
this.barSubItem1.Caption = "File";
this.barSubItem1.Id = 0;
this.barSubItem1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItemExit)});
this.barSubItem1.Name = "barSubItem1";
//
// barButtonItemExit
//
this.barButtonItemExit.Caption = "Exit";
this.barButtonItemExit.Id = 4;
this.barButtonItemExit.Name = "barButtonItemExit";
this.barButtonItemExit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItemExit_ItemClick);
//
// barSubItem2
//
this.barSubItem2.Caption = "Help";
this.barSubItem2.Id = 1;
this.barSubItem2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItemAbout)});
this.barSubItem2.Name = "barSubItem2";
//
// barButtonItemAbout
//
this.barButtonItemAbout.Caption = "About";
this.barButtonItemAbout.Id = 3;
this.barButtonItemAbout.Name = "barButtonItemAbout";
this.barButtonItemAbout.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItemAbout_ItemClick);
//
// bar3
//
this.bar3.BarName = "Status bar";
this.bar3.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.bar3.DockCol = 0;
this.bar3.DockRow = 0;
this.bar3.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.bar3.OptionsBar.AllowQuickCustomization = false;
this.bar3.OptionsBar.DrawDragBorder = false;
this.bar3.OptionsBar.DrawSizeGrip = true;
this.bar3.OptionsBar.UseWholeRow = true;
this.bar3.Text = "Status bar";
//
// barDockControlTop
//
this.barDockControlTop.CausesValidation = false;
this.barDockControlTop.Dock = System.Windows.Forms.DockStyle.Top;
this.barDockControlTop.Location = new System.Drawing.Point(0, 0);
this.barDockControlTop.Size = new System.Drawing.Size(906, 24);
//
// barDockControlBottom
//
this.barDockControlBottom.CausesValidation = false;
this.barDockControlBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
this.barDockControlBottom.Location = new System.Drawing.Point(0, 512);
this.barDockControlBottom.Size = new System.Drawing.Size(906, 22);
//
// barDockControlLeft
//
this.barDockControlLeft.CausesValidation = false;
this.barDockControlLeft.Dock = System.Windows.Forms.DockStyle.Left;
this.barDockControlLeft.Location = new System.Drawing.Point(0, 24);
this.barDockControlLeft.Size = new System.Drawing.Size(0, 488);
//
// barDockControlRight
//
this.barDockControlRight.CausesValidation = false;
this.barDockControlRight.Dock = System.Windows.Forms.DockStyle.Right;
this.barDockControlRight.Location = new System.Drawing.Point(906, 24);
this.barDockControlRight.Size = new System.Drawing.Size(0, 488);
//
// dockPanelNavigation
//
this.dockPanelNavigation.Controls.Add(this.dockPanel1_Container);
this.dockPanelNavigation.Dock = DevExpress.XtraBars.Docking.DockingStyle.Left;
this.dockPanelNavigation.ID = new System.Guid("60887b45-60b4-4607-8e57-1428cdc2e1af");
this.dockPanelNavigation.Location = new System.Drawing.Point(0, 24);
this.dockPanelNavigation.Name = "dockPanelNavigation";
this.dockPanelNavigation.Options.AllowDockRight = false;
this.dockPanelNavigation.Options.AllowDockTop = false;
this.dockPanelNavigation.Options.AllowFloating = false;
this.dockPanelNavigation.Options.FloatOnDblClick = false;
this.dockPanelNavigation.Options.ShowAutoHideButton = false;
this.dockPanelNavigation.Options.ShowCloseButton = false;
this.dockPanelNavigation.OriginalSize = new System.Drawing.Size(200, 200);
this.dockPanelNavigation.Size = new System.Drawing.Size(200, 488);
this.dockPanelNavigation.Text = "Navigation";
//
// dockPanel1_Container
//
this.dockPanel1_Container.Controls.Add(this.navBarControl1);
this.dockPanel1_Container.Location = new System.Drawing.Point(3, 24);
this.dockPanel1_Container.Name = "dockPanel1_Container";
this.dockPanel1_Container.Size = new System.Drawing.Size(194, 461);
this.dockPanel1_Container.TabIndex = 0;
//
// xtraTabControl1
//
this.xtraTabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.xtraTabControl1.Location = new System.Drawing.Point(200, 24);
this.xtraTabControl1.Name = "xtraTabControl1";
this.xtraTabControl1.Size = new System.Drawing.Size(706, 488);
this.xtraTabControl1.TabIndex = 6;
//
// defaultLookAndFeel1
//
this.defaultLookAndFeel1.LookAndFeel.SkinName = "Springtime";
//
// navBarItemContacts
//
this.navBarItemContacts.Caption = "Contacts";
this.navBarItemContacts.Name = "navBarItemContacts";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(906, 534);
this.Controls.Add(this.xtraTabControl1);
this.Controls.Add(this.dockPanelNavigation);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.Text = "HomeBudget";
((System.ComponentModel.ISupportInitialize)(this.navBarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dockManager1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
this.dockPanelNavigation.ResumeLayout(false);
this.dockPanel1_Container.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraNavBar.NavBarControl navBarControl1;
private DevExpress.XtraNavBar.NavBarGroup navBarGroup1;
private DevExpress.XtraBars.Docking.DockManager dockManager1;
private DevExpress.XtraTab.XtraTabControl xtraTabControl1;
private DevExpress.XtraBars.Docking.DockPanel dockPanelNavigation;
private DevExpress.XtraBars.Docking.ControlContainer dockPanel1_Container;
private DevExpress.XtraNavBar.NavBarItem navBarItemVenituriLunare;
private DevExpress.XtraNavBar.NavBarItem navBarItemAlteVenituri;
private DevExpress.XtraNavBar.NavBarGroup navBarGroup2;
private DevExpress.XtraNavBar.NavBarItem navBarItemMonthlyPayments;
private DevExpress.XtraNavBar.NavBarItem navBarItemCheltuieli;
private DevExpress.XtraNavBar.NavBarItem navBarItemReceipts;
private DevExpress.XtraNavBar.NavBarGroup navBarGroupPawnShop;
private DevExpress.XtraNavBar.NavBarItem navBarItemJewelry;
private DevExpress.XtraNavBar.NavBarGroup navBarGroupRapoarte;
private DevExpress.XtraNavBar.NavBarItem navBarItemPayments;
private DevExpress.XtraNavBar.NavBarItem navBarItem1;
private DevExpress.XtraNavBar.NavBarItem navBarItem3;
private DevExpress.XtraNavBar.NavBarGroup navBarGroupGeneral;
private DevExpress.LookAndFeel.DefaultLookAndFeel defaultLookAndFeel1;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarManager barManager1;
private DevExpress.XtraBars.Bar bar2;
private DevExpress.XtraBars.Bar bar3;
private DevExpress.XtraBars.BarSubItem barSubItem1;
private DevExpress.XtraBars.BarSubItem barSubItem2;
private DevExpress.XtraBars.BarButtonItem barButtonItemAbout;
private DevExpress.XtraBars.BarButtonItem barButtonItemExit;
private DevExpress.XtraNavBar.NavBarItem navBarItemContacts;
}
}
| mit |
JChanceHud/Agate | examples/josh_chance_thing/server/serverGame.js | 2667 | // serverGame.js
//
var loopRate = 100.0; //100 ms
exports.Game = function(clients, io){
//clients is an array of client sockets
this.io = io;
this.ships = []; //handles the controllable ships
this.shipIDs = [];
this.size = {width:1000,height:1000};
var clientCount = clients.length;
this.clients = clients;
for(x = 0; x < this.clients.length; x++){
this.clients[x].on('inputReceived', inputReceivedFunction().bind(this));
this.ships[x] = new Ship(this.clients[x].id);
console.log("client id: "+this.clients[x].id);
//this.ships[x].position.x = x*(this.size.width/clientCount);
//this.ships[x].position.y = (this.size.height/2.0);
this.ships[x].position.x = 100+(x+1)*100; //random positions to just move them more toward the center of the screen
this.ships[x].position.y = 150;
this.shipIDs[this.clients[x].id] = x;
}
this.lastFrame = 0;
};
exports.Game.prototype.startGame = function(){
console.log("start game");
this.startGameLoop();
};
exports.Game.prototype.startGameLoop = function(){
setInterval(this.update.bind(this), loopRate);
};
exports.Game.prototype.update = function(){
var t = 0.1;
for(var x = 0; x < this.ships.length; x++){
if(this.ships[x].moving){
var ship = this.ships[x];
var dx = ship.target.x-ship.position.x;
var dy = ship.target.y-ship.position.y;
var dist = Math.sqrt(dx*dx+dy*dy);
if(dist <= ship.moveSpeed*t){
ship.position.x = ship.target.x;
ship.position.y = ship.target.y;
ship.moving = false;
}
else{
//calculate the change in position
var deltaX = (dx/dist)*ship.moveSpeed*t;
var deltaY = (dy/dist)*ship.moveSpeed*t;
this.ships[x].position.x += deltaX;
this.ships[x].position.y += deltaY;
}
}
}
this.io.sockets.emit('update', this.ships);
};
function Ship(clientID){
this.size = {width:50,height:50};
this.target = {x:0,y:0};
this.moving = false;
this.nextMoveSpace = {x:0,y:0};
this.position = {x:0,y:0};
this.id = clientID;
this.moveSpeed = 150;
}
function inputReceivedFunction(){
return function(data){
console.log("input recieved+"+data.id);
var ship = this.ships[this.shipIDs[data.id]];
if(data.mouse){
ship.target.x = data.mouseX;
ship.target.y = data.mouseY;
ship.moving = true;
}
if(data.stop)
ship.moving = false;
};
}
| mit |
rodzewich/playground | xlib/ui/element/elements/html/IOptions.ts | 342 | /// <reference path="../IOptions.ts" />
/// <reference path="IElement.ts" />
module xlib.ui.element.elements.html {
export interface IOptions<T> extends elements.IOptions<T> {
lang?: any;
xmlLang?: any;
dir?: any;
xmlNS?: any;
items?: (
elements.head.IElement<T> |
elements.body.IElement<T>
)[];
}
} | mit |
gofullstack/stickies | stickies/stickies/base.js | 4011 | /*global window, dojo, dojox */
dojo.provide("stickies.base");
dojo.addOnLoad(function () {
var url = "http://websticki.es",
css = url + "/css/stickies.css",
loc = { // page and domain for query
domain : window.location.host,
path : window.location.pathname
},
body = dojo.body(),
center = (function () { // center of the screen
var vp = dijit.getViewport(), offset = 120;
return {
x : (vp.w / 2) - offset,
y : (vp.h / 2) - offset
};
})(),
s; // The sticky store
/** Insert stickies CSS */
function insertCSS() {
dojo.place(dojo.create("link", {
href : css,
rel : "stylesheet",
type : "text/css",
media : "screen"
}), dojo.query("head")[0]);
}
/** Fetch Stickies! from store and open them */
function fetch(store) {
store.fetch({
// FIXME: Querying is messed up. Is it the xdomain thing or some
// encoding thing?
query : "?domain='" + loc.domain + "'",//'&path='" + loc.path + "'",
onComplete : function (results) {
if (typeof results === "object") {
for (var r in results) {
if (results.hasOwnProperty(r) && Number(r) >= 0) {
open(results[r]);
}
}
}
}
});
}
/** Create a new sticky */
function open(item) {
var isNew = typeof item !== "object",
a, d, x, dm; // elements and mover
function insert() {
dojo.place(a, d);
dojo.place(x, d);
// Fade in new notes
if (isNew) { dojo.attr(d, { opacity : 0 }); }
dojo.place(d, body);
if (isNew) { dojo.anim(d, { opacity : 1 }); }
}
function handleEvents() {
dm = new dojo.dnd.Moveable(d, { skip : true });
dojo.connect(a, "onblur", function (evt) {
s.setValue(item, "text", a.value);
s.save();
});
dojo.connect(dm, "onMoveStop", function (mover) {
var c = dojo.coords(mover.node);
s.setValue(item, "x", c.x);
s.setValue(item, "y", c.y);
s.save();
});
dojo.connect(x, "onclick", function (evt) {
dojo.stopEvent(evt);
dojo.anim(d, { // fade note out
opacity : 0,
onEnd : function () { dojo.destroy(d); }
});
s.deleteItem(item);
s.save();
});
}
// When no object gets passed in to open, create a new one
if (isNew) {
item = s.newItem(dojo.mixin(center, loc));
s.setValue(item, "text", "");
}
// Text area
a = dojo.create("textarea", { innerHTML : item.text });
// Close button
x = dojo.create("a", { innerHTML : "×", href : "#" });
// Enclosing div
d = dojo.create("div", {
className : "stickiesSticky",
style : {
left: item.x + "px",
top: item.y + "px"
}
});
insert();
handleEvents();
}
/** Insert link to make a new sticky! */
function insertLink() {
var link = dojo.create("a", {
innerHTML : "new Sticky!",
className : "stickiesNew",
href : "#"
});
dojo.connect(link, "onclick", function (evt) {
dojo.stopEvent(evt);
open();
});
dojo.place(link, body);
}
insertCSS();
insertLink();
// Set up notes
dojox.data.PersevereStore.getStores(url).addCallback(function (stores) {
s = stores.Sticky;
fetch(s);
});
});
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_security/lib/2019-01-01-preview/generated/azure_mgmt_security/assessments.rb | 24315 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Security::Mgmt::V2019_01_01_preview
#
# API spec for Microsoft.Security (Azure Security Center) resource provider
#
class Assessments
include MsRestAzure
#
# Creates and initializes a new instance of the Assessments class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [SecurityCenter] reference to the SecurityCenter
attr_reader :client
#
# Get security assessments on all your scanned resources inside a scope
#
# @param scope [String] Scope of the query, can be subscription
# (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
# (/providers/Microsoft.Management/managementGroups/mgName).
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<SecurityAssessment>] operation results.
#
def list(scope, custom_headers:nil)
first_page = list_as_lazy(scope, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Get security assessments on all your scanned resources inside a scope
#
# @param scope [String] Scope of the query, can be subscription
# (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
# (/providers/Microsoft.Management/managementGroups/mgName).
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(scope, custom_headers:nil)
list_async(scope, custom_headers:custom_headers).value!
end
#
# Get security assessments on all your scanned resources inside a scope
#
# @param scope [String] Scope of the query, can be subscription
# (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
# (/providers/Microsoft.Management/managementGroups/mgName).
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(scope, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, 'scope is nil' if scope.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{scope}/providers/Microsoft.Security/assessments'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'scope' => scope},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2019_01_01_preview::Models::SecurityAssessmentList.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Get a security assessment on your scanned resource
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param expand [ExpandEnum] OData expand. Optional. Possible values include:
# 'links', 'metadata'
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityAssessment] operation results.
#
def get(resource_id, assessment_name, expand:nil, custom_headers:nil)
response = get_async(resource_id, assessment_name, expand:expand, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Get a security assessment on your scanned resource
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param expand [ExpandEnum] OData expand. Optional. Possible values include:
# 'links', 'metadata'
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_id, assessment_name, expand:nil, custom_headers:nil)
get_async(resource_id, assessment_name, expand:expand, custom_headers:custom_headers).value!
end
#
# Get a security assessment on your scanned resource
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param expand [ExpandEnum] OData expand. Optional. Possible values include:
# 'links', 'metadata'
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_id, assessment_name, expand:nil, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, 'resource_id is nil' if resource_id.nil?
fail ArgumentError, 'assessment_name is nil' if assessment_name.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{resourceId}/providers/Microsoft.Security/assessments/{assessmentName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'assessmentName' => assessment_name},
skip_encoding_path_params: {'resourceId' => resource_id},
query_params: {'api-version' => @client.api_version,'$expand' => expand},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2019_01_01_preview::Models::SecurityAssessment.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Create a security assessment on your resource. An assessment metadata that
# describes this assessment must be predefined with the same name before
# inserting the assessment result
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param assessment [SecurityAssessment] Calculated assessment on a pre-defined
# assessment metadata
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityAssessment] operation results.
#
def create_or_update(resource_id, assessment_name, assessment, custom_headers:nil)
response = create_or_update_async(resource_id, assessment_name, assessment, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Create a security assessment on your resource. An assessment metadata that
# describes this assessment must be predefined with the same name before
# inserting the assessment result
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param assessment [SecurityAssessment] Calculated assessment on a pre-defined
# assessment metadata
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def create_or_update_with_http_info(resource_id, assessment_name, assessment, custom_headers:nil)
create_or_update_async(resource_id, assessment_name, assessment, custom_headers:custom_headers).value!
end
#
# Create a security assessment on your resource. An assessment metadata that
# describes this assessment must be predefined with the same name before
# inserting the assessment result
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param assessment [SecurityAssessment] Calculated assessment on a pre-defined
# assessment metadata
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def create_or_update_async(resource_id, assessment_name, assessment, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, 'resource_id is nil' if resource_id.nil?
fail ArgumentError, 'assessment_name is nil' if assessment_name.nil?
fail ArgumentError, 'assessment is nil' if assessment.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Security::Mgmt::V2019_01_01_preview::Models::SecurityAssessment.mapper()
request_content = @client.serialize(request_mapper, assessment)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = '{resourceId}/providers/Microsoft.Security/assessments/{assessmentName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'assessmentName' => assessment_name},
skip_encoding_path_params: {'resourceId' => resource_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 201 || status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2019_01_01_preview::Models::SecurityAssessment.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2019_01_01_preview::Models::SecurityAssessment.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Delete a security assessment on your resource. An assessment metadata that
# describes this assessment must be predefined with the same name before
# inserting the assessment result
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def delete(resource_id, assessment_name, custom_headers:nil)
response = delete_async(resource_id, assessment_name, custom_headers:custom_headers).value!
nil
end
#
# Delete a security assessment on your resource. An assessment metadata that
# describes this assessment must be predefined with the same name before
# inserting the assessment result
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def delete_with_http_info(resource_id, assessment_name, custom_headers:nil)
delete_async(resource_id, assessment_name, custom_headers:custom_headers).value!
end
#
# Delete a security assessment on your resource. An assessment metadata that
# describes this assessment must be predefined with the same name before
# inserting the assessment result
#
# @param resource_id [String] The identifier of the resource.
# @param assessment_name [String] The Assessment Key - Unique key for the
# assessment type
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def delete_async(resource_id, assessment_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, 'resource_id is nil' if resource_id.nil?
fail ArgumentError, 'assessment_name is nil' if assessment_name.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{resourceId}/providers/Microsoft.Security/assessments/{assessmentName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'assessmentName' => assessment_name},
skip_encoding_path_params: {'resourceId' => resource_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 204
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
result
end
promise.execute
end
#
# Get security assessments on all your scanned resources inside a scope
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityAssessmentList] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Get security assessments on all your scanned resources inside a scope
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Get security assessments on all your scanned resources inside a scope
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2019_01_01_preview::Models::SecurityAssessmentList.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Get security assessments on all your scanned resources inside a scope
#
# @param scope [String] Scope of the query, can be subscription
# (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
# (/providers/Microsoft.Management/managementGroups/mgName).
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityAssessmentList] which provide lazy access to pages of the
# response.
#
def list_as_lazy(scope, custom_headers:nil)
response = list_async(scope, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| mit |
BONDARENKO-q/bitrise | version/version.go | 56 | package version
// VERSION ...
const VERSION = "1.3.5"
| mit |
RobinCPC/algorithm-practice | IntegerArray/generate.cpp | 1297 | /*
* #: 118
* Title: Pascal's Triangle
* Description:
* ------
* Given numRows, generate the first numRows of Pascal's triangle.
*
*
* For example, given numRows = 5,
* Return
* ```
* [
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
* ]
* ```
* ------
* Time: O(n)
* Space: O(n)
* Difficulty: Easy
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res={};
if (numRows == 0)
return res;
res.push_back(vector<int>{1});
if (numRows == 1)
return res;
res.push_back(vector<int>{1,1});
if (numRows == 2)
return res;
for( int i=2; i < numRows; ++i){
vector<int> tmp{1};
for(int j=1; j < i; ++j){
tmp.push_back( res[i-1][j-1] + res[i-1][j]);
}
tmp.push_back(1);
res.push_back(tmp);
}
return res;
}
};
int main(void)
{
Solution sol = Solution();
int numRows = 5;
vector<vector<int>> res = sol.generate(numRows);
for(vector<int> i : res){
cout << "[ ";
for(auto j : i){
cout << j << ' ';
}
cout << "]\n";
}
return 0;
}
| mit |
webzeppelin/wz-docker-starter-lib | public-server/public-server-python3/flask_app/services.py | 8156 | """Entry point for the server application."""
import logging
import json
import uuid
# import time
import redis
from gevent.wsgi import WSGIServer
from flask import request, Response, jsonify
from datetime import datetime
from pytz import timezone, utc
from tzlocal import get_localzone
from .config import configure_app, app, HOSTNAME, PORT
from .utils import encode, oidc
from .models import HealthStatus, ServerTime, GuestbookEntry, GuestbookEntrySet
from flask_app import config
GUESTBOOK_BROWSE_PAGE_SIZE = 10
@app.before_first_request
def set_up():
"""Configure the application to be used by the application."""
configure_app(app)
@app.route('/api/v1/health', methods=['GET'])
def get_health():
"""Return service health information."""
ret = HealthStatus(is_up=True)
return jsonify(**(ret.to_dict()))
@app.route('/api/v1/time', methods=['GET'])
def get_time():
"""Return the current server time in the server's timezone"""
tz = get_localzone()
t = datetime.now(tz)
#t = tz.localize(t, is_dst=None)
st = ServerTime(hour=t.hour,
minute=t.minute,
second=t.second,
tz_name=tz.zone,
tz_offset=tz.utcoffset(datetime.now()).total_seconds()/3600)
return jsonify(st.to_dict())
@app.route('/api/v1/guestbook', methods=['POST'])
def sign_guestbook():
"""Accept a new guestbook entry posted to the API and return the new entry"""
print('Signing the guestbook')
payload = request.get_json(force=True)
if payload is None:
return error_response(400, 'Missing guestbook entry in POST payload')
name = payload.get('name')
message = payload.get('message')
if not name or not message:
return error_response(400, 'Missing required parameters')
entry = GuestbookEntry(
id=new_guid(),
name=name,
message=message,
timestamp=current_datetime()
)
# this is where it will get stored in redis
redis_key = get_guestbook_redis_key(entry.id)
json_str = json.dumps(entry.to_dict(), cls=encode.MyJSONEncoder)
r = get_redis()
r.set(redis_key, json_str)
r.lpush('guestbook_list', redis_key)
return success_response(entry.to_dict())
@app.route('/api/v1/guestbook', methods=['GET'])
def browse_guestbook():
"""Return the most recent guestbook entries"""
print('Browsing the guestbook')
last_id = request.args.get("last_id")
if last_id is None:
last_id = 0
else:
last_id = int(last_id)
r = get_redis()
keys = r.lrange('guestbook_list', last_id, (last_id+GUESTBOOK_BROWSE_PAGE_SIZE-1))
# map(lambda x:x.decode('utf-8'), keys)
entries = []
for key in keys:
json_str = r.get(key).decode('utf-8')
json_dic = json.loads(json_str)
entry = GuestbookEntry.from_dict(json_dic)
entries.append(entry)
entry_set = GuestbookEntrySet(
entries=entries,
count=len(entries),
last_id=str(last_id+len(entries)),
has_more=len(entries)==GUESTBOOK_BROWSE_PAGE_SIZE
)
return success_response(entry_set.to_dict())
@app.route('/api/v1/login', methods=['GET'])
def login_start():
client = oidc.OIDCClient(app.oidc_config)
session_id = new_guid()
redirect_uri = request.args.get('redirect_uri') or app.oidc_config.default_redirect_uri
scope = request.args.get('scope') or app.oidc_config.default_scope
state = oidc.OIDCClient.gen_nonce()
login_url = client.get_login_url(redirect_uri, scope, state)
# create session in redis and store state and redirect_uri for later use/validation
redis_key = get_login_redis_key(session_id)
r = get_redis()
r.hset(redis_key, 'state', state)
r.hset(redis_key, 'redirect_uri', redirect_uri)
return success_response(
{
'session_id': session_id,
'state': state,
'scope': scope,
'redirect_uri': redirect_uri,
'login_url': login_url
}
)
@app.route('/api/v1/login/token', methods=['POST'])
def login_token():
client = oidc.OIDCClient(app.oidc_config)
payload = request.get_json(force=True)
if payload is None:
return error_response(400, 'Missing POST body in login token request')
session_id = request.args.get('session_id') or payload.get('session_id') or request.cookies.get('wzstarter.login.session_id')
code = request.args.get('code') or payload.get('code')
state = request.args.get('state') or payload.get('state')
if not session_id:
return error_response(400, 'Missing session_id in login token request')
if not code:
return error_response(400, 'Missing code in login token request')
if not state:
return error_response(400, 'Missing state in login token request')
redis_key = get_login_redis_key(session_id)
r = get_redis()
print('final state: '+state)
cached_state = r.hget(redis_key, 'state').decode('utf-8')
print('cached state: ' + cached_state)
if state != cached_state:
return error_response(400, 'Incorrect state value provided')
cached_redirect_uri = r.hget(redis_key, 'redirect_uri')
tokens = client.get_tokens(cached_redirect_uri, code)
r.delete(redis_key)
return success_response(tokens.to_dict())
@app.route('/api/v1/login/info', methods=['GET'])
def get_user_info():
client = oidc.OIDCClient(app.oidc_config)
id_token = get_id_token(request)
if not id_token:
return error_response(401, "Missing id token")
try:
token = client.validate_token(id_token)
except:
return error_response(401, "Invalid id token")
return success_response(
{
'name': token.get('name'),
'sub': token.get('sub'),
'email': token.get('email')
}
)
def get_id_token(request):
id_token = request.headers.get("Authorization")
if id_token and id_token.startswith("Bearer "):
id_token = id_token[7:]
if not id_token:
id_token = request.cookies.get('wzstarter.oidc.id_token')
return id_token
def get_access_token(request):
access_token = request.headers.get("Authorization")
if access_token and access_token.startswith("Bearer "):
access_token = access_token[7:]
if not access_token:
access_token = request.cookies.get('wzstarter.oidc.access_token')
return access_token
def current_datetime():
return datetime.now(utc)
def error_response(status_code=400, message="Bad request"):
print('Sending error response')
ret = jsonify(message=message)
ret.status_code = status_code
ret.mimetype = 'application/json'
return ret
def success_response(response_dict={}):
print('Sending success response')
ret = jsonify(response_dict)
ret.status_code = 200
ret.mimetype='application/json'
return ret
@app.errorhandler(500)
def internal_server_error(error):
app.logger.error('Server Error: %s', (error))
return error_response(500, str(error))
@app.errorhandler(404)
def internal_server_error(error):
return error_response(404, "Not found")
@app.errorhandler(Exception)
def unhandled_exception(e):
app.logger.error('Unhandled Exception: %s', (e))
print('Unhandled Exception: %s', (e))
return error_response(500, str(e))
def new_guid():
return str(uuid.uuid4())
def get_redis():
cfg = app.redis_config
return redis.StrictRedis(host=cfg.hostname, port=cfg.port)
def get_guestbook_redis_key(id):
return 'guestbook:'+id
def get_login_redis_key(id):
return 'login:'+id
def parse_redis_key(key):
return key.split(':')[1]
def main():
"""Main entry point of the app."""
try:
http_server = WSGIServer((HOSTNAME, PORT),
app,
log=logging,
error_log=logging)
http_server.serve_forever()
except Exception as exc:
logging.error(exc.message)
finally:
# get last entry and insert build appended if not completed
# Do something here
pass
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_hybrid_compute/lib/2020-08-02/generated/azure_mgmt_hybrid_compute/models/machine_extension.rb | 6329 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::HybridCompute::Mgmt::V2020_08_02
module Models
#
# Describes a Machine Extension.
#
class MachineExtension < TrackedResource
include MsRestAzure
# @return [String] How the extension handler should be forced to update
# even if the extension configuration has not changed.
attr_accessor :force_update_tag
# @return [String] The name of the extension handler publisher.
attr_accessor :publisher
# @return [String] Specifies the type of the extension; an example is
# "CustomScriptExtension".
attr_accessor :machine_extension_type
# @return [String] Specifies the version of the script handler.
attr_accessor :type_handler_version
# @return [Boolean] Indicates whether the extension should use a newer
# minor version if one is available at deployment time. Once deployed,
# however, the extension will not upgrade minor versions unless
# redeployed, even with this property set to true.
attr_accessor :auto_upgrade_minor_version
# @return Json formatted public settings for the extension.
attr_accessor :settings
# @return The extension can contain either protectedSettings or
# protectedSettingsFromKeyVault or no protected settings at all.
attr_accessor :protected_settings
# @return [String] The provisioning state, which only appears in the
# response.
attr_accessor :provisioning_state
# @return [MachineExtensionPropertiesInstanceView] The machine extension
# instance view.
attr_accessor :instance_view
#
# Mapper for MachineExtension class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'MachineExtension',
type: {
name: 'Composite',
class_name: 'MachineExtension',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
location: {
client_side_validation: true,
required: true,
serialized_name: 'location',
type: {
name: 'String'
}
},
force_update_tag: {
client_side_validation: true,
required: false,
serialized_name: 'properties.forceUpdateTag',
type: {
name: 'String'
}
},
publisher: {
client_side_validation: true,
required: false,
serialized_name: 'properties.publisher',
type: {
name: 'String'
}
},
machine_extension_type: {
client_side_validation: true,
required: false,
serialized_name: 'properties.type',
type: {
name: 'String'
}
},
type_handler_version: {
client_side_validation: true,
required: false,
serialized_name: 'properties.typeHandlerVersion',
type: {
name: 'String'
}
},
auto_upgrade_minor_version: {
client_side_validation: true,
required: false,
serialized_name: 'properties.autoUpgradeMinorVersion',
type: {
name: 'Boolean'
}
},
settings: {
client_side_validation: true,
required: false,
serialized_name: 'properties.settings',
type: {
name: 'Object'
}
},
protected_settings: {
client_side_validation: true,
required: false,
serialized_name: 'properties.protectedSettings',
type: {
name: 'Object'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
instance_view: {
client_side_validation: true,
required: false,
serialized_name: 'properties.instanceView',
type: {
name: 'Composite',
class_name: 'MachineExtensionPropertiesInstanceView'
}
}
}
}
}
end
end
end
end
| mit |
matija94/show-me-the-code | trydjango/restaurants/admin.py | 138 | from django.contrib import admin
# Register your models here.
from restaurants.models import Restaurant
admin.site.register(Restaurant)
| mit |
ddrinka/ApacheOrcDotNet | src/ApacheOrcDotNet/OrcWriter`.cs | 812 | using System.Collections.Generic;
using System.IO;
using ApacheOrcDotNet.FluentSerialization;
namespace ApacheOrcDotNet
{
public class OrcWriter<T> : IOrcWriter<T>
{
readonly OrcWriter _underlyingOrcWriter;
public OrcWriter(Stream outputStream, WriterConfiguration configuration, SerializationConfiguration serializationConfiguration = null)
{
_underlyingOrcWriter = new OrcWriter(typeof(T), outputStream, configuration, serializationConfiguration);
}
public void AddRow(T row) => _underlyingOrcWriter.AddRow(row);
public void AddRows(IEnumerable<T> rows) => _underlyingOrcWriter.AddRows((IEnumerable<object>)rows);
public void AddUserMetadata(string key, byte[] value) => _underlyingOrcWriter.AddUserMetadata(key, value);
public void Dispose() => _underlyingOrcWriter.Dispose();
}
}
| mit |
Mugen87/yuka | test/unit_test/math/OBB.tests.js | 15152 | /**
* @author Mugen87 / https://github.com/Mugen87
*/
const expect = require( 'chai' ).expect;
const YUKA = require( '../../../build/yuka.js' );
const MathJSONs = require( '../../files/MathJSONs.js' );
const AABB = YUKA.AABB;
const BoundingSphere = YUKA.BoundingSphere;
const OBB = YUKA.OBB;
const Plane = YUKA.Plane;
const Quaternion = YUKA.Quaternion;
const Matrix3 = YUKA.Matrix3;
const Vector3 = YUKA.Vector3;
const points = [
new Vector3( 1, 1, 1 ),
new Vector3( 4, - 1, 4 ),
new Vector3( 3, 6, - 3 ),
new Vector3( - 7, - 5, 0 ),
new Vector3( 2, 9, 19 ),
new Vector3( 7, 4, 8 ),
new Vector3( 14, - 14, 2 ),
new Vector3( - 9, 1, 11 ),
new Vector3( 0, 14, - 8 )
];
describe( 'OBB', function () {
const obb = new OBB().fromPoints( points );
describe( '#constructor()', function () {
it( 'should create an object with correct default values', function () {
const obb = new OBB();
expect( obb.center ).to.be.an.instanceof( Vector3 );
expect( obb.halfSizes ).to.be.an.instanceof( Vector3 );
expect( obb.rotation ).to.be.an.instanceof( Matrix3 );
} );
it( 'should create an object with properties according to the given values', function () {
const center = new Vector3();
const halfSizes = new Vector3();
const rotation = new Matrix3();
const obb = new OBB( center, halfSizes, rotation );
expect( obb.center ).to.equal( center );
expect( obb.halfSizes ).to.equal( halfSizes );
expect( obb.rotation ).to.equal( rotation );
} );
} );
describe( '#set()', function () {
it( 'should apply the given values to the object', function () {
const center = new Vector3();
const halfSizes = new Vector3();
const rotation = new Matrix3();
const obb = new OBB().set( center, halfSizes, rotation );
expect( obb.center ).to.equal( center );
expect( obb.halfSizes ).to.equal( halfSizes );
expect( obb.rotation ).to.equal( rotation );
} );
} );
describe( '#copy()', function () {
it( 'should copy all values from the given object', function () {
const center = new Vector3( 1, 1, 1 );
const halfSizes = new Vector3( 2, 2, 2 );
const rotation = new Matrix3().set( 2, 2, 2, 2, 2, 2, 2, 2, 2 );
const obb1 = new OBB( center, halfSizes, rotation );
const obb2 = new OBB();
obb2.copy( obb1 );
expect( obb2.center ).to.deep.equal( obb1.center );
expect( obb2.halfSizes ).to.deep.equal( obb1.halfSizes );
expect( obb2.rotation ).to.deep.equal( obb1.rotation );
} );
} );
describe( '#clone()', function () {
it( 'should create a new object', function () {
const obb1 = new OBB();
const obb2 = obb1.clone();
expect( obb1 ).not.to.equal( obb2 );
} );
it( 'should copy the values of the current object to the new one', function () {
const center = new Vector3( 1, 1, 1 );
const halfSizes = new Vector3( 2, 2, 2 );
const rotation = new Matrix3().set( 2, 2, 2, 2, 2, 2, 2, 2, 2 );
const obb1 = new OBB( center, halfSizes, rotation );
const obb2 = obb1.clone();
expect( obb2.center ).to.deep.equal( obb1.center );
expect( obb2.halfSizes ).to.deep.equal( obb1.halfSizes );
expect( obb2.rotation ).to.deep.equal( obb1.rotation );
} );
} );
describe( '#getSize()', function () {
it( 'should return the size of the OBB', function () {
const center = new Vector3( 1, 1, 1 );
const halfSizes = new Vector3( 2, 2, 2 );
const rotation = new Matrix3().set( 2, 2, 2, 2, 2, 2, 2, 2, 2 );
const obb = new OBB( center, halfSizes, rotation );
const size = new Vector3();
obb.getSize( size );
expect( size ).to.deep.equal( new Vector3( 4, 4, 4 ) );
} );
} );
describe( '#fromAABB()', function () {
it( 'should computes the OBB from an AABB', function () {
const aabb = new AABB().fromCenterAndSize( new Vector3( 1, 1, 1 ), new Vector3( 2, 2, 2 ) );
const obb = new OBB().fromAABB( aabb );
expect( obb.center ).to.deep.equal( new Vector3( 1, 1, 1 ) );
expect( obb.halfSizes ).to.deep.equal( new Vector3( 1, 1, 1 ) );
expect( obb.rotation ).to.deep.equal( new Matrix3() );
} );
} );
describe( '#fromPoints()', function () {
it( 'should compute an OBB that encloses the given set of points', function () {
expect( obb.center.x ).to.closeTo( 2.0778426352496924, Number.EPSILON );
expect( obb.center.y ).to.closeTo( - 4.007474094173611, Number.EPSILON );
expect( obb.center.z ).to.closeTo( 3.1023614747658463, Number.EPSILON );
expect( obb.halfSizes.x ).to.closeTo( 8.43764728814747, Number.EPSILON );
expect( obb.halfSizes.y ).to.closeTo( 14.657724277890626, Number.EPSILON );
expect( obb.halfSizes.z ).to.closeTo( 13.754912222752461, Number.EPSILON );
expect( obb.rotation.elements[ 0 ] ).to.closeTo( 0.8634950831013628, Number.EPSILON );
expect( obb.rotation.elements[ 1 ] ).to.closeTo( 0.5033385631350236, Number.EPSILON );
expect( obb.rotation.elements[ 2 ] ).to.closeTo( 0.032039543082580876, Number.EPSILON );
expect( obb.rotation.elements[ 3 ] ).to.closeTo( - 0.50184074522067, Number.EPSILON );
expect( obb.rotation.elements[ 4 ] ).to.closeTo( 0.8511132886686104, Number.EPSILON );
expect( obb.rotation.elements[ 5 ] ).to.closeTo( 0.15414939600292202, Number.EPSILON );
expect( obb.rotation.elements[ 6 ] ).to.closeTo( 0.05032005461178748, Number.EPSILON );
expect( obb.rotation.elements[ 7 ] ).to.closeTo( - 0.1491859936886602, Number.EPSILON );
expect( obb.rotation.elements[ 8 ] ).to.closeTo( 0.9875279395495573, Number.EPSILON );
} );
} );
describe( '#clampPoint()', function () {
it( 'should ensure the given point is inside this OBB and stores the result in the given vector', function () {
const closestPoint = new Vector3();
const point1 = new Vector3();
const point2 = new Vector3( 0, 20, 0 );
const point3 = new Vector3( 14, - 14, 2 );
obb.clampPoint( point1, closestPoint ); // point inside
expect( closestPoint.x ).to.closeTo( - 7.771561172376096e-16, Number.EPSILON );
expect( closestPoint.y ).to.closeTo( 1.6653345369377348e-15, Number.EPSILON );
expect( closestPoint.z ).to.closeTo( - 1.3322676295501878e-15, Number.EPSILON );
obb.clampPoint( point2, closestPoint ); // point outside
expect( closestPoint.x ).to.closeTo( 1.6682157671156284, Number.EPSILON );
expect( closestPoint.y ).to.closeTo( 13.721879399308623, Number.EPSILON );
expect( closestPoint.z ).to.closeTo( - 1.0334415138496267, Number.EPSILON );
obb.clampPoint( point3, closestPoint ); // point on OBB
expect( closestPoint.x ).to.closeTo( 14.000000000000005, Number.EPSILON );
expect( closestPoint.y ).to.closeTo( - 14.000000000000004, Number.EPSILON );
expect( closestPoint.z ).to.closeTo( 1.9999999999999996, Number.EPSILON );
} );
} );
describe( '#containsPoint()', function () {
it( 'should return true if the given point is inside this OBB', function () {
const point1 = new Vector3();
const point2 = new Vector3( 0, 20, 0 );
const point3 = new Vector3( 14, - 14, 2 );
expect( obb.containsPoint( point1 ) ).to.be.true; // point inside
expect( obb.containsPoint( point2 ) ).to.be.false; // point outside
expect( obb.containsPoint( point3 ) ).to.be.true; // point on OBB
} );
} );
describe( '#intersectsAABB()', function () {
it( 'should return true if the given AABB intersects this OBB', function () {
const aabb1 = new AABB().fromCenterAndSize( new Vector3(), new Vector3( 1, 1, 1 ) );
const aabb2 = new AABB().fromCenterAndSize( new Vector3(), new Vector3( 50, 50, 50 ) );
const aabb3 = new AABB().fromCenterAndSize( new Vector3( 0, 20, 0 ), new Vector3( 20, 20, 20 ) );
expect( obb.intersectsAABB( aabb1 ) ).to.be.true; // AABB fully contained in OBB
expect( obb.intersectsAABB( aabb2 ) ).to.be.true; // OBB fully contained in AABB
expect( obb.intersectsAABB( aabb3 ) ).to.be.true; // intersection
} );
it( 'should return false if there is no intersection', function () {
const aabb = new AABB().fromCenterAndSize( new Vector3( 0, 20, 0 ), new Vector3( 1, 1, 1 ) );
expect( obb.intersectsAABB( aabb ) ).to.be.false;
} );
} );
describe( '#intersectsBoundingSphere()', function () {
it( 'should return true if the given bounding sphere intersects this OBB', function () {
const sphere1 = new BoundingSphere( new Vector3(), 5 );
const sphere2 = new BoundingSphere( new Vector3(), 50 );
const sphere4 = new BoundingSphere( new Vector3( 0, 20, 0 ), 10 );
expect( obb.intersectsBoundingSphere( sphere1 ) ).to.be.true; // sphere fully contained in OBB
expect( obb.intersectsBoundingSphere( sphere2 ) ).to.be.true; // OBB fully contained in sphere
expect( obb.intersectsBoundingSphere( sphere4 ) ).to.be.true; // intersection
} );
it( 'should return false if there is no intersection', function () {
const sphere = new BoundingSphere( new Vector3( 0, 20, 0 ), 1 );
expect( obb.intersectsBoundingSphere( sphere ) ).to.be.false;
} );
} );
describe( '#intersectsOBB()', function () {
it( 'should return true if the given OBB intersects this OBB', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb2.center.set( 4, 1, 15 );
obb2.halfSizes.set( 5, 5, 5 );
expect( obb1.intersectsOBB( obb2 ) ).to.be.true; // interesction
} );
it( 'should return true if the given OBB is fully contained in this OBB', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb2.center.set( 4, 1, 10 );
obb2.halfSizes.set( 2, 2, 2 );
expect( obb1.intersectsOBB( obb2 ) ).to.be.true;
} );
it( 'should return false if there is no intersection (test A0,A1,A2)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb2.center.set( 4, 1, - 10 );
obb2.halfSizes.set( 5, 5, 5 );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
} );
it( 'should return false if there is no intersection (test B0,B1,B2)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb1.rotation.fromQuaternion( new Quaternion().fromEuler( Math.PI * 0.25, 0, 0 ) );
obb2.center.set( 4, 1, - 10 );
obb2.halfSizes.set( 10, 10, 10 );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
} );
it( 'should return false if there is no intersection (test A2 x B0 and A0 x B2)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb1.rotation.fromQuaternion( new Quaternion().fromEuler( 0, 0, Math.PI * 0.25 ) );
obb2.center.set( 4, 20, 10 );
obb2.halfSizes.set( 8, 8, 8 );
obb2.rotation.fromQuaternion( new Quaternion().fromEuler( Math.PI * 0.25, 0, 0 ) );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
expect( obb2.intersectsOBB( obb1 ) ).to.be.false;
} );
it( 'should return false if there is no intersection (test A2 x B1 abd A1 x B2)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb1.rotation.fromQuaternion( new Quaternion().fromEuler( 0, Math.PI * 0.25, 0 ) );
obb2.center.set( 20, 1, 8 );
obb2.halfSizes.set( 5, 5, 5 );
obb2.rotation.fromQuaternion( new Quaternion().fromEuler( 0, 0, Math.PI * 0.25 ) );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
expect( obb2.intersectsOBB( obb1 ) ).to.be.false;
} );
it( 'should return false if there is no intersection (test A0 x B1 and A1 x B0)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb1.rotation.fromQuaternion( new Quaternion().fromEuler( Math.PI * 0.25, 0, 0 ) );
obb2.center.set( 4, 1, - 8 );
obb2.halfSizes.set( 5, 5, 5 );
obb2.rotation.fromQuaternion( new Quaternion().fromEuler( 0, Math.PI * 0.25, 0 ) );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
expect( obb2.intersectsOBB( obb1 ) ).to.be.false;
} );
it( 'should return false if there is no intersection (test A0 x B0)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb2.center.set( 4, - 10, 20 );
obb2.halfSizes.set( 5, 5, 5 );
obb2.rotation.fromQuaternion( new Quaternion().fromEuler( Math.PI * 0.2, - Math.PI * 0.2, Math.PI * 0.5 ) );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
} );
it( 'should return false if there is no intersection (test A1 x B1)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb2.center.set( - 8, 1, 0 );
obb2.halfSizes.set( 5, 5, 5 );
obb2.rotation.fromQuaternion( new Quaternion().fromEuler( Math.PI * 0.2, Math.PI * 0.2, Math.PI * 0.5 ) );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
} );
it( 'should return false if there is no intersection (test A2 x B2)', function () {
const obb1 = new OBB();
const obb2 = new OBB();
obb1.center.set( 4, 1, 10 );
obb1.halfSizes.set( 5, 5, 5 );
obb2.center.set( 14, 11, 10 );
obb2.halfSizes.set( 5, 5, 5 );
obb2.rotation.fromQuaternion( new Quaternion().fromEuler( - Math.PI * 0.1, - Math.PI * 0.2, 0 ) );
expect( obb1.intersectsOBB( obb2 ) ).to.be.false;
} );
} );
describe( '#intersectsPlane()', function () {
it( 'should return true if the given plane intersects this OBB', function () {
const plane = new Plane( new Vector3( 0, 1, 0 ), 0 );
expect( obb.intersectsPlane( plane ) ).to.be.true;
} );
it( 'should return false if there is no intersection', function () {
const plane = new Plane( new Vector3( 0, 1, 0 ), 20 );
expect( obb.intersectsPlane( plane ) ).to.be.false;
} );
} );
describe( '#equals()', function () {
it( 'should execute a deep comparison between two objects', function () {
const center = new Vector3( 1, 1, 1 );
const halfSizes = new Vector3( 2, 2, 2 );
const rotation = new Matrix3().set( 2, 2, 2, 2, 2, 2, 2, 2, 2 );
const obb1 = new OBB( center, halfSizes, rotation );
const obb2 = new OBB( new Vector3( 1, 1, 1 ), halfSizes, rotation );
const obb3 = new OBB( new Vector3( 1, 0, 1 ), halfSizes, rotation );
expect( obb1.equals( obb2 ) ).to.be.true;
expect( obb1.equals( obb3 ) ).to.be.false;
} );
} );
describe( '#toJSON()', function () {
it( 'should serialize this instance to a JSON object', function () {
const obb = new OBB();
const json = obb.toJSON();
expect( json ).to.be.deep.equal( MathJSONs.OBB );
} );
} );
describe( '#fromJSON()', function () {
it( 'should deserialize this instance from the given JSON object', function () {
const obb1 = new OBB();
const obb2 = new OBB( new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ).fromJSON( MathJSONs.OBB );
expect( obb1 ).to.be.deep.equal( obb2 );
} );
} );
} );
| mit |
TomHennen/AntennaPod | app/src/main/java/de/danoeh/antennapod/activity/OnlineFeedViewActivity.java | 23310 | package de.danoeh.antennapod.activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.examples.HtmlToPlainText;
import org.jsoup.nodes.Document;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.adapter.FeedItemlistDescriptionAdapter;
import de.danoeh.antennapod.core.dialog.DownloadRequestErrorDialogCreator;
import de.danoeh.antennapod.core.feed.EventDistributor;
import de.danoeh.antennapod.core.feed.Feed;
import de.danoeh.antennapod.core.feed.FeedItem;
import de.danoeh.antennapod.core.feed.FeedPreferences;
import de.danoeh.antennapod.core.glide.ApGlideSettings;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.service.download.DownloadRequest;
import de.danoeh.antennapod.core.service.download.DownloadStatus;
import de.danoeh.antennapod.core.service.download.Downloader;
import de.danoeh.antennapod.core.service.download.HttpDownloader;
import de.danoeh.antennapod.core.storage.DBReader;
import de.danoeh.antennapod.core.storage.DownloadRequestException;
import de.danoeh.antennapod.core.storage.DownloadRequester;
import de.danoeh.antennapod.core.syndication.handler.FeedHandler;
import de.danoeh.antennapod.core.syndication.handler.FeedHandlerResult;
import de.danoeh.antennapod.core.syndication.handler.UnsupportedFeedtypeException;
import de.danoeh.antennapod.core.util.DownloadError;
import de.danoeh.antennapod.core.util.FileNameGenerator;
import de.danoeh.antennapod.core.util.StorageUtils;
import de.danoeh.antennapod.core.util.URLChecker;
import de.danoeh.antennapod.core.util.syndication.FeedDiscoverer;
import de.danoeh.antennapod.dialog.AuthenticationDialog;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Downloads a feed from a feed URL and parses it. Subclasses can display the
* feed object that was parsed. This activity MUST be started with a given URL
* or an Exception will be thrown.
* <p/>
* If the feed cannot be downloaded or parsed, an error dialog will be displayed
* and the activity will finish as soon as the error dialog is closed.
*/
public class OnlineFeedViewActivity extends ActionBarActivity {
private static final String TAG = "OnlineFeedViewActivity";
public static final String ARG_FEEDURL = "arg.feedurl";
// Optional argument: specify a title for the actionbar.
public static final String ARG_TITLE = "title";
private static final int EVENTS = EventDistributor.DOWNLOAD_HANDLED | EventDistributor.DOWNLOAD_QUEUED | EventDistributor.FEED_LIST_UPDATE;
public static final int RESULT_ERROR = 2;
private volatile List<Feed> feeds;
private Feed feed;
private String selectedDownloadUrl;
private Downloader downloader;
private boolean isPaused;
private Dialog dialog;
private Button subscribeButton;
private Subscription download;
private Subscription parser;
private Subscription updater;
private EventDistributor.EventListener listener = new EventDistributor.EventListener() {
@Override
public void update(EventDistributor eventDistributor, Integer arg) {
if ((arg & EventDistributor.FEED_LIST_UPDATE) != 0) {
updater = Observable.defer(() -> Observable.just(DBReader.getFeedList()))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(feeds -> {
OnlineFeedViewActivity.this.feeds = feeds;
setSubscribeButtonState(feed);
}
);
} else if ((arg & EVENTS) != 0) {
setSubscribeButtonState(feed);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(UserPreferences.getTheme());
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (getIntent() != null && getIntent().hasExtra(ARG_TITLE)) {
getSupportActionBar().setTitle(getIntent().getStringExtra(ARG_TITLE));
}
StorageUtils.checkStorageAvailability(this);
final String feedUrl;
if (getIntent().hasExtra(ARG_FEEDURL)) {
feedUrl = getIntent().getStringExtra(ARG_FEEDURL);
} else if (StringUtils.equals(getIntent().getAction(), Intent.ACTION_SEND)
|| StringUtils.equals(getIntent().getAction(), Intent.ACTION_VIEW)) {
feedUrl = (StringUtils.equals(getIntent().getAction(), Intent.ACTION_SEND))
? getIntent().getStringExtra(Intent.EXTRA_TEXT) : getIntent().getDataString();
getSupportActionBar().setTitle(R.string.add_new_feed_label);
} else {
throw new IllegalArgumentException("Activity must be started with feedurl argument!");
}
Log.d(TAG, "Activity was started with url " + feedUrl);
setLoadingLayout();
if (savedInstanceState == null) {
startFeedDownload(feedUrl, null, null);
} else {
startFeedDownload(feedUrl, savedInstanceState.getString("username"), savedInstanceState.getString("password"));
}
}
/**
* Displays a progress indicator.
*/
private void setLoadingLayout() {
RelativeLayout rl = new RelativeLayout(this);
RelativeLayout.LayoutParams rlLayoutParams = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
ProgressBar pb = new ProgressBar(this);
pb.setIndeterminate(true);
RelativeLayout.LayoutParams pbLayoutParams = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
pbLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
rl.addView(pb, pbLayoutParams);
addContentView(rl, rlLayoutParams);
}
@Override
protected void onResume() {
super.onResume();
isPaused = false;
EventDistributor.getInstance().register(listener);
}
@Override
protected void onPause() {
super.onPause();
isPaused = true;
EventDistributor.getInstance().unregister(listener);
}
@Override
protected void onStop() {
super.onStop();
if (downloader != null && !downloader.isFinished()) {
downloader.cancel();
}
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(updater != null) {
updater.unsubscribe();
}
if(download != null) {
download.unsubscribe();
}
if(parser != null) {
parser.unsubscribe();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (feed != null && feed.getPreferences() != null) {
outState.putString("username", feed.getPreferences().getUsername());
outState.putString("password", feed.getPreferences().getPassword());
}
}
private void resetIntent(String url, String title) {
Intent intent = new Intent();
intent.putExtra(ARG_FEEDURL, url);
intent.putExtra(ARG_TITLE, title);
setIntent(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent destIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, destIntent)) {
startActivity(destIntent);
} else {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void startFeedDownload(String url, String username, String password) {
Log.d(TAG, "Starting feed download");
url = URLChecker.prepareURL(url);
feed = new Feed(url, new Date(0));
if (username != null && password != null) {
feed.setPreferences(new FeedPreferences(0, false, FeedPreferences.AutoDeleteAction.GLOBAL, username, password));
}
String fileUrl = new File(getExternalCacheDir(),
FileNameGenerator.generateFileName(feed.getDownload_url())).toString();
feed.setFile_url(fileUrl);
final DownloadRequest request = new DownloadRequest(feed.getFile_url(),
feed.getDownload_url(), "OnlineFeed", 0, Feed.FEEDFILETYPE_FEED, username, password,
true, null);
download = Observable.create(new Observable.OnSubscribe<DownloadStatus>() {
@Override
public void call(Subscriber<? super DownloadStatus> subscriber) {
feeds = DBReader.getFeedList();
downloader = new HttpDownloader(request);
downloader.call();
Log.d(TAG, "Download was completed");
subscriber.onNext(downloader.getResult());
subscriber.onCompleted();
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(status -> {
if (status != null) {
if (!status.isCancelled()) {
if (status.isSuccessful()) {
parseFeed();
} else if (status.getReason() == DownloadError.ERROR_UNAUTHORIZED) {
if (!isFinishing() && !isPaused) {
dialog = new FeedViewAuthenticationDialog(OnlineFeedViewActivity.this,
R.string.authentication_notification_title, downloader.getDownloadRequest().getSource());
dialog.show();
}
} else {
String errorMsg = status.getReason().getErrorString(OnlineFeedViewActivity.this);
if (errorMsg != null && status.getReasonDetailed() != null) {
errorMsg += " (" + status.getReasonDetailed() + ")";
}
showErrorDialog(errorMsg);
}
}
} else {
Log.wtf(TAG, "DownloadStatus returned by Downloader was null");
finish();
}
});
}
private void parseFeed() {
if (feed == null || feed.getFile_url() == null && feed.isDownloaded()) {
throw new IllegalStateException("feed must be non-null and downloaded when parseFeed is called");
}
Log.d(TAG, "Parsing feed");
parser = Observable.create(new Observable.OnSubscribe<FeedHandlerResult>() {
@Override
public void call(Subscriber<? super FeedHandlerResult> subscriber) {
FeedHandler handler = new FeedHandler();
try {
FeedHandlerResult result = handler.parseFeed(feed);
subscriber.onNext(result);
} catch (UnsupportedFeedtypeException e) {
Log.d(TAG, "Unsupported feed type detected");
if (StringUtils.equalsIgnoreCase("html", e.getRootElement())) {
showFeedDiscoveryDialog(new File(feed.getFile_url()), feed.getDownload_url());
} else {
subscriber.onError(e);
}
} catch (Exception e) {
subscriber.onError(e);
} finally {
boolean rc = new File(feed.getFile_url()).delete();
Log.d(TAG, "Deleted feed source file. Result: " + rc);
subscriber.onCompleted();
}
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
beforeShowFeedInformation(result.feed);
showFeedInformation(result.feed, result.alternateFeedUrls);
}, error -> {
String errorMsg = DownloadError.ERROR_PARSER_EXCEPTION.getErrorString(
OnlineFeedViewActivity.this) + " (" + error.getMessage() + ")";
showErrorDialog(errorMsg);
});
}
/**
* Called after the feed has been downloaded and parsed and before showFeedInformation is called.
* This method is executed on a background thread
*/
private void beforeShowFeedInformation(Feed feed) {
// remove HTML tags from descriptions
Log.d(TAG, "Removing HTML from shownotes");
if (feed.getItems() != null) {
HtmlToPlainText formatter = new HtmlToPlainText();
for (FeedItem item : feed.getItems()) {
if (item.getDescription() != null) {
Document description = Jsoup.parse(item.getDescription());
item.setDescription(StringUtils.trim(formatter.getPlainText(description)));
}
}
}
}
/**
* Called when feed parsed successfully.
* This method is executed on the GUI thread.
*/
private void showFeedInformation(final Feed feed, Map<String, String> alternateFeedUrls) {
setContentView(R.layout.listview_activity);
this.feed = feed;
this.selectedDownloadUrl = feed.getDownload_url();
EventDistributor.getInstance().register(listener);
ListView listView = (ListView) findViewById(R.id.listview);
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View header = inflater.inflate(R.layout.onlinefeedview_header, listView, false);
listView.addHeaderView(header);
listView.setAdapter(new FeedItemlistDescriptionAdapter(this, 0, feed.getItems()));
ImageView cover = (ImageView) header.findViewById(R.id.imgvCover);
TextView title = (TextView) header.findViewById(R.id.txtvTitle);
TextView author = (TextView) header.findViewById(R.id.txtvAuthor);
TextView description = (TextView) header.findViewById(R.id.txtvDescription);
Spinner spAlternateUrls = (Spinner) header.findViewById(R.id.spinnerAlternateUrls);
subscribeButton = (Button) header.findViewById(R.id.butSubscribe);
if (feed.getImage() != null && StringUtils.isNotBlank(feed.getImage().getDownload_url())) {
Glide.with(this)
.load(feed.getImage().getDownload_url())
.placeholder(R.color.light_gray)
.error(R.color.light_gray)
.diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY)
.fitCenter()
.dontAnimate()
.into(cover);
}
title.setText(feed.getTitle());
author.setText(feed.getAuthor());
description.setText(feed.getDescription());
subscribeButton.setOnClickListener(v -> {
try {
Feed f = new Feed(selectedDownloadUrl, new Date(0), feed.getTitle());
f.setPreferences(feed.getPreferences());
this.feed = f;
DownloadRequester.getInstance().downloadFeed(this, f);
} catch (DownloadRequestException e) {
e.printStackTrace();
DownloadRequestErrorDialogCreator.newRequestErrorDialog(OnlineFeedViewActivity.this,
e.getMessage());
}
setSubscribeButtonState(feed);
});
if (alternateFeedUrls.isEmpty()) {
spAlternateUrls.setVisibility(View.GONE);
} else {
spAlternateUrls.setVisibility(View.VISIBLE);
final List<String> alternateUrlsList = new ArrayList<>();
final List<String> alternateUrlsTitleList = new ArrayList<>();
alternateUrlsList.add(feed.getDownload_url());
alternateUrlsTitleList.add(feed.getTitle());
alternateUrlsList.addAll(alternateFeedUrls.keySet());
for (String url : alternateFeedUrls.keySet()) {
alternateUrlsTitleList.add(alternateFeedUrls.get(url));
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, alternateUrlsTitleList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spAlternateUrls.setAdapter(adapter);
spAlternateUrls.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedDownloadUrl = alternateUrlsList.get(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
setSubscribeButtonState(feed);
}
private void setSubscribeButtonState(Feed feed) {
if (subscribeButton != null && feed != null) {
if (DownloadRequester.getInstance().isDownloadingFile(feed.getDownload_url())) {
subscribeButton.setEnabled(false);
subscribeButton.setText(R.string.downloading_label);
} else if (feedInFeedlist(feed)) {
subscribeButton.setEnabled(false);
subscribeButton.setText(R.string.subscribed_label);
} else {
subscribeButton.setEnabled(true);
subscribeButton.setText(R.string.subscribe_label);
}
}
}
private boolean feedInFeedlist(Feed feed) {
if (feeds == null || feed == null) {
return false;
}
for (Feed f : feeds) {
if (f.getIdentifyingValue().equals(feed.getIdentifyingValue())) {
return true;
}
}
return false;
}
private void showErrorDialog(String errorMsg) {
assert(Looper.myLooper() == Looper.getMainLooper()); // run on UI thread
if (!isFinishing() && !isPaused) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.error_label);
if (errorMsg != null) {
builder.setMessage(getString(R.string.error_msg_prefix) + errorMsg);
} else {
builder.setMessage(R.string.error_msg_prefix);
}
builder.setNeutralButton(android.R.string.ok,
(dialog, which) -> {
dialog.cancel();
}
);
builder.setOnCancelListener(dialog -> {
setResult(RESULT_ERROR);
finish();
});
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = builder.show();
}
}
private void showFeedDiscoveryDialog(File feedFile, String baseUrl) {
FeedDiscoverer fd = new FeedDiscoverer();
final Map<String, String> urlsMap;
try {
urlsMap = fd.findLinks(feedFile, baseUrl);
if (urlsMap == null || urlsMap.isEmpty()) {
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
if (isPaused || isFinishing()) {
return;
}
final List<String> titles = new ArrayList<>();
final List<String> urls = new ArrayList<>();
urls.addAll(urlsMap.keySet());
for (String url : urls) {
titles.add(urlsMap.get(url));
}
final ArrayAdapter<String> adapter = new ArrayAdapter<>(OnlineFeedViewActivity.this, R.layout.ellipsize_start_listitem, R.id.txtvTitle, titles);
DialogInterface.OnClickListener onClickListener = (dialog, which) -> {
String selectedUrl = urls.get(which);
dialog.dismiss();
resetIntent(selectedUrl, titles.get(which));
FeedPreferences prefs = feed.getPreferences();
if(prefs != null) {
startFeedDownload(selectedUrl, prefs.getUsername(), prefs.getPassword());
} else {
startFeedDownload(selectedUrl, null, null);
}
};
AlertDialog.Builder ab = new AlertDialog.Builder(OnlineFeedViewActivity.this)
.setTitle(R.string.feeds_label)
.setCancelable(true)
.setOnCancelListener(dialog -> finish())
.setAdapter(adapter, onClickListener);
runOnUiThread(() -> {
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = ab.show();
});
}
private class FeedViewAuthenticationDialog extends AuthenticationDialog {
private String feedUrl;
public FeedViewAuthenticationDialog(Context context, int titleRes, String feedUrl) {
super(context, titleRes, true, false, null, null);
this.feedUrl = feedUrl;
}
@Override
protected void onCancelled() {
super.onCancelled();
finish();
}
@Override
protected void onConfirmed(String username, String password, boolean saveUsernamePassword) {
startFeedDownload(feedUrl, username, password);
}
}
}
| mit |
monde-sistemas/brcobranca | spec/brcobranca/remessa/cnab400/banco_brasilia_spec.rb | 9592 | # -*- encoding: utf-8 -*-
require 'spec_helper'
RSpec.describe Brcobranca::Remessa::Cnab400::BancoBrasilia do
let(:pagamento) do
Brcobranca::Remessa::Pagamento.new(valor: 199.9,
data_vencimento: Date.current,
nosso_numero: 123,
documento: 6969,
documento_sacado: '12345678901',
nome_sacado: 'PABLO DIEGO JOSÉ FRANCISCO DE PAULA JUAN NEPOMUCENO MARÍA DE LOS REMEDIOS CIPRIANO DE LA SANTÍSSIMA TRINIDAD RUIZ Y PICASSO',
logradouro_sacado: 'RUA RIO GRANDE DO SUL São paulo Minas caçapa da silva junior',
numero_sacado: '999',
bairro_sacado: 'São josé dos quatro apostolos magros',
cep_sacado: '12345678',
cidade_sacado: 'Santa rita de cássia maria da silva',
uf_sacado: 'SP',
especie_titulo: 'DS')
end
let(:params) do
{
carteira: '2',
agencia: '083',
conta_corrente: '0000490',
digito_conta: '1',
empresa_mae: 'SOCIEDADE BRASILEIRA DE ZOOLOGIA LTDA',
pagamentos: [pagamento]
}
end
let(:banco_brasilia) { subject.class.new(params) }
context 'validacoes dos campos' do
context '@agencia' do
it 'deve ser invalido se nao possuir uma agencia' do
object = subject.class.new(params.merge!(agencia: nil))
expect(object.invalid?).to be true
expect(object.errors.full_messages).to include('Agencia não pode estar em branco.')
end
it 'deve ser invalido se a agencia tiver mais de 3 digitos' do
banco_brasilia.agencia = '1234'
expect(banco_brasilia.invalid?).to be true
expect(banco_brasilia.errors.full_messages).to include('Agencia é muito longo (máximo: 3 caracteres).')
end
end
context '@digito_conta' do
it 'deve ser invalido se nao possuir um digito da conta corrente' do
objeto = subject.class.new(params.merge!(digito_conta: nil))
expect(objeto.invalid?).to be true
expect(objeto.errors.full_messages).to include('Digito conta não pode estar em branco.')
end
it 'deve ser inválido se o dígito da conta tiver mais de 1 dígito' do
banco_brasilia.digito_conta = '12'
expect(banco_brasilia.invalid?).to be true
expect(banco_brasilia.errors.full_messages).to include('Digito conta é muito longo (máximo: 1 caracteres).')
end
end
context '@conta_corrente' do
it 'deve ser invalido se nao possuir uma conta corrente' do
object = subject.class.new(params.merge!(conta_corrente: nil))
expect(object.invalid?).to be true
expect(object.errors.full_messages).to include('Conta corrente não pode estar em branco.')
end
it 'deve ser invalido se a conta corrente tiver mais de 7 digitos' do
banco_brasilia.conta_corrente = '12345678'
expect(banco_brasilia.invalid?).to be true
expect(banco_brasilia.errors.full_messages).to include('Conta corrente é muito longo (máximo: 7 caracteres).')
end
end
context '@carteira' do
it 'deve ser inválido se não possuir uma carteira' do
object = subject.class.new(params.merge!(carteira: nil))
expect(object.invalid?).to be true
expect(object.errors.full_messages).to include('Carteira não pode estar em branco.')
end
it 'deve ser inválido se a carteira tiver 1 dígito' do
banco_brasilia.carteira = '12'
expect(banco_brasilia.invalid?).to be true
expect(banco_brasilia.errors.full_messages).to include('Carteira é muito longo (máximo: 1 caracteres).')
end
end
end
context 'formatacoes dos valores' do
it 'cod_banco deve ser 070' do
expect(banco_brasilia.cod_banco).to eq '070'
end
it 'info_conta deve retornar com 10 posicoes as informacoes da conta' do
info_conta = banco_brasilia.info_conta
expect(info_conta.size).to eq 10
expect(info_conta[0..2]).to eq '083' # num. da agencia
expect(info_conta[3..9]).to eq '0000490' # num. da conta
end
end
context 'monta remessa' do
# it_behaves_like 'cnab400'
context 'header' do
it 'deve ter 39 posicoes' do
expect(banco_brasilia.monta_header.size).to eq 39
end
it 'informacoes devem estar posicionadas corretamente no header' do
header = banco_brasilia.monta_header
expect(header[0..2]).to eq 'DCB' # literal DCB
expect(header[3..5]).to eq '001' # versão
expect(header[6..8]).to eq '075' # arquivo
expect(header[9..18]).to eq banco_brasilia.info_conta # informacoes da conta
expect(header[19..32]).to eq Time.now.strftime('%Y%m%d%H%M%S') # data/hora de formação
expect(header[33..38]).to eq '000002' # num. de registros
end
end
context 'detalhe' do
it 'deve ter 400 posições' do
expect(banco_brasilia.monta_detalhe(pagamento, 1).size).to eq 400
end
it 'informacoes devem estar posicionadas corretamente no detalhe' do
detalhe = banco_brasilia.monta_detalhe pagamento, 1
expect(detalhe[0..1]).to eq '01' # identificador
expect(detalhe[2..11]).to eq banco_brasilia.info_conta # info da conta
expect(detalhe[12..25]).to eq '00012345678901' # identificador
expect(detalhe[26..60]).to eq 'PABLO DIEGO JOSE FRANCISCO DE PAULA' # nome do pagador
expect(detalhe[61..95]).to eq 'RUA RIO GRANDE DO SUL Sao paulo Min' # endereço do pagador
expect(detalhe[96..110]).to eq 'Santa rita de c' # cidade do pagador
expect(detalhe[111..112]).to eq 'SP' # uf do pagador
expect(detalhe[113..120]).to eq '12345678' # cep do pagador
expect(detalhe[121..121]).to eq '1' # tipo de pessoa
expect(detalhe[122..134]).to eq '6969'.rjust(13, '0') # seu numero
expect(detalhe[135..135]).to eq '2' # categoria de cobranca
expect(detalhe[136..143]).to eq Date.current.strftime('%d%m%Y') # data de emissao
expect(detalhe[144..145]).to eq '31' # tipo do documento
expect(detalhe[146..146]).to eq '0' # código da natureza
expect(detalhe[147..147]).to eq '0' # código da cond. pagamento
expect(detalhe[148..149]).to eq '02' # código da moeda
expect(detalhe[150..152]).to eq '070' # código do banco
expect(detalhe[153..156]).to eq '0083' # código da agência
expect(detalhe[157..186]).to eq ''.rjust(30, ' ') # praça de cobranca
expect(detalhe[187..194]).to eq Date.current.strftime('%d%m%Y') # data de vencimento
expect(detalhe[195..208]).to eq '00000000019990' # valor do titulo
expect(detalhe[209..220]).to eq '200012307038' # nosso numero
expect(detalhe[221..222]).to eq '00' # tipo de juros
expect(detalhe[223..236]).to eq ''.rjust(14, '0') # valor dos juros
expect(detalhe[237..250]).to eq ''.rjust(14, '0') # valor dos abatimento
expect(detalhe[251..252]).to eq '00' # tipo de desconto
expect(detalhe[253..260]).to eq ''.rjust(8, '0') # data limite de desconto
expect(detalhe[261..274]).to eq ''.rjust(14, '0') # valor dos descontos
expect(detalhe[288..327]).to eq 'SOCIEDADE BRASILEIRA DE ZOOLOGIA LTDA ' # emitente do titulo
end
it 'espécie do título RC converte para código correspondente' do
pagamento.especie_titulo = 'RC'
detalhe = banco_brasilia.monta_detalhe(pagamento, 1)
expect(detalhe[144..145]).to eq '25' # tipo documento (espécie título)
end
it 'espécie título não informada utiliza padrão' do
pagamento.especie_titulo = ''
detalhe = banco_brasilia.monta_detalhe pagamento, 1
expect(detalhe[144..145]).to eq '21'
end
end
it 'montagem da remessa deve falhar se o objeto nao for valido' do
expect { subject.class.new.gera_arquivo }.to raise_error(Brcobranca::RemessaInvalida)
end
it 'remessa deve conter os registros mais as quebras de linha' do
remessa = banco_brasilia.gera_arquivo
expect(remessa.size).to eq 443
# registros
expect(remessa[0..38]).to eq banco_brasilia.monta_header
expect(remessa[41..440]).to eq banco_brasilia.monta_detalhe(pagamento, 2).upcase
# quebras de linha
expect(remessa[39..40]).to eq "\r\n"
expect(remessa[441..442]).to eq "\r\n"
end
context 'arquivo' do
before { Timecop.freeze(Time.local(2015, 7, 14, 16, 15, 15)) }
after { Timecop.return }
it { expect(banco_brasilia.gera_arquivo).to eq(read_remessa('remessa-banco-brasilia-cnab400.rem', banco_brasilia.gera_arquivo)) }
end
end
end
| mit |
pokedextracker/pokedextracker.com | app/utils/api.js | 1037 | import { stringify } from 'qs';
import { Store } from '../stores';
async function handleResponse (response) {
const json = await response.json();
if (response.status >= 200 && response.status < 300) {
return json;
}
const error = new Error(json.error.message);
error.response = response;
throw error;
}
function getHeaders () {
return {
Authorization: `Bearer ${Store.getState().token}`,
'Content-Type': 'application/json'
};
}
export const API = {
async delete (url, payload) {
const response = await fetch(url, {
method: 'DELETE',
body: JSON.stringify(payload),
headers: getHeaders()
});
return handleResponse(response);
},
async get (url, params) {
const response = await fetch(`${url}?${stringify(params)}`);
return handleResponse(response);
},
async post (url, payload) {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(payload),
headers: getHeaders()
});
return handleResponse(response);
}
};
| mit |
alaxos/alaskyzer | src/Model/Table/TasksTable.php | 3194 | <?php
namespace App\Model\Table;
use App\Model\Entity\Task;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Event\Event;
use Cake\I18n\I18n;
use Cake\I18n\Time;
use Cake\Core\Configure;
/**
* Tasks Model
*/
class TasksTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->setTable('tasks');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('Alaxos.UserLink');
$this->addBehavior('Alaxos.Timezoned');
$this->belongsTo('TaskCategories', [
'foreignKey' => 'task_category_id'
]);
$this->belongsTo('Applications', [
'foreignKey' => 'application_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Servers', [
'foreignKey' => 'server_id'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create')
->requirePresence('name', 'create')
->notEmpty('name')
->allowEmpty('description')
->add('due_date', 'valid', ['rule' => 'date'])
->allowEmpty('due_date')
->add('closed', 'valid', ['rule' => 'datetime'])
->allowEmpty('closed')
->add('created_by', 'valid', ['rule' => 'numeric'])
->allowEmpty('created_by')
->add('modified_by', 'valid', ['rule' => 'numeric'])
->allowEmpty('modified_by');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['task_category_id'], 'TaskCategories'));
$rules->add($rules->existsIn(['application_id'], 'Applications'));
$rules->add($rules->existsIn(['server_id'], 'Servers'));
return $rules;
}
public function close($id, $datetime = null)
{
$task = $this->get($id);
if(!isset($task->closed))
{
$this->patchEntity($task, ['closed' => new Time()]);
return $this->save($task);
}
else
{
return false;
}
}
public function open($id, $datetime = null)
{
$task = $this->get($id);
if(isset($task->closed) || isset($task->abandoned))
{
$this->patchEntity($task, ['closed' => null, 'abandoned' => null]);
return $this->save($task);
}
else
{
return false;
}
}
}
| mit |
mrpapercut/wscript | testfiles/COMobjects/JSclasses/Microsoft.Update.WebProxy.1.js | 778 | class microsoft_update_webproxy_1 {
constructor() {
// string Address () {get} {set}
this.Address = undefined;
// bool AutoDetect () {get} {set}
this.AutoDetect = undefined;
// IStringCollection BypassList () {get} {set}
this.BypassList = undefined;
// bool BypassProxyOnLocal () {get} {set}
this.BypassProxyOnLocal = undefined;
// bool ReadOnly () {get}
this.ReadOnly = undefined;
// string UserName () {get} {set}
this.UserName = undefined;
}
// void PromptForCredentials (IUnknown, string)
PromptForCredentials(IUnknown, string) {
}
// void SetPassword (string)
SetPassword(string) {
}
}
module.exports = microsoft_update_webproxy_1;
| mit |
yoku2010/smil-epub | client/actions/navLinkActions.js | 170 | import { NAV_LINK_HEADER_BAR } from "./types";
export const navLinkHeaderDetails = (message) => {
return {
type: NAV_LINK_HEADER_BAR,
message
}
} | mit |
gmillward/math-flashcards | client/components/navbar/navbar.controller.js | 405 | 'use strict';
angular.module('yoFlashcardFullstackApp')
.controller('NavbarCtrl', function ($scope, $location) {
$scope.menu = [
{
'title': 'Home',
'link': '/'
},
{
'title': 'Settings',
'link': '/settings'
}
];
$scope.isCollapsed = true;
$scope.isActive = function (route) {
return route === $location.path();
};
}); | mit |
gmessner/ajf | src/main/java/com/messners/ajf/data/converters/StringConverter.java | 1400 | package com.messners.ajf.data.converters;
import com.messners.ajf.data.ConversionException;
import com.messners.ajf.data.Converter;
/**
* Default {@link Converter} implementation to convert a value object
* into a String instance.
*
* @author Greg Messner <gmessner@messners.com>
*/
public final class StringConverter implements Converter<String> {
/**
* Create a {@link Converter} to convert to and from
* <code>java.lang.String</code>.
*/
public StringConverter () {
}
/**
* Convert the provided object into an object of the specified type.
*
* @param value the value to be converted
* @exception ConversionException if an error occurs during conversion
*/
public String convert (Object value) throws ConversionException {
if (value == null) {
return ((String)null);
} else {
return (value.toString());
}
}
/**
* Convert the passed value to a String.
*
* @param value the Object to convert to a String
* @return the converted String
* @throws ConversionException if value is not the proper type
*/
public String toString (Object value) throws ConversionException {
try {
if (value instanceof String) {
return ((String)value);
} else {
return (value.toString());
}
} catch (Exception e) {
throw new ConversionException(e);
}
}
}
| mit |
holin/nodestroyed | lib/nodestroyed.rb | 1929 | module ActiveRecord #:nodoc:
module Nodestroyed #:nodoc:
def self.included(base)
base.extend(ClassMethods)
class << base
alias_method :find_origin, :find
alias_method :destroy_origin, :destroy
end
base.instance_eval do
alias_method :destroy_origin, :destroy
end
end
module ClassMethods
def act_as_nodestroyed
extend(ActiveRecord::Nodestroyed::SingletonMethods)
include(ActiveRecord::Nodestroyed::InstanceMethods)
end
end
module SingletonMethods
def nodestroyed?
self.new.nodestroyed?
end
def find(*args)
return find_origin(*args) unless self.nodestroyed?
return find_origin(*args) unless args.include?(:all)
options = args.extract_options!
args << options_excluding_destroyed(options)
find_origin *args
end
def destroyed_condition(table_name)
"#{table_name}.destroyed = 0"
end
def options_excluding_destroyed(options)
# need check :join, :include
options = Hash.new if options.nil?
if options.has_key?(:conditions) and !options[:conditions].nil?
case options[:conditions]
when Array
options[:conditions][0] = destroyed_condition(quoted_table_name)+" AND "+options[:conditions][0]
when Hash
options[:conditions][:destroyed] = 0
else
options[:conditions] = destroyed_condition(quoted_table_name)+" AND "+options[:conditions]
end
else
options[:conditions] = destroyed_condition(quoted_table_name)
end
options
end
end
module InstanceMethods
def nodestroyed?
self.respond_to? :destroyed
end
def destroy
return self.destroy_origin unless nodestroyed?
self.destroyed = true
save
end
end
end
end | mit |
miled/wordpress-social-login | hybridauth/library/src/Provider/Amazon.php | 1529 | <?php
/*!
* Hybridauth
* https://hybridauth.github.io | https://github.com/hybridauth/hybridauth
* (c) 2019 Hybridauth authors | https://hybridauth.github.io/license.html
*/
namespace Hybridauth\Provider;
use Hybridauth\Adapter\OAuth2;
use Hybridauth\Exception\UnexpectedApiResponseException;
use Hybridauth\Data;
use Hybridauth\User;
/**
* Amazon OAuth2 provider adapter.
*/
class Amazon extends OAuth2
{
/**
* {@inheritdoc}
*/
protected $scope = 'profile';
/**
* {@inheritdoc}
*/
protected $apiBaseUrl = 'https://api.amazon.com/';
/**
* {@inheritdoc}
*/
protected $authorizeUrl = 'https://www.amazon.com/ap/oa';
/**
* {@inheritdoc}
*/
protected $accessTokenUrl = 'https://api.amazon.com/auth/o2/token';
/**
* {@inheritdoc}
*/
protected $apiDocumentation = 'https://developer.amazon.com/docs/login-with-amazon/documentation-overview.html';
/**
* {@inheritdoc}
*/
public function getUserProfile()
{
$response = $this->apiRequest('user/profile');
$data = new Data\Collection($response);
if (!$data->exists('user_id')) {
throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
}
$userProfile = new User\Profile();
$userProfile->identifier = $data->get('user_id');
$userProfile->displayName = $data->get('name');
$userProfile->email = $data->get('email');
return $userProfile;
}
}
| mit |
magic-lang/magic-doc | source/frontend/tokens/TokenKind.ts | 162 | export enum TokenKind {
Unknown,
EndOfLine,
LineComment,
BlockComment,
DocComment,
Identifier,
Separator,
Operator,
Literal
}
| mit |
kevinsamyn/sportmonks-soccer | src/main/java/com/sportmonks/data/entity/TeamSeasonStatsRow.java | 1348 | package com.sportmonks.data.entity;
import com.fasterxml.jackson.annotation.*;
import java.util.HashMap;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"total", "home", "away"})
public class TeamSeasonStatsRow {
@JsonProperty("total")
private Integer total;
@JsonProperty("home")
private Integer home;
@JsonProperty("away")
private Integer away;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("total")
public Integer getTotal() {
return total;
}
@JsonProperty("total")
public void setTotal(Integer total) {
this.total = total;
}
@JsonProperty("home")
public Integer getHome() {
return home;
}
@JsonProperty("home")
public void setHome(Integer home) {
this.home = home;
}
@JsonProperty("away")
public Integer getAway() {
return away;
}
@JsonProperty("away")
public void setAway(Integer away) {
this.away = away;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
} | mit |
JonathonMA/zippo | lib/zippo/binary_structure/base.rb | 3719 | require 'zippo/binary_structure/structure_member'
require 'zippo/binary_structure/structure'
require 'zippo/binary_structure/binary_packer'
require 'zippo/binary_structure/binary_unpacker'
module Zippo
# BinaryStructure defines a class level DSL for
# implementing binary strucutures.
#
# The class will then have an ::Unpacker and ::Packer class
# defined underneath it that can be used to read and write
# the defined fields from an io.
#
# The DSL itself is fairly simple, fields are defined with
# a field name, "packing code" (per standard ruby
# Array#pack) and possibly options.
#
# - the :signature option indicates the field is a fixed
# signature
# - the :size => <field> option indicates the field is a variable
# width size field, with the size previously recorded in
# the specified field
#
# @example
# binary_structure do
# field :foo, 'L'
# field :yay, 'a4', :signature => "baz"
# field :bar, 'S'
# field :quux, 'a*', :size => :foo
# end
#
# @see Array#pack
module BinaryStructure
module Base
def binary_structure(&block)
@structure = Structure.create(self, &block)
const_set :Packer, Class.new(BinaryPacker)
self::Packer.structure = @structure
const_set :Unpacker, Class.new(BinaryUnpacker)
self::Unpacker.structure = @structure
@structure.fields.each do |field|
attr_reader field.name
if @structure.dependent? field.name
define_method "#{field.name}=" do |_value|
fail "can't mutate a dependent field"
end
else
if field.dependent
class_eval """
def #{field.name}= value
@#{field.dependent} = value.bytesize
@#{field.name} = value
end
"""
else
attr_writer field.name
end
end
end
include InstanceMethods
extend ClassMethods
Base.after_structure_definition_hooks_for(self)
end
class << self
def after_structure_definition_hooks_for(klass)
@hooks.each do |hook|
hook.call(klass)
end if @hooks
end
def after_structure_definition(&block)
@hooks ||= []
@hooks << block
end
end
module InstanceMethods
def defaults
self.class.structure.fields.each do |field|
instance_variable_set "@#{field.name}", field.options[:default] if field.options[:default]
instance_variable_set "@#{field.name}", field.options[:signature] if field.options[:signature]
end
self
end
def size
self.class.structure.fields.map do |field|
if field.dependent
send field.dependent
else
field.width
end
end.reduce(&:+)
end
def convert_to(other)
other.default.tap do |obj|
self.class.common_fields_with(other).each do |field|
obj.instance_variable_set "@#{field}", send(field)
end
end
end
end
module ClassMethods
attr_reader :structure
def default
new.defaults
end
# Returns the fields that this data type has in common with other.
#
# - common fields are fields with the same name
# - signature fields are never common
def common_fields_with(other)
structure.fields.map(&:name) &
other.structure.fields.reject(&:signature?).map(&:name)
end
end
end
end
end
| mit |
sylpheeed/blog-api-example | spec/controllers/api/registration_controller_spec.rb | 798 | require 'rails_helper'
RSpec.describe Api::RegistrationController, :type => :controller do
def user_attrs
@attrs ||= FactoryGirl.attributes_for(:user)
end
describe 'POST /api/registration' do
it 'responds successful and it includes status true and user information' do
post :create, {registration: user_attrs}
result = JSON.parse response.body
expect(response).to have_http_status(200)
expect(result['user']).not_to be_empty
expect(result['token']).not_to be_empty
end
it 'respond with status code 400 and it includes message' do
post :create, {registration: {email: 'tet', password: '1234'}}
result = JSON.parse response.body
expect(response).to have_http_status(400)
expect(result).not_to be_empty
end
end
end
| mit |
moq/moq.proxy | src/Moq.Proxy.Tests/GeneratorTests.cs | 4016 | using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Xunit.Abstractions;
using System.Reflection;
using Moq.Proxy.Templates;
using System.IO;
using System.Collections;
namespace Moq.Proxy.Tests
{
public class GeneratorTests
{
ITestOutputHelper output;
public GeneratorTests (ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void when_creating_proxy_then_it_compiles ()
{
var generator = new CsInterfaceProxy(
"Foo",
"BarProxy",
typeof(object).GetTypeInfo(),
new [] { typeof(IDictionary<string, int>).GetTypeInfo() });
var source = generator.TransformText();
File.WriteAllText ("Foo.cs", source);
var syntax = CSharpSyntaxTree.ParseText(source, path: Path.Combine(Directory.GetCurrentDirectory(), "Foo.cs"));
var compilation = CSharpCompilation.Create ("Foo",
new [] { syntax },
AppDomain.CurrentDomain.GetAssemblies()
.Where(x => File.Exists(x.ManifestModule.FullyQualifiedName))
.Select(x => MetadataReference.CreateFromFile(x.ManifestModule.FullyQualifiedName)),
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var result = compilation.Emit("Foo.dll");
if (!result.Success)
output.WriteLine (string.Join (Environment.NewLine, result.Diagnostics.Select (d => d.ToString ())));
Assert.True (result.Success);
}
public class MyDict<TKey, TValue> : IDictionary<TKey, TValue>
{
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
int ICollection<KeyValuePair<TKey, TValue>>.Count
{
get
{
throw new NotImplementedException ();
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get
{
throw new NotImplementedException ();
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
throw new NotImplementedException ();
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
throw new NotImplementedException ();
}
}
void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException ();
}
void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
{
throw new NotImplementedException ();
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear ()
{
throw new NotImplementedException ();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException ();
}
bool IDictionary<TKey, TValue>.ContainsKey (TKey key)
{
throw new NotImplementedException ();
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
throw new NotImplementedException ();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator ()
{
throw new NotImplementedException ();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException ();
}
bool IDictionary<TKey, TValue>.Remove (TKey key)
{
throw new NotImplementedException ();
}
bool IDictionary<TKey, TValue>.TryGetValue (TKey key, out TValue value)
{
throw new NotImplementedException ();
}
}
public interface IFoo
{
void Do ();
}
public interface IBar
{
void Do ();
}
public class Foo : IFoo
{
public virtual void Do () { }
}
public class DerivedFoo : Foo
{
public override void Do ()
{
base.Do ();
Action method = base.Do;
var info = method.GetMethodInfo();
Assert.Equal (info.DeclaringType, typeof (Foo));
}
}
}
}
| mit |
sadakurapati/playground | src/com/sada/misc/InfluenceFinder.java | 2244 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Sada Kurapati <sadakurapati@gmail.com>
*
* 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.
*/
package com.sada.misc;
public class InfluenceFinder {
public static void main(String[] args) {
boolean[][] followingMatrix = {
{false, true, true},
{true, false, false},
{false, true, false}};
System.out.println(getInfluencer(followingMatrix));
}
public static int getInfluencer(boolean[][] followingMatrix) {
for (int j = 0; j < followingMatrix.length; j++) {
if (isEveryBodyFollowingMe(followingMatrix, j) && !amIFollowingAnybody(followingMatrix, j)) {
return j;
}
}
return -1;
}
private static boolean isEveryBodyFollowingMe(boolean[][] matrix, int j) {
for (int i = 0; i < matrix.length; i++) {
if (i != j && !matrix[i][j]) return false;
}
return true;
}
private static boolean amIFollowingAnybody(boolean[][] matrix, int j) {
for (int i = 0; i < matrix.length; i++) {
if (i != j && matrix[j][i]) return true;
}
return false;
}
}
| mit |
CS2103JAN2017-T09-B4/main | src/main/java/seedu/tache/commons/events/ui/CalendarNextRequestEvent.java | 351 | //@@author A0142255M
package seedu.tache.commons.events.ui;
import seedu.tache.commons.events.BaseEvent;
/**
* Indicates a request to view the next day / week / month at the calendar.
*/
public class CalendarNextRequestEvent extends BaseEvent {
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| mit |
softcover/polytexnic | lib/polytexnic/literal.rb | 10554 | module Polytexnic
module Literal
extend self
# Matches the line for syntax highlighting.
# %= lang: <language>[, options: ...]
LANG_REGEX = /^\s*%=\s+lang:\s*([\w+]+)(?:,\s*options:(.*))?/
# Makes the caches for literal environments.
def cache_literal(polytex, format = :html)
output = []
lines = polytex.split("\n")
cache_literal_environments(lines, output, format)
output.join("\n")
end
# Returns supported math environments.
# Note that the custom AMS-TeX environments are supported
# in addition to the LaTeX defaults.
def math_environments
%w[align align*
eqnarray eqnarray* equation equation*
gather gather* gathered
multline multline*
]
end
# Returns a list of all literal types.
def literal_types
%w[verbatim Vertatim code metacode] + math_environments
end
# Handles environments that should be passed through the pipeline intact.
# The includes verbatim environments ('verbatim', 'Verbatim') and all the
# equation environments handled by MathJax ('equation', 'align', etc.).
# We take care to keep count of the number of begins we see so that the
# code handles nested environments correctly. I.e.,
# \begin{verbatim}
# \begin{verbatim}
# \emph{foo bar}
# \end{verbatim}
# \end{verbatim}
# lorem ipsum
# includes the internal literal text without stopping after the first
# \end{verbatim}.
#
# The control flow here is really nasty, but attempts to refactor it
# into a multi-pass solution have only resulted in even more complexity,
# and even then I've failed to get it to work. Thus, it shall for now
# follow the "ball of mud" pattern. (The only saving grace is that it's
# very thoroughly tested.)
def cache_literal_environments(lines, output, format, cache = nil)
latex = (format == :latex)
language = nil
in_verbatim = false
in_codelisting = false
while (line = lines.shift)
if line =~ LANG_REGEX && !in_verbatim
language = $1
highlight_options = $2
elsif line =~ /\s*\\begin\{codelisting\}/ && !in_verbatim
in_codelisting = true
output << line
elsif line =~ /\s*\\end\{codelisting\}/ && !in_verbatim
in_codelisting = false
output << line
elsif (included_code = CodeInclusion::Code.for(line)) && !in_verbatim
# Reduce to a previously solved problem.
# We transform
# %= <<(/path/to/file.rb)
# to
# %= lang:rb
# \begin{code}
# <content of file or section.rb>
# \end{code}
# and then prepend the code to the current `lines` array.
lines.unshift(*included_code.to_s)
elsif line.begin_literal?
in_verbatim = true
literal_type = line.literal_type
skip = line.math_environment? || latex
if line.math_environment? && !latex
output << '\begin{xmlelement*}{equation}'
output << '\begin{equation}'
end
math = line.math_environment?
label = nil
output << xmlelement(element(literal_type), skip) do
count = 1
text = []
text << line if line.math_environment? || (latex && !language)
while (line = lines.shift)
if line.begin_literal?(literal_type)
count += 1
elsif line.end_literal?(literal_type)
count -= 1
if count.zero?
in_verbatim = false
text << line if line.math_environment? || (latex && !language)
break
end
end
label = line if math && line =~ /^\s*\\label{.*?}\s*$/
text << line
end
raise "Missing \\end{#{line.literal_type}}" if count != 0
content = text.join("\n")
if math
key = digest(content)
literal_cache[key] = content
elsif language.nil?
key = digest(content)
literal_cache[key] = content
tag = 'literal'
else
format = latex ? 'latex' : 'html'
id = "#{content}--#{language}--#{format}--#{in_codelisting}--#{highlight_options}"
key = digest(id, salt: code_salt)
code_cache[key] = [content, language, in_codelisting, highlight_options]
tag = 'code'
end
if latex || tag == 'code' || math
key
else
xmlelement(tag) { key }
end
end
if math && !latex
unless label.nil?
key = digest(label)
math_label_cache[key] = label
output << key
end
output << '\end{equation}'
unless label.nil?
string = label.scan(/\{(.*?)\}/).flatten.first
string = string.gsub(':', '-').gsub('_', underscore_digest)
output << "\\xbox{data-label}{#{string}}"
end
output << '\end{xmlelement*}'
end
language = nil
(output << '') unless latex # Force the next element to be a paragraph
else
output << line
end
end
end
# Returns a permanent salt for the syntax highlighting cache.
def code_salt
'fbbc13ed4a51e27608037365e1d27a5f992b6339'
end
# Caches both display and inline math.
def cache_display_inline_math(output)
output.tap do
cache_display_math(output)
cache_inline_math(output)
end
end
# Caches display math.
# We support both TeX-style $$...$$ and LaTeX-style \[ ... \].
def cache_display_math(output)
output.gsub!(/\\\[(.*?)\\\]|\$\$(.*?)\$\$/m) do
math = "\\[ #{$1 || $2} \\]"
equation_element(math)
end
end
# Returns an equation element while caching the given content.
# We use this only for unnumbered, display equations, which requires using
# the `equation*` environment in place of `equation`.
def equation_element(content)
key = digest(content)
literal_cache[key] = content
"\\begin{xmlelement*}{equation}
\\begin{equation*}
#{key}
\\end{equation*}
\\end{xmlelement*}"
end
# Caches inline math.
# We support both TeX-style $...$ and LaTeX-style \( ... \).
# There's an annoying edge case involving literal dollar signs, as in \$.
# Handling it significantly complicates the regex, and necessesitates
# introducing an additional group to catch the character before the math
# dollar sign in $2 and prepend it to the inline math element.
def cache_inline_math(output)
output.gsub!(/(?:\\\((.*?)\\\)|([^\\]|^)\$(.*?[^\\])\$)/m) do
math = "\\( #{$1 || $3} \\)"
key = digest(math)
literal_cache[key] = math
$2.to_s + xmlelement('inline') { key }
end
end
# Converts references to hyperrefs.
# We want to convert
# Chapter~\ref{cha:foo}
# to
# \hyperref[cha:foo]{Chapter~\ref{cha:foo}
# which is then handled by LaTeX's hyperref package
# or by Tralics (where it converted to a link
# by the postprocessor).
# For completeness, we handle the case where the author neglects to
# use the nonbreak space ~.
def hyperrefs(string)
part = language_labels["part"]
chapter = language_labels["chapter"]["word"]
section = language_labels["section"]
appendix = language_labels["appendix"]
table = language_labels["table"]
box = language_labels["aside"]
figure = language_labels["figure"]
fig = language_labels["fig"]
listing = language_labels["listing"]
equation = language_labels["equation"]
eq = language_labels["eq"]
linked_item = "(#{part}|#{chapter}|#{section}|#{appendix}|#{table}|#{box}|#{figure}" +
"|#{fig}\.|#{listing}|#{equation}|#{eq}\.)"
ref = /(?:#{linked_item}(~| ))*(\\(?:eq)*ref){(.*?)}/i
string.gsub!(ref) do
"\\hyperref[#{$4}]{#{$1}#{$2}#{$3}{#{$4}}}"
end
end
# Handles non-ASCII Unicode characters.
# The Tralics part of the pipeline doesn't properly handle Unicode,
# which is odd since Tralics is a French project. Nevertheless,
# we can hack around the restriction by treating non-ASCII Unicode
# characters as literal elements and simply pass them through the
# pipeline intact.
def cache_unicode(string)
non_ascii_unicode = /([^\x00-\x7F]+)/
string.gsub!(non_ascii_unicode) do
key = digest($1)
unicode_cache[key] = $1
key
end
end
def element(literal_type)
if math_environments.include?(literal_type)
'equation'
else
literal_type
end
end
end
end
class String
include Polytexnic::Literal
# Returns true if self matches \begin{...} where ... is a literal environment.
# Note: Support for the 'metacode' environment exists solely to allow
# meta-discussion of the 'code' environment.
def begin_literal?(literal_type = nil)
return false unless include?('\begin')
literal_type ||= "(?:verbatim|Verbatim|code|metacode|" +
"#{math_environment_regex})"
match(/^\s*\\begin{#{literal_type}}\s*$/)
end
# Returns true if self matches \end{...} where ... is a literal environment.
def end_literal?(literal_type)
return false unless include?('\end')
match(/^\s*\\end{#{Regexp.escape(literal_type)}}\s*$/)
end
# Returns the type of literal environment.
# '\begin{verbatim}' => 'verbatim'
# '\begin{equation}' => 'equation'
# '\[' => 'display'
def literal_type
scan(/\\begin{(.*?)}/).flatten.first || 'display'
end
# Returns true if self begins a math environment.
def begin_math?
return false unless include?('\begin')
literal_type = "(?:#{math_environment_regex})"
match(/^\s*\\begin{#{literal_type}}\s*$/)
end
# Returns true if self matches a valid math environment.
def math_environment?
match(/(?:#{math_environment_regex})/)
end
private
# Returns a regex matching valid math environments.
def math_environment_regex
Polytexnic::Literal.math_environments.map do |s|
Regexp.escape(s)
end.join('|')
end
end
| mit |
plewis/phycas | src/python/probdist/_Lot.py | 3218 | from _ProbDistExt import *
class Lot(LotBase):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
Lot is the pseudorandom number generator used in Phycas. It is based
on code written by J. Monahan, Statistics Department, North Carolina
State University, and published in the first (1990) edition of Bruce
Weir's Genetic Data Analysis (Sinauer, Sunderland, Massachusetts).
Based on Schrage. 1979. ACM Trans. Math. Software 5:132-138.
Translated to C++ by Paul O. Lewis, Dec. 10, 1992.
This class was called Lot because the noun lot is defined as "an
object used in deciding something by chance" according to The New
Merriam-Webster Dictionary.
"""
def __init__(self, seed = 0):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
Creates a Lot object initialized using the specified psuedorandom
number seed. If seed is the default value (0), the actual seed used
is taken from the system clock.
>>> from phycas.probdist import *
>>> r1 = Lot(3157)
>>> print r1.getInitSeed()
3157
>>> r2 = Lot() # this would seed r2 using the system clock
"""
LotBase.__init__(self, seed)
def setSeed(self, rnseed):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
Sets the pseudorandom number seed. Useful if you want to regenerate
a sequence of pseudorandom numbers identical to a sequence that you
have previously generated.
>>> from phycas.probdist import *
>>> lot = Lot()
>>> lot.setSeed(1357)
>>> lot.getSeed()
1357
"""
return LotBase.setSeed(self, rnseed)
def getSeed(self):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
Returns the current pseudorandom number seed. Call this function
and store the result before generating a sequence of pseudorandom
numbers if you want to later regenerate the same sequence.
"""
return LotBase.getSeed(self)
def getInitSeed(self):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
Returns the pseudorandom number seed set upon construction of this
Lot object using the system clock or, if setSeed has been called,
returns the seed specified in the most recent call to setSeed.
>>> from phycas.probdist import *
>>> lot = Lot()
>>> lot.setSeed(1357)
>>> lot.getInitSeed()
1357
"""
return LotBase.getInitSeed(self)
def uniform(self):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
Returns a pseudorandom number between 0.0 and 1.0.
"""
#from phycas import Phycas
return LotBase.uniform(self)
def sampleUInt(self, upper_bound):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
Returns a pseudorandom integer i such that 0 <= i < upper_bound.
"""
return LotBase.sampleUInt(self, upper_bound)
| mit |
krues8dr/lazuli | lib/install.js | 965 | 'use strict';
const repoManager = require('./pkgmanager/repoManager');
const pLimit = require('p-limit');
class Install {
constructor(options) {
// Todo: allow multiple repos for mods.
this.manager = new repoManager(options);
this.limit = pLimit(options.plimit || 5);
}
async init(args) {
return this.manager.init();
}
async shutdown(args) {
return this.manager.shutdown();
}
clear() {
this.manager.clear();
}
// mods argument can be:
// an object {'name1' => 'version1', 'name2', => 'version2'}
// or a list [['name1', 'version1'], ['name2', 'version2']]
run(mods) {
let promises = [];
if(mods) {
if(!Array.isArray(mods) && typeof mods === 'object') {
mods = Object.entries(mods);
}
for(let [mod, version] of mods) {
promises.push(this.limit(() => this.manager.install(mod, version)));
}
}
return Promise.all(promises);
}
}
module.exports = Install; | mit |
msotiroff/Programming-FUNDAMENTALS | HomeWorks/Arrays/4. Grab and Go/Program.cs | 993 | using System;
using System.Linq;
namespace _4.Grab_and_Go
{
class Program
{
static void Main(string[] args)
{
long[] inputNumbers = Console.ReadLine()
.Split(' ')
.Select(long.Parse)
.ToArray();
int n = int.Parse(Console.ReadLine());
long sum = 0;
bool foundN = false;
for (int i = inputNumbers.Length - 1; i >= 0; i--)
{
if (n == inputNumbers[i])
{
foundN = true;
for (int j = i - 1; j >= 0; j--)
{
sum += inputNumbers[j];
}
break;
}
}
if (foundN)
{
Console.WriteLine(sum);
}
else
{
Console.WriteLine("No occurrences were found!");
}
}
}
}
| mit |
kurraz-soft/prj-jack | modules/game/models/game_data/AttributesListCharacter.php | 1627 | <?php
/**
* Created by PhpStorm.
* User: Kurraz
*/
namespace app\modules\game\models\game_data;
use app\modules\game\models\game_data\attributes\BeautyMale;
use app\modules\game\models\game_data\attributes\GuildRepo;
use app\modules\game\models\game_data\attributes\HealthMale;
use app\modules\game\models\game_data\attributes\HygieneMale;
use app\modules\game\models\game_data\attributes\Libido;
use app\modules\game\models\game_data\attributes\Lifestyle;
use app\modules\game\models\game_data\attributes\Mark;
use app\modules\game\models\game_data\attributes\PersonalityMale;
use app\modules\game\models\game_data\attributes\StrengthMale;
use app\modules\game\models\game_data\base\BaseGameDataList;
/**
* Class AttributesListCharacter
* @package app\modules\game\models\game_data
*
* @property HealthMale $health
* @property StrengthMale $strength
* @property PersonalityMale $personality
* @property BeautyMale $beauty
* @property Libido $libido
* @property Mark $mark
* @property GuildRepo $guildRep
* @property Lifestyle $lifestyle
* @property HygieneMale $hygiene
*/
class AttributesListCharacter extends BaseGameDataList
{
public function serializableParams()
{
return [
'health' => HealthMale::class,
'strength' => StrengthMale::class,
'personality' => PersonalityMale::class,
'beauty' => BeautyMale::class,
'libido' => Libido::class,
'mark' => Mark::class,
'guildRep' => GuildRepo::class,
'lifestyle' => Lifestyle::class,
'hygiene' => HygieneMale::class,
];
}
} | mit |
gilt/ubar | js/ubar/tracking.js | 4429 | (function(exports, moduleName) {
'use strict';
function create (pubsub) {
/**
* Tracking:
*
* This module exists so that you can tie your
* existing tracking system into the UBAR system.
* The following events are called at various times
* during the workflow. All you have to do is include
* your app's specific tracking in the methods below.
*
* With this data, you can run analytics that tell you
* the percentage of people who opt into UBAR as
* well as the drop-off points.
*
* You can also use the data to better inform yourself
* as to whether the user has your app installed or not.
*
*/
/**
* Called when the user elects to opt into the
* UBAR feature. Publish event with key 'ubarTurnedOn'.
*
* @public
* @method: _turnUbarOn
* @param {Object} {location : 'where this was called'}
*
*/
function _turnUbarOn ( trackingLocationObject ) {
pubsub.publish('turnedUbarOn', trackingLocationObject);
}
/**
* Called when the user elects to opt out of the
* UBAR feature. Publish event with key 'ubarTurnedOff'.
*
* @public
* @method: _turnUbarOff
* @param {Object} {location : 'where this was called'}
*
*/
function _turnUbarOff ( trackingLocationObject ) {
pubsub.publish('turnedUbarOff', trackingLocationObject);
}
/**
* Called when the user elects to download the app.
* Publish event with key 'choseDownloadApp'.
*
* @public
* @method: _choseDownloadApp
* @param {Object} {location : 'where this was called'}
*
*/
function _choseDownloadApp (trackingLocationObject) {
pubsub.publish('choseDownloadApp', trackingLocationObject);
}
/**
* Called when the user closes the Ubar banner.
* Publish event with key 'closedBanner'.
*
* @public
* @method: _closeBanner
* @param {Object} {location : 'where this was called'}
*
*/
function _closeBanner (trackingLocationObject) {
pubsub.publish('closedBanner', trackingLocationObject);
}
/**
* Called when the user elects to return to the app.
* Publish event with key 'returnedToApp'.
*
* @public
* @method: _returnToApp
* @param {Object} {location : 'where this was called'}
*
*/
function _returnToApp (trackingLocationObject) {
pubsub.publish('returnedToApp', trackingLocationObject);
}
/**
* Called when an attempt has been made to redirect the
* user to the appstore to download your app.
* Publish event with key 'attemptedToRedirectToAppStore'.
*
* @public
* @method: _attemptToRedirectToAppStore
* @param {Object} { location : 'where this was called'}
*/
function _attemptToRedirectToAppStore ( trackingLocationObject ) {
pubsub.publish('attemptedToRedirectToAppStore', trackingLocationObject);
}
/**
* Called when an attempt has been made to redirect the
* user into the app. Publish event with key 'attemptedToRedirectToApp'.
*
* @public
* @method: _attemptToRedirectToAppStore
* @param {Object} { location : 'where this was called'}
*/
function _attemptToRedirectToApp ( trackingLocationObject ) {
pubsub.publish('attemptedToRedirectToApp', trackingLocationObject);
}
/**
* Called when an ubar banner is displayed to the user.
* Publish event with key 'showedBanner'.
*
* @public
* @method: _showBanner
* @param {Object} { location : 'where this was called'}
*/
function _showBanner ( trackingLocationObject ) {
pubsub.publish('showedBanner', trackingLocationObject);
}
return {
turnUbarOn: _turnUbarOn,
turnUbarOff: _turnUbarOff,
choseDownloadApp : _choseDownloadApp,
closeBanner : _closeBanner,
returnToApp : _returnToApp,
attemptToRedirectToAppStore: _attemptToRedirectToAppStore,
attemptToRedirectToApp: _attemptToRedirectToApp,
showBanner: _showBanner
};
}
if (typeof define === 'function' && define.amd) {
define(moduleName, ['./pubsub'], create);
} else if (typeof module === 'object' && module.exports) {
/*
Using CommonJS syntax, we have to explicitly require each
module because browserify uses static module analysis.
*/
module.exports = create(require('./pubsub'));
} else {
/*
Gilt build syntax. 'exports' variable could be window here
or an empty object, as in Gilt's case
*/
exports[moduleName] = create(
exports.ubar_pubsub || ubar_pubsub
);
}
}(typeof exports === 'object' && exports || this, 'ubar_tracking' /* moduleName */));
| mit |
JBZoo/JBZoo-CCK-Free | packages/jbuniversal/jbuniversal/framework/helpers/jbhtml.php | 14156 | <?php
/**
* JBZoo is universal CCK, application for YooTheme Zoo component
* @package JBZoo
* @author JBZoo App http://jbzoo.com
* @copyright Copyright (C) JBZoo.com
* @license http://www.gnu.org/licenses/gpl.html GNU/GPL
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
class JBHTMLHelper extends AppHelper {
/**
* Render option list
* @param $data
* @param $name
* @param null $attribs
* @param null $selected
* @param bool $idtag
* @param bool $translate
* @return string
*/
public function radio(
$data,
$name,
$attribs = null,
$selected = null,
$idtag = false,
$translate = false
)
{
if (empty($data)) {
return null;
}
$attribs = $this->_buildAttrs($attribs);
return $this->_list('radio', $data, $name, $attribs, $selected, $idtag, $translate);
}
/**
* Render checkbox list
* @param $data
* @param $name
* @param null $attribs
* @param null $selected
* @param bool $idtag
* @param bool $translate
* @return string
*/
public function checkbox(
$data,
$name,
$attribs = null,
$selected = null,
$idtag = false,
$translate = false
)
{
if (empty($data)) {
return null;
}
if ($idtag) {
$attribs['id'] = $idtag;
}
$attribs = $this->_buildAttrs($attribs);
return $this->_list('checkbox', $data, $name, $attribs, $selected, $idtag, $translate);
}
/**
* Render select list
* @param $data
* @param $name
* @param null $attribs
* @param null $selected
* @param bool $idtag
* @param bool $translate
* @return string
*/
public function select(
$data,
$name,
$attribs = null,
$selected = null,
$idtag = false,
$translate = false
)
{
if (empty($data)) {
return null;
}
if ($idtag) {
$attribs['id'] = $idtag;
}
if (isset($attribs['multiple']) && $attribs['multiple'] == 'multiple') {
$name = $name . '[]';
}
$attribs = $this->_buildAttrs($attribs);
return $this->app->html->_('zoo.genericlist', $data, $name, $attribs, 'value', 'text', $selected, $idtag, $translate);
}
/**
* Render text field
* @param $name
* @param null $value
* @param null $attribs
* @param null $idtag
* @return string
*/
public function text($name, $value = null, $attribs = null, $idtag = null)
{
if ($idtag) {
$attribs['id'] = $idtag;
}
$attribs = $this->_buildAttrs($attribs);
if (strpos($attribs, 'jsAutocomplete') !== false) {
$this->app->jbassets->jqueryui();
$this->app->jbassets->initAutocomplete();
}
return $this->app->html->_('control.text', $name, $value, $attribs);
}
/**
* Render hidden field
* @param $name
* @param null $value
* @param null $attribs
* @param null $idtag
* @return string
*/
public function hidden($name, $value = null, $attribs = null, $idtag = null)
{
if ($idtag) {
$attribs['id'] = $idtag;
}
$attribs = $this->_buildAttrs($attribs);
$value = $this->cleanAttrValue($value);
return '<input type="hidden" name="' . $name . '" ' . $attribs . ' value="' . $value . '" />';
}
/**
* Render calendar element
* @param $name
* @param null $value
* @param null $attribs
* @param null $idtag
* @param array $params
* @return string
*/
public function calendar($name, $value = null, $attribs = null, $idtag = null, $params = array())
{
if ($idtag) {
$attribs['id'] = $idtag;
}
$params['dateFormat'] = trim($params['dateFormat']);
$this->app->jbassets->jqueryui();
$this->app->jbassets->addScript('jQuery(function($){
$("#' . $idtag . '").datepicker(' . json_encode($params) . ');
});');
return $this->text($name, $value, $attribs, $idtag);
}
/**
* Render jQueryUI slider
* @param array $params
* @param string $value
* @param string $name
* @param string $idtag
* @return string
*/
public function slider($params, $value = '', $name = '', $idtag = '')
{
if (!empty($value)) {
$value = explode('/', $value);
} else {
$value = array($params['min'], $params['max']);
}
$this->app->jbassets->jqueryui();
$this->app->jbassets->addScript('jQuery(function($){
$("#' . $idtag . '-wrapper").removeAttr("slide");
$("#' . $idtag . '-wrapper")[0].slide = null;
$("#' . $idtag . '-wrapper").slider({
"range" : true,
"min" : ' . ((float)$params['min'] ? (float)$params['min'] : 0) . ',
"max" : ' . ((float)$params['max'] ? (float)$params['max'] : 10000) . ',
"step" : ' . ((float)$params['step'] ? (float)$params['step'] : 100) . ',
"values": [' . (float)$value['0'] . ', ' . (float)$value['1'] . '],
"slide" : function(event,ui) {
$("#' . $idtag . '-value").val(ui.values[0] + "/" + ui.values[1]);
$("#' . $idtag . '-value-0").html(ui.values[0]);
$("#' . $idtag . '-value-1").html(ui.values[1]);
}
});
$("#' . $idtag . '-value").val(' . (float)$value['0'] . '+ "/" +' . (float)$value['1'] . ');
});');
return '<div id="' . $idtag . '-wrapper"> </div>' . "\n"
. '<span id="' . $idtag . '-value-0" class="slider-value-0">' . (float)$value['0'] . '</span>' . "\n"
. '<span id="' . $idtag . '-value-1" class="slider-value-1">' . (float)$value['1'] . '</span>' . "\n"
. '<input type="hidden" id="' . $idtag . '-value" name="' . $name . '" />' . "\n";
}
/**
* Render option list
* @param $data
* @param $name
* @param null $attribs
* @param null $selected
* @param bool $idtag
* @param bool $translate
* @return string
*/
public function buttonsJqueryUI(
$data,
$name,
$attribs = null,
$selected = null,
$idtag = false,
$translate = false
)
{
if (isset($attribs['multiple'])) {
$html = $this->checkbox($data, $name, $attribs, $selected, $idtag, $translate);
} else {
$html = $this->radio($data, $name, $attribs, $selected, $idtag, $translate);
}
$this->app->jbassets->jqueryui();
$this->app->jbassets->addScript('jQuery(function($){
$("#' . $idtag . '-wrapper' . '").buttonset();
});');
return '<div id="' . $idtag . '-wrapper">' . $html . '</div>';
}
/**
* Render chosen
* @param $data
* @param $name
* @param null $attribs
* @param null $selected
* @param bool $idtag
* @param bool $translate
* @return string
*/
public function selectChosen(
$data,
$name,
$attribs = null,
$selected = null,
$idtag = false,
$translate = false
)
{
$this->app->jbassets->chosen();
$this->app->jbassets->addScript('jQuery(function($){
$("#' . $idtag . '").chosen();
});');
return $this->select($data, $name, $attribs, $selected, $idtag, $translate);
}
/**
* Select cascade
* @param array $selectInfo
* @param string $name
* @param array $selected
* @param array $attribs
* @param bool $idtag
* @return string
*/
public function selectCascade(
$selectInfo,
$name,
$selected = array(),
$attribs = null,
$idtag = false)
{
$itemList = $selectInfo['items'];
$maxLevel = $selectInfo['maxLevel'];
$listNames = $selectInfo['names'];
$uniqId = uniqid();
$deepLevelCheck = $deepLevel = 0;
$html = array();
for ($i = 0; $i <= $maxLevel; $i++) {
$value = isset($selected[$i]) ? $selected[$i] : null;
$attrs = array(
'class' => 'jbselect-' . $i,
'name' => $name . '[]',
'list-order' => $i,
'disabled' => 'disabled',
'id' => 'jbselect-' . $i . '-' . $uniqId,
);
$html[] = '<div>';
$html[] = '<label for="' . $attrs['id'] . '">' . $listNames[$i] . '</label>';
$html[] = '<select ' . $this->app->jbhtml->buildAttrs($attrs) . '>';
$html[] = '<option value=""> - </option>';
if ($deepLevelCheck == $deepLevel) {
$deepLevelCheck++;
foreach ($itemList as $key => $item) {
if ($value == $key) {
$html[] = '<option value="' . $key . '" selected="selected">' . $key . '</option>';
} else {
$html[] = '<option value="' . $key . '">' . $key . '</option>';
}
}
}
if (isset($itemList[$value])) {
$itemList = $itemList[$value];
$deepLevel++;
}
if (isset($selectInfo['items'][$value]) && !empty($selectInfo['items'][$value])) {
$tmpItems = $selectInfo['items'][$value];
}
$html[] = '</select></div>';
}
$this->app->jbassets->initSelectCascade();
$this->app->jbassets->initJBCascadeSelect($uniqId, $selectInfo['items']);
$attribs['class'][] = 'jbcascadeselect';
return '<div class="jbcascadeselect-wrapper jbcascadeselect-' . $uniqId . '">'
. '<div ' . $this->app->jbhtml->buildAttrs($attribs) . '>'
. implode(" ", $html)
. '</div></div>';
}
/**
* Generates an HTML checkbox/radio list.
* @param string $inputType Type of html input element
* @param array $data An array of objects
* @param string $name The value of the HTML name attribute
* @param string $attribs Additional HTML attributes for the <select> tag
* @param string $selected The name of the object variable for the option text
* @param boolean $idtag Value of the field id or null by default
* @param boolean $translate True if options will be translated
* @param boolean $isLabelWrap True if options wrappeed label tag
* @return string HTML for the select list
*/
private function _list($inputType, $data, $name, $attribs = null, $selected = null, $idtag = false,
$translate = false, $isLabelWrap = false
)
{
reset($data);
if (is_array($attribs)) {
$attribs = $this->_buildAttrs($attribs);
}
$idText = $idtag ? $idtag : $name;
if ($inputType == 'checkbox') {
$name = $name . '[]';
}
$html = array();
foreach ($data as $obj) {
$value = $obj->value;
$text = $translate ? JText::_($obj->text) : $obj->text;
$id = (isset($obj->id) ? $obj->id : null);
$extra = array(
'value' => $value,
'name' => $name,
'type' => $inputType,
'id' => $idText . $value,
);
if (is_array($selected)) {
foreach ($selected as $val) {
if ($value == $val) {
$extra['checked'] = 'checked';
break;
}
}
} else {
if ((string)$value == (string)$selected) {
$extra['checked'] = 'checked';
}
}
$extraLabel = array(
'for' => $extra['id'],
'class' => $inputType . '-lbl',
);
if ($isLabelWrap) {
$html[] = '<label ' . $this->_buildAttrs($extraLabel) . '>'
. '<input ' . $this->_buildAttrs($extra) . ' />'
. $text . '</label>';
} else {
$html[] = '<input ' . $this->_buildAttrs($extra) . ' />'
. '<label ' . $this->_buildAttrs($extraLabel) . '>' . $text . '</label>';
}
}
return implode("\n\t", $html);
}
/**
* Build attrs
* @param $attrs
* @return null|string
*/
public function buildAttrs($attrs)
{
return $this->_buildAttrs($attrs);
}
/**
* Build attrs
* TODO: Remove method, replace to public
* @param $attrs
* @return null|string
*/
protected function _buildAttrs($attrs)
{
$result = ' ';
if (is_string($attrs)) {
$result .= $attrs;
} elseif (!empty($attrs)) {
foreach ($attrs as $key => $param) {
$param = (array)$param;
$value = $this->cleanAttrValue(implode(' ', $param));
if (!empty($value) || $value == '0' || $key == 'value') {
$result .= ' ' . $key . '="' . $value . '"';
}
}
}
return JString::trim($result);
}
/**
* Clear attribute value
* @param string $value
* @return string
*/
public function cleanAttrValue($value)
{
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
$value = JString::trim($value);
return $value;
}
} | mit |
johnsnow91/myBlog | app/cache/dev/twig/d/b/db5cf5f2365d7c9271ad0fb42b031ea70f93865870fe2e75ad43955a0a6e8185.php | 2951 | <?php
/* @WebProfiler/Profiler/toolbar_item.html.twig */
class __TwigTemplate_db5cf5f2365d7c9271ad0fb42b031ea70f93865870fe2e75ad43955a0a6e8185 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_091ba015591fad0133be25f088f39d74b553faa4a17a42ec4e97c0eb215aadc4 = $this->env->getExtension("native_profiler");
$__internal_091ba015591fad0133be25f088f39d74b553faa4a17a42ec4e97c0eb215aadc4->enter($__internal_091ba015591fad0133be25f088f39d74b553faa4a17a42ec4e97c0eb215aadc4_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@WebProfiler/Profiler/toolbar_item.html.twig"));
// line 1
if ((isset($context["link"]) ? $context["link"] : $this->getContext($context, "link"))) {
// line 2
echo " ";
ob_start();
// line 3
echo " <a href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_profiler", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "panel" => (isset($context["name"]) ? $context["name"] : $this->getContext($context, "name")))), "html", null, true);
echo "\">";
echo twig_escape_filter($this->env, (isset($context["icon"]) ? $context["icon"] : $this->getContext($context, "icon")), "html", null, true);
echo "</a>
";
$context["icon"] = ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
}
// line 6
echo "<div class=\"sf-toolbar-block\">
<div class=\"sf-toolbar-icon\">";
// line 7
echo twig_escape_filter($this->env, ((array_key_exists("icon", $context)) ? (_twig_default_filter((isset($context["icon"]) ? $context["icon"] : $this->getContext($context, "icon")), "")) : ("")), "html", null, true);
echo "</div>
<div class=\"sf-toolbar-info\">";
// line 8
echo twig_escape_filter($this->env, ((array_key_exists("text", $context)) ? (_twig_default_filter((isset($context["text"]) ? $context["text"] : $this->getContext($context, "text")), "")) : ("")), "html", null, true);
echo "</div>
</div>
";
$__internal_091ba015591fad0133be25f088f39d74b553faa4a17a42ec4e97c0eb215aadc4->leave($__internal_091ba015591fad0133be25f088f39d74b553faa4a17a42ec4e97c0eb215aadc4_prof);
}
public function getTemplateName()
{
return "@WebProfiler/Profiler/toolbar_item.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 43 => 8, 39 => 7, 36 => 6, 27 => 3, 24 => 2, 22 => 1,);
}
}
| mit |
Kalvar/MLKNN | ml_distance_kernel.rb | 86 | module MLDistanceKernel
COSINE_SIMILARITY = 0
ECULIDEAN = 1
RBF = 2
end | mit |
syfo/jcropper | lib/jcropper/cropped_image.rb | 1749 | module JCropper
class CroppedImage
attr_reader :original_geometry, :cropped_geometry, :attachment_name, :style_name, :coord_names, :starting_crop, :attachment, :options
def initialize(object, options)
@object = object
@options = options
@attachment_name = object.class.jcropper_defs[:attachment]
@style_name = object.jcropper_defs[:style]
@attachment = object.send(attachment_name)
@coord_names = {}
%w(x y w h).each{|v| @coord_names[v.to_sym] = JCropper.jattr(attachment_name, style_name, v)}
@starting_crop = @coord_names.inject({}) {|h,pair| h.merge({ pair[0] => object.send("#{pair[1].to_s}_was") }) }
end
###CRZ these two might get out of date...
def original_geometry
if attachment.to_file(:original) and File.exists? attachment.to_file(:original)
@original_geometry ||= Paperclip::Geometry.from_file(attachment.to_file(:original))
else
nil
end
end
def target_geometry
@target_geometry ||= Paperclip::Geometry.parse(@object.send(attachment_name).styles[style_name.to_sym][:geometry])
end
def max_crop
if options[:maintain_aspect_ratio]
north_center_gravity_max_crop
else
[0, 0, original_geometry.width, original_geometry.height]
end
end
def north_center_gravity_max_crop
scale = JCropper.find_bounding_scale([original_geometry.width, original_geometry.height], [target_geometry.width, target_geometry.height])
final_size = {:width => scale*target_geometry.width, :height => scale*target_geometry.height}
[(original_geometry.width - final_size[:width]) / 2, 0, final_size[:width], final_size[:height]].map &:to_i
end
end
end | mit |
sqdron/sqdron.UI | src/layouts/index.js | 37 | export Master from './Master/Master'
| mit |
nubbel/swift-tensorflow | NodeGenerated/oprequest.js | 50349 | /**
* @fileoverview
* @enhanceable
* @public
*/
// GENERATED CODE -- DO NOT EDIT!
goog.provide('proto.xla.OpRequest');
goog.require('jspb.Message');
goog.require('jspb.BinaryReader');
goog.require('jspb.BinaryWriter');
goog.require('proto.xla.BinaryOpRequest');
goog.require('proto.xla.BroadcastRequest');
goog.require('proto.xla.CallRequest');
goog.require('proto.xla.ComputationHandle');
goog.require('proto.xla.ConcatenateRequest');
goog.require('proto.xla.ConstantRequest');
goog.require('proto.xla.ConvertRequest');
goog.require('proto.xla.ConvolveRequest');
goog.require('proto.xla.CrossReplicaSumRequest');
goog.require('proto.xla.CustomCallRequest');
goog.require('proto.xla.DynamicSliceRequest');
goog.require('proto.xla.DynamicUpdateSliceRequest');
goog.require('proto.xla.GetTupleElementRequest');
goog.require('proto.xla.InfeedRequest');
goog.require('proto.xla.MapRequest');
goog.require('proto.xla.OpMetadata');
goog.require('proto.xla.OutfeedRequest');
goog.require('proto.xla.PadRequest');
goog.require('proto.xla.ParameterRequest');
goog.require('proto.xla.RecvRequest');
goog.require('proto.xla.ReduceRequest');
goog.require('proto.xla.ReduceWindowRequest');
goog.require('proto.xla.ReshapeRequest');
goog.require('proto.xla.ReverseRequest');
goog.require('proto.xla.RngRequest');
goog.require('proto.xla.SelectAndScatterRequest');
goog.require('proto.xla.SendRequest');
goog.require('proto.xla.SliceRequest');
goog.require('proto.xla.TernaryOpRequest');
goog.require('proto.xla.TraceRequest');
goog.require('proto.xla.TransposeRequest');
goog.require('proto.xla.UnaryOpRequest');
goog.require('proto.xla.VariadicOpRequest');
goog.require('proto.xla.WhileRequest');
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.xla.OpRequest = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, proto.xla.OpRequest.oneofGroups_);
};
goog.inherits(proto.xla.OpRequest, jspb.Message);
if (goog.DEBUG && !COMPILED) {
proto.xla.OpRequest.displayName = 'proto.xla.OpRequest';
}
/**
* Oneof group definitions for this message. Each group defines the field
* numbers belonging to that group. When of these fields' value is set, all
* other fields in the group are cleared. During deserialization, if multiple
* fields are encountered for a group, only the last value seen will be kept.
* @private {!Array<!Array<number>>}
* @const
*/
proto.xla.OpRequest.oneofGroups_ = [[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,34,27,28,29,30,31,32]];
/**
* @enum {number}
*/
proto.xla.OpRequest.OpCase = {
OP_NOT_SET: 0,
BINARY_OP_REQUEST: 2,
BROADCAST_REQUEST: 3,
CALL_REQUEST: 4,
CONCATENATE_REQUEST: 5,
CONSTANT_REQUEST: 6,
CONVERT_REQUEST: 7,
CONVOLVE_REQUEST: 8,
CROSS_REPLICA_SUM_REQUEST: 9,
CUSTOM_CALL_REQUEST: 10,
DYNAMIC_SLICE_REQUEST: 11,
DYNAMIC_UPDATE_SLICE_REQUEST: 12,
GET_TUPLE_ELEMENT_REQUEST: 13,
INFEED_REQUEST: 14,
MAP_REQUEST: 15,
PAD_REQUEST: 16,
PARAMETER_REQUEST: 17,
REDUCE_REQUEST: 18,
REDUCE_WINDOW_REQUEST: 19,
RESHAPE_REQUEST: 20,
REVERSE_REQUEST: 21,
RNG_REQUEST: 22,
SELECT_AND_SCATTER_REQUEST: 23,
SLICE_REQUEST: 24,
TERNARY_OP_REQUEST: 25,
TRACE_REQUEST: 26,
TRANSPOSE_REQUEST: 34,
UNARY_OP_REQUEST: 27,
VARIADIC_OP_REQUEST: 28,
WHILE_REQUEST: 29,
SEND_REQUEST: 30,
RECV_REQUEST: 31,
OUTFEED_REQUEST: 32
};
/**
* @return {proto.xla.OpRequest.OpCase}
*/
proto.xla.OpRequest.prototype.getOpCase = function() {
return /** @type {proto.xla.OpRequest.OpCase} */(jspb.Message.computeOneofCase(this, proto.xla.OpRequest.oneofGroups_[0]));
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto suitable for use in Soy templates.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.
* @param {boolean=} opt_includeInstance Whether to include the JSPB instance
* for transitional soy proto support: http://goto/soy-param-migration
* @return {!Object}
*/
proto.xla.OpRequest.prototype.toObject = function(opt_includeInstance) {
return proto.xla.OpRequest.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Whether to include the JSPB
* instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.xla.OpRequest} msg The msg instance to transform.
* @return {!Object}
*/
proto.xla.OpRequest.toObject = function(includeInstance, msg) {
var f, obj = {
computation: (f = msg.getComputation()) && proto.xla.ComputationHandle.toObject(includeInstance, f),
metadata: (f = msg.getMetadata()) && proto.xla.OpMetadata.toObject(includeInstance, f),
binaryOpRequest: (f = msg.getBinaryOpRequest()) && proto.xla.BinaryOpRequest.toObject(includeInstance, f),
broadcastRequest: (f = msg.getBroadcastRequest()) && proto.xla.BroadcastRequest.toObject(includeInstance, f),
callRequest: (f = msg.getCallRequest()) && proto.xla.CallRequest.toObject(includeInstance, f),
concatenateRequest: (f = msg.getConcatenateRequest()) && proto.xla.ConcatenateRequest.toObject(includeInstance, f),
constantRequest: (f = msg.getConstantRequest()) && proto.xla.ConstantRequest.toObject(includeInstance, f),
convertRequest: (f = msg.getConvertRequest()) && proto.xla.ConvertRequest.toObject(includeInstance, f),
convolveRequest: (f = msg.getConvolveRequest()) && proto.xla.ConvolveRequest.toObject(includeInstance, f),
crossReplicaSumRequest: (f = msg.getCrossReplicaSumRequest()) && proto.xla.CrossReplicaSumRequest.toObject(includeInstance, f),
customCallRequest: (f = msg.getCustomCallRequest()) && proto.xla.CustomCallRequest.toObject(includeInstance, f),
dynamicSliceRequest: (f = msg.getDynamicSliceRequest()) && proto.xla.DynamicSliceRequest.toObject(includeInstance, f),
dynamicUpdateSliceRequest: (f = msg.getDynamicUpdateSliceRequest()) && proto.xla.DynamicUpdateSliceRequest.toObject(includeInstance, f),
getTupleElementRequest: (f = msg.getGetTupleElementRequest()) && proto.xla.GetTupleElementRequest.toObject(includeInstance, f),
infeedRequest: (f = msg.getInfeedRequest()) && proto.xla.InfeedRequest.toObject(includeInstance, f),
mapRequest: (f = msg.getMapRequest()) && proto.xla.MapRequest.toObject(includeInstance, f),
padRequest: (f = msg.getPadRequest()) && proto.xla.PadRequest.toObject(includeInstance, f),
parameterRequest: (f = msg.getParameterRequest()) && proto.xla.ParameterRequest.toObject(includeInstance, f),
reduceRequest: (f = msg.getReduceRequest()) && proto.xla.ReduceRequest.toObject(includeInstance, f),
reduceWindowRequest: (f = msg.getReduceWindowRequest()) && proto.xla.ReduceWindowRequest.toObject(includeInstance, f),
reshapeRequest: (f = msg.getReshapeRequest()) && proto.xla.ReshapeRequest.toObject(includeInstance, f),
reverseRequest: (f = msg.getReverseRequest()) && proto.xla.ReverseRequest.toObject(includeInstance, f),
rngRequest: (f = msg.getRngRequest()) && proto.xla.RngRequest.toObject(includeInstance, f),
selectAndScatterRequest: (f = msg.getSelectAndScatterRequest()) && proto.xla.SelectAndScatterRequest.toObject(includeInstance, f),
sliceRequest: (f = msg.getSliceRequest()) && proto.xla.SliceRequest.toObject(includeInstance, f),
ternaryOpRequest: (f = msg.getTernaryOpRequest()) && proto.xla.TernaryOpRequest.toObject(includeInstance, f),
traceRequest: (f = msg.getTraceRequest()) && proto.xla.TraceRequest.toObject(includeInstance, f),
transposeRequest: (f = msg.getTransposeRequest()) && proto.xla.TransposeRequest.toObject(includeInstance, f),
unaryOpRequest: (f = msg.getUnaryOpRequest()) && proto.xla.UnaryOpRequest.toObject(includeInstance, f),
variadicOpRequest: (f = msg.getVariadicOpRequest()) && proto.xla.VariadicOpRequest.toObject(includeInstance, f),
whileRequest: (f = msg.getWhileRequest()) && proto.xla.WhileRequest.toObject(includeInstance, f),
sendRequest: (f = msg.getSendRequest()) && proto.xla.SendRequest.toObject(includeInstance, f),
recvRequest: (f = msg.getRecvRequest()) && proto.xla.RecvRequest.toObject(includeInstance, f),
outfeedRequest: (f = msg.getOutfeedRequest()) && proto.xla.OutfeedRequest.toObject(includeInstance, f)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.xla.OpRequest}
*/
proto.xla.OpRequest.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.xla.OpRequest;
return proto.xla.OpRequest.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.xla.OpRequest} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.xla.OpRequest}
*/
proto.xla.OpRequest.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new proto.xla.ComputationHandle;
reader.readMessage(value,proto.xla.ComputationHandle.deserializeBinaryFromReader);
msg.setComputation(value);
break;
case 33:
var value = new proto.xla.OpMetadata;
reader.readMessage(value,proto.xla.OpMetadata.deserializeBinaryFromReader);
msg.setMetadata(value);
break;
case 2:
var value = new proto.xla.BinaryOpRequest;
reader.readMessage(value,proto.xla.BinaryOpRequest.deserializeBinaryFromReader);
msg.setBinaryOpRequest(value);
break;
case 3:
var value = new proto.xla.BroadcastRequest;
reader.readMessage(value,proto.xla.BroadcastRequest.deserializeBinaryFromReader);
msg.setBroadcastRequest(value);
break;
case 4:
var value = new proto.xla.CallRequest;
reader.readMessage(value,proto.xla.CallRequest.deserializeBinaryFromReader);
msg.setCallRequest(value);
break;
case 5:
var value = new proto.xla.ConcatenateRequest;
reader.readMessage(value,proto.xla.ConcatenateRequest.deserializeBinaryFromReader);
msg.setConcatenateRequest(value);
break;
case 6:
var value = new proto.xla.ConstantRequest;
reader.readMessage(value,proto.xla.ConstantRequest.deserializeBinaryFromReader);
msg.setConstantRequest(value);
break;
case 7:
var value = new proto.xla.ConvertRequest;
reader.readMessage(value,proto.xla.ConvertRequest.deserializeBinaryFromReader);
msg.setConvertRequest(value);
break;
case 8:
var value = new proto.xla.ConvolveRequest;
reader.readMessage(value,proto.xla.ConvolveRequest.deserializeBinaryFromReader);
msg.setConvolveRequest(value);
break;
case 9:
var value = new proto.xla.CrossReplicaSumRequest;
reader.readMessage(value,proto.xla.CrossReplicaSumRequest.deserializeBinaryFromReader);
msg.setCrossReplicaSumRequest(value);
break;
case 10:
var value = new proto.xla.CustomCallRequest;
reader.readMessage(value,proto.xla.CustomCallRequest.deserializeBinaryFromReader);
msg.setCustomCallRequest(value);
break;
case 11:
var value = new proto.xla.DynamicSliceRequest;
reader.readMessage(value,proto.xla.DynamicSliceRequest.deserializeBinaryFromReader);
msg.setDynamicSliceRequest(value);
break;
case 12:
var value = new proto.xla.DynamicUpdateSliceRequest;
reader.readMessage(value,proto.xla.DynamicUpdateSliceRequest.deserializeBinaryFromReader);
msg.setDynamicUpdateSliceRequest(value);
break;
case 13:
var value = new proto.xla.GetTupleElementRequest;
reader.readMessage(value,proto.xla.GetTupleElementRequest.deserializeBinaryFromReader);
msg.setGetTupleElementRequest(value);
break;
case 14:
var value = new proto.xla.InfeedRequest;
reader.readMessage(value,proto.xla.InfeedRequest.deserializeBinaryFromReader);
msg.setInfeedRequest(value);
break;
case 15:
var value = new proto.xla.MapRequest;
reader.readMessage(value,proto.xla.MapRequest.deserializeBinaryFromReader);
msg.setMapRequest(value);
break;
case 16:
var value = new proto.xla.PadRequest;
reader.readMessage(value,proto.xla.PadRequest.deserializeBinaryFromReader);
msg.setPadRequest(value);
break;
case 17:
var value = new proto.xla.ParameterRequest;
reader.readMessage(value,proto.xla.ParameterRequest.deserializeBinaryFromReader);
msg.setParameterRequest(value);
break;
case 18:
var value = new proto.xla.ReduceRequest;
reader.readMessage(value,proto.xla.ReduceRequest.deserializeBinaryFromReader);
msg.setReduceRequest(value);
break;
case 19:
var value = new proto.xla.ReduceWindowRequest;
reader.readMessage(value,proto.xla.ReduceWindowRequest.deserializeBinaryFromReader);
msg.setReduceWindowRequest(value);
break;
case 20:
var value = new proto.xla.ReshapeRequest;
reader.readMessage(value,proto.xla.ReshapeRequest.deserializeBinaryFromReader);
msg.setReshapeRequest(value);
break;
case 21:
var value = new proto.xla.ReverseRequest;
reader.readMessage(value,proto.xla.ReverseRequest.deserializeBinaryFromReader);
msg.setReverseRequest(value);
break;
case 22:
var value = new proto.xla.RngRequest;
reader.readMessage(value,proto.xla.RngRequest.deserializeBinaryFromReader);
msg.setRngRequest(value);
break;
case 23:
var value = new proto.xla.SelectAndScatterRequest;
reader.readMessage(value,proto.xla.SelectAndScatterRequest.deserializeBinaryFromReader);
msg.setSelectAndScatterRequest(value);
break;
case 24:
var value = new proto.xla.SliceRequest;
reader.readMessage(value,proto.xla.SliceRequest.deserializeBinaryFromReader);
msg.setSliceRequest(value);
break;
case 25:
var value = new proto.xla.TernaryOpRequest;
reader.readMessage(value,proto.xla.TernaryOpRequest.deserializeBinaryFromReader);
msg.setTernaryOpRequest(value);
break;
case 26:
var value = new proto.xla.TraceRequest;
reader.readMessage(value,proto.xla.TraceRequest.deserializeBinaryFromReader);
msg.setTraceRequest(value);
break;
case 34:
var value = new proto.xla.TransposeRequest;
reader.readMessage(value,proto.xla.TransposeRequest.deserializeBinaryFromReader);
msg.setTransposeRequest(value);
break;
case 27:
var value = new proto.xla.UnaryOpRequest;
reader.readMessage(value,proto.xla.UnaryOpRequest.deserializeBinaryFromReader);
msg.setUnaryOpRequest(value);
break;
case 28:
var value = new proto.xla.VariadicOpRequest;
reader.readMessage(value,proto.xla.VariadicOpRequest.deserializeBinaryFromReader);
msg.setVariadicOpRequest(value);
break;
case 29:
var value = new proto.xla.WhileRequest;
reader.readMessage(value,proto.xla.WhileRequest.deserializeBinaryFromReader);
msg.setWhileRequest(value);
break;
case 30:
var value = new proto.xla.SendRequest;
reader.readMessage(value,proto.xla.SendRequest.deserializeBinaryFromReader);
msg.setSendRequest(value);
break;
case 31:
var value = new proto.xla.RecvRequest;
reader.readMessage(value,proto.xla.RecvRequest.deserializeBinaryFromReader);
msg.setRecvRequest(value);
break;
case 32:
var value = new proto.xla.OutfeedRequest;
reader.readMessage(value,proto.xla.OutfeedRequest.deserializeBinaryFromReader);
msg.setOutfeedRequest(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.xla.OpRequest.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.xla.OpRequest.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.xla.OpRequest} message
* @param {!jspb.BinaryWriter} writer
*/
proto.xla.OpRequest.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getComputation();
if (f != null) {
writer.writeMessage(
1,
f,
proto.xla.ComputationHandle.serializeBinaryToWriter
);
}
f = message.getMetadata();
if (f != null) {
writer.writeMessage(
33,
f,
proto.xla.OpMetadata.serializeBinaryToWriter
);
}
f = message.getBinaryOpRequest();
if (f != null) {
writer.writeMessage(
2,
f,
proto.xla.BinaryOpRequest.serializeBinaryToWriter
);
}
f = message.getBroadcastRequest();
if (f != null) {
writer.writeMessage(
3,
f,
proto.xla.BroadcastRequest.serializeBinaryToWriter
);
}
f = message.getCallRequest();
if (f != null) {
writer.writeMessage(
4,
f,
proto.xla.CallRequest.serializeBinaryToWriter
);
}
f = message.getConcatenateRequest();
if (f != null) {
writer.writeMessage(
5,
f,
proto.xla.ConcatenateRequest.serializeBinaryToWriter
);
}
f = message.getConstantRequest();
if (f != null) {
writer.writeMessage(
6,
f,
proto.xla.ConstantRequest.serializeBinaryToWriter
);
}
f = message.getConvertRequest();
if (f != null) {
writer.writeMessage(
7,
f,
proto.xla.ConvertRequest.serializeBinaryToWriter
);
}
f = message.getConvolveRequest();
if (f != null) {
writer.writeMessage(
8,
f,
proto.xla.ConvolveRequest.serializeBinaryToWriter
);
}
f = message.getCrossReplicaSumRequest();
if (f != null) {
writer.writeMessage(
9,
f,
proto.xla.CrossReplicaSumRequest.serializeBinaryToWriter
);
}
f = message.getCustomCallRequest();
if (f != null) {
writer.writeMessage(
10,
f,
proto.xla.CustomCallRequest.serializeBinaryToWriter
);
}
f = message.getDynamicSliceRequest();
if (f != null) {
writer.writeMessage(
11,
f,
proto.xla.DynamicSliceRequest.serializeBinaryToWriter
);
}
f = message.getDynamicUpdateSliceRequest();
if (f != null) {
writer.writeMessage(
12,
f,
proto.xla.DynamicUpdateSliceRequest.serializeBinaryToWriter
);
}
f = message.getGetTupleElementRequest();
if (f != null) {
writer.writeMessage(
13,
f,
proto.xla.GetTupleElementRequest.serializeBinaryToWriter
);
}
f = message.getInfeedRequest();
if (f != null) {
writer.writeMessage(
14,
f,
proto.xla.InfeedRequest.serializeBinaryToWriter
);
}
f = message.getMapRequest();
if (f != null) {
writer.writeMessage(
15,
f,
proto.xla.MapRequest.serializeBinaryToWriter
);
}
f = message.getPadRequest();
if (f != null) {
writer.writeMessage(
16,
f,
proto.xla.PadRequest.serializeBinaryToWriter
);
}
f = message.getParameterRequest();
if (f != null) {
writer.writeMessage(
17,
f,
proto.xla.ParameterRequest.serializeBinaryToWriter
);
}
f = message.getReduceRequest();
if (f != null) {
writer.writeMessage(
18,
f,
proto.xla.ReduceRequest.serializeBinaryToWriter
);
}
f = message.getReduceWindowRequest();
if (f != null) {
writer.writeMessage(
19,
f,
proto.xla.ReduceWindowRequest.serializeBinaryToWriter
);
}
f = message.getReshapeRequest();
if (f != null) {
writer.writeMessage(
20,
f,
proto.xla.ReshapeRequest.serializeBinaryToWriter
);
}
f = message.getReverseRequest();
if (f != null) {
writer.writeMessage(
21,
f,
proto.xla.ReverseRequest.serializeBinaryToWriter
);
}
f = message.getRngRequest();
if (f != null) {
writer.writeMessage(
22,
f,
proto.xla.RngRequest.serializeBinaryToWriter
);
}
f = message.getSelectAndScatterRequest();
if (f != null) {
writer.writeMessage(
23,
f,
proto.xla.SelectAndScatterRequest.serializeBinaryToWriter
);
}
f = message.getSliceRequest();
if (f != null) {
writer.writeMessage(
24,
f,
proto.xla.SliceRequest.serializeBinaryToWriter
);
}
f = message.getTernaryOpRequest();
if (f != null) {
writer.writeMessage(
25,
f,
proto.xla.TernaryOpRequest.serializeBinaryToWriter
);
}
f = message.getTraceRequest();
if (f != null) {
writer.writeMessage(
26,
f,
proto.xla.TraceRequest.serializeBinaryToWriter
);
}
f = message.getTransposeRequest();
if (f != null) {
writer.writeMessage(
34,
f,
proto.xla.TransposeRequest.serializeBinaryToWriter
);
}
f = message.getUnaryOpRequest();
if (f != null) {
writer.writeMessage(
27,
f,
proto.xla.UnaryOpRequest.serializeBinaryToWriter
);
}
f = message.getVariadicOpRequest();
if (f != null) {
writer.writeMessage(
28,
f,
proto.xla.VariadicOpRequest.serializeBinaryToWriter
);
}
f = message.getWhileRequest();
if (f != null) {
writer.writeMessage(
29,
f,
proto.xla.WhileRequest.serializeBinaryToWriter
);
}
f = message.getSendRequest();
if (f != null) {
writer.writeMessage(
30,
f,
proto.xla.SendRequest.serializeBinaryToWriter
);
}
f = message.getRecvRequest();
if (f != null) {
writer.writeMessage(
31,
f,
proto.xla.RecvRequest.serializeBinaryToWriter
);
}
f = message.getOutfeedRequest();
if (f != null) {
writer.writeMessage(
32,
f,
proto.xla.OutfeedRequest.serializeBinaryToWriter
);
}
};
/**
* optional ComputationHandle computation = 1;
* @return {?proto.xla.ComputationHandle}
*/
proto.xla.OpRequest.prototype.getComputation = function() {
return /** @type{?proto.xla.ComputationHandle} */ (
jspb.Message.getWrapperField(this, proto.xla.ComputationHandle, 1));
};
/** @param {?proto.xla.ComputationHandle|undefined} value */
proto.xla.OpRequest.prototype.setComputation = function(value) {
jspb.Message.setWrapperField(this, 1, value);
};
proto.xla.OpRequest.prototype.clearComputation = function() {
this.setComputation(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasComputation = function() {
return jspb.Message.getField(this, 1) != null;
};
/**
* optional OpMetadata metadata = 33;
* @return {?proto.xla.OpMetadata}
*/
proto.xla.OpRequest.prototype.getMetadata = function() {
return /** @type{?proto.xla.OpMetadata} */ (
jspb.Message.getWrapperField(this, proto.xla.OpMetadata, 33));
};
/** @param {?proto.xla.OpMetadata|undefined} value */
proto.xla.OpRequest.prototype.setMetadata = function(value) {
jspb.Message.setWrapperField(this, 33, value);
};
proto.xla.OpRequest.prototype.clearMetadata = function() {
this.setMetadata(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasMetadata = function() {
return jspb.Message.getField(this, 33) != null;
};
/**
* optional BinaryOpRequest binary_op_request = 2;
* @return {?proto.xla.BinaryOpRequest}
*/
proto.xla.OpRequest.prototype.getBinaryOpRequest = function() {
return /** @type{?proto.xla.BinaryOpRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.BinaryOpRequest, 2));
};
/** @param {?proto.xla.BinaryOpRequest|undefined} value */
proto.xla.OpRequest.prototype.setBinaryOpRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 2, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearBinaryOpRequest = function() {
this.setBinaryOpRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasBinaryOpRequest = function() {
return jspb.Message.getField(this, 2) != null;
};
/**
* optional BroadcastRequest broadcast_request = 3;
* @return {?proto.xla.BroadcastRequest}
*/
proto.xla.OpRequest.prototype.getBroadcastRequest = function() {
return /** @type{?proto.xla.BroadcastRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.BroadcastRequest, 3));
};
/** @param {?proto.xla.BroadcastRequest|undefined} value */
proto.xla.OpRequest.prototype.setBroadcastRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 3, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearBroadcastRequest = function() {
this.setBroadcastRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasBroadcastRequest = function() {
return jspb.Message.getField(this, 3) != null;
};
/**
* optional CallRequest call_request = 4;
* @return {?proto.xla.CallRequest}
*/
proto.xla.OpRequest.prototype.getCallRequest = function() {
return /** @type{?proto.xla.CallRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.CallRequest, 4));
};
/** @param {?proto.xla.CallRequest|undefined} value */
proto.xla.OpRequest.prototype.setCallRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 4, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearCallRequest = function() {
this.setCallRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasCallRequest = function() {
return jspb.Message.getField(this, 4) != null;
};
/**
* optional ConcatenateRequest concatenate_request = 5;
* @return {?proto.xla.ConcatenateRequest}
*/
proto.xla.OpRequest.prototype.getConcatenateRequest = function() {
return /** @type{?proto.xla.ConcatenateRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ConcatenateRequest, 5));
};
/** @param {?proto.xla.ConcatenateRequest|undefined} value */
proto.xla.OpRequest.prototype.setConcatenateRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 5, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearConcatenateRequest = function() {
this.setConcatenateRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasConcatenateRequest = function() {
return jspb.Message.getField(this, 5) != null;
};
/**
* optional ConstantRequest constant_request = 6;
* @return {?proto.xla.ConstantRequest}
*/
proto.xla.OpRequest.prototype.getConstantRequest = function() {
return /** @type{?proto.xla.ConstantRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ConstantRequest, 6));
};
/** @param {?proto.xla.ConstantRequest|undefined} value */
proto.xla.OpRequest.prototype.setConstantRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 6, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearConstantRequest = function() {
this.setConstantRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasConstantRequest = function() {
return jspb.Message.getField(this, 6) != null;
};
/**
* optional ConvertRequest convert_request = 7;
* @return {?proto.xla.ConvertRequest}
*/
proto.xla.OpRequest.prototype.getConvertRequest = function() {
return /** @type{?proto.xla.ConvertRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ConvertRequest, 7));
};
/** @param {?proto.xla.ConvertRequest|undefined} value */
proto.xla.OpRequest.prototype.setConvertRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 7, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearConvertRequest = function() {
this.setConvertRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasConvertRequest = function() {
return jspb.Message.getField(this, 7) != null;
};
/**
* optional ConvolveRequest convolve_request = 8;
* @return {?proto.xla.ConvolveRequest}
*/
proto.xla.OpRequest.prototype.getConvolveRequest = function() {
return /** @type{?proto.xla.ConvolveRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ConvolveRequest, 8));
};
/** @param {?proto.xla.ConvolveRequest|undefined} value */
proto.xla.OpRequest.prototype.setConvolveRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 8, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearConvolveRequest = function() {
this.setConvolveRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasConvolveRequest = function() {
return jspb.Message.getField(this, 8) != null;
};
/**
* optional CrossReplicaSumRequest cross_replica_sum_request = 9;
* @return {?proto.xla.CrossReplicaSumRequest}
*/
proto.xla.OpRequest.prototype.getCrossReplicaSumRequest = function() {
return /** @type{?proto.xla.CrossReplicaSumRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.CrossReplicaSumRequest, 9));
};
/** @param {?proto.xla.CrossReplicaSumRequest|undefined} value */
proto.xla.OpRequest.prototype.setCrossReplicaSumRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 9, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearCrossReplicaSumRequest = function() {
this.setCrossReplicaSumRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasCrossReplicaSumRequest = function() {
return jspb.Message.getField(this, 9) != null;
};
/**
* optional CustomCallRequest custom_call_request = 10;
* @return {?proto.xla.CustomCallRequest}
*/
proto.xla.OpRequest.prototype.getCustomCallRequest = function() {
return /** @type{?proto.xla.CustomCallRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.CustomCallRequest, 10));
};
/** @param {?proto.xla.CustomCallRequest|undefined} value */
proto.xla.OpRequest.prototype.setCustomCallRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 10, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearCustomCallRequest = function() {
this.setCustomCallRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasCustomCallRequest = function() {
return jspb.Message.getField(this, 10) != null;
};
/**
* optional DynamicSliceRequest dynamic_slice_request = 11;
* @return {?proto.xla.DynamicSliceRequest}
*/
proto.xla.OpRequest.prototype.getDynamicSliceRequest = function() {
return /** @type{?proto.xla.DynamicSliceRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.DynamicSliceRequest, 11));
};
/** @param {?proto.xla.DynamicSliceRequest|undefined} value */
proto.xla.OpRequest.prototype.setDynamicSliceRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 11, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearDynamicSliceRequest = function() {
this.setDynamicSliceRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasDynamicSliceRequest = function() {
return jspb.Message.getField(this, 11) != null;
};
/**
* optional DynamicUpdateSliceRequest dynamic_update_slice_request = 12;
* @return {?proto.xla.DynamicUpdateSliceRequest}
*/
proto.xla.OpRequest.prototype.getDynamicUpdateSliceRequest = function() {
return /** @type{?proto.xla.DynamicUpdateSliceRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.DynamicUpdateSliceRequest, 12));
};
/** @param {?proto.xla.DynamicUpdateSliceRequest|undefined} value */
proto.xla.OpRequest.prototype.setDynamicUpdateSliceRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 12, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearDynamicUpdateSliceRequest = function() {
this.setDynamicUpdateSliceRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasDynamicUpdateSliceRequest = function() {
return jspb.Message.getField(this, 12) != null;
};
/**
* optional GetTupleElementRequest get_tuple_element_request = 13;
* @return {?proto.xla.GetTupleElementRequest}
*/
proto.xla.OpRequest.prototype.getGetTupleElementRequest = function() {
return /** @type{?proto.xla.GetTupleElementRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.GetTupleElementRequest, 13));
};
/** @param {?proto.xla.GetTupleElementRequest|undefined} value */
proto.xla.OpRequest.prototype.setGetTupleElementRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 13, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearGetTupleElementRequest = function() {
this.setGetTupleElementRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasGetTupleElementRequest = function() {
return jspb.Message.getField(this, 13) != null;
};
/**
* optional InfeedRequest infeed_request = 14;
* @return {?proto.xla.InfeedRequest}
*/
proto.xla.OpRequest.prototype.getInfeedRequest = function() {
return /** @type{?proto.xla.InfeedRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.InfeedRequest, 14));
};
/** @param {?proto.xla.InfeedRequest|undefined} value */
proto.xla.OpRequest.prototype.setInfeedRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 14, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearInfeedRequest = function() {
this.setInfeedRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasInfeedRequest = function() {
return jspb.Message.getField(this, 14) != null;
};
/**
* optional MapRequest map_request = 15;
* @return {?proto.xla.MapRequest}
*/
proto.xla.OpRequest.prototype.getMapRequest = function() {
return /** @type{?proto.xla.MapRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.MapRequest, 15));
};
/** @param {?proto.xla.MapRequest|undefined} value */
proto.xla.OpRequest.prototype.setMapRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 15, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearMapRequest = function() {
this.setMapRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasMapRequest = function() {
return jspb.Message.getField(this, 15) != null;
};
/**
* optional PadRequest pad_request = 16;
* @return {?proto.xla.PadRequest}
*/
proto.xla.OpRequest.prototype.getPadRequest = function() {
return /** @type{?proto.xla.PadRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.PadRequest, 16));
};
/** @param {?proto.xla.PadRequest|undefined} value */
proto.xla.OpRequest.prototype.setPadRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 16, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearPadRequest = function() {
this.setPadRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasPadRequest = function() {
return jspb.Message.getField(this, 16) != null;
};
/**
* optional ParameterRequest parameter_request = 17;
* @return {?proto.xla.ParameterRequest}
*/
proto.xla.OpRequest.prototype.getParameterRequest = function() {
return /** @type{?proto.xla.ParameterRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ParameterRequest, 17));
};
/** @param {?proto.xla.ParameterRequest|undefined} value */
proto.xla.OpRequest.prototype.setParameterRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 17, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearParameterRequest = function() {
this.setParameterRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasParameterRequest = function() {
return jspb.Message.getField(this, 17) != null;
};
/**
* optional ReduceRequest reduce_request = 18;
* @return {?proto.xla.ReduceRequest}
*/
proto.xla.OpRequest.prototype.getReduceRequest = function() {
return /** @type{?proto.xla.ReduceRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ReduceRequest, 18));
};
/** @param {?proto.xla.ReduceRequest|undefined} value */
proto.xla.OpRequest.prototype.setReduceRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 18, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearReduceRequest = function() {
this.setReduceRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasReduceRequest = function() {
return jspb.Message.getField(this, 18) != null;
};
/**
* optional ReduceWindowRequest reduce_window_request = 19;
* @return {?proto.xla.ReduceWindowRequest}
*/
proto.xla.OpRequest.prototype.getReduceWindowRequest = function() {
return /** @type{?proto.xla.ReduceWindowRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ReduceWindowRequest, 19));
};
/** @param {?proto.xla.ReduceWindowRequest|undefined} value */
proto.xla.OpRequest.prototype.setReduceWindowRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 19, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearReduceWindowRequest = function() {
this.setReduceWindowRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasReduceWindowRequest = function() {
return jspb.Message.getField(this, 19) != null;
};
/**
* optional ReshapeRequest reshape_request = 20;
* @return {?proto.xla.ReshapeRequest}
*/
proto.xla.OpRequest.prototype.getReshapeRequest = function() {
return /** @type{?proto.xla.ReshapeRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ReshapeRequest, 20));
};
/** @param {?proto.xla.ReshapeRequest|undefined} value */
proto.xla.OpRequest.prototype.setReshapeRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 20, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearReshapeRequest = function() {
this.setReshapeRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasReshapeRequest = function() {
return jspb.Message.getField(this, 20) != null;
};
/**
* optional ReverseRequest reverse_request = 21;
* @return {?proto.xla.ReverseRequest}
*/
proto.xla.OpRequest.prototype.getReverseRequest = function() {
return /** @type{?proto.xla.ReverseRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.ReverseRequest, 21));
};
/** @param {?proto.xla.ReverseRequest|undefined} value */
proto.xla.OpRequest.prototype.setReverseRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 21, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearReverseRequest = function() {
this.setReverseRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasReverseRequest = function() {
return jspb.Message.getField(this, 21) != null;
};
/**
* optional RngRequest rng_request = 22;
* @return {?proto.xla.RngRequest}
*/
proto.xla.OpRequest.prototype.getRngRequest = function() {
return /** @type{?proto.xla.RngRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.RngRequest, 22));
};
/** @param {?proto.xla.RngRequest|undefined} value */
proto.xla.OpRequest.prototype.setRngRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 22, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearRngRequest = function() {
this.setRngRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasRngRequest = function() {
return jspb.Message.getField(this, 22) != null;
};
/**
* optional SelectAndScatterRequest select_and_scatter_request = 23;
* @return {?proto.xla.SelectAndScatterRequest}
*/
proto.xla.OpRequest.prototype.getSelectAndScatterRequest = function() {
return /** @type{?proto.xla.SelectAndScatterRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.SelectAndScatterRequest, 23));
};
/** @param {?proto.xla.SelectAndScatterRequest|undefined} value */
proto.xla.OpRequest.prototype.setSelectAndScatterRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 23, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearSelectAndScatterRequest = function() {
this.setSelectAndScatterRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasSelectAndScatterRequest = function() {
return jspb.Message.getField(this, 23) != null;
};
/**
* optional SliceRequest slice_request = 24;
* @return {?proto.xla.SliceRequest}
*/
proto.xla.OpRequest.prototype.getSliceRequest = function() {
return /** @type{?proto.xla.SliceRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.SliceRequest, 24));
};
/** @param {?proto.xla.SliceRequest|undefined} value */
proto.xla.OpRequest.prototype.setSliceRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 24, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearSliceRequest = function() {
this.setSliceRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasSliceRequest = function() {
return jspb.Message.getField(this, 24) != null;
};
/**
* optional TernaryOpRequest ternary_op_request = 25;
* @return {?proto.xla.TernaryOpRequest}
*/
proto.xla.OpRequest.prototype.getTernaryOpRequest = function() {
return /** @type{?proto.xla.TernaryOpRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.TernaryOpRequest, 25));
};
/** @param {?proto.xla.TernaryOpRequest|undefined} value */
proto.xla.OpRequest.prototype.setTernaryOpRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 25, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearTernaryOpRequest = function() {
this.setTernaryOpRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasTernaryOpRequest = function() {
return jspb.Message.getField(this, 25) != null;
};
/**
* optional TraceRequest trace_request = 26;
* @return {?proto.xla.TraceRequest}
*/
proto.xla.OpRequest.prototype.getTraceRequest = function() {
return /** @type{?proto.xla.TraceRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.TraceRequest, 26));
};
/** @param {?proto.xla.TraceRequest|undefined} value */
proto.xla.OpRequest.prototype.setTraceRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 26, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearTraceRequest = function() {
this.setTraceRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasTraceRequest = function() {
return jspb.Message.getField(this, 26) != null;
};
/**
* optional TransposeRequest transpose_request = 34;
* @return {?proto.xla.TransposeRequest}
*/
proto.xla.OpRequest.prototype.getTransposeRequest = function() {
return /** @type{?proto.xla.TransposeRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.TransposeRequest, 34));
};
/** @param {?proto.xla.TransposeRequest|undefined} value */
proto.xla.OpRequest.prototype.setTransposeRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 34, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearTransposeRequest = function() {
this.setTransposeRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasTransposeRequest = function() {
return jspb.Message.getField(this, 34) != null;
};
/**
* optional UnaryOpRequest unary_op_request = 27;
* @return {?proto.xla.UnaryOpRequest}
*/
proto.xla.OpRequest.prototype.getUnaryOpRequest = function() {
return /** @type{?proto.xla.UnaryOpRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.UnaryOpRequest, 27));
};
/** @param {?proto.xla.UnaryOpRequest|undefined} value */
proto.xla.OpRequest.prototype.setUnaryOpRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 27, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearUnaryOpRequest = function() {
this.setUnaryOpRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasUnaryOpRequest = function() {
return jspb.Message.getField(this, 27) != null;
};
/**
* optional VariadicOpRequest variadic_op_request = 28;
* @return {?proto.xla.VariadicOpRequest}
*/
proto.xla.OpRequest.prototype.getVariadicOpRequest = function() {
return /** @type{?proto.xla.VariadicOpRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.VariadicOpRequest, 28));
};
/** @param {?proto.xla.VariadicOpRequest|undefined} value */
proto.xla.OpRequest.prototype.setVariadicOpRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 28, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearVariadicOpRequest = function() {
this.setVariadicOpRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasVariadicOpRequest = function() {
return jspb.Message.getField(this, 28) != null;
};
/**
* optional WhileRequest while_request = 29;
* @return {?proto.xla.WhileRequest}
*/
proto.xla.OpRequest.prototype.getWhileRequest = function() {
return /** @type{?proto.xla.WhileRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.WhileRequest, 29));
};
/** @param {?proto.xla.WhileRequest|undefined} value */
proto.xla.OpRequest.prototype.setWhileRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 29, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearWhileRequest = function() {
this.setWhileRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasWhileRequest = function() {
return jspb.Message.getField(this, 29) != null;
};
/**
* optional SendRequest send_request = 30;
* @return {?proto.xla.SendRequest}
*/
proto.xla.OpRequest.prototype.getSendRequest = function() {
return /** @type{?proto.xla.SendRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.SendRequest, 30));
};
/** @param {?proto.xla.SendRequest|undefined} value */
proto.xla.OpRequest.prototype.setSendRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 30, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearSendRequest = function() {
this.setSendRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasSendRequest = function() {
return jspb.Message.getField(this, 30) != null;
};
/**
* optional RecvRequest recv_request = 31;
* @return {?proto.xla.RecvRequest}
*/
proto.xla.OpRequest.prototype.getRecvRequest = function() {
return /** @type{?proto.xla.RecvRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.RecvRequest, 31));
};
/** @param {?proto.xla.RecvRequest|undefined} value */
proto.xla.OpRequest.prototype.setRecvRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 31, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearRecvRequest = function() {
this.setRecvRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasRecvRequest = function() {
return jspb.Message.getField(this, 31) != null;
};
/**
* optional OutfeedRequest outfeed_request = 32;
* @return {?proto.xla.OutfeedRequest}
*/
proto.xla.OpRequest.prototype.getOutfeedRequest = function() {
return /** @type{?proto.xla.OutfeedRequest} */ (
jspb.Message.getWrapperField(this, proto.xla.OutfeedRequest, 32));
};
/** @param {?proto.xla.OutfeedRequest|undefined} value */
proto.xla.OpRequest.prototype.setOutfeedRequest = function(value) {
jspb.Message.setOneofWrapperField(this, 32, proto.xla.OpRequest.oneofGroups_[0], value);
};
proto.xla.OpRequest.prototype.clearOutfeedRequest = function() {
this.setOutfeedRequest(undefined);
};
/**
* Returns whether this field is set.
* @return {!boolean}
*/
proto.xla.OpRequest.prototype.hasOutfeedRequest = function() {
return jspb.Message.getField(this, 32) != null;
};
| mit |
SaschaMoellering/jmxtrans-agent | src/main/java/org/jmxtrans/agent/FileOverwriterOutputWriter.java | 8178 | /*
* Copyright (c) 2010-2013 the original author or authors
*
* 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.
*
*/
package org.jmxtrans.agent;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
import java.util.TimeZone;
import static org.jmxtrans.agent.util.ConfigurationUtils.getBoolean;
import static org.jmxtrans.agent.util.ConfigurationUtils.getString;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class FileOverwriterOutputWriter extends AbstractOutputWriter {
public final static String SETTING_FILE_NAME = "fileName";
public final static String SETTING_FILE_NAME_DEFAULT_VALUE = "jmxtrans-agent.data";
public final static String SETTING_SHOW_TIMESTAMP = "showTimeStamp";
public final static Boolean SETTING_SHOW_TIMESTAMP_DEFAULT = false;
protected Writer temporaryFileWriter;
protected File temporaryFile;
protected File file = new File(SETTING_FILE_NAME_DEFAULT_VALUE);
protected Boolean showTimeStamp;
private static Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
private static DateFormat dfISO8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
@Override
public synchronized void postConstruct(Map<String, String> settings) {
super.postConstruct(settings);
dfISO8601.setTimeZone(TimeZone.getTimeZone("GMT"));
file = new File(getString(settings, SETTING_FILE_NAME, SETTING_FILE_NAME_DEFAULT_VALUE));
showTimeStamp = getBoolean(settings, SETTING_SHOW_TIMESTAMP, SETTING_SHOW_TIMESTAMP_DEFAULT);
logger.log(getInfoLevel(), "FileOverwriterOutputWriter configured with file " + file.getAbsolutePath());
}
protected Writer getTemporaryFileWriter() throws IOException {
if (temporaryFile == null) {
temporaryFile = File.createTempFile("jmxtrans-agent-", ".data");
temporaryFile.deleteOnExit();
if (logger.isLoggable(getDebugLevel()))
logger.log(getDebugLevel(), "Created temporary file " + temporaryFile.getAbsolutePath());
temporaryFileWriter = null;
}
if (temporaryFileWriter == null) {
temporaryFileWriter = new BufferedWriter(new FileWriter(temporaryFile, false));
}
return temporaryFileWriter;
}
@Override
public void writeInvocationResult(String invocationName, Object value) throws IOException {
writeQueryResult(invocationName, null, value);
}
public synchronized void writeQueryResult(@Nonnull String name, @Nullable String type, @Nullable Object value) throws IOException {
try {
if (showTimeStamp){
getTemporaryFileWriter().write("["+dfISO8601.format(Calendar.getInstance().getTime()) +"] "+name + " " + value + "\n");
} else {
getTemporaryFileWriter().write(name + " " + value + "\n");
}
} catch (IOException e) {
releaseTemporaryWriter();
throw e;
}
}
protected void releaseTemporaryWriter() {
try {
IoUtils.closeQuietly(getTemporaryFileWriter());
} catch (IOException e) {
// silently skip
}
if (temporaryFile != null) {
temporaryFile.delete();
}
temporaryFile = null;
}
@Override
public synchronized void postCollect() throws IOException {
try {
getTemporaryFileWriter().close();
if (logger.isLoggable(getDebugLevel()))
logger.log(getDebugLevel(), "Overwrite " + file.getAbsolutePath() + " by " + temporaryFile.getAbsolutePath());
IoUtils.replaceFile(temporaryFile, file);
} finally {
temporaryFileWriter = null;
}
}
public static class IoUtils {
/**
* Simple implementation without chunking if the source file is big.
*
* @param source
* @param destination
* @throws java.io.IOException
*/
private static void doCopySmallFile(File source, File destination) throws IOException {
if (destination.exists() && destination.isDirectory()) {
throw new IOException("Can not copy file, destination is a directory: " + destination.getAbsolutePath());
}
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel input = null;
FileChannel output = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(destination, false);
input = fis.getChannel();
output = fos.getChannel();
output.transferFrom(input, 0, input.size());
} finally {
closeQuietly(output);
closeQuietly(input);
closeQuietly(fis);
closeQuietly(fos);
}
if (destination.length() != source.length()) {
throw new IOException("Failed to copy content from '" +
source + "' (" + source.length() + "bytes) to '" + destination + "' (" + destination.length() + ")");
}
}
public static void closeQuietly(Closeable closeable) {
if (closeable == null)
return;
try {
closeable.close();
} catch (Exception e) {
// ignore silently
}
}
public static void closeQuietly(Writer writer) {
if (writer == null)
return;
try {
writer.close();
} catch (Exception e) {
// ignore silently
}
}
/**
* Needed for old JVMs where {@link java.io.InputStream} does not implement {@link java.io.Closeable}.
*/
public static void closeQuietly(InputStream inputStream) {
if (inputStream == null)
return;
try {
inputStream.close();
} catch (Exception e) {
// ignore silently
}
}
private static void replaceFile(File source, File destination) throws IOException {
boolean destinationExists;
if (destination.exists()) {
boolean deleted = destination.delete();
if (deleted) {
destinationExists = false;
} else {
destinationExists = true;
}
} else {
destinationExists = false;
}
if (destinationExists) {
doCopySmallFile(source, destination);
} else {
boolean renamed = source.renameTo(destination);
if (!renamed) {
doCopySmallFile(source, destination);
}
}
}
}
}
| mit |
duritong/ruby-rhn_satellite | lib/rhn_satellite/api.rb | 987 | module RhnSatellite
class Api < RhnSatellite::Connection::Base
class << self
def api_version(disconnect=true)
@api_version ||= get_version('getVersion',disconnect)
end
def satellite_version(disconnect=true)
@satellite_version ||= get_version('systemVersion',disconnect)
end
def test_connection(user=nil,pwd=nil)
reset
test_base = RhnSatellite::Connection::Handler.instance_for(self.name, hostname, user||username, pwd||password, https)
test_base.connect
result = test_base.login && test_base.logout
test_base.disconnect
result
end
def reset
@api_version = @satellite_version = nil
super
end
private
def get_version(cmd,disconnect=true)
base.connect unless base.connected?
result = base.make_call("api.#{cmd}")
base.disconnect if disconnect
result
end
end
end
end | mit |
jsurfer/JsonSurfer | jsurfer-core/src/main/java/org/jsfr/json/JsonSaxHandler.java | 2168 | /*
* MIT License
*
* Copyright (c) 2019 WANG Lingsong
*
* 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.
*/
package org.jsfr.json;
/**
* SAX like handler API
*/
public interface JsonSaxHandler {
/**
* @return Return false to stop the parsing immediately
*/
boolean startJSON();
/**
* @return Return false to stop the parsing immediately
*/
boolean endJSON();
/**
* @return Return false to stop the parsing immediately
*/
boolean startObject();
/**
* @param key Entry key
* @return Return false to stop the parsing immediately
*/
boolean startObjectEntry(String key);
/**
* @return Return false to stop the parsing immediately
*/
boolean endObject();
/**
* @return Return false to stop the parsing immediately
*/
boolean startArray();
/**
* @return Return false to stop the parsing immediately
*/
boolean endArray();
/**
* @param primitiveHolder PrimitiveHolder
* @return Return false to stop the parsing immediately
*/
boolean primitive(PrimitiveHolder primitiveHolder);
}
| mit |
pengkobe/ionic-chat | server/middlewares/verify_token.js | 993 | "use strict";
var config = require("../config/config.js"), jwt = require("jsonwebtoken");
module.exports = function(req, res, next) {
var token = "";
if (
req.headers.authorization &&
req.headers.authorization.split(" ")[0] === "ionchat"
) {
var token = req.headers.authorization.split(" ")[1];
} else if (req.query && req.query.token) {
var token = req.query.token;
}
if ("" === token) {
console.log(
"jsonwebtoken err",
"401 no token detected in http header 'Authorization'"
);
}
console.log("req jsonwebtoken:", token);
console.log("config.jwt.cert:", config.jwt.cert);
var tokenContent;
jwt.co_verify(token, config.jwt.cert)(function(err, tokenContent) {
if (err) {
// 处理错误
console.log("Authorization err", err);
var err = new Error("Authorization err");
err.status = 401;
next(err);
} else {
console.log("Authorization tokenContent", tokenContent);
next();
}
});
};
| mit |
iron-bound-designs/IronBound-DB | src/Table/Column/Date.php | 1155 | <?php
/**
* Contains the class for the DateTime column type.
*
* @author Steven A Zahm
* @since 2.0
* @license MIT
* @copyright Iron Bound Designs, 2016.
*/
namespace IronBound\DB\Table\Column;
use IronBound\DB\Exception\InvalidDataForColumnException;
/**
* Class DateTime
*
* @package IronBound\DB\Table\Column
*/
class Date extends DateTime {
/**
* @inheritDoc
*/
public function get_mysql_type() {
return 'DATE';
}
/**
* @inheritDoc
*/
public function prepare_for_storage( $value ) {
if ( empty( $value ) ) {
return null;
} elseif ( is_numeric( $value ) ) {
$value = new \DateTime( "@$value", new \DateTimeZone( 'UTC' ) );
} elseif ( is_string( $value ) ) {
$value = new \DateTime( $value, new \DateTimeZone( 'UTC' ) );
} elseif ( is_object( $value ) && ! $value instanceof \DateTime && ! $value instanceof \DateTimeInterface ) {
throw new InvalidDataForColumnException(
'Non \DateTime object encountered while preparing value.', $this, $value
);
} elseif ( is_object( $value ) ) {
$value->setTimezone( new \DateTimeZone( 'UTC' ) );
}
return $value->format( 'Y-m-d' );
}
}
| mit |
anelda/website | assets/js/39.0e7a4f4a.js | 689 | (window.webpackJsonp=window.webpackJsonp||[]).push([[39],{354:function(t,e,s){"use strict";s.r(e);var o=["There's nothing here.","How did we get here?","That's a Four-Oh-Four.","Looks like we've got some broken links."],n={methods:{getMsg:function(){return o[Math.floor(Math.random()*o.length)]}}},i=s(1),h=Object(i.a)(n,(function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"theme-container"},[e("div",{staticClass:"theme-default-content"},[e("h1",[this._v("404")]),this._v(" "),e("blockquote",[this._v(this._s(this.getMsg()))]),this._v(" "),e("router-link",{attrs:{to:"/"}},[this._v("Take me home.")])],1)])}),[],!1,null,null,null);e.default=h.exports}}]); | mit |
FernandoPucci/EstudosAspNetMvc | ExercicioVendasMasterDetail/ExercicioVendasMasterDetail/App_Start/IdentityConfig.cs | 4362 | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using ExercicioVendasMasterDetail.Models;
namespace ExercicioVendasMasterDetail
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
| mit |
roooodcastro/gamedev-coursework | Game/SortAndSweep.cpp | 201 | #include "SortAndSweep.h"
SortAndSweep::SortAndSweep(void) {
}
SortAndSweep::~SortAndSweep(void) {
}
void SortAndSweep::performDetection(std::vector<PhysicalBody*> *bodies, float millisElapsed) {
} | mit |
s10018/homebrew-tl | normalizenumexp.rb | 429 | require "formula"
class Normalizenumexp < Formula
homepage "http://www.cl.ecei.tohoku.ac.jp/~katsuma/software/normalizeNumexp/"
url "https://github.com/nullnull/normalizeNumexp.git", :branch => 'master'
version "3.0"
depends_on 'ux'
depends_on 'pficommon'
def install
system "./waf configure --prefix=#{prefix}"
system "./waf build"
system "./waf install"
end
test do
system "false"
end
end
| mit |
SimpleWeek/desktop-tray-app | app/constants/TaskStatuses.js | 100 | export const STATUS_ACTIVE = 1;
export const STATUS_COMPLETED = 2;
export const STATUS_DELETED = 3;
| mit |
martianfield/bindery | index.js | 636 | 'use strict'
const bitbucket = require(__dirname + '/lib/bitbucket')
// bitbucket.demo()
// .then(data => { console.log(data) })
// .catch(err => { console.error(err) })
// bitbucket.changesets('martianfield', 'bindery_test')
// .then(data => { console.log(data) })
// .catch(err => { console.error(err) })
bitbucket.files('martianfield', 'bindery_test')
.then(data => { console.log("done:", data) })
.catch(err => { console.error(err) })
// bitbucket.file('martianfield', 'bindery_test', 'dc804605bb17', 'sub1/test_sub_2.md')
// .then(data => { console.log("src:", data)})
// .catch(err => { console.error(err)}) | mit |
siciarek/baseapp | src/Application/MainBundle/DataFixtures/ORM/LoadUserData.php | 3147 | <?php
namespace Application\MainBundle\DataFixtures\ORM;
use Application\MainBundle\DataFixtures\BasicFixture;
use Doctrine\Common\Persistence\ObjectManager;
class LoadUserData extends BasicFixture {
/**
* @var numeric
*/
protected $order = 2;
/**
* {@inheritDoc}
*/
public function load(ObjectManager $manager) {
$data = [
[
'enabled' => true,
'username' => 'system',
'firstname' => null,
'lastname' => null,
'dob' => null,
'gender' => \Sonata\UserBundle\Model\UserInterface::GENDER_UNKNOWN,
'password' => $this->getContainer()->getParameter('secret'),
'email' => 'siciarek@hotmail.com',
'groups' => [
]
],
[
'enabled' => true,
'username' => 'jsiciarek',
'firstname' => 'Jacek',
'lastname' => 'Siciarek',
'dob' => '1966-10-21',
'gender' => \Sonata\UserBundle\Model\UserInterface::GENDER_MALE,
'password' => 'pass',
'email' => 'siciarek@gmail.com',
'groups' => [
'Superadmins',
]
],
[
'enabled' => true,
'username' => 'colak',
'firstname' => 'Czesław',
'lastname' => 'Olak',
'dob' => '1985-04-11',
'gender' => \Sonata\UserBundle\Model\UserInterface::GENDER_MALE,
'password' => 'pass',
'email' => 'colak@gmail.com',
'groups' => [
'Admins',
]
],
[
'enabled' => true,
'username' => 'molak',
'firstname' => 'Marianna',
'lastname' => 'Olak',
'dob' => '1989-11-05',
'gender' => \Sonata\UserBundle\Model\UserInterface::GENDER_FEMALE,
'password' => 'pass',
'email' => 'molak@gmail.com',
'groups' => [
'Users',
]
],
];
/**
* @var Sonata\UserBundle\Entity\UserManager $mngr
*/
$mngr = $this->getContainer()->get('fos_user.user_manager');
foreach ($data as $o) {
$user = $mngr->createUser();
$user->setEnabled($o['enabled']);
$user->setUsername($o['username']);
$user->setFirstname($o['firstname']);
$user->setLastname($o['lastname']);
$user->setGender($o['gender']);
$user->setEmail($o['email']);
$user->setDateOfBirth(new \DateTime($o['dob']));
$user->setPlainPassword($o['password']);
foreach ($o['groups'] as $group) {
$user->addGroup($this->getReference('group' . $group));
}
$mngr->updateUser($user);
$this->setReference('user' . $user->getUsername(), $user);
}
}
}
| mit |
kpdecker/six-speed | lib/data-store.js | 681 | const _ = require('lodash');
const Fs = require('fs');
const dataFile = `${__dirname}/../data.json`;
const notesFile = `${__dirname}/../notes.json`;
module.exports.load = () => JSON.parse(Fs.readFileSync(dataFile).toString());
module.exports.notes = () => JSON.parse(Fs.readFileSync(notesFile).toString());
module.exports.store = function(browser, tag, version, stats) {
const data = this.load();
tag = tag || version;
data[browser] = data[browser] || {};
data[browser][tag] = data[browser][tag] || {stats: {}};
data[browser][tag].version = version;
_.extend(data[browser][tag].stats, stats);
Fs.writeFileSync(dataFile, JSON.stringify(data, undefined, 2));
};
| mit |
barneywilliams/cmock-build | scripts/create_runner.rb | 956 | if ($0 == __FILE__)
#make sure there is at least one parameter left (the input file)
if ARGV.length < 2
puts ["\nusage: ruby #{__FILE__} input_test_file (output)",
"",
" input_test_file - this is the C file you want to create a runner for",
" output - this is the name of the runner file to generate",
" defaults to (input_test_file)_Runner",
].join("\n")
exit 1
end
require 'cmock'
require 'fileutils'
root = File.expand_path(File.join(File.dirname(__FILE__), '../'))
src_dir = ENV.fetch('SRC_DIR', File.join(root, 'src'))
test_dir = ENV.fetch('TEST_DIR', File.join(root, 'test'))
runners_dir = ENV.fetch('RUNNERS_DIR', File.join(root, 'build/runners'))
require "#{root}/vendor/cmock/vendor/unity/auto/generate_test_runner"
test = ARGV[0]
runner = ARGV[1]
generator = UnityTestRunnerGenerator.new
generator.run(test, runner)
end
| mit |
drminix/ctsimulator | source/imagewidget.cpp | 1368 | /****************************
* Author: Sanghyeb(Sam) Lee
* Date: Jan/2013
* email: drminix@gmail.com
* Copyright 2013 Sang hyeb(Sam) Lee MIT License
*
* X-ray CT simulation & reconstruction
*****************************/
#include "imagewidget.h"
imageWidget::imageWidget(double* data,int twidth,int theight,drawingarea *md):
QWidget(0), phantom_width(twidth), phantom_height(theight), maindrawingarea(md) {
setStyleSheet("background-color:red;");
//create an image phantom
mymatrix = new matrix(data,theight,twidth);
phantom = mymatrix->getQImage();
}
void imageWidget::paintEvent(QPaintEvent *) {
//creates a painter object for drawing on this device
QPainter painter(this);
//use stylesheets
QStyleOption opt;
opt.init(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
//draw phantom
if(this->phantom!=NULL ) {
//new size
QSize widgetSize= this->phantom->size();
widgetSize.setWidth(widgetSize.width()*maindrawingarea->zoomfactor);
widgetSize.setHeight(widgetSize.height()*maindrawingarea->zoomfactor);
QImage scaledImage = phantom->scaled(widgetSize);
QPointF point(this->width()/2 - scaledImage.width()/2,
this->height()/2 - scaledImage.height()/2);
painter.drawImage(point,scaledImage);
}
}
| mit |
k-kuwahara/event_manage | application/tests/models/query_model_test.php | 11386 | <?php
/**
* DBへのデータ挿入、更新、論理削除、物理削除のテスト
* データ抽出は必ず使用するため明示的には記載しない
**/
class Query_model_test extends TestCase {
// セットアップ
public function setUp()
{
$this->CI =& get_instance();
$this->CI->load->model('query_model');
$this->obj_query = $this->CI->query_model;
}
// 全データの物理削除テスト
public function test_index() {
// 全イベントを削除
$event_delete_result = $this->obj_query->physical_delete('dt_event');
// 全回答を削除
$answer_delete_result = $this->obj_query->physical_delete('dt_answer');
// 正常終了確認
$this->assertTrue($event_delete_result);
$this->assertTrue($answer_delete_result);
// 登録データ取得
$tmp = $this->obj_query->select(
'dt_event',
'*',
''
);
$events = $tmp->result_array();
$tmp = $this->obj_query->select(
'dt_answer',
'*',
''
);
$answers = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($events), 0);
$this->assertEquals(count($answers), 0);
}
// データ挿入テスト
public function test_data_insert() {
// イベントデータの挿入
$test_events = [
[
'event_title' => 'テストイベントタイトル1',
'create_date' => date('Y-m-d H:i:s'),
'update_date' => date('Y-m-d H:i:s'),
'event_date' => '2015/12/22 19:00',
'email' => 'foo@gmail.com',
'del_flg' => 0,
],
[
'event_title' => 'テストイベントタイトル2',
'create_date' => date('Y-m-d H:i:s'),
'update_date' => date('Y-m-d H:i:s'),
'event_date' => '2015/12/25 20:30',
'email' => 'bar@yahoo.co.jp',
'del_flg' => 1,
],
[
'event_title' => 'テストイベントタイトル3',
'create_date' => date('Y-m-d H:i:s'),
'update_date' => date('Y-m-d H:i:s'),
'event_date' => '2016/01/04 09:30',
'email' => 'baz@hotmail.co.jp',
'del_flg' => 0,
]
];
foreach ($test_events as $event) {
// 登録実行
$result = $this->obj_query->insert('dt_event', $event);
// 正常終了確認
$this->assertTrue($result);
}
// 登録イベントデータ全件取得
$tmp = $this->obj_query->select(
'dt_event',
'*',
''
);
$events = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($events), 3);
$this->assertEquals($events[0]['event_title'], 'テストイベントタイトル1');
$this->assertEquals($events[1]['del_flg'], '1');
$this->assertEquals($events[2]['email'], 'baz@hotmail.co.jp');
// 登録イベントデータ取得(del_flg = 0)
$tmp = $this->obj_query->select(
'dt_event',
'*',
[
'del_flg' => 0
]
);
$events = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($events), 2);
$this->assertEquals($events[0]['event_title'], 'テストイベントタイトル1');
$this->assertEquals($events[1]['email'], 'baz@hotmail.co.jp');
// 回答データの挿入
$answers = [
[
'event_id' => $events[0]['event_id'],
'answer_date' => date('Y-m-d H:i:s'),
'answer' => 3,
'answer_name' => 'ほげテスト',
'email' => 'hogehoge@gmail.com',
'memo' => 'テストメモ1',
],
[
'event_id' => $events[0]['event_id'],
'answer_date' => date('Y-m-d H:i:s'),
'answer' => 1,
'answer_name' => 'ふがテスト',
'email' => 'fugafuga@yahoo.co.jp',
'memo' => 'テストメモ2',
],
[
'event_id' => $events[1]['event_id'],
'answer_date' => date('Y-m-d H:i:s'),
'answer' => 2,
'answer_name' => 'ぴよテスト',
'email' => 'piyopiyo@hotmail.co.jp',
'memo' => 'テストメモ3',
]
];
foreach ($answers as $answer) {
// 登録実行
$result = $this->obj_query->insert('dt_answer', $answer);
// 正常終了確認
$this->assertTrue($result);
}
// 登録回答データ全件取得
$tmp = $this->obj_query->select(
'dt_answer',
'*',
''
);
$answers = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($answers), 3);
$this->assertEquals($answers[0]['answer_name'], 'ほげテスト');
$this->assertEquals($answers[1]['answer'], '1');
$this->assertEquals($answers[2]['email'], 'piyopiyo@hotmail.co.jp');
}
// データ更新テスト
public function test_data_update() {
// 登録イベントデータ全件取得
$tmp = $this->obj_query->select(
'dt_event',
'*',
''
);
$events = $tmp->result_array();
// 登録回答データ全件取得
$tmp = $this->obj_query->select(
'dt_answer',
'*',
''
);
$answers = $tmp->result_array();
// イベントデータ更新
foreach ($events as $e_key => $event) {
$event_update_result = $this->obj_query->update(
'dt_event',
[
'event_title' => 'イベントタイトルテストNo'. ($e_key+1),
'create_date' => date('Y-m-d H:i:s'),
'update_date' => date('Y-m-d H:i:s'),
'del_flg' => 0
],
[
'event_id' => $event['event_id'],
]
);
// 正常終了確認
$this->assertTrue($event_update_result);
}
// 登録イベントデータ全件取得
$tmp = $this->obj_query->select(
'dt_event',
'*',
''
);
$events = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($events), 3);
$this->assertEquals($events[0]['event_title'], 'イベントタイトルテストNo1');
$this->assertEquals($events[1]['event_title'], 'イベントタイトルテストNo2');
$this->assertEquals($events[2]['event_title'], 'イベントタイトルテストNo3');
// 回答データ更新
foreach ($answers as $a_key => $answer) {
$answer_update_result = $this->obj_query->update(
'dt_answer',
[
'answer_date' => date('Y-m-d H:i:s'),
'answer' => $a_key+1,
'memo' => 'メモテストNo' . ($a_key+1),
],
[
'answer_id' => $answer['answer_id'],
]
);
// 正常終了確認
$this->assertTrue($answer_update_result);
}
// 登録回答データ全件取得
$tmp = $this->obj_query->select(
'dt_answer',
'*',
''
);
$answers = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($answers), 3);
$this->assertEquals($answers[0]['answer'], '1');
$this->assertEquals($answers[1]['answer'], '2');
$this->assertEquals($answers[2]['answer'], '3');
$this->assertEquals($answers[0]['memo'], 'メモテストNo1');
$this->assertEquals($answers[1]['memo'], 'メモテストNo2');
$this->assertEquals($answers[2]['memo'], 'メモテストNo3');
}
// イベントデータ論理削除(回答にはdel_flgが存在しないため対象外)
public function test_logical_delete() {
// 登録イベントデータ取得(del_flg=0)
$tmp = $this->obj_query->select(
'dt_event',
'*',
[
'del_flg' => 0
]
);
$events = $tmp->result_array();
$event_id = $events[0]['event_id'];
// イベント論理削除
$result = $this->obj_query->logical_delete(
'dt_event',
[
'event_id' => $event_id,
]
);
// 正常終了確認
$this->assertTrue($result);
// 論理削除したイベントデータを再度取得
$tmp = $this->obj_query->select(
'dt_event',
'*',
[
'event_id' => $event_id
]
);
$one_event = $tmp->result_array();
// 正常終了確認
$this->assertEquals($one_event[0]['del_flg'], '1');
// 全件論理削除
$result = $this->obj_query->logical_delete('dt_event', '');
// 正常終了確認
$this->assertTrue($result);
// 登録イベントデータ全件取得
$tmp = $this->obj_query->select(
'dt_event',
'*',
[
'del_flg' => 1
]
);
$events = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($events), 3);
}
// テストデータを全件削除したい方は以下のコメントアウトを外してください。
/*
// 全データの物理削除テスト
public function test_alldelete() {
// 全イベントを削除
$event_delete_result = $this->obj_query->physical_delete('dt_event');
// 全回答を削除
$answer_delete_result = $this->obj_query->physical_delete('dt_answer');
// 正常終了確認
$this->assertTrue($event_delete_result);
$this->assertTrue($answer_delete_result);
// 登録データ取得
$tmp = $this->obj_query->select(
'dt_event',
'*',
''
);
$events = $tmp->result_array();
$tmp = $this->obj_query->select(
'dt_answer',
'*',
''
);
$answers = $tmp->result_array();
// 正常終了確認
$this->assertEquals(count($events), 0);
$this->assertEquals(count($answers), 0);
}
*/
}
| mit |
cdnjs/cdnjs | ajax/libs/react-timeago/4.0.0/language-strings/de-short.min.js | 335 | "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var strings={prefixAgo:null,prefixFromNow:null,suffixAgo:"",suffixFromNow:"",seconds:"s",minute:"1m",minutes:"%dm",hour:"1h",hours:"%dh",day:"1T.",days:"%dT.",month:"1Mt.",months:"%dMt.",year:"1J.",years:"%dJ.",wordSeparator:" ",numbers:null};exports.default=strings; | mit |
evought/VCard-Tools | src/TypedPropertyBuilderTrait.php | 3053 | <?php
/**
* A trait for a TypedPropertyBuilder.
*
* @link https://github.com/evought/VCard-Tools
* @author Eric Vought
* @see RFC 2426, RFC 2425, RFC 6350
* @license MIT http://opensource.org/licenses/MIT
*/
/*
* The MIT License
*
* Copyright 2014 evought.
*
* 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.
*/
namespace EVought\vCardTools;
/**
* A trait to contain reusable code for TypePropertyBuilders.
*/
trait TypedPropertyBuilderTrait
{
private $types;
protected function initTypes()
{
$this->types = [];
\assert(array_key_exists( 'allowedTypes',
$this->getSpecification()->getConstraints()) );
}
protected function setTypesFromLine(VCardLine $line)
{
if (!empty($line->getParameter('type')))
$this->setTypes($line->getParameter('type'));
}
public function addType($type)
{
$this->checkType($type);
if (!(in_array($type, $this->types)))
$this->types[] = $type;
return $this;
}
protected function checkType($type)
{
\assert(null !== $type);
\assert(is_string($type));
if (empty($this->getAllowedTypes())) return true;
if (!(in_array($type, $this->getAllowedTypes())))
throw new \DomainException( $type . ' is not an allowed type for '
. $this->getName() );
return true;
}
public function getTypes()
{
return $this->types;
}
public function setTypes(Array $types)
{
$this->types = array_filter($types, [$this, 'checkType']);
return $this;
}
/**
* If the array is empty, all types are permitted.
* This is used for X-tended properties for which we do not have a
* specification and therefore cannot enforce type constraints.
* @return type
*/
public function getAllowedTypes()
{
return $this->getSpecification()->getConstraints()['allowedTypes'];
}
}
| mit |
ephp/JF | app/Resources/public/js/actions.js | 11504 | var ws;
$(document).ready(function() {
ws = $('body').width();
$('a.fancybox').each(function() {
if ($(this).attr('href').startsWith('#')) {
$(this).fancybox({
hideOnOverlayClick: false,
transitionIn: 'elastic',
padding: 3,
margin: 0
});
} else {
$(this).fancybox({
type: 'ajax',
hideOnOverlayClick: false,
transitionIn: 'elastic',
padding: 3,
margin: 0
});
}
});
$('.live-filter').keyup(function() {
var $filter = $(this);
var $elements = $('.' + $(this).attr('rel'));
$elements.hide();
$elements.each(function(element) {
if ($(this).attr('livefilter').toLowerCase().search($filter.val().toLowerCase()) >= 0) {
$(this).show();
}
});
});
$('nav').each(function() {
if ($(this).attr('append')) {
$(this).children('ul').addClass($(this).attr('append'));
$(this).removeAttr('append');
}
});
$('li.submenu').append('<div class="open"></div>').removeClass('submenu');
/* Site settings */
var sSet = $.cookies.get('sSet');
if (null == sSet) {
$.cookies.set('sSet', '1');
$.cookies.set('cNav', 'bordered');
}
var cNav = $.cookies.get('cNav');
var cCont = $.cookies.get('cCont');
if (null != cNav) {
if (cNav == 'bordered') {
$(".sidebar .navigation").addClass('bordered');
$(".cNav").attr('checked', false);
$(".cNav[value='bordered']").attr('checked', true).parent('span').addClass('checked');
}
} else
$(".cNav[value='default']").attr('checked', true).parent('span').addClass('checked');
if (null != cCont) {
$(".wrapper").addClass(cCont);
$(".cCont").attr('checked', false);
$(".cCont[value='" + cCont + "']").attr('checked', true).parent('span').addClass('checked');
} else
$(".cCont[value='']").attr('checked', true).parent('span').addClass('checked');
$(".cNav").click(function() {
var val = $(this).val();
if (val != 'default') {
$(".sidebar .navigation").addClass(val);
$.cookies.set('cNav', val);
} else {
$(".sidebar .navigation").removeClass('bordered');
$.cookies.set('cNav', null);
}
});
$(".cCont").click(function() {
var val = $(this).val();
$(".wrapper").removeClass('fixed').addClass(val);
$.cookies.set('cCont', val);
});
/* eof site settings */
$(".navigation.narrow > li > a").click(function() {
var li = $(this).parent('li');
if (li.find('ul').length > 0) {
if (li.hasClass('active'))
li.removeClass('active');
else
li.addClass('active');
return false;
}
});
$(".navButton a, .sidebar .close").click(function() {
if ($(".sidebar").is(":visible"))
$(".sidebar").slideUp();
else
$(".sidebar").slideDown();
});
$(".sbutton a").click(function() {
var popup = $(this).parent('.sbutton').find('.popup');
if (popup.length > 0) {
if (popup.hasClass('active'))
popup.removeClass('active');
else {
popup.addClass('active');
popup.find('.checker').show();
popup.find('.radio').show();
}
return false;
}
});
/* input file */
$(".file .btn, .file input:text").click(function() {
var block = $(this).parent('.file');
block.find('input:file').click();
block.find('input:file').change(function() {
block.find('input:text').val(block.find('input:file').val());
});
});
/* eof input file */
//temp as example
$(".ublock").click(function() {
var block = $(this).parents('[class^=block]');
add_loader(block);
setTimeout(function() {
remove_loader(block);
}, 2000);
return false;
});
$(".head .buttons > li > a").click(function(event) {
var li = $(this).parent('li');
if (li.find('ul').length > 0) {
if (li.hasClass('active'))
li.removeClass('active');
else
li.addClass('active');
return false;
}
event.stopPropagation();
});
$(".cblock").click(function() {
var block = $(this).parents('.block').find("[class^=data]");
if (block.is(':visible')) {
block.fadeOut();
} else {
block.fadeIn();
}
return false;
});
$(".body .navigation li a").click(function() {
if ($(this).attr('href') == '#') {
if ($(this).parent('li').hasClass("active")) {
$(this).parent('li').removeClass('active');
} else {
$(".body .navigation li").removeClass('active');
$(this).parent('li').addClass('active');
}
return false;
}
});
$(".sidebar .navigation > li > a, .sidebar .navigation > li > .open").click(function() {
if ($(this).parent('li').find('ul').length > 0) {
if ($(this).parent('li').hasClass('active')) {
$(this).parent('li').removeClass('active');
} else {
$(this).parent('li').addClass('active');
}
return false;
}
});
/* table checkall */
$("table .checkall").click(function() {
var iC = $(this).parents('th').index(); //index of checkall checkbox
var tB = $(this).parents('table').find('tbody'); // tbody of table
if ($(this).is(':checked'))
tB.find('tr').each(function() {
$(this).addClass('active').find('td:eq(' + iC + ') input:checkbox').attr('checked', true).parent('span').addClass('checked');
});
else
tB.find('tr').each(function() {
$(this).removeClass('active').find('td:eq(' + iC + ') input:checkbox').attr('checked', false).parent('span').removeClass('checked');
});
});
/* eof table checkall */
$("table .checker").click(function(event) {
var tr = $(this).parents('tr');
if (tr.hasClass('active'))
tr.removeClass('active');
else
tr.addClass('active');
event.stopPropagation();
});
/* table row check */
$(".table-row-check tbody tr").click(function() {
if ($(this).hasClass('active'))
$(this).removeClass('active');
else
$(this).addClass('active');
$(this).find('input:checkbox').each(function() {
if ($(this).is(':checked')) {
$(this).attr('checked', false).parent('span').removeClass('checked');
} else {
$(this).attr('checked', true).parent('span').addClass('checked');
}
});
});
/* eof table row check */
/* alert click */
$(".alert").click(function() {
$(this).animate({opacity: 0}, '200', 'linear', function() {
$(this).remove();
});
});
/* eof alert click*/
if(ws <= 768) {
$('.body .navigation').children('.active').find('a').click();
}
});
$(window).load(function() {
fix();
$("#loader").hide();
if ($('body').width() <= 1024) {
$('.navigation').addClass('narrow');
if ($('.navigation').hasClass('bordered'))
$('.navigation').removeClass('bordered').addClass('btemp');
}
if ($(".thumbs").length > 0)
thumbs();
});
$(window).resize(function() {
if (Math.abs(ws - $('body').width()) > 50) {
ws = $('body').width();
fix();
if ($('body').width() <= 1024) {
$('.navigation').addClass('narrow');
if ($('.navigation').hasClass('bordered'))
$('.navigation').removeClass('bordered').addClass('btemp');
} else {
$(".sidebar").removeAttr('style');
$('.navigation').removeClass('narrow');
if ($('.navigation').hasClass('btemp'))
$('.navigation').removeClass('btemp').addClass('bordered');
}
if ($(".thumbs").length > 0)
thumbs();
}
});
function fix() {
fix_block_items_width('.input-prepend', ['.add-on', 'button'], 'input');
fix_block_items_width('.input-append', ['.add-on', 'button'], 'input');
if ($(".wrapper > .body").height() < window.innerHeight)
$(".wrapper > .body").height(window.innerHeight + 10);
else
$(".wrapper > .body").removeAttr('style');
}
function add_loader(block) {
var bW = $(block).width();
var bH = $(block).height();
$(block).append('<div class="loader" style="width: ' + bW + 'px; height: ' + bH + 'px;"><img src="img/loader.gif"/></div>');
}
function remove_loader(block) {
$(block).find('.loader').remove();
}
function fix_block_items_width(block, what, to) {
/* Func for fix bootstrap prepended items(bootstrap)
* by Aqvatarius for Aries
* */
$(block).each(function() {
var iWidth = $(this).width();
if (what.length > 0) {
for (var i = 0; i < what.length; i++) {
$(this).find(what[i]).each(function() {
iWidth -= $(this).width() + (parseInt($(this).css('padding-left')) * 2);
});
}
$(this).find(to).width(iWidth - 14);
}
});
}
function source(doc) {
$("#source").dialog({autoOpen: false,
modal: true,
width: (3 * $('body').width() / 4),
zindex: 30,
position: "right",
dialogClass: 'sourcePosition',
close: function() {
$("#source").html('');
}
});
$.get(Routing.generate(doc), function(data) {
$("#source").html(data);
$('.rollover li').each(function() {
$(this).html('<a href="javascript:void(0)">' + $(this).html() + '</a>');
});
$('.rollover li a').click(function() {
$('.' + $(this).closest('.rollover').attr('rel')).hide();
$('.' + $(this).closest('li').attr('rel')).show();
});
}).fail(function() {
$("#source").html('Unknown document');
});
$("#source").dialog('open');
}
function thumbs() {
$(".thumbs").each(function() {
var maxImgHeight = 0;
var maxTextHeight = 0;
$(this).find(".thumbnail").each(function() {
var imgHeight = $(this).find('a > img').height();
var textHeight = $(this).find('.caption').height();
maxImgHeight = maxImgHeight < imgHeight ? imgHeight : maxImgHeight;
maxTextHeight = maxTextHeight < textHeight ? textHeight : maxTextHeight;
});
$(this).find('.thumbnail > a').height(maxImgHeight);
$(this).find('.thumbnail .caption').height(maxTextHeight);
});
var w_block = $(".thumbs").width() - 20;
var w_item = $(".thumbs .thumbnail").width() + 10;
var c_items = Math.floor(w_block / w_item);
var m_items = Math.floor((w_block - w_item * c_items) / (c_items * 2));
$(".thumbs .thumbnail").css('margin', m_items);
} | mit |
waqasilyas/json-converter-bmpr | BmprArchiveModel/Model/MockupSymbol.cs | 459 | namespace BmprArchiveModel.Model
{
public class MockupSymbol : AbstractControl
{
#region Properties
/*
[JsonProperty(Order = 20)]
public MockupControl[] Symbols
{
get
{
if (Children != null && Children.Controls != null)
return Children.Controls.Control;
return null;
}
}
*/
#endregion
}
}
| mit |
psliwa/idea-composer-plugin | src/test/scala/org/psliwa/idea/composerJson/composer/model/version/VersionSuggestionsTest.scala | 4121 | package org.psliwa.idea.composerJson.composer.model.version
import org.psliwa.idea.composerJson.BasePropSpec
import org.psliwa.idea.composerJson.composer.model.version.{VersionGenerators => gen}
import org.scalacheck.{Gen, Prop}
import org.scalacheck.Prop.{forAll, propBoolean}
class VersionSuggestionsTest extends BasePropSpec {
//generators
def semanticVersionGen(prefix: String = ""): Gen[GeneratedVersion] =
gen.semanticVersion(3).map(version => GeneratedVersion(prefix + version.presentation))
def nonSemanticVersionGen: Gen[GeneratedVersion] =
Gen.oneOf(gen.devVersion, gen.hashVersion).map(version => GeneratedVersion(version.presentation))
def prefixGen: Gen[Prefix] =
for {
prefixVersion <- Gen.option(Gen.oneOf(semanticVersionGen(), nonSemanticVersionGen).map(_.get))
prefix <- gen.constraintOperator.map(_.toString)
} yield Prefix(prefix + prefixVersion.getOrElse(""))
//properties
property("suggestions for pure semantic version") {
forAll(semanticVersionGen(prefix = "")) { version: GeneratedVersion =>
val suggestions = VersionSuggestions.suggestionsForVersion(version.get, "")
checkSemanticVersionAlternatives(version.get, suggestions)
}
}
property("suggestions for pure semantic version and prefix") {
forAll(prefixGen, semanticVersionGen(prefix = "")) { (prefix: Prefix, version: GeneratedVersion) =>
val suggestions = VersionSuggestions.suggestionsForVersion(version.get, prefix.get)
val suggestionsForPrefixedVersion = VersionSuggestions.suggestionsForVersion(s"v${version.get}", prefix.get)
suggestions.contains(version.get) :| "suggestions contain original version" &&
(!suggestions.exists(_.contains('*'))) :| "suggestions don't contain wildcarded versions" &&
(suggestionsForPrefixedVersion == suggestions) :| "suggestions for 'v' prefixed versions are the same"
}
}
property("suggestions for prefixed semantic version") {
forAll(semanticVersionGen(prefix = "v")) { version: GeneratedVersion =>
val suggestions = VersionSuggestions.suggestionsForVersion(version.get, "")
val pureSemanticVersion = version.get.drop(1)
val suggestionsWithoutOriginal = suggestions.filterNot(_ == version.get)
checkSemanticVersionAlternatives(pureSemanticVersion, suggestionsWithoutOriginal) &&
suggestions.contains(version.get) :| "suggestions contain prefixed semantic version"
}
}
property("suggestions for non semantic version") {
forAll(nonSemanticVersionGen) { version: GeneratedVersion =>
val suggestions = VersionSuggestions.suggestionsForVersion(version.get, "")
suggestions.contains(version.get) :| "suggestions contain original version" &&
(suggestions.size == 1) :| "suggestions contain only one suggestion"
}
}
def checkSemanticVersionAlternatives(version: String, suggestions: Seq[String]): Prop = {
val wildcards = wildcard(suggestions)
suggestions.contains(version) :| "suggestions contain original pure semantic version" &&
(suggestions.size == 3) :| s"there are 3 suggestions: $suggestions" &&
(suggestions.distinct.size == 3) :| s"suggestions are unique: $suggestions" &&
(wildcard(suggestions).size == 2) :| "there are 2 wildcard suggestions" &&
wildcards.forall(_.endsWith(".*")) :| "wildcard suggestions end with *" &&
wildcards.forall(matches(_, version)) :| "all wildcard suggestions matches original one" &&
wildcards.forall(_.startsWith(version.substring(0, 1))) :| "wildcard suggestions start as same as original one"
}
def wildcard(suggestions: Seq[String]): Seq[String] = suggestions.filter(_.contains("*"))
def matches(wildcard: String, version: String): Boolean = {
val regexp = ("^" + wildcard.replace(".", "\\.").replace("*", ".*") + "$").r
regexp.findFirstMatchIn(version).isDefined
}
case class GeneratedVersion(get: String)
case class Prefix(get: String)
}
| mit |
mkechinov/frontend_template | template/template.rb | 6345 | # Simple wrapper to replace Gemfile completely and add readability
# @param [Block] block
# @return Replaces Gemfile contents with new one from the block
def gemfile(&block)
run 'echo "" > Gemfile'
yield
end
gemfile do
add_source 'https://rubygems.org'
append_file 'Gemfile', "\n\# Last stable rails gem", verbose: false
gem 'rails', version: '4.2.1'
append_file 'Gemfile', "\n\n\# Database gem", verbose: false
gem 'pg'
unless no? 'Use ActiveAdmin? [Yn]'
run 'echo "" >> Gemfile'
append_file 'Gemfile', "\n\n\# Authentication", verbose: false
@activeadmin = true
gem 'devise'
gem 'activeadmin', github: 'activeadmin'
end
append_file 'Gemfile', "\n\n\# Frontend gems", verbose: false
gem 'autoprefixer-rails'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'sass'
gem 'sass-rails'
gem 'slim-rails'
append_file 'Gemfile', "\n\n\# Developer gems", verbose: false
gem_group :development do
gem 'better_errors'
gem 'binding_of_caller'
gem 'capistrano'
gem 'capistrano-bundler'
gem 'capistrano-rails'
gem 'capistrano-rvm'
gem 'capistrano-sidekiq'
gem 'jazz_hands', github: 'nixme/jazz_hands', branch: 'bring-your-own-debugger'
gem 'letter_opener_web'
gem 'quiet_assets'
gem 'spring'
gem 'thin'
gem 'yard'
end
end
say 'Setting up application config (config/application.rb)..'
application do
"# Setup generators
config.generators do |generate|
generate.orm :active_record
generate.helper false
generate.assets false
generate.test_framework false
end
"
end
application do
"# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run 'rake -D time' for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = \'Moscow\'
"
end
application do
'# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.autoload_paths += %W(#{config.root}/lib)
'
end
say 'Setting up application environments (config/environments/*.rb)..'
environment nil, env: 'development' do
"config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :letter_opener_web
"
end
say 'Setting up locale config for Russian (config/initializers/locale.rb)..'
initializer 'locale.rb' do
"I18n.enforce_available_locales = false
I18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
I18n.default_locale = :ru
"
end
after_bundle do
# Readme.md
say 'Using GitHub markdown for Readme file..'
run 'rm README.rdoc && touch README.md'
# .gitignore
say 'Updating .gitignore file..'
run 'curl -o .gitignore https://raw.githubusercontent.com/mkechinov/frontend_template/master/.gitignore'
inside 'config' do
say 'Replacing database.yml with its example..'
run 'curl -o database.yml.example https://raw.githubusercontent.com/mkechinov/frontend_template/master/template/database.yml.example'
run 'cp database.yml.example database.yml'
say 'Adding bower folders to asset paths..'
inside 'initializers' do
run "echo \"\n# Add paths to shorten manifests\' links to files\nRails.application.config.assets.paths << Rails.root.join\(\'vendor\', \'assets\', \'components\'\)\" >> assets.rb"
end
end
inside 'app/assets' do
inside 'stylesheets' do
run 'mkdir includes'
inside 'includes' do
run 'echo "// Set all variables here" > _variables.sass'
run 'echo "// Set all fonts here" > _fonts.sass'
run 'echo "// This is a mini-manifest file to be included into every file in project\n// It imports all variables and mixins\n@import \"sass-mediaqueries/media-queries\"\n@import \"variables\"\n@import \"fonts\" " > mixins.sass'
end
run 'mkdir project && echo "@import \"includes/mixins\"\n\n// All helper-classes should start with \'h-\' prefix, i.e. h-text-center" > project/_helpers.sass'
run 'mkdir third-party'
run 'echo "/*\n *= require_tree ./third-party\n *= require_tree ./project\n */" > application.css'
end
inside 'javascripts' do
run 'echo "//= require jquery\n//= require jquery_ujs" > application.js'
end
end
# Setup activeadmin
if @activeadmin
run 'spring stop'
devise_model_name = ask("What would you like the user model to be called? [User]")
devise_model_name = 'User' if devise_model_name.blank?
generate 'devise:install'
generate 'devise', devise_model_name.camelize
activeadmin_model_name = ask("What would you like the admin_user model to be called? [AdminUser]")
activeadmin_model_name = 'AdminUser' if activeadmin_model_name.blank?
generate "active_admin:install #{activeadmin_model_name.camelize}"
end
# Setup bower
run 'curl -o bower.json https://raw.githubusercontent.com/mkechinov/frontend_template/master/template/bower.json'
run "echo '{\n \"directory\": \"vendor/assets/components\"\n}' > .bowerrc"
run 'bower install'
# Setup Capistrano
run 'bundle exec cap install'
# Add bower task to capistrano
run "echo \"\nnamespace :deploy do
desc 'install assets dependencies with bower'
task :prepare_assets_dependencies do
on roles(:web) do
within release_path do
with rails_env: fetch(:rails_env) do
execute :bower, :install
end
end
end
end
before 'deploy:updated', 'deploy:prepare_assets_dependencies'
end\" >> config/deploy.rb"
# Setup Git
# Use git flow for (develop -> staging) and (master -> production) deploys
say 'Setting git up..'
git :init
git checkout: '-b develop'
git add: '--all'
git commit: "-m 'Initial commit'"
repo = ask('Введите адрес git-репозитория: ').strip
git remote: "add origin #{repo}"
# git push: '-u origin develop'
say "\n\nNew application constructed."
if @activeadmin
say "\n\nMake sure all migrations are correct and then run"
say "\tbundle exec rake db:migrate"
say "over your database"
end
say "\n\nDon't forget to set fixed versions for all gems!"
say "\n\nRemember to configure Capistrano (Capfile, config/deploy.rb, config/deploy/*.rb)"
end
| mit |
excellentingenuity/EloquentUUID | src/EloquentUUID.php | 420 | <?php
namespace eig\EloquentUUID;
use eig\EloquentUUID\Traits\UUID;
use Illuminate\Database\Eloquent\Model;
/**
* Class EloquentUUID
* @package App
* @license MIT
* @author James Johnson
* @author Excellent InGenuity LLC
*/
abstract class EloquentUUID extends Model
{
use UUID;
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
}
| mit |
iobuild/io_ask | db/seeds.rb | 310 | IoAsk::Topic.create(:title => 'test title1')
IoAsk::Topic.create(:title => 'test title2')
ask_root_category = IoAsk.category_class.create(:name => 'Ask')
IoAsk.category_class.create(:name => 'test c1', :parent => ask_root_category)
IoAsk.category_class.create(:name => 'test c2', :parent => ask_root_category) | mit |
dieggop/prefeiturasertania | resources/views/site/downloads.blade.php | 1073 | @extends('site.index')
@section('content_index')
<div class="container">
<div class="row">
<!-- Slider -->
<div class="col-sm-12 col-lg-12">
<div class="well">
<h3><strong>Downloads</strong></h3>
<div class="divider-dashed">
<hr>
</div>
<div class="list-group">
@foreach($downloads as $download)
<a href="{!! route('downloads-one', $download->id) !!}" target="_blank" class="list-group-item">
<span class="badge">{!! $download->quantidade !!} downloads</span>
<h4 class="list-group-item-heading"><strong>{!! $download->title !!}</strong></h4>
<p class="list-group-item-text">{!! $download->sobre !!}</p>
</a>
@endforeach
</div>
</div>
</div>
</div>
</div>
@endsection | mit |
olegfox/olere | src/Sylius/Bundle/CoreBundle/Model/VariantInterface.php | 1991 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\CoreBundle\Model;
use Doctrine\Common\Collections\Collection;
use Sylius\Bundle\VariableProductBundle\Model\VariantInterface as BaseVariantInterface;
use Sylius\Bundle\InventoryBundle\Model\StockableInterface;
use Sylius\Bundle\ShippingBundle\Model\ShippableInterface;
/**
* Sylius core product Variant interface.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
interface VariantInterface extends BaseVariantInterface, PriceableInterface, ShippableInterface, StockableInterface
{
/**
* Get images.
*
* @return Collection|VariantImageInterface[]
*/
public function getImages();
/**
* Checks if product has image.
*
* @param VariantImageInterface $image
*
* @return Boolean
*/
public function hasImage(VariantImageInterface $image);
/**
* Add image.
*
* @param VariantImageInterface $image
*/
public function addImage(VariantImageInterface $image);
/**
* Remove image.
*
* @param VariantImageInterface $image
*/
public function removeImage(VariantImageInterface $image);
/**
* @return integer
*/
public function getWeight();
/**
* @param integer $weight
*/
public function setWeight($weight);
/**
* @return integer
*/
public function getWidth();
/**
* @param integer $width
*/
public function setWidth($width);
/**
* @return integer
*/
public function getHeight();
/**
* @param integer $height
*/
public function setHeight($height);
/**
* @return integer
*/
public function getDepth();
/**
* @param integer $depth
*/
public function setDepth($depth);
}
| mit |
gponster/laravel-oauth-server | src/models/AccessToken.php | 713 | <?php
namespace Gponster\OAuth\Provider;
use Illuminate\Database\Eloquent\Model;
/**
* Class AccessToken
*
* @author Vu Dang a.k.a Gponster <anhvudg@gmail.com>
* @see http://code.google.com/p/oauth-php
*/
class AccessToken extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'oauth_access_tokens';
/**
*
* @var array
*/
protected $guarded = [];
public function __construct($attributes = array()) {
parent::__construct($attributes);
$connectionName = \Config::get('gponster/laravel-oauth-server::database.default');
if(! empty($connectionName)) {
$this->connection = 'gponster/laravel-oauth-server::' . $connectionName;
}
}
} | mit |
datapimp/basicpages | lib/basicpages.rb | 13 | # Basicpages
| mit |
RectorPHP/Rector | rules/Transform/Rector/StaticCall/StaticCallToFuncCallRector.php | 2991 | <?php
declare (strict_types=1);
namespace Rector\Transform\Rector\StaticCall;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Name\FullyQualified;
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\Transform\ValueObject\StaticCallToFuncCall;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use RectorPrefix20210615\Webmozart\Assert\Assert;
/**
* @see \Rector\Tests\Transform\Rector\StaticCall\StaticCallToFuncCallRector\StaticCallToFuncCallRectorTest
*/
final class StaticCallToFuncCallRector extends \Rector\Core\Rector\AbstractRector implements \Rector\Core\Contract\Rector\ConfigurableRectorInterface
{
/**
* @var string
*/
public const STATIC_CALLS_TO_FUNCTIONS = 'static_calls_to_functions';
/**
* @var mixed[]
*/
private $staticCallsToFunctions = [];
/**
* @param StaticCallToFuncCall[] $staticCallsToFunctions
*/
public function __construct(array $staticCallsToFunctions = [])
{
$this->staticCallsToFunctions = $staticCallsToFunctions;
}
public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
{
return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns static call to function call.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('OldClass::oldMethod("args");', 'new_function("args");', [self::STATIC_CALLS_TO_FUNCTIONS => [new \Rector\Transform\ValueObject\StaticCallToFuncCall('OldClass', 'oldMethod', 'new_function')]])]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [\PhpParser\Node\Expr\StaticCall::class];
}
/**
* @param StaticCall $node
*/
public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
{
foreach ($this->staticCallsToFunctions as $staticCallToFunction) {
if (!$this->isObjectType($node->class, $staticCallToFunction->getObjectType())) {
continue;
}
if (!$this->isName($node->name, $staticCallToFunction->getMethod())) {
continue;
}
return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name\FullyQualified($staticCallToFunction->getFunction()), $node->args);
}
return null;
}
/**
* @param array<string, StaticCallToFuncCall[]> $configuration
*/
public function configure(array $configuration) : void
{
$staticCallsToFunctions = $configuration[self::STATIC_CALLS_TO_FUNCTIONS] ?? [];
\RectorPrefix20210615\Webmozart\Assert\Assert::allIsInstanceOf($staticCallsToFunctions, \Rector\Transform\ValueObject\StaticCallToFuncCall::class);
$this->staticCallsToFunctions = $staticCallsToFunctions;
}
}
| mit |
mensly/attolass | sdl/main.cpp | 1219 | #ifdef MOCK_SDL
#include "../attolass.h"
#include "Mockboy.h"
#include <iostream>
SDL_Window* gWindow = NULL;
//SDL_Renderer* gRenderer = NULL;
extern Mockboy arduboy;
int main(int argc, const char * argv[]) {
//Start up SDL and create window
if (!arduboy.initSDL()) {
printf("Failed to initialize!\n");
}
else {
bool quit = false;
SDL_Event e;
arduboy.clear();
setup();
do {
while (SDL_PollEvent(&e) != 0)
{
switch (e.type) {
case SDL_QUIT:
quit = true;
break;
case SDL_KEYDOWN:
if (e.key.keysym.sym == SDLK_ESCAPE) {
quit = true;
}
else {
arduboy.onKeyDown(e.key.keysym.sym);
}
break;
case SDL_KEYUP:
arduboy.onKeyUp(e.key.keysym.sym);
break;
}
}
loop();
} while (!quit);
}
arduboy.close();
return 0;
}
#endif | mit |
daniel-rodas/wsj | fuel/app/views/blog/frontend/post/show/related.php | 838 | <?php if(empty($related_articles)): ?>
<!-- <p>--><?//= __('frontend.post.empty'); ?><!--</p>-->
<div class="advertisement blog-post-related ">
<p>Advertisement</p>
</div>
<?php else: ?>
<div class=" blog-post-related">
<?php foreach($related_articles as $post): ?>
<article id="post-related-<?php echo $post->id; ?>" >
<small>
<a href="<?= \Router::get('show_post_category', array('category' => $post->category->slug)); ?>"><?= $post->category->name; ?></a>
</small>
<a href="<?= \Router::get('show_post', array('segment' => $post->slug)); ?>" >
<h2 class=""><?= \Str::truncate($post->name, \Config::get('application.truncate', 50)); ?></h2>
</a>
</article>
<?php endforeach; ?>
</div>
<?php endif; ?> | mit |
shitikanth/jabref | src/main/java/org/jabref/model/pdf/FileAnnotation.java | 6911 | package org.jabref.model.pdf;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
public class FileAnnotation {
private static final Log LOGGER = LogFactory.getLog(FileAnnotation.class);
private final static int ABBREVIATED_ANNOTATION_NAME_LENGTH = 45;
private static final String DATE_TIME_STRING = "^D:\\d{14}$";
private static final String DATE_TIME_STRING_WITH_TIME_ZONE = "^D:\\d{14}.+";
private static final String ANNOTATION_DATE_FORMAT = "yyyyMMddHHmmss";
private final String author;
private final LocalDateTime timeModified;
private final int page;
private final String content;
private final FileAnnotationType annotationType;
private final Optional<FileAnnotation> linkedFileAnnotation;
/**
* A flexible constructor, mainly used as dummy if there is actually no annotation.
*
* @param author The authors of the annotation
* @param timeModified The last time this annotation was modified
* @param pageNumber The page of the pdf where the annotation occurs
* @param content the actual content of the annotation
* @param annotationType the type of the annotation
*/
public FileAnnotation(final String author, final LocalDateTime timeModified, final int pageNumber,
final String content, final FileAnnotationType annotationType, final Optional<FileAnnotation> linkedFileAnnotation) {
this.author = author;
this.timeModified = timeModified;
this.page = pageNumber;
this.content = parseContent(content);
this.annotationType = annotationType;
this.linkedFileAnnotation = linkedFileAnnotation;
}
/**
* Creating a normal FileAnnotation from a PDAnnotation.
*
* @param annotation The actual annotation that holds the information
* @param pageNumber The page of the pdf where the annotation occurs
*/
public FileAnnotation(final PDAnnotation annotation, final int pageNumber) {
this(annotation.getDictionary().getString(COSName.T),
extractModifiedTime(annotation.getModifiedDate()),
pageNumber, annotation.getContents(), FileAnnotationType.parse(annotation), Optional.empty());
}
/**
* For creating a FileAnnotation that has a connection to another FileAnnotation. Needed when creating a text
* highlighted or underlined annotation with a sticky note.
*
* @param annotation The actual annotation that holds the information
* @param pageNumber The page of the pdf where the annotation occurs
* @param linkedFileAnnotation The corresponding note of a marked text area.
*/
public FileAnnotation(final PDAnnotation annotation, final int pageNumber, FileAnnotation linkedFileAnnotation) {
this(annotation.getDictionary().getString(COSName.T), extractModifiedTime(annotation.getModifiedDate()),
pageNumber, annotation.getContents(), FileAnnotationType.parse(annotation), Optional.of(linkedFileAnnotation));
}
/**
* Parses a String into a LocalDateTime.
*
* @param dateTimeString In this case of format yyyyMMddHHmmss.
* @return a LocalDateTime parsed from the dateTimeString
*/
public static LocalDateTime extractModifiedTime(String dateTimeString) {
if (dateTimeString == null) {
return LocalDateTime.now();
}
if (dateTimeString.matches(DATE_TIME_STRING_WITH_TIME_ZONE)) {
dateTimeString = dateTimeString.substring(2, 16);
} else if (dateTimeString.matches(DATE_TIME_STRING)) {
dateTimeString = dateTimeString.substring(2);
}
try {
return LocalDateTime.parse(dateTimeString, DateTimeFormatter.ofPattern(ANNOTATION_DATE_FORMAT));
} catch (DateTimeParseException e) {
LOGGER.info(String.format("Expected a parseable date string! However, this text could not be parsed: '%s'", dateTimeString));
return LocalDateTime.now();
}
}
private String parseContent(final String content) {
if (content == null) {
return "";
}
final String unreadableContent = "þÿ";
if (content.trim().equals(unreadableContent)) {
return "";
}
return content.trim();
}
/**
* Abbreviate annotation names when they are longer than {@code ABBREVIATED_ANNOTATION_NAME_LENGTH} chars
*
* @param annotationName annotation to be shortened
* @return the abbreviated name
*/
private String abbreviateAnnotationName(final String annotationName) {
if (annotationName.length() > ABBREVIATED_ANNOTATION_NAME_LENGTH) {
return annotationName.subSequence(0, ABBREVIATED_ANNOTATION_NAME_LENGTH).toString() + "...";
}
return annotationName;
}
@Override
public String toString() {
return abbreviateAnnotationName(content);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if ((other == null) || (getClass() != other.getClass())) {
return false;
}
FileAnnotation that = (FileAnnotation) other;
return Objects.equals(this.annotationType, that.annotationType)
&& Objects.equals(this.author, that.author)
&& Objects.equals(this.content, that.content)
&& Objects.equals(this.page, that.page)
&& Objects.equals(this.linkedFileAnnotation, that.linkedFileAnnotation)
&& Objects.equals(this.timeModified, that.timeModified);
}
@Override
public int hashCode() {
return Objects.hash(annotationType, author, content, page, linkedFileAnnotation, timeModified);
}
public String getAuthor() {
return author;
}
public LocalDateTime getTimeModified() {
return timeModified;
}
public int getPage() {
return page;
}
public String getContent() {
return content;
}
public FileAnnotationType getAnnotationType() {
return annotationType;
}
public boolean hasLinkedAnnotation() {
return this.linkedFileAnnotation.isPresent();
}
/**
* Before this getter is called the presence of the linked annotation must be checked via hasLinkedAnnotation()!
*
* @return the note attached to the annotation
*/
public FileAnnotation getLinkedFileAnnotation() {
return linkedFileAnnotation.get();
}
}
| mit |
stivalet/PHP-Vulnerability-test-suite | URF/CWE_601/safe/CWE_601__shell_exec__whitelist_using_array__http_redirect_file_id-concatenation_simple_quote.php | 1354 | <?php
/*
Safe sample
input : use shell_exec to cat /tmp/tainted.txt
SANITIZE : use in_array to check if $tainted is in the white list
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = shell_exec('cat /tmp/tainted.txt');
$legal_table = array("safe1", "safe2");
if (in_array($tainted, $legal_table, true)) {
$tainted = $tainted;
} else {
$tainted = $legal_table[0];
}
$var = http_redirect("pages/'". $tainted . "'.php");
?> | mit |
dbreen/games | games/settings.py | 1171 | import os
from local_settings import *
PROJECT_ROOT = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/admin_media/'
TIME_ZONE = 'America/New_York'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
SECRET_KEY = 'cz9)$^d0*3v#f(-c5gvwz&@x9e7%teb7yl#-0-0&u1zkm8fa(7'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'games.urls'
TEMPLATE_DIRS = (
'%s/templates' % PROJECT_ROOT,
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'south',
'django_extensions',
'games.core',
)
| mit |
xujianming/Alpha | AlphaClient/AlphaGraph/CRenderer.cpp | 795 | #include "stdafx.h"
#include "CRenderer.h"
#include "CGraphicD3D9.h"
#include "CModel.h"
#include "AlphaCommon\CAlphaWindow.h"
#pragma comment(lib, "d3dx9.lib")
CRenderer::CRenderer()
{
m_pModel = 0;
}
CRenderer::~CRenderer()
{
}
void CRenderer::Initialize( CAlphaWindow* pWnd )
{
m_pWnd = pWnd;
m_pGraphic = new CGraphicD3D9(m_pWnd);
m_pGraphic->Create();
m_pModel = new CModel(m_pGraphic);
bool result = m_pModel->Initialize("../data/cube.txt", "../data/seafloor.dds");
if(!result)
{
MessageBox(m_pWnd->GetHandle(), "Could not initialize the model object.", "Error", MB_OK);
return;
}
}
void CRenderer::EnterOneFrame()
{
if (!m_pGraphic->RenderBegin())
return;
m_pGraphic->RenderEnd();
}
void CRenderer::SetMainScene( CScene *pScene )
{
m_pMainScene = pScene;
}
| mit |
kelthalas/agent-terrain-gen | src/camera.cpp | 5074 | #include "camera.h"
#include <cmath>
#include <QKeyEvent>
#include <iostream>
static const float pi = 4 * std::atan(1);
float degToRad(float x) {
return x * pi / 180.0f;
}
float radToDeg(float x) {
return x * 180.0f / pi;
}
Camera::Camera() : m_speed{600.0f}, m_phi{4.72111f}, m_theta{-1.1781f},
m_thetaMax{degToRad(75.0f)}, m_sensi{0.5f}, m_position{2560.0f, 5000.0f, 0.0f},
m_direction{Direction::NONE}, m_mousePressed{false}, m_isDirty{true} {
}
void Camera::update(int dt) {
// On translate la caméra
float mul = (dt / 1000.0f) * m_speed;
QVector3D move = getDirection();
move = move * mul;
move = move + m_position;
setPosition(move);
}
void Camera::setPosition(const QVector3D& v) {
m_lastPosition = m_position;
m_position = v;
m_isDirty = true;
}
QVector3D Camera::getLastPosition() const {
return m_lastPosition;
}
QVector3D Camera::getPosition() const {
return m_position;
}
QVector3D Camera::getDirection() {
QVector3D frontdir = frontDir();
QVector3D rightdir = QVector3D::crossProduct(frontDir(), QVector3D{0.0f, 1.0f, 0.0f});
QVector3D d;
switch (m_direction) {
case Direction::NONE:
return {};
break;
case Direction::UP:
return frontdir;
break;
case Direction::DOWN:
return frontdir * -1;
break;
case Direction::LEFT:
return rightdir * -1;
break;
case Direction::RIGHT:
return rightdir;
break;
case Direction::UP_RIGHT:
d = (frontdir + rightdir);
d.normalize();
return d;
break;
case Direction::UP_LEFT:
d = (frontdir + rightdir * -1);
d.normalize();
return d;
break;
case Direction::DOWN_RIGHT:
d = (frontdir * -1 + rightdir);
d.normalize();
return d;
break;
case Direction::DOWN_LEFT:
d = (frontdir + rightdir) * -1;
d.normalize();
return d;
break;
}
return {};
}
const QMatrix4x4& Camera::getViewMatrix() {
// Si la caméra a été modifiée on re-calcule la matrice
if (m_isDirty) {
QVector3D front = frontDir();
front.normalize();
QVector3D to = m_position + front;
m_viewMatrix.setToIdentity();
m_viewMatrix.lookAt(m_position, to, QVector3D(0.0, 1.0, 0.0));
m_isDirty = false;
}
return m_viewMatrix;
}
void Camera::keyPressEvent(QKeyEvent* event) {
Direction mod = Direction::NONE;
if (event->key() == Qt::Key_Z) {
mod = Direction::UP;
} else if (event->key() == Qt::Key_S) {
mod = Direction::DOWN;
} else if (event->key() == Qt::Key_Q) {
mod = Direction::LEFT;
} else if (event->key() == Qt::Key_D) {
mod = Direction::RIGHT;
} else {
mod = Direction::NONE;
}
m_direction = (Direction)((int)m_direction | (int)mod);
}
void Camera::keyReleaseEvent(QKeyEvent* event) {
Direction mod = Direction::NONE;
if (event->key() == Qt::Key_Z) {
mod = Direction::UP;
} else if (event->key() == Qt::Key_S) {
mod = Direction::DOWN;
} else if (event->key() == Qt::Key_Q) {
mod = Direction::LEFT;
} else if (event->key() == Qt::Key_D) {
mod = Direction::RIGHT;
} else {
mod = Direction::NONE;
}
m_direction = (Direction)((int)m_direction & (~(int)mod));
}
void Camera::mousePressEvent(QMouseEvent* event) {
if (event->button() == Qt::MouseButton::RightButton) {
m_mousePressed = true;
m_oldMousPos = event->pos();
}
}
void Camera::mouseReleaseEvent(QMouseEvent* event) {
if (event->button() == Qt::MouseButton::RightButton) {
m_mousePressed = false;
}
}
void Camera::mouseMoveEvent(QMouseEvent* event) {
if (m_mousePressed) {
float dx = event->x() - m_oldMousPos.x();
float dy = event->y() - m_oldMousPos.y();
m_oldMousPos = event->pos();
m_phi -= degToRad(dx * m_sensi);
m_theta -= degToRad(dy * m_sensi);
/*
* On évite à phi de devenir trop grand (ou trop petit)
* en enlevant (ou ajoutant) 1 tour à chaque tour
*/
if (m_phi > degToRad(360.0f)) {
m_phi -= degToRad(360.0f);
} else if (m_phi < 0.0f) {
m_phi += degToRad(360.0f);
}
// On évite que theta dépasse la limite
if (m_theta > m_thetaMax) {
m_theta = m_thetaMax;
} else if (m_theta < -m_thetaMax) {
m_theta = -m_thetaMax;
}
//std::cout << "phi : " << m_phi << " m_theta : " << m_theta << std::endl;
m_isDirty = true;
}
}
////////////////////////////////////////////////////////////////////////////////
// FONCTIONS PRIVEES
////////////////////////////////////////////////////////////////////////////////
QVector3D Camera::frontDir() {
QVector3D v{cos(m_theta) * cos(m_phi),
sin(m_theta),
-cos(m_theta) * sin(m_phi)};
return v;
}
| mit |
ambethia/twaxdotcom | app/assets/javascripts/application.js | 751 | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .
//= require_self
$(function() {
$('[data-toggle="tooltip"]').tooltip()
});
| mit |
joshuaavalon/FluentQuery | fluent-query/src/main/java/com/joshuaavalon/fluentquery/Query.java | 4222 | package com.joshuaavalon.fluentquery;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.CheckResult;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Query {
@NonNull
private final List<String> columns;
@NonNull
private final Table table;
@NonNull
private Optional<Condition> condition;
@NonNull
private List<String> groupBy;
@NonNull
private Optional<Condition> having;
@NonNull
private List<Order> sortOrder;
@IntRange(from = 0)
private int limit;
@IntRange(from = 0)
private int offset;
private boolean distinct;
Query(@NonNull final List<String> columns, @NonNull final Table table) {
this.columns = columns;
this.table = table;
condition = Optional.absent();
groupBy = new ArrayList<>();
having = Optional.absent();
sortOrder = new ArrayList<>();
limit = 0;
offset = 0;
}
@NonNull
public static Column select(@NonNull final String... columns) {
return new Column(Arrays.asList(columns));
}
@NonNull
public static Column select(@NonNull final List<String> columns) {
return new Column(new ArrayList<>(columns));
}
@NonNull
public Query where(@NonNull final Condition conditions) {
this.condition = Optional.of(conditions);
return this;
}
@NonNull
public Query having(@NonNull final Condition conditions) {
this.condition = Optional.of(conditions);
return this;
}
@NonNull
public Query groupBy(@NonNull final String... columns) {
this.groupBy = Arrays.asList(columns);
return this;
}
@NonNull
public Query groupBy(@NonNull final List<String> columns) {
this.groupBy = new ArrayList<>(columns);
return this;
}
@NonNull
public Query orderBy(@NonNull final Order... columns) {
this.sortOrder = Arrays.asList(columns);
return this;
}
@NonNull
public Query orderBy(@NonNull final List<Order> columns) {
this.sortOrder = new ArrayList<>(columns);
return this;
}
@NonNull
public Query limit(@IntRange(from = 1) int limit) {
this.limit = limit;
return this;
}
@NonNull
public Query offset(@IntRange(from = 1) int offset) {
this.offset = offset;
return this;
}
@NonNull
public Query distinct() {
distinct = true;
return this;
}
@NonNull
@CheckResult
public Cursor commit(@NonNull final SQLiteOpenHelper helper) {
return commit(helper.getReadableDatabase());
}
@NonNull
@CheckResult
public Cursor commit(@NonNull final SQLiteDatabase db) {
final String[] columns = this.columns.size() != 0 ?
Iterables.toArray(this.columns, String.class) : new String[]{"*"};
final String selection = condition.isPresent() ? condition.get().getExpression() : null;
final String[] selectionArgs = condition.isPresent() ?
Iterables.toArray(condition.get().getArguments(), String.class) : null;
final Iterable<String> orderByClauses = Iterables.transform(sortOrder, new Function<Order,
String>() {
@Override
public String apply(Order input) {
return input.getFullExpression();
}
});
final String orderBy = Joiner.on(", ").join(orderByClauses);
final String limitClause = limit == 0 ? null : (offset == 0 ? String.valueOf(limit) :
limit + "," + offset);
return db.query(distinct,
table.getFullExpression(),
columns,
selection,
selectionArgs,
Joiner.on(", ").join(groupBy),
having.isPresent() ? having.get().getFullExpression() : null,
orderBy,
limitClause);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("columns", columns.toString())
.add("table", table.getFullExpression())
.add("condition", condition.toString())
.add("groupBy", groupBy.toString())
.add("having", having.toString())
.add("sortOrder", sortOrder.toString())
.add("limit", limit)
.add("offset", offset)
.add("distinct", distinct).toString();
}
}
| mit |
hck/open_nlp | spec/pos_tagger_spec.rb | 1257 | require 'spec_helper'
RSpec.describe OpenNlp::POSTagger do
let(:model) { OpenNlp::Model::POSTagger.new(File.join(FIXTURES_DIR, 'en-pos-maxent.bin')) }
let(:pos_tagger) { described_class.new(model) }
describe 'initialization' do
it 'initialize with a valid model' do
expect(pos_tagger.j_instance).to be_a(described_class.java_class)
end
it 'raises an ArgumentError without a valid model' do
expect { described_class.new(nil) }.to raise_error(ArgumentError)
end
end
describe '#tag' do
it 'tags parts of a provided document' do
tagged = pos_tagger.tag('The quick brown fox jumps over the lazy dog.')
expect(tagged).to eq('The/DT quick/JJ brown/JJ fox/NN jumps/NNS over/IN the/DT lazy/JJ dog./NN')
end
it 'tags provided tokens' do
tagged = pos_tagger.tag(%w[The quick brown fox jumps over the lazy dog .])
expect(tagged.to_ary).to eq(%w[DT JJ JJ NN NNS IN DT JJ NN .])
end
it 'raises an ArgumentError when nil is passed as an argument' do
expect { pos_tagger.tag(nil) }.to raise_error(ArgumentError)
end
it 'raises an ArgumentError when fixnum is passed as an argument' do
expect { pos_tagger.tag(111) }.to raise_error(ArgumentError)
end
end
end
| mit |
DavsX/FCleaner | spec/spec_helper.rb | 279 | require_relative '../lib/fcleaner'
require 'date'
require 'webmock/rspec'
RSpec.configure do |config|
config.before { allow($stdout).to receive(:puts) }
config.mock_with :rspec do |mock|
mock.verify_doubled_constant_names = true
end
end
WebMock.disable_net_connect!
| mit |
cahyaong/cop.gaia | Archive/Gaia.Engine/Common/IProbabilityManager.cs | 1787 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="IProbabilityManager.cs" company="nGratis">
// The MIT License (MIT)
//
// Copyright (c) 2014 - 2015 Cahya Ong
//
// 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.
// </copyright>
// <author>Cahya Ong - cahya.ong@gmail.com</author>
// <creation_timestamp>Monday, 7 September 2015 12:25:14 PM UTC</creation_timestamp>
// --------------------------------------------------------------------------------------------------------------------
namespace nGratis.Cop.Gaia.Engine
{
public interface IProbabilityManager : IManager
{
float Roll();
float Roll(float min, float max);
}
} | mit |
SuperUncleCat/ServerMonitoring | node_modules/semantic-ui-react/src/collections/Grid/GridColumn.js | 3028 | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
customPropTypes,
createShorthandFactory,
getElementType,
getUnhandledProps,
META,
SUI,
useKeyOnly,
useOnlyProp,
useTextAlignProp,
useValueAndKey,
useVerticalAlignProp,
useWidthProp,
} from '../../lib'
/**
* A column sub-component for Grid.
*/
function GridColumn(props) {
const {
children,
className,
computer,
color,
floated,
largeScreen,
mobile,
only,
stretched,
tablet,
textAlign,
verticalAlign,
widescreen,
width,
} = props
const classes = cx(
color,
useKeyOnly(stretched, 'stretched'),
useOnlyProp(only, 'only'),
useTextAlignProp(textAlign),
useValueAndKey(floated, 'floated'),
useVerticalAlignProp(verticalAlign),
useWidthProp(computer, 'wide computer'),
useWidthProp(largeScreen, 'wide large screen'),
useWidthProp(mobile, 'wide mobile'),
useWidthProp(tablet, 'wide tablet'),
useWidthProp(widescreen, 'wide widescreen'),
useWidthProp(width, 'wide'),
'column',
className,
)
const rest = getUnhandledProps(GridColumn, props)
const ElementType = getElementType(GridColumn, props)
return <ElementType {...rest} className={classes}>{children}</ElementType>
}
GridColumn._meta = {
name: 'GridColumn',
parent: 'Grid',
type: META.TYPES.COLLECTION,
}
GridColumn.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** A grid column can be colored. */
color: PropTypes.oneOf(SUI.COLORS),
/** A column can specify a width for a computer. */
computer: PropTypes.oneOf(SUI.WIDTHS),
/** A column can sit flush against the left or right edge of a row. */
floated: PropTypes.oneOf(SUI.FLOATS),
/** A column can specify a width for a large screen device. */
largeScreen: PropTypes.oneOf(SUI.WIDTHS),
/** A column can specify a width for a mobile device. */
mobile: PropTypes.oneOf(SUI.WIDTHS),
/** A row can appear only for a specific device, or screen sizes. */
only: customPropTypes.onlyProp(SUI.VISIBILITY),
/** A column can stretch its contents to take up the entire grid or row height. */
stretched: PropTypes.bool,
/** A column can specify a width for a tablet device. */
tablet: PropTypes.oneOf(SUI.WIDTHS),
/** A column can specify its text alignment. */
textAlign: PropTypes.oneOf(SUI.TEXT_ALIGNMENTS),
/** A column can specify its vertical alignment to have all its columns vertically centered. */
verticalAlign: PropTypes.oneOf(SUI.VERTICAL_ALIGNMENTS),
/** A column can specify a width for a wide screen device. */
widescreen: PropTypes.oneOf(SUI.WIDTHS),
/** Represents width of column. */
width: PropTypes.oneOf(SUI.WIDTHS),
}
GridColumn.create = createShorthandFactory(GridColumn, children => ({ children }))
export default GridColumn
| mit |
davidmnoll/wp-pdf-tpl | lib/lib/fonts/dompdf_font_family_cache.php | 3265 | <?php return array (
'sans-serif' => array(
'normal' => $fontDir . '/Helvetica',
'bold' => $fontDir . '/Helvetica-Bold',
'italic' => $fontDir . '/Helvetica-Oblique',
'bold_italic' => $fontDir . '/Helvetica-BoldOblique',
),
'times' => array(
'normal' => $fontDir . '/Times-Roman',
'bold' => $fontDir . '/Times-Bold',
'italic' => $fontDir . '/Times-Italic',
'bold_italic' => $fontDir . '/Times-BoldItalic',
),
'times-roman' => array(
'normal' => $fontDir . '/Times-Roman',
'bold' => $fontDir . '/Times-Bold',
'italic' => $fontDir . '/Times-Italic',
'bold_italic' => $fontDir . '/Times-BoldItalic',
),
'courier' => array(
'normal' => $fontDir . '/Courier',
'bold' => $fontDir . '/Courier-Bold',
'italic' => $fontDir . '/Courier-Oblique',
'bold_italic' => $fontDir . '/Courier-BoldOblique',
),
'helvetica' => array(
'normal' => $fontDir . '/Helvetica',
'bold' => $fontDir . '/Helvetica-Bold',
'italic' => $fontDir . '/Helvetica-Oblique',
'bold_italic' => $fontDir . '/Helvetica-BoldOblique',
),
'zapfdingbats' => array(
'normal' => $fontDir . '/ZapfDingbats',
'bold' => $fontDir . '/ZapfDingbats',
'italic' => $fontDir . '/ZapfDingbats',
'bold_italic' => $fontDir . '/ZapfDingbats',
),
'symbol' => array(
'normal' => $fontDir . '/Symbol',
'bold' => $fontDir . '/Symbol',
'italic' => $fontDir . '/Symbol',
'bold_italic' => $fontDir . '/Symbol',
),
'serif' => array(
'normal' => $fontDir . '/Times-Roman',
'bold' => $fontDir . '/Times-Bold',
'italic' => $fontDir . '/Times-Italic',
'bold_italic' => $fontDir . '/Times-BoldItalic',
),
'monospace' => array(
'normal' => $fontDir . '/Courier',
'bold' => $fontDir . '/Courier-Bold',
'italic' => $fontDir . '/Courier-Oblique',
'bold_italic' => $fontDir . '/Courier-BoldOblique',
),
'fixed' => array(
'normal' => $fontDir . '/Courier',
'bold' => $fontDir . '/Courier-Bold',
'italic' => $fontDir . '/Courier-Oblique',
'bold_italic' => $fontDir . '/Courier-BoldOblique',
),
'dejavu sans' => array(
'bold' => $fontDir . '/DejaVuSans-Bold',
'bold_italic' => $fontDir . '/DejaVuSans-BoldOblique',
'italic' => $fontDir . '/DejaVuSans-Oblique',
'normal' => $fontDir . '/DejaVuSans',
),
'dejavu sans mono' => array(
'bold' => $fontDir . '/DejaVuSansMono-Bold',
'bold_italic' => $fontDir . '/DejaVuSansMono-BoldOblique',
'italic' => $fontDir . '/DejaVuSansMono-Oblique',
'normal' => $fontDir . '/DejaVuSansMono',
),
'dejavu serif' => array(
'bold' => $fontDir . '/DejaVuSerif-Bold',
'bold_italic' => $fontDir . '/DejaVuSerif-BoldItalic',
'italic' => $fontDir . '/DejaVuSerif-Italic',
'normal' => $fontDir . '/DejaVuSerif',
),
'source sans pro' => array(
'normal' => $fontDir . '/bcc8bb1f1faa36ec1408b6c973e97e93',
'bold' => $fontDir . '/688cf132f2db1a25f7e92c52663c1c6e',
'italic' => $fontDir . '/e1c15c41a005df8c4b9606d8490eaeb4',
'bold_italic' => $fontDir . '/a357f713de2b3f869846d3f7eb6605e2',
),
'lora' => array(
'normal' => $fontDir . '/803bd0b1be163fe908f693896a9303f2',
'italic' => $fontDir . '/d40308fd24456af1490e79694af6ba3c',
),
) ?> | mit |
xsolve-pl/xsolve-feat | client/src/app/project/detail/project-detail.component.spec.ts | 854 | /* tslint:disable:no-unused-variable */
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DebugElement} from '@angular/core';
import {ProjectDetailComponent} from './project-detail.component';
describe('ProjectDetailComponent', () => {
let component: ProjectDetailComponent;
let fixture: ComponentFixture<ProjectDetailComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ProjectDetailComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProjectDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| mit |
jimmy-go/srest | _examples/simple/main.go | 607 | package main
import (
"flag"
"log"
"net/http"
"runtime"
"github.com/jimmy-go/srest"
)
var (
port = flag.Int("port", 9000, "Listen port")
)
func main() {
flag.Parse()
runtime.GOMAXPROCS(runtime.NumCPU())
m := srest.New(nil)
m.Get("/", http.HandlerFunc(homeHandler))
<-m.Run(*port)
log.Println("Done")
}
// Response type for common API responses.
type Response struct {
Message string `json:"response"`
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
res := &Response{"hello world"}
if err := srest.JSON(w, res); err != nil {
log.Printf("home : json : err [%s]", err)
}
}
| mit |
QueueHammer/Mandelbrot | app.js | 116 | var express = require('express');
var app = express();
app.use(express.static(__dirname + '/'));
app.listen(3000); | mit |
60East/amps-client-excel | src/ActiveSub.cs | 8271 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AMPS.Client;
using Excel= Microsoft.Office.Interop.Excel;
using System.Threading;
using System.Runtime.InteropServices;
namespace AMPSExcel
{
public class ActiveSub
{
Client _client;
CommandId _cmdId;
int _row, _col;
Excel.Worksheet _worksheet;
Excel.Workbook _workbook;
AMPSAddin.SubscriptionDefinition _def;
MessageType _messageType;
Dictionary<string, int> _columns = new Dictionary<string, int>();
Dictionary<string, int> _rows = new Dictionary<string, int>();
Dictionary<string, object> _shredded = new Dictionary<string, object>();
Queue<int> _empty = new Queue<int>();
volatile int _lastrow = 0;
bool _running = true;
static Dictionary<AMPSAddin.SubscriptionDefinition, ActiveSub> _actives = new Dictionary<AMPSAddin.SubscriptionDefinition, ActiveSub>();
public static ActiveSub activate(AMPSAddin.SubscriptionDefinition d, Client client, string messageType, Excel.Workbook workbook)
{
if (!_actives.ContainsKey(d))
{
_actives[d] = new ActiveSub(client, messageType, d, workbook);
}
return _actives[d];
}
public static bool isActive(AMPSAddin.SubscriptionDefinition d)
{
return _actives.ContainsKey(d);
}
public static ActiveSub find(AMPSAddin.SubscriptionDefinition d)
{
if (_actives.ContainsKey(d))
{
return _actives[d];
}
else
{
return null;
}
}
private void vbaInvoke(System.Action thing)
{
while (_running)
{
try
{
thing.Invoke();
break;
}
catch (COMException)
{
Thread.Yield();
}
}
}
private void ReceivedMessage(AMPS.Client.Message msg)
{
if (!_running) return;
/*try
{*/
string sowKey = msg.getSowKey();
// if an OOF, remove the row if we know of it
Message.Commands commandType = msg.Command;
if (commandType == AMPS.Client.Message.Commands.OOF && _rows.ContainsKey(sowKey))
{
int theRow = _rows[sowKey];
vbaInvoke(() =>
{
Excel.Range range = _worksheet.Rows[theRow];
range.ClearContents();
_worksheet.Cells[theRow, _col] = "(deleted)";
}
);
_rows.Remove(sowKey);
_empty.Enqueue(theRow);
}
else if (commandType == AMPS.Client.Message.Commands.Publish ||
commandType == AMPS.Client.Message.Commands.DeltaPublish ||
commandType == AMPS.Client.Message.Commands.SOW)
{
int thisRow = 0;
// try and find the row
if (!_rows.TryGetValue(sowKey,out thisRow))
{
string findKey = "|" + sowKey + "|";
vbaInvoke(() =>
{
if (_empty.Count > 0)
{
thisRow = _empty.Dequeue();
}
else
{
thisRow = _lastrow++;
}
_rows[sowKey] = thisRow;
_worksheet.Cells[thisRow, _col].Value = findKey;
});
if (thisRow == -1) return;
}
// row == the row we want
_shredded.Clear();
var dataField = msg.getDataRaw();
_messageType.PopulateDictionary(dataField.buffer, dataField.position, dataField.length, _shredded);
foreach (var x in _shredded.Keys)
{
int thisCol = 0;
if (!_columns.ContainsKey(x))
{
// find a spot for a new column. hopefully this happens rarely.
for (int i = _col + 1; i < 1024768; i++)
{
vbaInvoke(() =>
{
dynamic c = _worksheet.Cells[_row, i];
if (c.Text == x)
{
thisCol = i;
_columns.Add(x, thisCol);
}
else if (c.Text == null || c.Text == "")
{
c.Value = x;
c.Font.Bold = true;
thisCol = i;
_columns.Add(x, thisCol);
}
});
if (thisCol != 0) break;
}
if (thisCol == 0) return; // no room
}
else { thisCol = _columns[x]; }
vbaInvoke(() => _worksheet.Cells[thisRow, thisCol].Value = _shredded[x].ToString());
}
}
/*}
catch (Exception e)
{
this.close();
_running = false;
}*/
}
private ActiveSub(Client c, string messageType, AMPSExcel.AMPSAddin.SubscriptionDefinition d, Excel.Workbook workbook)
{
_def = d;
_client = c;
_messageType = MessageTypeFactory.forName(messageType);
string[] rangeParts = d.WorksheetRange.Split('!');
_worksheet = workbook.Worksheets[rangeParts[0]];
Excel.Range where = _worksheet.Range[rangeParts[1]];
_row = where.Row;
_col = where.Column;
_columns["SOWKey"] = where.Column;
_workbook = workbook;
where.Value = "AMPS Subscription: "+ d.Name;
_empty.Clear();
int count = _worksheet.Rows.Count;
for (int i = _row; i < count; ++i)
{
var cell = _worksheet.Cells[i, _col];
if (!string.IsNullOrEmpty(cell.Text))
{
string text = cell.Text;
if (text == "(deleted)")
_empty.Enqueue(i);
else
_rows[text.Trim('|')] = i;
}
else
{
_lastrow = i;
break;
}
}
_cmdId = c.sowAndDeltaSubscribe(x => ReceivedMessage(x), d.Topic, d.Filter, 100, true, true, 1000);
Globals.AMPSAddin.Application.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(Application_WorkbookBeforeClose);
workbook.BeforeClose += new Excel.WorkbookEvents_BeforeCloseEventHandler(workbook_BeforeClose);
}
void Application_WorkbookBeforeClose(Excel.Workbook Wb, ref bool Cancel)
{
if (Wb.Equals(_workbook))
{
close();
}
}
void Subscription_Disposed(object sender, EventArgs e)
{
close();
}
void Worksheet_Deactivate()
{
close();
}
public void close()
{
try
{
if (_client != null)
{
_client.close();
_client = null;
}
}
catch (Exception)
{
}
ActiveSub._actives.Remove(_def);
_running = false;
}
void workbook_BeforeClose(ref bool Cancel)
{
close();
}
}
}
| mit |
VoidSt4r/Diablo2HeroEditor | src/Diablo2FileFormat/BitOperations.cs | 2191 | // -----------------------------------------------------------------------
// Copyright (c) VoidSt4r. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diablo2FileFormat
{
public class BitOperations
{
public static uint ReadBits(byte[] data, ref int offset, ref int bitOffset, int bitLength)
{
int bitsRemainingInCurrentByte = 8 - bitOffset;
int bitsToRead = bitsRemainingInCurrentByte;
uint mask = 0xFFFFFFFF;
if (bitLength < bitsRemainingInCurrentByte)
{
// We don't want to read some of the most significant bits
bitsToRead = bitLength;
mask = ~((mask >> (bitOffset + bitLength)) << (bitOffset + bitLength));
}
uint val = (data[offset] & mask) >> bitOffset;
bitOffset = (bitOffset + bitsToRead) % 8;
bitLength -= bitsToRead;
if (bitOffset == 0)
{
++offset;
}
if (bitLength > 0)
{
val += ReadBits(data, ref offset, ref bitOffset, bitLength) << bitsToRead;
}
return val;
}
public static void WriteBits(byte[] data, uint value, ref int offset, ref int bitOffset, int bitLength)
{
int bitsRemainingInCurrentByte = 8 - bitOffset;
data[offset] += (byte)(value << bitOffset);
if (bitLength >= bitsRemainingInCurrentByte)
{
bitOffset = 0;
++offset;
bitLength -= bitsRemainingInCurrentByte;
if (bitLength > 0)
{
WriteBits(data, value >> bitsRemainingInCurrentByte, ref offset, ref bitOffset, bitLength);
}
}
else
{
bitOffset += bitLength;
}
}
}
}
| mit |
naoto/naobot-webhook | plugins/wikipedia.rb | 1122 | # encoding: utf-8
require 'open-uri'
require 'nokogiri'
class Wikipedia < Naobot::Webhook::Base
def on_privmsg(message)
channel = message.to
message = message.body
if message =~ /(?<keyword>.+)って(何|なに|誰|だれ)$/
index($~[:keyword]).each do |result|
notice(channel, result)
end
end
rescue
notice(channel, 'Not Found')
end
private
def index(keyword)
begin
url = URI.escape("http://ja.wikipedia.org/wiki/#{keyword}")
rescue
url = search(keyword)
end
html = Nokogiri::HTML(open(url).read)
[html.search('p').first.inner_text[0..300], url]
end
def search(keyword)
body = Nokogiri::HTML(open(URI.escape("http://ja.wikipedia.org/w/index.php?title=特別%3A検索&search=#{keyword}")))
search_results = body.search('ul.mw-search-results')
unless search_results.nil?
url = "http://ja.wikipedia.org#{search_results.search('a').first.attributes['href']}"
else
url = URI.escape("http://ja.wikipedia.org/wiki/#{body.at('#firstHeading').inner_text}")
end
end
end
| mit |
davidfstr/iTunes-Connect-Autodownload | autodownload_trampoline.py | 500 | #!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
import subprocess
import notifymail
import sys
# Run script
python = sys.executable
scriptDir = sys.path[0]
script = subprocess.Popen([python, 'autodownload.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=scriptDir)
out, err = script.communicate()
output = out + err
# Display output
print output,
# If error, then send a notification email
if script.returncode != 0:
notifymail.send('[ITC Autodownload] Error', output) | mit |
ivangabriele/vue-medium | karma.conf.js | 391 | let webpackConfig = require('./webpack.config.js')
delete webpackConfig.entry
module.exports = function (config) {
config.set({
browsers: ['PhantomJS'],
frameworks: ['jasmine'],
files: ['test/index.js'],
preprocessors: {
'test/index.js': ['webpack'],
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
},
singleRun: true,
})
}
| mit |
enova/churnhub | config/environments/production.rb | 2482 | Churnhub::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_security/lib/2017-08-01-preview/generated/azure_mgmt_security/pricings.rb | 39379 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Security::Mgmt::V2017_08_01_preview
#
# API spec for Microsoft.Security (Azure Security Center) resource provider
#
class Pricings
include MsRestAzure
#
# Creates and initializes a new instance of the Pricings class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [SecurityCenter] reference to the SecurityCenter
attr_reader :client
#
# Security pricing configurations in the subscription
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Pricing>] operation results.
#
def list(custom_headers:nil)
first_page = list_as_lazy(custom_headers:custom_headers)
first_page.get_all_items
end
#
# Security pricing configurations in the subscription
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(custom_headers:nil)
list_async(custom_headers:custom_headers).value!
end
#
# Security pricing configurations in the subscription
#
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'Pattern': '^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'" if !@client.subscription_id.nil? && @client.subscription_id.match(Regexp.new('^^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$$')).nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Security/pricings'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::PricingList.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configurations in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Pricing>] operation results.
#
def list_by_resource_group(resource_group_name, custom_headers:nil)
first_page = list_by_resource_group_as_lazy(resource_group_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Security pricing configurations in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_resource_group_with_http_info(resource_group_name, custom_headers:nil)
list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value!
end
#
# Security pricing configurations in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_resource_group_async(resource_group_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'Pattern': '^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'" if !@client.subscription_id.nil? && @client.subscription_id.match(Regexp.new('^^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$$')).nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/pricings'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::PricingList.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configuration in the subscriptionSecurity pricing
# configuration in the subscription
#
# @param pricing_name [String] name of the pricing configuration
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Pricing] operation results.
#
def get_subscription_pricing(pricing_name, custom_headers:nil)
response = get_subscription_pricing_async(pricing_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Security pricing configuration in the subscriptionSecurity pricing
# configuration in the subscription
#
# @param pricing_name [String] name of the pricing configuration
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_subscription_pricing_with_http_info(pricing_name, custom_headers:nil)
get_subscription_pricing_async(pricing_name, custom_headers:custom_headers).value!
end
#
# Security pricing configuration in the subscriptionSecurity pricing
# configuration in the subscription
#
# @param pricing_name [String] name of the pricing configuration
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_subscription_pricing_async(pricing_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'Pattern': '^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'" if !@client.subscription_id.nil? && @client.subscription_id.match(Regexp.new('^^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$$')).nil?
fail ArgumentError, 'pricing_name is nil' if pricing_name.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Security/pricings/{pricingName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'pricingName' => pricing_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::Pricing.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configuration in the subscription
#
# @param pricing_name [String] name of the pricing configuration
# @param pricing [Pricing] Pricing object
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Pricing] operation results.
#
def update_subscription_pricing(pricing_name, pricing, custom_headers:nil)
response = update_subscription_pricing_async(pricing_name, pricing, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Security pricing configuration in the subscription
#
# @param pricing_name [String] name of the pricing configuration
# @param pricing [Pricing] Pricing object
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def update_subscription_pricing_with_http_info(pricing_name, pricing, custom_headers:nil)
update_subscription_pricing_async(pricing_name, pricing, custom_headers:custom_headers).value!
end
#
# Security pricing configuration in the subscription
#
# @param pricing_name [String] name of the pricing configuration
# @param pricing [Pricing] Pricing object
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def update_subscription_pricing_async(pricing_name, pricing, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'Pattern': '^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'" if !@client.subscription_id.nil? && @client.subscription_id.match(Regexp.new('^^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$$')).nil?
fail ArgumentError, 'pricing_name is nil' if pricing_name.nil?
fail ArgumentError, 'pricing is nil' if pricing.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::Pricing.mapper()
request_content = @client.serialize(request_mapper, pricing)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Security/pricings/{pricingName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'pricingName' => pricing_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::Pricing.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configuration in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param pricing_name [String] name of the pricing configuration
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Pricing] operation results.
#
def get_resource_group_pricing(resource_group_name, pricing_name, custom_headers:nil)
response = get_resource_group_pricing_async(resource_group_name, pricing_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Security pricing configuration in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param pricing_name [String] name of the pricing configuration
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_resource_group_pricing_with_http_info(resource_group_name, pricing_name, custom_headers:nil)
get_resource_group_pricing_async(resource_group_name, pricing_name, custom_headers:custom_headers).value!
end
#
# Security pricing configuration in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param pricing_name [String] name of the pricing configuration
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_resource_group_pricing_async(resource_group_name, pricing_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'Pattern': '^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'" if !@client.subscription_id.nil? && @client.subscription_id.match(Regexp.new('^^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$$')).nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
fail ArgumentError, 'pricing_name is nil' if pricing_name.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/pricings/{pricingName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'pricingName' => pricing_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::Pricing.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configuration in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param pricing_name [String] name of the pricing configuration
# @param pricing [Pricing] Pricing object
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Pricing] operation results.
#
def create_or_update_resource_group_pricing(resource_group_name, pricing_name, pricing, custom_headers:nil)
response = create_or_update_resource_group_pricing_async(resource_group_name, pricing_name, pricing, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Security pricing configuration in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param pricing_name [String] name of the pricing configuration
# @param pricing [Pricing] Pricing object
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def create_or_update_resource_group_pricing_with_http_info(resource_group_name, pricing_name, pricing, custom_headers:nil)
create_or_update_resource_group_pricing_async(resource_group_name, pricing_name, pricing, custom_headers:custom_headers).value!
end
#
# Security pricing configuration in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param pricing_name [String] name of the pricing configuration
# @param pricing [Pricing] Pricing object
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def create_or_update_resource_group_pricing_async(resource_group_name, pricing_name, pricing, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'Pattern': '^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'" if !@client.subscription_id.nil? && @client.subscription_id.match(Regexp.new('^^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$$')).nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
fail ArgumentError, 'pricing_name is nil' if pricing_name.nil?
fail ArgumentError, 'pricing is nil' if pricing.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::Pricing.mapper()
request_content = @client.serialize(request_mapper, pricing)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/pricings/{pricingName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'pricingName' => pricing_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::Pricing.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configurations in the subscription
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [PricingList] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Security pricing configurations in the subscription
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Security pricing configurations in the subscription
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::PricingList.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configurations in the resource group
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [PricingList] operation results.
#
def list_by_resource_group_next(next_page_link, custom_headers:nil)
response = list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Security pricing configurations in the resource group
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_resource_group_next_with_http_info(next_page_link, custom_headers:nil)
list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Security pricing configurations in the resource group
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_resource_group_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Security::Mgmt::V2017_08_01_preview::Models::PricingList.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Security pricing configurations in the subscription
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [PricingList] which provide lazy access to pages of the response.
#
def list_as_lazy(custom_headers:nil)
response = list_async(custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
#
# Security pricing configurations in the resource group
#
# @param resource_group_name [String] The name of the resource group within the
# user's subscription. The name is case insensitive.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [PricingList] which provide lazy access to pages of the response.
#
def list_by_resource_group_as_lazy(resource_group_name, custom_headers:nil)
response = list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| mit |