repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
vvilhonen/bacon.js
src/sample.js
1469
// build-dependencies: core, source // build-dependencies: functionconstruction // build-dependencies: when, map Bacon.EventStream.prototype.sampledBy = function(sampler, combinator) { return withDesc( new Bacon.Desc(this, "sampledBy", [sampler, combinator]), this.toProperty().sampledBy(sampler, combinator)); }; Bacon.Property.prototype.sampledBy = function(sampler, combinator) { var lazy = false; if ((typeof combinator !== "undefined" && combinator !== null)) { combinator = toCombinator(combinator); } else { lazy = true; combinator = function(f) { return f.value(); }; } var thisSource = new Source(this, false, lazy); var samplerSource = new Source(sampler, true, lazy); var stream = Bacon.when([thisSource, samplerSource], combinator); var result = sampler._isProperty ? stream.toProperty() : stream; return withDesc(new Bacon.Desc(this, "sampledBy", [sampler, combinator]), result); }; Bacon.Property.prototype.sample = function(interval) { return withDesc( new Bacon.Desc(this, "sample", [interval]), this.sampledBy(Bacon.interval(interval, {}))); }; Bacon.Observable.prototype.map = function(p, ...args) { if (p && p._isProperty) { return p.sampledBy(this, former); } else { return convertArgsToFunction(this, p, args, function(f) { return withDesc(new Bacon.Desc(this, "map", [f]), this.withHandler(function(event) { return this.push(event.fmap(f)); })); }); } };
mit
mlakkadshaw/bugtracker
build/.module-cache/ba75a781d11befa683a2c0f3c2d3c119dbdc695b.js
1521
var React = require('react'); var BugInput = require('./BugInput.react'); var AppVersionActions = require('../appversionactions'); var AppVersionStore = require('../stores/AppVersionStore'); var BugList = require('./BugList.react'); var BugVersion = require('./BugVersion.react'); function getAppVersionState() { return { appVersions: AppVersionStore.getAll() }; }; var Bugs = React.createClass({displayName: "Bugs", getInitialState: function() { return getAppVersionState(); }, componentDidMount: function() { AppVersionStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { AppVersionStore.removeChangeListener(this._onChange); }, _onChange: function() { this.setState(getAppVersionState()); }, _onSave: function(appVersion) { AppVersionActions.create(appVersion); }, render: function() { var appVersions = this.state.appVersions; var bugLists = []; for(var key in appVersions) { bugLists.push( React.createElement("div", null, React.createElement("h3", null, "Version: ", key), React.createElement("div", null, appVersions[key].changeLog ), React.createElement("br", null), React.createElement(BugList, {key: key, appVersion: appVersions[key]}), React.createElement("hr", null) ) ) } bugLists.reverse(); return ( React.createElement("div", null, React.createElement(BugVersion, {onSave: this._onSave}), React.createElement("div", null, bugLists ) ) ) } }); module.exports = Bugs;
mit
hadim/FilamentDetector
src/main/java/sc/fiji/filamentdetector/exporter/FilamentsExporter.java
1490
/*- * #%L * A Fiji plugin that allow easy, fast and accurate detection and tracking of biological filaments. * %% * Copyright (C) 2016 - 2020 Fiji developers. * %% * 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. * #L% */ package sc.fiji.filamentdetector.exporter; import org.scijava.Context; public abstract class FilamentsExporter<Filaments> extends AbstractDataExporter<Filaments> { public FilamentsExporter(Context context) { super(context); } }
mit
Tiger66639/travis-core
spec/travis/travis_yml_stats_spec.rb
7043
require "spec_helper" require "travis/travis_yml_stats" describe Travis::TravisYmlStats do let(:publisher) { mock("keen-publisher") } subject { described_class.store_stats(request, publisher) } let(:config) { {} } let(:request) do stub({ config: config, payload: { "repository" => {} }, repository_id: 123, event_type: "push", owner_id: 234, owner_type: "User", builds: [ stub(matrix: [ stub, stub ]) ] }) end def requests_should_contain(opts) publisher.expects(:perform_async).with(has_entries(opts), anything) end def deployments_should_contain(items) publisher.expects(:perform_async).with(anything, all_of(items.each {|i| includes(i)})) end describe ".travis.yml language key" do context "when `language: ruby'" do before do request.config["language"] = "ruby" end it "sets the language key to 'ruby'" do requests_should_contain language: "ruby" subject end end context "when not specified" do it "sets the language key to nil" do requests_should_contain language: "default" subject end end context "when `language: [ 'ruby', 'python' ]'" do before do request.config["language"] = [ "ruby", "python" ] end it "sets the language key to 'invalid'" do requests_should_contain language: "invalid" subject end end context "when `language: objective c'" do before do request.config["language"] = "objective c" end it "retains the space" do requests_should_contain language: "objective c" subject end end end describe "repository language reported by GitHub" do context "Ruby" do before do request.payload["repository"]["language"] = "Ruby" end it "sets the github_language key to 'Ruby'" do requests_should_contain github_language: "Ruby" subject end end context "F#" do before do request.payload["repository"]["language"] = "F#" end it "sets the github_language key to 'F#'" do requests_should_contain github_language: "F#" subject end end context "no language reported" do before do request.payload["repository"]["language"] = nil end it "sets the github_language key to nil" do requests_should_contain github_language: nil subject end end end describe ".travis.yml ruby key" do context "when `ruby: 2.1.2'" do before do request.config["ruby"] = "2.1.2" end it "sets the language_version.ruby key to ['2.1.2']" do requests_should_contain language_version: { ruby: ["2.1.2"] } subject end end context "when `ruby: [ '2.1.2', '2.0.0' ]'" do before do request.config["ruby"] = %w[ 2.1.2 2.0.0 ] end it "sets the language_version.ruby key to ['2.0.0', '2.1.2']" do requests_should_contain language_version: { ruby: %w[2.0.0 2.1.2] } subject end end context "when `ruby: [ '2.1.2', 2.0 ]'" do before do request.config["ruby"] = [ "2.1.2", 2.0 ] end it "sets the language_version.ruby key to ['2.0', '2.1.2']" do requests_should_contain language_version: { ruby: %w[2.0 2.1.2] } subject end end end describe "sudo being used in a command" do context "sudo is used in a command" do before do request.config["before_install"] = "sudo apt-get update" end it "sets the uses_sudo key to true" do requests_should_contain uses_sudo: true subject end end context "sudo is not used in any commands" do it "sets the uses_sudo key to false" do requests_should_contain uses_sudo: false subject end end end describe "apt-get being used in a command" do context "apt-get is used in a command" do before do request.config["before_install"] = "sudo apt-get update" end it "sets the uses_apt_get key to true" do requests_should_contain uses_apt_get: true subject end end context "apt-get is not used in any commands" do it "sets the uses_apt_get key to false" do requests_should_contain uses_apt_get: false subject end end end describe "a push" do before do request.stubs(:event_type).returns("push") end it "sets the event_type to 'push'" do requests_should_contain event_type: "push" subject end end describe "a pull_request" do before do request.stubs(:event_type).returns("pull_request") end it "sets the event_type to 'pull_request'" do requests_should_contain event_type: "pull_request" subject end end describe "a build with two jobs" do it "sets the matrix_size to 2" do requests_should_contain matrix_size: 2 subject end end it "owner_type and owner_id are set" do requests_should_contain owner_id: 234, owner_type: "User", owner: ["User", 234] subject end describe "a request without 'dist' key" do it "sets the dist_name key to 'default'" do requests_should_contain dist_name: 'default' subject end end describe "a request with 'dist' key" do before do request.config['dist'] = 'trusty' end it "sets the dist_name key to 'trusty'" do requests_should_contain dist_name: 'trusty' subject end end describe "a request without 'group' key" do it "sets the group_name key to 'default'" do requests_should_contain group_name: 'default' subject end end describe "a request with 'group' key" do before do request.config['group'] = 'dev' end it "sets the group_name key to 'dev'" do requests_should_contain group_name: 'dev' subject end end context "when payload contains a single deployment provider" do let(:config) { { "deploy" => { "provider" => "s3" } } } it "reports deployment count correctly" do deployments_should_contain( [{:provider => 's3', :repository_id => 123}] ) subject end end context "when payload contains multiple deployment providers" do let(:config) { { "deploy" => [ { "provider" => "s3" }, { "provider" => "npm" } ] } } it "reports deployment count correctly" do deployments_should_contain( [{:provider => 's3', :repository_id => 123}, {:provider => 'npm', :repository_id => 123}] ) subject end end context "when payload contains multiple deployment providers of the same type" do let(:config) { { "deploy" => [ { "provider" => "s3" }, { "provider" => "s3" } ] } } it "reports deployment count correctly" do deployments_should_contain( [{:provider => 's3', :repository_id => 123}] ) subject end end end
mit
Ghrind/yabs
lib/yabs/commands/show_index.rb
663
module Yabs class ShowIndex < ConsoleApp::Command def initialize(vault, packages) @vault = vault @packages = packages end def run! # TODO: This seems to create distant folder (which are useless) # List all local packages puts 'Local packages' puts puts "Backup store: #{@vault}" puts content = @packages.map do |p| v = p.version(:last) || Yabs::PackageVersion.blank { folder: p.directory, version: v.index, last_backup: v.timestamp } end tp content puts puts 'Hint: Version numbering starts at 0.' end end end
mit
msk-repo01/genetic_algo
src/examples/math_functions/schaffer_n4_func_demo.cpp
1465
/* * schaffer_n4_func_demo.cpp * A demo for minimizing Schaffer N.4 function * * Created on: Feb 22, 2017 * Author: S.Khan * */ #define _USE_MATH_DEFINES #include "function_minimizer_ga.h" using namespace std; /** * Schaffer N.4 Function DEMO * ========================== * A demo run for minimizing Schaffer N.4 function * when x, y both are in [-100, 100] * */ /** * Schaffer N.4 function * f(x, y) = 0.5 + ((((cos(sin(|x^2 - y^2|))^2) - 0.5)) / ((1 + (0.001*(x^2 + y^2)))^2)) */ double schaffer_n4_func(double x, double y) { double function_x_y = 0.5 + ((pow(cos(sin(abs(pow(x, 2) - pow(y, 2)))), 2) - 0.5) / (pow((1 + (0.001*(pow(x, 2) + pow(y, 2)))), 2))); return function_x_y; } int main() { // set precision for display to 15 decimal places cout.precision(15); function_minimizer_ga _function_minimizer_ga(&schaffer_n4_func, -100, 100); _function_minimizer_ga.setParameters(100, 2000, 0.5, 0.025, -1, true); _function_minimizer_ga.run(); _function_minimizer_ga.displaySettings(); _function_minimizer_ga.displayResults(); // display the actual function value after running GA cout<<"===================================="<<endl; function_variables best_value = _function_minimizer_ga.getBestSolution(); cout<<"Schaffer N.4 function minimum value was found at"<<endl<< "x = "<<best_value.x<<", y = "<<best_value.y<<endl<< "value = "<<schaffer_n4_func(best_value.x, best_value.y)<<endl; return 0; }
mit
aksakalli/gtop
lib/monitor/disk.js
671
var si = require('systeminformation'), utils = require('../utils'); var colors = utils.colors; function Disk(donut) { this.donut = donut; si.fsSize(data => { this.updateData(data); }); this.interval = setInterval(() => { si.fsSize(data => { this.updateData(data); }); }, 10000); } Disk.prototype.updateData = function(data) { var disk = data[0]; var label = utils.humanFileSize(disk.used, true) + ' of ' + utils.humanFileSize(disk.size, true); this.donut.setData([ { percent: disk.use / 100, label: label, color: colors[5], }, ]); this.donut.screen.render(); }; module.exports = Disk;
mit
mars2601/Eventure-Prod
config/env/development.js
1415
'use strict'; module.exports = { db: 'mongodb://localhost/eventure-dev', app: { title: 'Eventure - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || '1382193778748790', clientSecret: process.env.FACEBOOK_SECRET || 'b449a91f961f5cea3f541f5c13f241d4', callbackURL: 'http://eventure-app.marcel-pirnay.be/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'QEgtRtXbDsmHthB9BWOEi9esw', clientSecret: process.env.TWITTER_SECRET || 'tWDvq5UkfTnO7jv7ff66GxQF4JVIRkYlRH7l6eDAr3YVYdvgRC', callbackURL: 'http://eventure-app.marcel-pirnay.be/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'hello.eventure@gmail.com', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'Gmail', auth: { user: process.env.MAILER_EMAIL_ID || 'hello.eventure@gmail.com', pass: process.env.MAILER_PASSWORD || 'eventure3000' } } } };
mit
daureg/illalla
neighborhood.py
34865
#! /usr/bin/python2 # vim: set fileencoding=utf-8 """Match polygonal regions between cities Input: name of two cities a list of coordinates that make up a polygon in one city Output: a list of coordinates that make up a polygon in the other city """ from __future__ import print_function import cities import ClosestNeighbor as cn # import explore as xp import numpy as np import utils as u import itertools as i import shapely.geometry as sgeo import scipy.cluster.vq as vq import emd_leftover import logging # pylint: disable=E1101 # pylint: disable=W0621 NB_CLUSTERS = 3 JUST_READING = False MAX_EMD_POINTS = 750 NO_WEIGHT = True QUERY_NAME = None GROUND_TRUTH = None import os OTMPDIR = os.environ.get('OTMPDIR') def profile(func): return func @profile def load_surroundings(city): """Load projected coordinates and extra field of all venues, checkins and photos within `city`, as well as returning city geographical bounds.""" import persistent as p surroundings = [p.load_var('{}_svenues.my'.format(city)), None, None] # surroundings = [p.load_var('{}_s{}s.my'.format(city, kind)) # for kind in ['venue', 'checkin', 'photo']] venues_pos = np.vstack(surroundings[0].loc) city_extent = list(np.min(venues_pos, 0)) + list(np.max(venues_pos, 0)) return surroundings, city_extent @profile def polygon_to_local(city, geojson): """Convert a `geojson` geometry to a local bounding box in `city`, and return its center, radius and a predicate indicating membership.""" assert geojson['type'] == 'Polygon' coords = np.fliplr(np.array(geojson['coordinates'][0])) projected = sgeo.Polygon(cities.GEO_TO_2D[city](coords)) minx, miny, maxx, maxy = projected.bounds center = list(projected.centroid.coords[0]) radius = max(maxx - minx, maxy - miny)*0.5 return center, radius, projected.bounds, projected.contains @profile def describe_region(center, radius, belongs_to, surroundings, city_fv, threshold=10): """Return the description (X, x, w, ids) of the region defined by `center`, `radius` and `belongs_to`, provided that it contains enough venues.""" svenues, scheckins, sphotos = surroundings vids, _ = gather_entities(svenues, center, radius, belongs_to, threshold) if not vids: return None, None, None, None vids = filter(city_fv['index'].__contains__, vids) if len(vids) < threshold: return None, None, None, None # _, ctime = gather_entities(scheckins, center, radius, belongs_to) # _, ptime = gather_entities(sphotos, center, radius, belongs_to) mask = np.where(np.in1d(city_fv['index'], vids))[0] assert mask.size == len(vids) weights = weighting_venues(mask if NO_WEIGHT else city_fv['users'][mask]) # time_activity = lambda visits: xp.aggregate_visits(visits, 1, 4)[0] # activities = np.hstack([xp.to_frequency(time_activity(ctime)), # xp.to_frequency(time_activity(ptime))]) activities = np.ones((12, 1)) return city_fv['features'][mask, :], activities, weights, vids @profile def features_support(features): """Return a list of intervals representing the support of the probability distribution for each dimension.""" return zip(np.min(features, 0), np.max(features, 0)) @u.memodict def right_bins(dim): extent = RIGHT_SUPPORT[dim][1] - RIGHT_SUPPORT[dim][0] bins = 10 size = 1.0/bins return [RIGHT_SUPPORT[dim][0] + j*size*extent for j in range(bins+1)] @profile def features_as_density(features, weights, support, bins=10): """Turn raw `features` into probability distribution over each dimension, with respect to `weights`.""" def get_bins_full(dim): extent = support[dim][1] - support[dim][0] size = 1.0/bins return [support[dim][0] + j*size*extent for j in range(bins+1)] get_bins = right_bins if support is RIGHT_SUPPORT else get_bins_full return np.vstack([np.histogram(features[:, i], weights=weights, bins=get_bins(i))[0] for i in range(features.shape[1])]) def features_as_lists(features): """Turn numpy `features` into a list of list, suitable for emd function.""" return features.tolist() @profile def weighting_venues(values): """Transform `values` into a list of positive weights that sum up to 1.""" if NO_WEIGHT: return np.ones(values.size)/values.size from sklearn.preprocessing import MinMaxScaler scale = MinMaxScaler() size = values.size scaled = scale.fit_transform(np.power(values, .2).reshape((size, 1))) normalized = scaled.ravel()/np.sum(scaled) normalized[normalized < 1e-6] = 1e-6 return normalized @profile def gather_entities(surrounding, center, radius, belongs_to, threshold=0): """Filter points in `surrounding` that belong to the given region.""" ids, info, locs = surrounding.around(center, radius) info = len(ids)*[0, ] if len(info) == 0 else list(info[0]) if len(ids) < threshold: return None, None if belongs_to is None: return ids, info is_inside = lambda t: belongs_to(sgeo.Point(t[2])) res = zip(*(i.ifilter(is_inside, i.izip(ids, info, locs)))) if len(res) != 3: return None, None ids[:], info[:], locs[:] = res if len(ids) < threshold: return None, None return ids, info @profile def jensen_shannon_divergence(P, Q): """Compute JSD(P || Q) as defined in https://en.wikipedia.org/wiki/Jensen–Shannon_divergence """ avg = 0.5*(P + Q) avg_entropy = 0.5*(u.compute_entropy(P) + u.compute_entropy(Q)) return u.compute_entropy(avg) - avg_entropy @profile def proba_distance(density1, global1, density2, global2, theta): """Compute total distances between all distributions""" proba = np.dot(theta, [jensen_shannon_divergence(p, q) for p, q in zip(density1, density2)]) return proba[0] + np.linalg.norm(global1 - global2) SURROUNDINGS, CITY_FEATURES, THRESHOLD = None, None, None METRIC_NAME, CITY_SUPPORT, DISTANCE_FUNCTION, RADIUS = None, None, None, None RIGHT_SUPPORT = None @profile def generic_distance(metric, distance, features, weights, support, c_times=None, id_=None): """Compute the distance of (`features`, `weights`) using `distance` function (corresponding to `metric`).""" if c_times is None: c_times = np.ones((12, 1)) if 'emd' in metric: c_density = features_as_lists(features) supp = weights elif 'cluster' == metric: c_density = features supp = weights elif 'leftover' in metric: c_density = features supp = (weights, id_) elif 'jsd' in metric: c_density = features_as_density(features, weights, support) supp = c_times else: raise ValueError('unknown metric {}'.format(metric)) return distance(c_density, supp) @profile def one_cell(args): cx, cy, id_x, id_y, id_ = args center = [cx, cy] contains = None candidate = describe_region(center, RADIUS, contains, SURROUNDINGS, CITY_FEATURES, THRESHOLD) features, c_times, weights, c_vids = candidate if features is not None: distance = generic_distance(METRIC_NAME, DISTANCE_FUNCTION, features, weights, CITY_SUPPORT, c_times=c_times, id_=id_) return [cx, cy, distance, c_vids] else: return [None, None, None, None] @profile def brute_search(city_desc, hsize, distance_function, threshold, metric='jsd'): """Move a sliding circle over the whole city and keep track of the best result.""" global SURROUNDINGS, CITY_FEATURES, THRESHOLD, RADIUS global METRIC_NAME, CITY_SUPPORT, DISTANCE_FUNCTION import multiprocessing RADIUS = hsize THRESHOLD = threshold METRIC_NAME = metric city_size, CITY_SUPPORT, CITY_FEATURES, city_infos = city_desc SURROUNDINGS, bounds = city_infos DISTANCE_FUNCTION = distance_function minx, miny, maxx, maxy = bounds nb_x_step = int(3*np.floor(city_size[0]) / hsize + 1) nb_y_step = int(3*np.floor(city_size[1]) / hsize + 1) best = [1e20, [], [], RADIUS] res_map = [] pool = multiprocessing.Pool(4) x_steps = np.linspace(minx+hsize, maxx-hsize, nb_x_step) y_steps = np.linspace(miny+hsize, maxy-hsize, nb_y_step) x_vals, y_vals = np.meshgrid(x_steps, y_steps) to_cell_arg = lambda _: (float(_[1][0]), float(_[1][1]), _[0] % nb_x_step, _[0]/nb_x_step, _[0]) cells = i.imap(to_cell_arg, enumerate(i.izip(np.nditer(x_vals), np.nditer(y_vals)))) res = pool.map(one_cell, cells) pool.close() pool.join() res_map = [] if metric == 'leftover': dsts = emd_leftover.collect_matlab_output(len(res)) for cell, dst in i.izip(res, dsts): if cell[0]: cell[2] = dst clean_tmp_mats() for cell in res: if cell[0] is None: continue res_map.append(cell[:3]) if cell[2] < best[0]: best = [cell[2], cell[3], [cell[0], cell[1]], RADIUS] if QUERY_NAME: import persistent as p logging.info('wrote: '+str(os.path.join(OTMPDIR, QUERY_NAME))) p.save_var(os.path.join(OTMPDIR, QUERY_NAME), [[cell[2], cell[3], [cell[0], cell[1]], RADIUS] for cell in res if cell[0]]) yield best, res_map, 1.0 def interpret_query(from_city, to_city, region, metric): """Load informations about cities and compute useful quantities.""" # Load info of the first city suffix = '_tsne.mat' if metric == 'emd-tsne' else '' left = cn.gather_info(from_city+suffix, knn=1, raw_features='lmnn' not in metric, hide_category=metric != 'jsd') left_infos = load_surroundings(from_city) left_support = features_support(left['features']) # Compute info about the query region center, radius, _, contains = polygon_to_local(from_city, region) query = describe_region(center, radius, contains, left_infos[0], left) features, times, weights, vids = query # print('{} venues in query region.'.format(len(vids))) venue_proportion = 1.0*len(vids) / left['features'].shape[0] # And use them to define the metric that will be used theta = np.ones((1, left['features'].shape[1])) theta = np.array([[0.0396, 0.0396, 0.2932, 0.0396, 0.0396, 0.0396, 0.0396, 0.3404, 0.0396, 0.0396, 0.0396, 0.0396, 0.0396, 0.3564, 0.0396, 0.3564, 0.0396, 0.3564, 0.3564, 0.3564, 0.0396, 0.0396, 0.0396, 0.0396, 0.3564, 0.0396, 0.0396, 0.0396, 0.0396, 0.0396, 0.0396]]) ltheta = len(theta.ravel())*[1, ] if 'emd' in metric: from emd import emd from emd_dst import dist_for_emd if 'tsne' in metric: from specific_emd_dst import dst_tsne as dist_for_emd if 'itml' in metric: from specific_emd_dst import dst_itml as dist_for_emd query_num = features_as_lists(features) @profile def regions_distance(r_features, r_weigths): if len(r_features) >= MAX_EMD_POINTS: return 1e20 return emd((query_num, map(float, weights)), (r_features, map(float, r_weigths)), lambda a, b: float(dist_for_emd(a, b, ltheta))) elif 'cluster' in metric: from scipy.spatial.distance import cdist query_num = weighted_clusters(features, NB_CLUSTERS, weights) def regions_distance(r_features, r_weigths): r_cluster = weighted_clusters(r_features, NB_CLUSTERS, r_weigths) costs = cdist(query_num, r_cluster).tolist() return min_cost(costs) elif 'leftover' in metric: @profile def regions_distance(r_features, second_arg): r_weigths, idx = second_arg emd_leftover.write_matlab_problem(features, weights, r_features, r_weigths, idx) return -1 else: query_num = features_as_density(features, weights, left_support) @profile def regions_distance(r_density, r_global): """Return distance of a region from `query_num`.""" return proba_distance(query_num, times, r_density, r_global, theta) # Load info of the target city right = cn.gather_info(to_city+suffix, knn=2, raw_features='lmnn' not in metric, hide_category=metric != 'jsd') right_infos = load_surroundings(to_city) minx, miny, maxx, maxy = right_infos[1] right_city_size = (maxx - minx, maxy - miny) right_support = features_support(right['features']) global RIGHT_SUPPORT RIGHT_SUPPORT = right_support # given extents, compute threshold of candidate threshold = 0.7 * venue_proportion * right['features'].shape[0] right_desc = [right_city_size, right_support, right, right_infos] return [left, right, right_desc, regions_distance, vids, threshold] def best_match(from_city, to_city, region, tradius, progressive=False, metric='jsd'): """Try to match a `region` from `from_city` to `to_city`. If progressive, yield intermediate result.""" assert metric in ['jsd', 'emd', 'jsd-nospace', 'jsd-greedy', 'cluster', 'leftover', 'emd-lmnn', 'emd-itml', 'emd-tsne'] infos = interpret_query(from_city, to_city, region, metric) left, right, right_desc, regions_distance, vids, threshold = infos threshold /= 4.0 if JUST_READING: yield vids, None, None raise Exception() res, vals = None, None if metric.endswith('-nospace'): res, vals = search_no_space(vids, 10.0/7*threshold, regions_distance, left, right, RIGHT_SUPPORT) elif metric.endswith('-greedy'): res, vals = greedy_search(10.0/7*threshold, regions_distance, right, RIGHT_SUPPORT) else: # Use case for https://docs.python.org/3/whatsnew/3.3.html#pep-380 for res, vals, progress in brute_search(right_desc, tradius, regions_distance, threshold, metric=metric): if progressive: yield res, vals, progress else: print(progress, end='\t') yield res, vals, 1.0 @profile def weighted_clusters(venues, k, weights): """Return `k` centroids from `venues` (clustering is unweighted by centroid computation honors `weights` of each venues).""" labels = np.zeros(venues.shape[0]) if k > 1: nb_tries = 0 while len(np.unique(labels)) != k and nb_tries < 5: _, labels = vq.kmeans2(venues, k, iter=5, minit='points') nb_tries += 1 try: return np.array([np.average(venues[labels == i, :], 0, weights[labels == i]) for i in range(k)]) except ZeroDivisionError: print(labels) print(weights) print(np.sum(weights)) raise @profile def min_cost(costs): """Return average min-cost of assignment of row and column of the `costs` matrix.""" import munkres assignment = munkres.Munkres().compute(costs) cost = sum([costs[r][c] for r, c in assignment]) return cost/len(costs) def one_method_seed_regions(from_city, to_city, region, metric, candidate_generation, clustering): """Return promising clusters matching `region`.""" assert candidate_generation in ['knn', 'dst'] assert clustering in ['discrepancy', 'dbscan'] infos = interpret_query(from_city, to_city, region, metric) left, right, right_desc, regions_distance, vids, threshold = infos if candidate_generation == 'knn': candidates = get_knn_candidates(vids, left, right, threshold, at_most=15*threshold) elif candidate_generation == 'dst': candidates = get_neighborhood_candidates(regions_distance, right, metric, at_most=15*threshold) clusters = find_promising_seeds(candidates[1], right_desc[3][0][0], clustering, right) how_many = min(len(clusters), 6) msg = 'size of cluster: ' msg += str([len(_[1]) for _ in clusters]) msg += '\ndistance, radius, nb_venues:\n' print(msg) for cluster in clusters[:how_many]: mask = np.where(np.in1d(right['index'], cluster[1]+cluster[2]))[0] weights = weighting_venues(right['users'][mask]) features = right['features'][mask, :] dst = generic_distance(metric, regions_distance, features, weights, support=right_desc[1]) msg += '{:.4f}, {:.1f}, {}\n'.format(dst, np.sqrt(cluster[0].area), len(mask)) print(msg) return [_[1] for _ in clusters[:how_many]], msg def get_seed_regions(from_city, to_city, region): for metric in ['jsd', 'emd']: infos = interpret_query(from_city, to_city, region, metric) left, right, right_desc, regions_distance, vids, threshold = infos knn_cds = get_knn_candidates(vids, left, right, threshold, at_most=250) ngh_cds = get_neighborhood_candidates(regions_distance, right, metric, at_most=250) for _, candidates in [knn_cds, ngh_cds]: for scan in ['dbscan', 'discrepancy']: clusters = find_promising_seeds(candidates, right_desc[3][0][0], scan, right) for cl in clusters: print(metric, scan, cl[1]) @profile def greedy_search(nb_venues, distance_function, right_knn, support): """Find `nb_venues` in `right_knn` that optimize the total distance according to `distance_function`.""" import random as r candidates_idx = [] nb_venues = int(nb_venues)+3 while len(candidates_idx) < nb_venues: best_dst, best_idx = 1e15, 0 for ridx in range(len(right_knn['index'])): if ridx in candidates_idx or r.random() > 0.3: continue mask = np.array([ridx] + candidates_idx) weights = weighting_venues(right_knn['users'][mask]) activities = np.ones((12, 1)) features = right_knn['features'][mask, :] density = features_as_density(features, weights, support) distance = distance_function(density, activities) if distance < best_dst: best_dst, best_idx = distance, ridx candidates_idx.append(best_idx) print('add: {}. dst = {:.4f}'.format(right_knn['index'][best_idx], best_dst)) r_vids = [right_knn['index'][_] for _ in candidates_idx] return [best_dst, r_vids, [], -1], None def get_knn_candidates(vids, left_knn, right_knn, at_least, at_most=None): """Return between `at_least` and `at_most` venue in right that are close (in the sense of euclidean distance) of the `vids` in left. Namely, it return their row number and their ids.""" import heapq candidates = [] candidates_id = [] knn = right_knn['knn'] at_most = int(at_most) or 50000 nb_venues = min(at_most, max(len(vids)*knn, at_least)) for idx, vid in enumerate(vids): _, rid, ridx, dst, _ = cn.find_closest(vid, left_knn, right_knn) for dst_, rid_, ridx_, idx_ in zip(dst, rid, ridx, range(knn)): if rid_ not in candidates_id: candidates_id.append(rid_) heapq.heappush(candidates, (dst_, idx*knn+idx_, (rid_, ridx_))) nb_venues = min(len(candidates), int(nb_venues)) closest = heapq.nsmallest(nb_venues, candidates) mask = np.array([v[2][1] for v in closest]) r_vids = np.array([v[2][0] for v in closest]) return mask, r_vids def get_neighborhood_candidates(distance_function, right_knn, metric, at_most=None): candidates = [] activities = np.ones((12, 1)) weights = [1.0] nb_dims = right_knn['features'].shape[1] for idx, vid in enumerate(right_knn['index']): features = right_knn['features'][idx, :].reshape(1, nb_dims) if 'jsd' in metric: density = features_as_density(features, weights, RIGHT_SUPPORT) dst = distance_function(density, activities) elif 'emd' in metric: dst = distance_function([list(features.ravel())], weights) else: raise ValueError('unknown metric {}'.format(metric)) candidates.append((dst, idx, vid)) nb_venues = min(int(at_most), len(candidates)) closest = sorted(candidates, key=lambda x: x[0])[:nb_venues] mask = np.array([v[1] for v in closest]) r_vids = np.array([v[2] for v in closest]) return mask, r_vids def search_no_space(vids, nb_venues, distance_function, left_knn, right_knn, support): """Find `nb_venues` in `right_knn` that are close to those in `vids` (in the sense of euclidean distance) and return the distance with this “virtual” neighborhood (for comparaison purpose)""" mask, r_vids = get_knn_candidates(vids, left_knn, right_knn, nb_venues) weights = weighting_venues(right_knn['users'][mask]) activities = np.ones((12, 1)) features = right_knn['features'][mask, :] density = features_as_density(features, weights, support) distance = distance_function(density, activities) return [distance, r_vids, [], -1], None def interpolate_distances(values_map, filename): """Plot the distance at every circle center and interpolate between""" from scipy.interpolate import griddata from matplotlib import pyplot as plt import persistent as p filename = os.path.join('distance_map', filename) x, y, z = [np.array(dim) for dim in zip(*[a for a in values_map])] x_ext = [x.min(), x.max()] y_ext = [y.min(), y.max()] xi = np.linspace(x_ext[0], x_ext[1], 100) yi = np.linspace(y_ext[0], y_ext[1], 100) zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method='cubic') fig = plt.figure(figsize=(22, 18)) plt.contour(xi, yi, zi, 20, linewidths=0.8, colors='#282828') plt.contourf(xi, yi, zi, 20, cmap=plt.cm.Greens) plt.colorbar() plt.scatter(x, y, marker='o', c='#282828', s=5) plt.tight_layout(pad=0) plt.xlim(*x_ext) plt.ylim(*y_ext) plt.savefig(filename, dpi=96, transparent=False, frameon=False, bbox_inches='tight', pad_inches=0.01) p.save_var(filename.replace('.png', '.my'), values_map) plt.close(fig) def choose_query_region(ground_truths): """Pick among all `ground_truths` regions one that have at least 20 venues, and is closest to 150.""" if not ground_truths: return None area_size = [(area, len(area['properties']['venues'])) for area in ground_truths if len(area['properties']['venues']) >= 20] if not area_size: return None return sorted(area_size, key=lambda x: abs(150 - x[1]))[0][0]['geometry'] def batch_matching(query_city='paris'): """Match preselected regions of `query_city` into the other target cities""" import ujson global QUERY_NAME global OTMPDIR with open('static/ground_truth.json') as gt: regions = ujson.load(gt) districts = sorted(regions.keys()) cities = sorted(regions.values()[0]['gold'].keys()) assert query_city in cities cities.remove(query_city) OTMPDIR = os.path.join(OTMPDIR, 'www_comparaison_'+query_city) try: os.mkdir(OTMPDIR) except OSError: pass # cities = ['berlin'] # districts = ['montmartre', 'triangle'] for city in cities: print(city) for neighborhood in districts: # for _ in [1]: # for city, neighborhood in [('washington', 'marais'), ('washington', 'montmartre')]: print(neighborhood) possible_regions = regions[neighborhood]['gold'].get(query_city) rgeo = choose_query_region(possible_regions) if not rgeo: continue for metric in ['emd-itml', 'emd-tsne']: # for metric in ['jsd', 'emd', 'cluster', 'emd-lmnn', 'leftover']: print(metric) for radius in np.linspace(200, 500, 5): print(radius) QUERY_NAME = '{}_{}_{}_{}.my'.format(city, neighborhood, int(radius), metric) logging.info('will write: '+str(os.path.join(OTMPDIR, QUERY_NAME))) if os.path.isfile(os.path.join(OTMPDIR, QUERY_NAME)): continue res, values, _ = best_match(query_city, city, rgeo, radius, metric=metric).next() continue distance, r_vids, center, radius = res print(distance) if center is None: result = {'dst': distance, 'metric': metric, 'nb_venues': 0} else: center = cities.euclidean_to_geo(city, center) result = {'geo': {'type': 'circle', 'center': center, 'radius': radius}, 'dst': distance, 'metric': metric, 'nb_venues': len(r_vids)} regions[neighborhood][city].append(result) # outname = '{}_{}_{}_{}.png'.format(city, neighborhood, # int(radius), metric) # interpolate_distances(values, outname) with open('static/cpresets.js', 'w') as out: out.write('var PRESETS =' + ujson.dumps(regions) + ';') def find_promising_seeds(good_ids, venues_infos, method, right): """Try to find high concentration of `good_ids` venues among all `venues_infos` using one of the following methods: ['dbscan'|'discrepancy']. Return a list of convex hulls with associated list of good and bad venues id""" vids, _, venues_loc = venues_infos.all() significant_id = {vid: loc for vid, loc in i.izip(vids, venues_loc) if vid in right['index']} good_loc = np.array([significant_id[v] for v in good_ids]) bad_ids = [v for v in significant_id.iterkeys() if v not in good_ids] bad_loc = np.array([significant_id[v] for v in bad_ids]) if method == 'discrepancy': hulls, gcluster, bcluster = discrepancy_seeds((good_ids, good_loc), (bad_ids, bad_loc), np.array(venues_loc)) elif method == 'dbscan': hulls, gcluster, bcluster = dbscan_seeds((good_ids, good_loc), (bad_ids, bad_loc)) else: raise ValueError('{} is not supported'.format(method)) clusters = zip(hulls, gcluster, bcluster) return sorted(clusters, key=lambda x: len(x[1]), reverse=True) def discrepancy_seeds(goods, bads, all_locs): """Find regions with concentration of good points compared with bad ones.""" import spatial_scan as sps size = 50 support = 8 sps.GRID_SIZE = size sps.TOP_K = 500 xedges, yedges = [np.linspace(low, high, size+1) for low, high in zip(np.min(all_locs, 0), np.max(all_locs, 0))] bins = (xedges, yedges) good_ids, good_loc = goods bad_ids, bad_loc = bads count, _, _ = np.histogram2d(good_loc[:, 0], good_loc[:, 1], bins=bins) measured = count.T.ravel() count, _, _ = np.histogram2d(bad_loc[:, 0], bad_loc[:, 1], bins=bins) background = count.T.ravel() total_b = np.sum(background) total_m = np.sum(measured) discrepancy = sps.get_discrepancy_function(total_m, total_b, support) def euc_index_to_rect(idx): """Return the bounding box of a grid's cell defined by its `idx`""" i = idx % size j = idx / size return [xedges[i], yedges[j], xedges[i+1], yedges[j+1]] sps.index_to_rect = euc_index_to_rect top_loc = sps.exact_grid(np.reshape(measured, (size, size)), np.reshape(background, (size, size)), discrepancy, sps.TOP_K, sps.GRID_SIZE/8) merged = sps.merge_regions(top_loc) gcluster = [] bcluster = [] hulls = [] for region in merged: gcluster.append([id_ for id_, loc in zip(good_ids, good_loc) if region[1].contains(sgeo.Point(loc))]) bcluster.append([id_ for id_, loc in zip(bad_ids, bad_loc) if region[1].contains(sgeo.Point(loc))]) hulls.append(region[1].convex_hull) return hulls, gcluster, bcluster def dbscan_seeds(goods, bads): """Find regions with concentration of good points.""" from scipy.spatial import ConvexHull import sklearn.cluster as cl good_ids, good_loc = goods bad_ids, bad_loc = bads labels = cl.DBSCAN(eps=150, min_samples=8).fit_predict(good_loc) gcluster = [] bcluster = [] hulls = [] for cluster in range(len(np.unique(labels))-1): points = good_loc[labels == cluster, :] hull = sgeo.Polygon(points[ConvexHull(points).vertices]) gcluster.append(list(i.compress(good_ids, labels == cluster))) bcluster.append([id_ for id_, loc in zip(bad_ids, bad_loc) if hull.contains(sgeo.Point(loc))]) hulls.append(hull) return hulls, gcluster, bcluster def get_gold_desc(city, district): """Return a feature description of each gold region of (`city`, `district`).""" try: golds = [_['properties']['venues'] for _ in GROUND_TRUTH[district]['gold'][city['city']]] except KeyError as oops: print(oops) return None res = [] for vids in golds: mask = np.where(np.in1d(city['index'], vids))[0] assert mask.size == len(vids) weights = weighting_venues(city['users'][mask]) activities = np.ones((12, 1)) res.append((city['features'][mask, :], activities, weights, vids)) return res def all_gold_dst(): """Compute the distance between all gold regions and the query ones for all metrics.""" assert GROUND_TRUTH, 'load GROUND_TRUTH before calling' districts = GROUND_TRUTH.keys() cities = GROUND_TRUTH.items()[0][1]['gold'].keys() cities.remove('paris') metrics = ['cluster', 'emd', 'emd-lmnn', 'jsd'] results = {} for city, district in i.product(cities, districts): geo = GROUND_TRUTH[district]['gold']['paris'][0]['geometry'] for metric in metrics: name = '_'.join([city, district, metric]) info = interpret_query('paris', city, geo, metric) _, target_city, target_desc, regions_distance, _, threshold = info support = target_desc[1] candidates = get_gold_desc(target_city, district) if not candidates: print(name + ' is empty') continue current_dsts = [] for region in candidates: features, _, weights, _ = region if metric == 'cluster' and weights.size < 3: print("{}: can't make three clusters".format(name)) continue dst = generic_distance(metric, regions_distance, features, weights, support) if metric == 'leftover': dst = emd_leftover.collect_matlab_output(1) clean_tmp_mats() current_dsts.append(dst) results[name] = current_dsts return results def clean_tmp_mats(): """Remove .mat file after leftover metric has finished its computation.""" from subprocess import check_call, CalledProcessError try: check_call('rm /tmp/mats/*.mat', shell=True) except CalledProcessError: pass if __name__ == '__main__': # pylint: disable=C0103 # import json # with open('static/ground_truth.json') as gt: # GROUND_TRUTH = json.load(gt) # import persistent as p # distances = all_gold_dst() # p.save_var('all_gold.my', distances) import sys batch_matching(sys.argv[1]) sys.exit() import arguments args = arguments.two_cities().parse_args() origin, dest = args.origin, args.dest user_input = {"type": "Polygon", "coordinates": [[[2.3006272315979004, 48.86419005209702], [2.311570644378662, 48.86941264251879], [2.2995758056640625, 48.872983451383305], [2.3006272315979004, 48.86419005209702]]]} get_seed_regions(origin, dest, user_input) sys.exit() res, values, _ = best_match(origin, dest, user_input, 400, metric='leftover').next() distance, r_vids, center, radius = res print(distance) sys.exit() for _ in sorted(r_vids): print("'{}',".format(str(_))) # print(distance, cities.euclidean_to_geo(dest, center)) # interpolate_distances(values, origin+dest+'.png') # KDE preprocessing # given all tweets, bin them according to time. # Then run KDE on each bin, and compute a normalized grid in both cities # (it's not cheap, but it's amortized over all queries) # Then, when given a query, compute its average value for each time # set a narrow range around each value and take the intersection of all # point within this range in the other city. # Increase range until we get big enough surface # (or at least starting point)
mit
boy-jer/santhathi-appointment
app/models/admin/role.rb
43
class Admin::Role < ActiveRecord::Base end
mit
CivicCommons/CivicCommons
app/helpers/reflections_helper.rb
29
module ReflectionsHelper end
mit
snf4j/snf4j
snf4j-core/src/main/java/org/snf4j/core/codec/EventDrivenCompoundEncoder.java
3262
/* * -------------------------------- MIT License -------------------------------- * * Copyright (c) 2021 SNF4J contributors * * 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.snf4j.core.codec; import org.snf4j.core.handler.SessionEvent; import org.snf4j.core.session.ISession; /** * An event driven compound encoder that processes input data through a chain of * the specified encoders. * * @param <I> * the type of the accepted inbound objects * @param <O> * the type of the produced outbound objects * * @author <a href="http://snf4j.org">SNF4J.ORG</a> */ abstract public class EventDrivenCompoundEncoder<I,O> extends CompoundEncoder<I,O> implements IEventDrivenCodec { private final IEventDrivenCodec[] codecs; private final int codecsCount; /** * Constructs an event driven compound encoder with a chain of the specified * encoders. * <p> * The encoder chain is organized in the following way: * <pre> * {data} -&gt; encoder1 -&gt; encoder2 -&gt; ... -&gt; encoderN -&gt; {out} * </pre> * * @param encoders * the chain of encoders * @throws IllegalArgumentException * if the specified encoders have incompatible inbound or * outbound types * @throws IllegalStateException if the param O is {@code Void} */ public EventDrivenCompoundEncoder(IEncoder<?,?>... encoders) { super(encoders); codecs = new IEventDrivenCodec[encoders.length]; int count = 0; for (IEncoder<?, ?> codec: encoders) { if (codec instanceof IEventDrivenCodec) { codecs[count++] = (IEventDrivenCodec)codec; } } codecsCount = count; } @Override public void added(ISession session, ICodecPipeline pipeline) { for (int i=0; i<codecsCount; ++i) { codecs[i].added(session, pipeline); } } @Override public void event(ISession session, SessionEvent event) { for (int i=0; i<codecsCount; ++i) { codecs[i].event(session, event); } } @Override public void removed(ISession session, ICodecPipeline pipeline) { for (int i=0; i<codecsCount; ++i) { codecs[i].removed(session, pipeline); } } }
mit
michaelmalonenz/enablefood
db/migrate/20141106060827_add_is_deleted_to_user.rb
206
class AddIsDeletedToUser < ActiveRecord::Migration def change add_column :users, :is_deleted, :boolean, :default => false, :null => false User.all.each {|user| user.is_deleted = false } end end
mit
Jamkyle/raha.zeuweb
app/cache/prod/twig/b5/42/d1da4aac9146cb6b97926fc1e991d868a2cff85deb99e11da4b1b88e0260.php
1760
<?php /* TwigBundle:Exception:error.html.twig */ class __TwigTemplate_b542d1da4aac9146cb6b97926fc1e991d868a2cff85deb99e11da4b1b88e0260 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()) { // line 1 echo "<!DOCTYPE html> <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>An Error Occurred: "; // line 5 echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true); echo "</title> </head> <body> <h1>Oops! An Error Occurred</h1> <h2>The server returned a \""; // line 9 echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : null), "html", null, true); echo " "; echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true); echo "\".</h2> <div> Something is broken. Please e-mail us at [email] and let us know what you were doing when this error occurred. We will fix it as soon as possible. Sorry for any inconvenience caused. </div> </body> </html> "; } public function getTemplateName() { return "TwigBundle:Exception:error.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 32 => 9, 25 => 5, 19 => 1,); } }
mit
ashrafuzzaman/discussion
test/unit/discussion/concerns_test.rb
154
require 'test_helper' module Discussion class ConcernsTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end end
mit
dominicm/goa
uuid/uuid_js.go
1401
// +build js //This part is copied from github.com/satori/go.uuid but some feature uses non gopherjs compliants calls //Since goa only needs a subset of the features the js copies them in here package uuid import ( "bytes" "encoding/hex" "fmt" ) // String parse helpers. var ( urnPrefix = []byte("urn:uuid:") byteGroups = []int{8, 4, 4, 4, 12} ) // FromString returns UUID parsed from string input. // Input is expected in a form accepted by UnmarshalText. func FromString(input string) (u UUID, err error) { err = u.UnmarshalText([]byte(input)) return } // UnmarshalText implements the encoding.TextUnmarshaler interface. // Following formats are supported: // "6ba7b810-9dad-11d1-80b4-00c04fd430c8", // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" func (u *UUID) UnmarshalText(text []byte) (err error) { if len(text) < 32 { err = fmt.Errorf("uuid: UUID string too short: %s", text) return } t := text[:] if bytes.Equal(t[:9], urnPrefix) { t = t[9:] } else if t[0] == '{' { t = t[1:] } b := u[:] for _, byteGroup := range byteGroups { if t[0] == '-' { t = t[1:] } if len(t) < byteGroup { err = fmt.Errorf("uuid: UUID string too short: %s", text) return } _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup]) if err != nil { return } t = t[byteGroup:] b = b[byteGroup/2:] } return }
mit
LeviRosol/TheWallsMiniGame
rubik_cube_man/plugins/walls/PlayerFoodLevelChangeListner.java
815
package rubik_cube_man.plugins.walls; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.FoodLevelChangeEvent; public class PlayerFoodLevelChangeListner implements Listener { private Walls plugin; public PlayerFoodLevelChangeListner(Walls walls) { this.plugin = walls; } @EventHandler public void onPlayerFoodChangeEvent(FoodLevelChangeEvent event){ if (event.getEntity() instanceof Player){ Player player = (Player) event.getEntity(); if (plugin.playerarena.get(player) != null){ if (plugin.arenas.get(plugin.playerarena.get(player)).getCounter() == null || plugin.arenas.get(plugin.playerarena.get(player)).getCounter() >= 0){ event.setCancelled(true); } } } } }
mit
starboymanzano/chs-map-directory
application/models/Establish_model.php
1537
<?php class Establish_model extends CI_Model { public function get_estabs($limit = FALSE, $offset = FALSE) { if ($limit) { $this->db->limit($limit, $offset); } $query = $this->db->get('school_establishment'); return $query->result_array(); } public function get_estab_info($id = FALSE) { if ($id === FALSE) { $query = $this->db->get('school_establishment'); return $query->result_array(); } $query = $this->db->get_where('school_establishment', array('EstID' => $id)); return $query->row_array(); } public function set_estab_info($id = 0) { $data = array( 'EstName' => $this->input->post('est_name'), 'EstDesc' => $this->input->post('description'), 'EstWalkTime' => $this->input->post('walktime'), 'EstDistance' => $this->input->post('distance') ); $this->db->where('EstID', $id); return $this->db->update('school_establishment', $data); } public function delete_estab_info($id) { date_default_timezone_set("Asia/Manila"); $today = date("Y-m-d H:i:s"); $data = array( 'EstDesc' => NULL, 'EstWalkTime' => NULL, 'EstDistance' => NULL, 'EstDateModified' => $today ); $this->db->where('EstID', $id); return $this->db->update('school_establishment', $data); } public function dateModified() { date_default_timezone_set("Asia/Manila"); $today = date("Y-m-d H:i:s"); $data = array( 'EstDateModified' => $today ); $this->db->where('EstID', $this->input->post('temp_id')); return $this->db->update('school_establishment', $data); } } ?>
mit
Krzysiek102/StowPatriot
scripts/postController.js
2503
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var stowPatriot; (function (stowPatriot) { var postController = (function () { function postController($scope, $routeParams, spPosts) { this.$scope = $scope; this.spPosts = spPosts; $scope.c = this; this.post = this.getPost($routeParams.id); } postController.prototype.getPost = function (id) { return undefined; }; postController.prototype.imagesMainCatalog = function () { return undefined; }; postController.$inject = ['$scope', '$routeParams', 'spPosts']; return postController; })(); stowPatriot.postController = postController; var newsItemController = (function (_super) { __extends(newsItemController, _super); function newsItemController($scope, $routeParams, spPosts) { _super.call(this, $scope, $routeParams, spPosts); this.$scope = $scope; this.spPosts = spPosts; } newsItemController.prototype.getPost = function (id) { return this.spPosts.getNewsItemById(id); }; newsItemController.prototype.imagesMainCatalog = function () { return "newsItem"; }; newsItemController.$inject = ['$scope', '$routeParams', 'spPosts']; return newsItemController; })(postController); stowPatriot.newsItemController = newsItemController; var archivesItemController = (function (_super) { __extends(archivesItemController, _super); function archivesItemController($scope, $routeParams, spPosts) { _super.call(this, $scope, $routeParams, spPosts); this.$scope = $scope; this.spPosts = spPosts; } archivesItemController.prototype.getPost = function (id) { return this.spPosts.getArchivesItemById(id); }; archivesItemController.prototype.imagesMainCatalog = function () { return "archivesItem"; }; archivesItemController.$inject = ['$scope', '$routeParams', 'spPosts']; return archivesItemController; })(postController); stowPatriot.archivesItemController = archivesItemController; })(stowPatriot || (stowPatriot = {}));
mit
andela-fmustapha/document-management
client/test/helper/helper.js
1262
import { jsdom } from 'jsdom'; //eslint-disable-line import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import nock from 'nock'; //eslint-disable-line import faker from 'faker'; import * as chai from 'chai'; import spies from 'chai-spies'; //eslint-disable-line import sinon from 'sinon'; import moxios from 'moxios'; //eslint-disable-line import { mount, shallow, render } from 'enzyme'; //eslint-disable-line const exposedProperties = ['window', 'navigator', 'document']; global.document = jsdom(''); global.window = document.defaultView; global.localStorage = { setItem: () => null, removeItem: () => null }; Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property); global[property] = document.defaultView[property]; } }); chai.use(spies); global.window.localStorage = { getItem: () => 'abc' }; global.sinon = sinon; global.expect = chai.expect; global.thunk = thunk; global.configureMockStore = configureMockStore; global.nock = nock; global.mount = mount; global.shallow = shallow; global.render = render; global.spy = spies; global.faker = faker; global.moxios = moxios; global.navigator = { userAgent: 'node.js' };
mit
bonzyKul/Agile
public/modules/core/controllers/card-controller.client.controller.js
458
'use strict'; var CardController = function ($scope) { $scope.card = {}; $scope.editTitle = false; $scope.editingDetails = false; $scope.editingTitle = false; $scope.$on('OpenCardDetails', function(e, card){ $scope.card = card; $scope.editingDetails = false; $scope.editingTitle = false; $scope.showCardDetails = true; }); }; angular.module('core').controller('CardController', CardController);
mit
xCss/bing
utils/bingUtils.js
3809
var request = require('superagent'); var objectAssign = require('object-assign'); var commonUtils = require('./commonUtils'); var bingURL = 'http://www.bing.com/HPImageArchive.aspx'; var story = 'http://cn.bing.com/cnhp/coverstory/'; var cookie = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' }; module.exports = { /** * 获取 当日Bing图片 */ fetchPicture: function(options, callback) { var defaultOptions = { ids: 0, n: 1, format: 'js' }; if (Object.prototype.toString.call(options) === '[object Object]') { // 合并对象 defaultOptions = objectAssign(defaultOptions, options); } else { callback = options; } request .get(bingURL) .set(cookie) .query(defaultOptions) .end(function(err, res) { commonUtils.convert(err, res, function(data) { for (var i in data['images']) { var images = data['images'][i]; module.exports.fetchStory({ d: images['enddate'] }, function(data) { data = objectAssign(images, data); var newData = { startdate: data.startdate, fullstartdate: data.fullstartdate, enddate: data.enddate, url: /(http|https)\:\/\//gi.test(data.url) ? data.url : 'http://s.cn.bing.net' + data.url, urlbase: data.urlbase, copyright: data.copyright, copyrightlink: data.copyrightlink, hsh: data.hsh, title: data.title, description: data.description, attribute: data.attribute, country: data.country, city: data.city, longitude: data.longitude, latitude: data.latitude, continent: data.continent } callback && callback(newData); }); } }); }); }, /** * 获取 当前Bing返回的所有图片集合 */ fetchPictures: function(callback) { var options = { ids: 14, n: 100 }; module.exports.fetchPicture(options, callback); }, /** * 获取 每日故事(默认当日) * * 若需要查询指定日期: * options = { * d:20161015 * } */ fetchStory: function(options, callback) { if (Object.prototype.toString.call(options) === '[object Function]') { callback = options; options = {}; } request .get(story) .set(cookie) .query(options) .end(function(err, res) { commonUtils.convert(err, res, function(data) { data['description'] = data.para1 || data.para2 || ''; data['country'] = data.Country || ''; data['city'] = data.City || ''; data['longitude'] = data.Longitude || ''; data['latitude'] = data.Latitude || ''; data['continent'] = data.Continent || ''; callback && callback(data); }); }); } };
mit
magnus-eriksson/config
src/Factory.php
834
<?php namespace Maer\Config; /** * A simple config package to load files containing multidimensional arrays * and fetch them easily using dot notation. * * @author Magnus Eriksson <mange@reloop.se> * @version 1.1.0 * @package Maer * @subpackage Config */ /** * Factory to get the same Config instance */ class Factory { /** * The Config instance * @var Config */ protected static $instance; /** * This class shouldn't be instanceable. It's a static helper class. */ protected function __construct() { } /** * Get the Config instance * * @return Config */ public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new Config; } return self::$instance; } }
mit
forsigner/fim
examples/example-react/src/pages/Svg.tsx
1050
import { Box } from '@fower/react'; export default () => { return ( <Box toCenter h-100vh space3 flexWrap> <Box as="svg" fillNone fillCurrent gray800 square10 viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" /> </Box> <Box square10 as="svg" fillNone // fillCurrent gray800 stroke-1 viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" /> </Box> </Box> ); };
mit
ProfilerTeam/Profiler
protected/vendors/Zend/Crypt/DiffieHellman.php
12792
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Crypt * @subpackage DiffieHellman * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * PHP implementation of the Diffie-Hellman public key encryption algorithm. * Allows two unassociated parties to establish a joint shared secret key * to be used in encrypting subsequent communications. * * @category Zend * @package Zend_Crypt * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Crypt_DiffieHellman { /** * Static flag to select whether to use PHP5.3's openssl extension * if available. * * @var boolean */ public static $useOpenssl = true; /** * Default large prime number; required by the algorithm. * * @var string */ private $_prime = null; /** * The default generator number. This number must be greater than 0 but * less than the prime number set. * * @var string */ private $_generator = null; /** * A private number set by the local user. It's optional and will * be generated if not set. * * @var string */ private $_privateKey = null; /** * BigInteger support object courtesy of Zend_Crypt_Math * * @var Zend_Crypt_Math_BigInteger */ private $_math = null; /** * The public key generated by this instance after calling generateKeys(). * * @var string */ private $_publicKey = null; /** * The shared secret key resulting from a completed Diffie Hellman * exchange * * @var string */ private $_secretKey = null; /** * Constants */ const BINARY = 'binary'; const NUMBER = 'number'; const BTWOC = 'btwoc'; /** * Constructor; if set construct the object using the parameter array to * set values for Prime, Generator and Private. * If a Private Key is not set, one will be generated at random. * * @param string $prime * @param string $generator * @param string $privateKey * @param string $privateKeyType */ public function __construct($prime, $generator, $privateKey = null, $privateKeyType = self::NUMBER) { $this->setPrime($prime); $this->setGenerator($generator); if ($privateKey !== null) { $this->setPrivateKey($privateKey, $privateKeyType); } $this->setBigIntegerMath(); } /** * Generate own public key. If a private number has not already been * set, one will be generated at this stage. * * @return Zend_Crypt_DiffieHellman */ public function generateKeys() { if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) { $details = array(); $details['p'] = $this->getPrime(); $details['g'] = $this->getGenerator(); if ($this->hasPrivateKey()) { $details['priv_key'] = $this->getPrivateKey(); } $opensslKeyResource = openssl_pkey_new( array('dh' => $details) ); $data = openssl_pkey_get_details($opensslKeyResource); $this->setPrivateKey($data['dh']['priv_key'], self::BINARY); $this->setPublicKey($data['dh']['pub_key'], self::BINARY); } else { // Private key is lazy generated in the absence of PHP 5.3's ext/openssl $publicKey = $this->_math->powmod($this->getGenerator(), $this->getPrivateKey(), $this->getPrime()); $this->setPublicKey($publicKey); } return $this; } /** * Setter for the value of the public number * * @param string $number * @param string $type * @throws Zend_Crypt_DiffieHellman_Exception * @return Zend_Crypt_DiffieHellman */ public function setPublicKey($number, $type = self::NUMBER) { if ($type == self::BINARY) { $number = $this->_math->fromBinary($number); } if (!preg_match("/^\d+$/", $number)) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number'); } $this->_publicKey = (string) $number; return $this; } /** * Returns own public key for communication to the second party to this * transaction. * * @param string $type * @throws Zend_Crypt_DiffieHellman_Exception * @return string */ public function getPublicKey($type = self::NUMBER) { if ($this->_publicKey === null) { // require_once 'Zend/Crypt/DiffieHellman/Exception.php'; throw new Zend_Crypt_DiffieHellman_Exception('A public key has not yet been generated using a prior call to generateKeys()'); } if ($type == self::BINARY) { return $this->_math->toBinary($this->_publicKey); } elseif ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_publicKey)); } return $this->_publicKey; } /** * Compute the shared secret key based on the public key received from the * the second party to this transaction. This should agree to the secret * key the second party computes on our own public key. * Once in agreement, the key is known to only to both parties. * By default, the function expects the public key to be in binary form * which is the typical format when being transmitted. * * If you need the binary form of the shared secret key, call * getSharedSecretKey() with the optional parameter for Binary output. * * @param string $publicKey * @param string $type * @param string $output * @throws Zend_Crypt_DiffieHellman_Exception * @return mixed */ public function computeSecretKey($publicKey, $type = self::NUMBER, $output = self::NUMBER) { if ($type == self::BINARY) { $publicKey = $this->_math->fromBinary($publicKey); } if (!preg_match("/^\d+$/", $publicKey)) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number'); } if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) { $this->_secretKey = openssl_dh_compute_key($publicKey, $this->getPublicKey()); } else { $this->_secretKey = $this->_math->powmod($publicKey, $this->getPrivateKey(), $this->getPrime()); } return $this->getSharedSecretKey($output); } /** * Return the computed shared secret key from the DiffieHellman transaction * * @param string $type * @throws Zend_Crypt_DiffieHellman_Exception * @return string */ public function getSharedSecretKey($type = self::NUMBER) { if (!isset($this->_secretKey)) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('A secret key has not yet been computed; call computeSecretKey()'); } if ($type == self::BINARY) { return $this->_math->toBinary($this->_secretKey); } elseif ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_secretKey)); } return $this->_secretKey; } /** * Setter for the value of the prime number * * @param string $number * @throws Zend_Crypt_DiffieHellman_Exception * @return Zend_Crypt_DiffieHellman */ public function setPrime($number) { if (!preg_match("/^\d+$/", $number) || $number < 11) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number or too small: should be a large natural number prime'); } $this->_prime = (string) $number; return $this; } /** * Getter for the value of the prime number * * @throws Zend_Crypt_DiffieHellman_Exception * @return string */ public function getPrime() { if (!isset($this->_prime)) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('No prime number has been set'); } return $this->_prime; } /** * Setter for the value of the generator number * * @param string $number * @throws Zend_Crypt_DiffieHellman_Exception * @return Zend_Crypt_DiffieHellman */ public function setGenerator($number) { if (!preg_match("/^\d+$/", $number) || $number < 2) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number greater than 1'); } $this->_generator = (string) $number; return $this; } /** * Getter for the value of the generator number * * @throws Zend_Crypt_DiffieHellman_Exception * @return string */ public function getGenerator() { if (!isset($this->_generator)) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('No generator number has been set'); } return $this->_generator; } /** * Setter for the value of the private number * * @param string $number * @param string $type * @throws Zend_Crypt_DiffieHellman_Exception * @return Zend_Crypt_DiffieHellman */ public function setPrivateKey($number, $type = self::NUMBER) { if ($type == self::BINARY) { $number = $this->_math->fromBinary($number); } if (!preg_match("/^\d+$/", $number)) { // require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number'); } $this->_privateKey = (string) $number; return $this; } /** * Getter for the value of the private number * * @param string $type * @return string */ public function getPrivateKey($type = self::NUMBER) { if (!$this->hasPrivateKey()) { $this->setPrivateKey($this->_generatePrivateKey(), self::BINARY); } if ($type == self::BINARY) { return $this->_math->toBinary($this->_privateKey); } elseif ($type == self::BTWOC) { return $this->_math->btwoc($this->_math->toBinary($this->_privateKey)); } return $this->_privateKey; } /** * Check whether a private key currently exists. * * @return boolean */ public function hasPrivateKey() { return isset($this->_privateKey); } /** * Setter to pass an extension parameter which is used to create * a specific BigInteger instance for a specific extension type. * Allows manual setting of the class in case of an extension * problem or bug. * * @param string $extension * @return void */ public function setBigIntegerMath($extension = null) { /** * @see Zend_Crypt_Math */ // require_once 'Zend/Crypt/Math.php'; $this->_math = new Zend_Crypt_Math($extension); } /** * In the event a private number/key has not been set by the user, * or generated by ext/openssl, a best attempt will be made to * generate a random key. Having a random number generator installed * on linux/bsd is highly recommended! The alternative is not recommended * for production unless without any other option. * * @return string */ protected function _generatePrivateKey() { $rand = $this->_math->rand($this->getGenerator(), $this->getPrime()); return $rand; } }
mit
pictawall/sdk-js
es5/src/core/Sdk.js
9779
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _StringUtil = require('../util/StringUtil'); var _StringUtil2 = _interopRequireDefault(_StringUtil); var _fetch = require('./fetch'); var _fetch2 = _interopRequireDefault(_fetch); var _URLSearchParams = require('./URLSearchParams'); var _URLSearchParams2 = _interopRequireDefault(_URLSearchParams); var _polyfills = require('./polyfills'); var _polyfills2 = _interopRequireDefault(_polyfills); var _Errors = require('./Errors'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @private */ function _insertCollections(event, collections) { // load everything at the last minute so polyfills have time to load. var AssetCollection = require('../collections/AssetCollection').default; var UserCollection = require('../collections/UserCollection').default; var AdCollection = require('../collections/AdCollection').default; var MessageCollection = require('../collections/MessageCollection').default; if (collections === void 0) { event.addCollection('users', new UserCollection(event)); event.addCollection('assets', new AssetCollection(event)); event.addCollection('ads', new AdCollection(event)); event.addCollection('messages', new MessageCollection(event)); } else { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = void 0; try { for (var _iterator = Object.getOwnPropertyNames(collections)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var collectionName = _step.value; event.addCollection(collectionName, collections[collectionName](event)); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } } /** * Entry point to the SDK. * * @class Sdk */ var Sdk = function () { /** * Pictawall endpoint (direct access via https://api.pictawall.com/v2.5) * @param {String} [apiBaseUrl = 'https://api.pictawall.net/v2.5'] The pictawall cached API endpoint. */ function Sdk() { var apiBaseUrl = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 'https://api.pictawall.net/v2.5'; _classCallCheck(this, Sdk); this.apiBaseUrl = apiBaseUrl; } /** * Creates and populates a new event model. * * @param {!String} identifier The identifier of the pictawall event. * @param {Object} [eventConfig = {}] The config object to give as a third parameter to {@link EventModel#constructor}. * @param {Object.<String, Function>} [collections = ] A list of collections factories to use to create the collections to add to the event and fetch. By default this will create one of each available collections: 'users', 'assets', 'messages', 'ads'. * @returns {Promise.<EventModel>} A promise which resolves when the model has been populated. * * @example * sdk.getEvent('undiscovered-london', {}, { * textAssets: event => new AssetCollection(event, { kind: 'text' }) * }); */ _createClass(Sdk, [{ key: 'getEvent', value: function getEvent(identifier, eventConfig, collections) { var _this = this; return (0, _polyfills2.default)().then(function () { var EventModel = require('../models/EventModel').default; var event = new EventModel(_this, identifier, eventConfig); _insertCollections(event, collections); return Sdk.Promise.all([event.fetch(), event.fetchCollections()]).then(function () { return event; }); }); } /** * <p>Creates and populates a new channel model.</p> * <p>The event configuration will be fetched from the API. If you need to have local control over it, you should use {@link Sdk#getEvent} instead.</p> * * @param {!String} identifier The identifier of the pictawall channel. * @param {Object} [eventConfig = {}] The config object to give as a third parameter to {@link EventModel#constructor}. * @param {Object.<String, Function>} [collections = ] A list of collections factories to use to create the collections to add to the event and fetch. By default this will create one of each available collections: 'users', 'assets', 'messages', 'ads'. * @returns {Promise.<ChannelModel>} A promise which resolves when the model has been populated. */ }, { key: 'getChannel', value: function getChannel(identifier, eventConfig, collections) { var _this2 = this; return (0, _polyfills2.default)().then(function () { var ChannelModel = require('../models/ChannelModel').default; var channel = new ChannelModel(_this2, identifier, eventConfig); return channel.fetch().then(function (channel) { _insertCollections(channel.event, collections); return channel.event.fetchCollections(); }).then(function () { return channel; }); }); } /** * Calls an endpoint on the API and returns the response * * @param {!String} path - The API endpoint. e. g. "/events" * @param {Object} [parameters = {}] - The options to give to {@link Global.fetch}. * @param {Object} [parameters.pathParameters = {}] - Parameters to insert in the path using {@link StringUtil#format}. * @param {Object} [parameters.queryParameters = {}] - List of key -> value parameters to add to the url as query parameters. * * @return {!Response} */ }, { key: 'callApi', value: function callApi(path, parameters) { var pathParameters, queryParameters, pathParameterKeys, qsBuilder, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, key, value; return regeneratorRuntime.async(function callApi$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: pathParameters = parameters.pathParameters || {}; queryParameters = parameters.queryParameters || {}; path = _StringUtil2.default.format(path, true, pathParameters); if (path.endsWith('/')) { path = path.slice(0, -1); } pathParameterKeys = Object.getOwnPropertyNames(queryParameters); if (!(pathParameterKeys.length > 0)) { _context.next = 27; break; } qsBuilder = new _URLSearchParams2.default.URLSearchParams(); _iteratorNormalCompletion2 = true; _didIteratorError2 = false; _iteratorError2 = void 0; _context.prev = 10; for (_iterator2 = pathParameterKeys[Symbol.iterator](); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { key = _step2.value; value = queryParameters[key]; qsBuilder.set(key, value); } _context.next = 18; break; case 14: _context.prev = 14; _context.t0 = _context['catch'](10); _didIteratorError2 = true; _iteratorError2 = _context.t0; case 18: _context.prev = 18; _context.prev = 19; if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } case 21: _context.prev = 21; if (!_didIteratorError2) { _context.next = 24; break; } throw _iteratorError2; case 24: return _context.finish(21); case 25: return _context.finish(18); case 26: path += '?' + qsBuilder.toString(); case 27: _context.prev = 27; _context.next = 30; return regeneratorRuntime.awrap(_fetch2.default.fetch(this.apiBaseUrl + path, parameters)); case 30: return _context.abrupt('return', _context.sent); case 33: _context.prev = 33; _context.t1 = _context['catch'](27); throw new _Errors.NetworkError(this, _context.t1); case 36: case 'end': return _context.stop(); } } }, null, this, [[10, 14, 18, 26], [19,, 21, 25], [27, 33]]); } /** * The promise implementation to use inside the SDK, replace this field by your promise implementation. * @type {function} */ }], [{ key: 'Promise', get: function get() { return Promise; } }]); return Sdk; }(); exports.default = Sdk;
mit
jbosboom/streamjit
src/edu/mit/streamjit/test/apps/fft5/FFT5.java
5244
/* * Copyright (c) 2013-2014 Massachusetts Institute of Technology * * 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 edu.mit.streamjit.test.apps.fft5; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.jeffreybosboom.serviceproviderprocessor.ServiceProvider; import edu.mit.streamjit.api.Filter; import edu.mit.streamjit.api.Input; import edu.mit.streamjit.api.Pipeline; import edu.mit.streamjit.api.StreamCompiler; import edu.mit.streamjit.impl.compiler2.Compiler2StreamCompiler; import edu.mit.streamjit.impl.interp.DebugStreamCompiler; import edu.mit.streamjit.test.SuppliedBenchmark; import edu.mit.streamjit.test.Benchmark; import edu.mit.streamjit.test.Datasets; import edu.mit.streamjit.test.Benchmarker; import java.nio.ByteOrder; import java.nio.file.Paths; /** * Rewritten StreamIt's asplos06 benchmarks. Refer * STREAMIT_HOME/apps/benchmarks/asplos06/fft/streamit/FFT5.str for original * implementations. Each StreamIt's language constructs (i.e., pipeline, filter * and splitjoin) are rewritten as classes in StreamJit. * * @author Sumanan sumanan@mit.edu * @since Mar 14, 2013 */ public final class FFT5 { private FFT5() {} public static void main(String[] args) throws InterruptedException { StreamCompiler sc = new DebugStreamCompiler(); Benchmarker.runBenchmark(new FFT5Benchmark(), sc).get(0).print(System.out); } @ServiceProvider(Benchmark.class) public static final class FFT5Benchmark extends SuppliedBenchmark { public FFT5Benchmark() { super("FFT5", FFT5Kernel.class, new Dataset("FFT5.in", (Input)Input.fromBinaryFile(Paths.get("data/FFT5.in"), Float.class, ByteOrder.LITTLE_ENDIAN) // , (Supplier)Suppliers.ofInstance((Input)Input.fromBinaryFile(Paths.get("/home/jbosboom/streamit/streams/apps/benchmarks/asplos06/fft/streamit/FFT5.out"), Float.class, ByteOrder.LITTLE_ENDIAN)) )); } } /** * This represents "void->void pipeline FFT5()". */ public static final class FFT5Kernel extends Pipeline<Float, Float> { public FFT5Kernel() { this(256); } public FFT5Kernel(int ways) { add(new FFTReorder(ways)); for (int j = 2; j <= ways; j *= 2) { add(new CombineDFT(j)); } } } private static final class CombineDFT extends Filter<Float, Float> { private final float wn_r, wn_i; private final int n; private CombineDFT(int n) { super(2 * n, 2 * n, 2 * n); this.n = n; this.wn_r = (float) Math.cos(2 * 3.141592654 / n); this.wn_i = (float) Math.sin(2 * 3.141592654 / n); } public void work() { float w_r = 1; float w_i = 0; float[] results = new float[2 * n]; for (int i = 0; i < n; i += 2) { // this is a temporary work-around since there seems to be // a bug in field prop that does not propagate nWay into the // array references. --BFT 9/10/02 // int tempN = nWay; // Fixed --jasperln // removed nWay, just using n --sitij 9/26/03 float y0_r = peek(i); float y0_i = peek(i + 1); float y1_r = peek(n + i); float y1_i = peek(n + i + 1); float y1w_r = y1_r * w_r - y1_i * w_i; float y1w_i = y1_r * w_i + y1_i * w_r; results[i] = y0_r + y1w_r; results[i + 1] = y0_i + y1w_i; results[n + i] = y0_r - y1w_r; results[n + i + 1] = y0_i - y1w_i; float w_r_next = w_r * wn_r - w_i * wn_i; float w_i_next = w_r * wn_i + w_i * wn_r; w_r = w_r_next; w_i = w_i_next; } for (int i = 0; i < 2 * n; i++) { pop(); push(results[i]); } } } private static final class FFTReorderSimple extends Filter<Float, Float> { private final int totalData; private final int n; private FFTReorderSimple(int n) { super(2 * n, 2 * n, 2 * n); this.n = n; this.totalData = 2*n; } public void work() { for (int i = 0; i < totalData; i += 4) { push(peek(i)); push(peek(i + 1)); } for (int i = 2; i < totalData; i += 4) { push(peek(i)); push(peek(i + 1)); } for (int i = 0; i < n; i++) { pop(); pop(); } } } private static final class FFTReorder extends Pipeline<Float, Float> { private FFTReorder(int n) { for (int i = 1; i < (n / 2); i *= 2) add(new FFTReorderSimple(n / i)); } } }
mit
phodal/growth-code
chapter6/fabfile.py
3739
import os from fabric.api import local from fabric.decorators import task from fabric.context_managers import settings, hide, cd, prefix from fabric.operations import sudo, run, put from fabric.state import env circus_file_path = os.path.realpath('deploy/circus.ini') circus_upstart_file_path = os.path.realpath('deploy/circus.conf') nginx_config_path = os.path.realpath('deploy/nginx') nginx_avaliable_path = "/etc/nginx/sites-available/" nginx_enable_path = "/etc/nginx/sites-enabled/" app_path = "~" virtual_env_path = "~/py35env/bin/activate" env.hosts = ['10.211.55.26'] env.user = 'phodal' env.password = '940217' @task def install(): """Install requirements packages""" local("pip install -r requirements.txt") @task def runserver(): """Run Server""" local("./manage.py runserver") @task def pep8(): """ Check the project for PEP8 compliance using `pep8` """ with settings(hide('warnings'), warn_only=True): local('pep8 .') @task def tag_version(version): """Tag New Version""" local("git tag %s" % version) local("git push origin %s" % version) @task def fetch_version(version): """Fetch Git Version""" local('wget https://codeload.github.com/phodal/growth_studio/tar.gz/%s' % version) @task def test(): """ Run Test """ local("./manage.py test") @task def host_type(): run('uname -a') @task def setup(): """ Setup the Ubuntu Env """ sudo('apt-get update') APT_GET_PACKAGES = [ "build-essential", "git", "python3-dev", "python3-pip", "nginx", "virtualenv", ] sudo("apt-get install -y " + " ".join(APT_GET_PACKAGES)) sudo('pip3 install circus') sudo('rm ' + nginx_enable_path + 'default') run('virtualenv --distribute -p /usr/bin/python3.5 py35env') def nginx_restart(): "Reset nginx" run("service nginx restart") def nginx_start(): "Start nginx" run("service nginx start") def nginx_config(nginx_config_path=nginx_config_path): "Send nginx configuration" for file_name in os.listdir(nginx_config_path): put(os.path.join(nginx_config_path, file_name), nginx_avaliable_path, use_sudo=True) def circus_config(): "Send Circus configuration" sudo('mkdir -p /etc/circus/') put(circus_file_path, '/etc/circus/', use_sudo=True) def circus_upstart_config(): "Send Circus Upstart configuration" put(circus_upstart_file_path, '/etc/init/', use_sudo=True) def circus_start(): "Send Circus Upstart configuration" sudo('/usr/local/bin/circusd /etc/circus/circus.ini --daemon') def nginx_enable_site(nginx_config_file): "Enable nginx site" with cd(nginx_enable_path): sudo('rm -f ' + nginx_config_file) sudo('ln -s ' + nginx_avaliable_path + nginx_config_file) @task def deploy(version): """ depoly app to cloud """ with cd(app_path): get_app(version) setup_app(version) config_app() nginx_config() nginx_enable_site('growth-studio.conf') circus_config() circus_upstart_config() circus_start() nginx_restart() def config_app(): with cd('growth-studio'): with prefix('source ' + virtual_env_path): run('python manage.py collectstatic -l --noinput') run('python manage.py migrate') def setup_app(version): with prefix('source ' + virtual_env_path): run('pip3 install -r growth-studio-%s/requirements/prod.txt' % version) run('rm -f growth-studio') run('ln -s growth-studio-%s growth-studio' % version) def get_app(version): run(('wget ' + 'https://codeload.github.com/phodal/growth_studio/tar.gz/v' + '%s') % version) run('tar xvf v%s' % version)
mit
Daz2345/dhPulse
packages/dh-api/lib/custom_fields.js
207
Users.addField({ fieldName: 'API_Enabled', fieldSchema: { type: Boolean, optional: true, defaultValue: false, editableBy: ["admin"], autoform: { group: 'API' } } });
mit
14islands/bem-helper-js
src/index.js
2036
/** * BEM helper for generating CSS class names in JS * Returns a chainable API * * @author David Lindkvist */ class BEM { constructor(block, element, modifiers = [], nonBemClasses = []) { this.block = block; this.element = element; this.modifiers = modifiers; this.nonBemClasses = nonBemClasses; } // Set element scope el(elementIdentifier) { let newBlock = this.clone() if (typeof elementIdentifier !== 'undefined' && elementIdentifier.toString().length) { newBlock.element = elementIdentifier; } return newBlock; } // Add BEM modifier is(modifier, isOn = true) { let modifiers = this.modifiers.slice(); isOn && typeof modifier !== 'undefined' && modifier.toString().length && modifiers.push(modifier); let newBlock = this.clone({ modifiers: modifiers, nonBemClasses: this.nonBemClasses }) return newBlock } // Add other non-BEM classname to the mix add(className) { let nonBemClasses = this.nonBemClasses.slice(); if (typeof className !== 'undefined' && className.toString().length) { nonBemClasses.push(className); } let newBlock = this.clone({ nonBemClasses: nonBemClasses, modifiers: this.modifiers }) return newBlock } // Render BEM chain as full class name string toString() { let prefix = typeof this.element !== 'undefined' ? this.block + '__' + this.element : this.block; const classes = [prefix]; for (let modifier of this.modifiers) { classes.push(prefix + '--' + modifier); } for (let extraClass of this.nonBemClasses) { classes.push(extraClass); } return classes.join(' '); } clone(newBlock = {}) { return new BEM(this.block, this.element, newBlock.modifiers, newBlock.nonBemClasses) } } // Creates BEM chain based on context type export default function(ctx) { if (typeof ctx === 'object') { if (ctx instanceof BEM) { return ctx; } return new BEM(ctx.constructor.name); } else if (typeof ctx === 'string') { return new BEM(ctx); } throw "BEM block not of valid type"; }
mit
EricSchles/angular-breadcrumb
test/spec/directive-interpolation-test.js
870
/*jshint undef: false */ describe('Directive with interpolation conf', function() { var element, scope, controller, compile; beforeEach(function() { module('ncy-interpolation-conf'); }); beforeEach(inject(function($rootScope, $compile, $controller) { element = angular.element('<div ncy-breadcrumb></div>'); compile = $compile(element); scope = $rootScope.$new(); controller = $controller; })); it('interpolates labels correctly', inject(function() { goToState('A.B'); controller('BCtrl', {'$scope' : scope} ); compile(scope); expect(scope.tripleB).toBeDefined(); scope.$emit('$viewContentLoaded'); scope.$digest(); console.info('Directive content : ' + element.text()); expect(element.text()).toContain('State BBB'); })); });
mit
devdigital/LiveDocs
Source/LiveDocs.Diagrams.Ui/Commands/ICommand.cs
143
namespace LiveDocs.Diagrams.Ui.Commands { public interface ICommand { string Name { get; } void Execute(); } }
mit
nilsschmidt1337/ldparteditor
src/org/nschmidt/ldparteditor/data/GTexture.java
38138
/* MIT - License Copyright (c) 2012 - this year, Nils Schmidt 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.nschmidt.ldparteditor.data; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL20; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.enumtype.View; import org.nschmidt.ldparteditor.helper.FileHelper; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.opengl.GLShader; import org.nschmidt.ldparteditor.opengl.OpenGLRenderer; import org.nschmidt.ldparteditor.opengl.OpenGLRenderer20; import org.nschmidt.ldparteditor.project.Project; import org.nschmidt.ldparteditor.shell.editor3d.Editor3DWindow; import org.nschmidt.ldparteditor.workbench.WorkbenchManager; import de.matthiasmann.twl.util.PNGDecoder; import de.matthiasmann.twl.util.PNGDecoder.Format; /** * @author nils * */ public class GTexture { static final GTexture NO_TEXTURE = new GTexture(); private long accessTime = System.currentTimeMillis(); private Map<OpenGLRenderer, Integer> openGlId = new HashMap<>(); private Map<OpenGLRenderer, Integer> openGlIdGlossmap = new HashMap<>(); private Map<OpenGLRenderer, Integer> openGlIdCubemap = new HashMap<>(); private Map<OpenGLRenderer, Integer> openGlIdCubemapMatte = new HashMap<>(); private Map<OpenGLRenderer, Integer> openGlIdCubemapMetal = new HashMap<>(); private Map<OpenGLRenderer, Boolean> openGlDisposed = new HashMap<>(); private String texture = ""; //$NON-NLS-1$ private String glossmap = ""; //$NON-NLS-1$ private boolean glossy = false; private int cubeMapIndex = 0; private final TexType type; private Vector3f point1 = new Vector3f(); private Vector3f point2 = new Vector3f(); private Vector3f point3 = new Vector3f(); private Vector3f[] tripoints = new Vector3f[]{new Vector3f(), new Vector3f(), new Vector3f()}; private float a = 0f; private float b = 0f; private float width; private float height; private static final float EPSILON = 1f; private Map<GData, UV> uvCache = new HashMap<>(); private Set<GData> cacheUsage = new HashSet<>(); private GTexture() { this.type = TexType.NONE; } public GTexture(TexType type, String texture, String glossmap, int useCubemap, Vector3f point1, Vector3f point2, Vector3f point3, float a, float b) { this.type = type; this.point1.set(point1); this.point2.set(point2); this.point3.set(point3); this.a = a; this.b = b; glossy = glossmap != null; cubeMapIndex = useCubemap; this.texture = texture; this.glossmap = glossmap; } private class UV { private final float[] uv = new float[8]; public UV(float[] u, float[] v) { this.uv[0] = u[0]; this.uv[1] = u[1]; this.uv[2] = u[2]; this.uv[3] = u[3]; this.uv[4] = v[0]; this.uv[5] = v[1]; this.uv[6] = v[2]; this.uv[7] = v[3]; } public float[] getUV() { return uv; } } void calcUVcoords1(float x, float y, float z, GData1 parent, GData id) { if (type == TexType.SPHERICAL) tripoints[0].set(x, y, z); calcUVcoords(x, y, z, parent, 0, id); } void calcUVcoords2(float x, float y, float z, GData1 parent) { if (type == TexType.SPHERICAL) tripoints[1].set(x, y, z); calcUVcoords(x, y, z, parent, 1, null); } void calcUVcoords3(float x, float y, float z, GData1 parent) { if (type == TexType.SPHERICAL) tripoints[2].set(x, y, z); calcUVcoords(x, y, z, parent, 2, null); } void calcUVcoords4(float x, float y, float z, GData1 parent) { calcUVcoords(x, y, z, parent, 3, null); } private float[] tU = new float[4]; private float[] tV = new float[4]; private boolean cacheTriggered = false; private void calcUVcoords(float x, float y, float z, GData1 parent, int i, GData id) { if (cacheTriggered) return; if (i == 0 && id != null && uvCache.containsKey(id)) { cacheUsage.add(id); cacheTriggered = true; float[] cacheUV = uvCache.get(id).getUV(); tU[0] = cacheUV[0]; tU[1] = cacheUV[1]; tU[2] = cacheUV[2]; tU[3] = cacheUV[3]; tV[0] = cacheUV[4]; tV[1] = cacheUV[5]; tV[2] = cacheUV[6]; tV[3] = cacheUV[7]; return; } Vector4f realPos = new Vector4f(x, y, z, 1f); Matrix4f.transform(parent.productMatrix, realPos, realPos); float[] uv = new float[2]; if (type == TexType.PLANAR) { final Vector3f diff1to3 = Vector3f.sub(point3, point1, null); final Vector3f diff1to2 = Vector3f.sub(point2, point1, null); final float length1to3 = diff1to3.length(); final float length1to2 = diff1to2.length(); if (length1to2 < EPSILON || length1to3 < EPSILON) { uv[0] = 0f; uv[1] = 0f; return; } diff1to2.normalise(); diff1to3.normalise(); final Vector3f pos = new Vector3f(realPos.x, realPos.y, realPos.z); float u = Vector3f.dot(Vector3f.sub(point1, pos, null), diff1to2); float v = Vector3f.dot(Vector3f.sub(point1, pos, null), diff1to3); if (v < 0f) { v = -v / length1to3; if (v > 1f) v = 1f; } else { v = v / length1to3; if (v > 1f) v = 1f; } if (u < 0f) { u = -u / length1to2; if (u > 1f) u = 1f; } else { u = u / length1to2; if (u > 1f) u = 1f; } tU[i] = u; tV[i] = v; uv[0] = u; uv[1] = v; } else if (type == TexType.CYLINDRICAL) { final Vector3f pos = new Vector3f(realPos.x, realPos.y, realPos.z); final Vector3f diff1to2 = Vector3f.sub(point2, point1, null); final Vector3f p1n = (Vector3f) Vector3f.sub(point2, point1, null).normalise(); final float p1d = Vector3f.dot(Vector3f.sub(point1, pos, null), p1n); final float length1to2 = diff1to2.length(); float v = p1d; if (v > 0f) { v = -v / length1to2; if (v > 1f) v = 1f; } else { v = v / length1to2; if (v > 1f) v = 1f; } uv[1] = v; tV[i] = v; final Vector3f p1D = new Vector3f(p1d * p1n.x, p1d * p1n.y, p1d * p1n.z); final Vector3f posP1 = Vector3f.add(pos, p1D, null); final Vector3f diff1toP1 = Vector3f.sub(posP1, point1, null); final Vector3f diff1to3 = Vector3f.sub(point3, point1, null); uv[0] = Vector3f.angle(diff1toP1, diff1to3); Vector3f cross = Vector3f.cross(diff1toP1, diff1to3, null); if (cross.length() == 0f) { cross = Vector3f.cross(diff1toP1, Vector3f.cross(diff1to3, p1n, null), null); } if (Vector3f.dot(p1n, cross) < 0f) { uv[0] = -uv[0]; } tU[i] = uv[0]; } else { final Vector4f posT = new Vector4f(realPos.x, realPos.y, realPos.z, 1f); final Matrix4f localToWorld = new Matrix4f(); localToWorld.m30 = point1.x; localToWorld.m31 = point1.y; localToWorld.m32 = point1.z; final Vector3f bz = Vector3f.sub(point2, point1, null); if (bz.lengthSquared() > 0f) { bz.normalise(); } else { uv[0] = 0f; uv[1] = 0f; return; } localToWorld.m02 = bz.x; localToWorld.m12 = bz.y; localToWorld.m22 = bz.z; final Vector3f by = Vector3f.sub(point3, point2, null); if (by.lengthSquared() > 0f) { by.normalise(); } else { uv[0] = 0f; uv[1] = 0f; return; } localToWorld.m01 = by.x; localToWorld.m11 = by.y; localToWorld.m21 = by.z; final Vector3f bx = Vector3f.cross(by, bz, null); if (bx.lengthSquared() > 0f) { bx.normalise(); } else { uv[0] = 0f; uv[1] = 0f; return; } localToWorld.m00 = bx.x; localToWorld.m10 = bx.y; localToWorld.m20 = bx.z; localToWorld.invert(); Matrix4f.transform(localToWorld, posT, posT); final Vector3f d = new Vector3f(posT.x, posT.y, posT.z); if (d.lengthSquared() > 0f) { d.normalise(); } tU[i] = (float) Math.atan2(d.x, d.z); tV[i] = (float) Math.asin(d.y); } } float[] getUVcoords(boolean isTriangle, GData id) { float[] result = new float[8]; final int size = isTriangle ? 3 : 4; if (cacheTriggered) { for (int i = 0; i < size; i++) { int r = 2 * i; result[r] = tU[i]; result[r + 1] = tV[i]; } cacheTriggered = false; return result; } if (type == TexType.PLANAR) { for (int i = 0; i < size; i++) { int r = 2 * i; result[r] = tU[i]; result[r + 1] = tV[i]; } } else if (type == TexType.CYLINDRICAL) { // Sign check boolean hasNegative = false; boolean hasPositive = false; for (int i = 0; i < size; i++) { float u = tU[i]; if (u >= Math.PI / 2f) hasPositive = true; if (u < -Math.PI / 2f) hasNegative = true; } if (hasNegative && hasPositive) { for (int i = 0; i < size; i++) { float u = tU[i]; if (u < -Math.PI / 2f) { tU[i] = (float) (u + Math.PI * 2f); } } } for (int i = 0; i < size; i++) { int r = 2 * i; float u = tU[i]; u = (float) (u / Math.PI / 2.0); if (u < -.5f && a < 3.141f) u = -.5f; if (u > .5f && a < 3.141f) u = .5f; u = .5f - u; if (i > 0) { float delta = Math.abs(u - tU[i - 1]); if (delta > .5f) { u = 1f - u; } } tU[i] = u; result[r] = u; result[r + 1] = tV[i]; } } else { // Correct poles if (isTriangle) { int poleIndex = -1; for (int i = 0; i < size; i++) { float u = tU[i]; float v = tV[i]; if (u < 0.001f && (v < -1.56f || v > 1.56f )) { poleIndex = i; break; } } if (poleIndex != -1 && id != null) { Vector3f pole = tripoints[poleIndex]; Vector3f adjacent1 = tripoints[(poleIndex + 1) % 3]; Vector3f adjacent2 = tripoints[(poleIndex + 2) % 3]; Vector3f adjacentMidpoint = new Vector3f(); Vector3f.add(adjacent1, adjacent2, adjacentMidpoint); adjacentMidpoint.scale(0.5f); Vector3f deltaPoleMidpoint = new Vector3f(); Vector3f.sub(pole, adjacentMidpoint, deltaPoleMidpoint); deltaPoleMidpoint.scale(0.999f); Vector3f.add(adjacentMidpoint, deltaPoleMidpoint, pole); calcUVcoords(pole.x, pole.y, pole.z, id.parent, poleIndex, id); } } // Sign check boolean hasNegative = false; boolean hasPositive = false; for (int i = 0; i < size; i++) { float u = tU[i]; if (u >= Math.PI / 2f) hasPositive = true; if (u < -Math.PI / 2f) hasNegative = true; } if (hasNegative && hasPositive) { for (int i = 0; i < size; i++) { float u = tU[i]; if (u < -Math.PI / 2f) { tU[i] = (float) (u + Math.PI * 2f); } } } for (int i = 0; i < size; i++) { int r = 2 * i; float u = tU[i]; u = (float) (u / Math.PI / 2.0); if (u < -.5f && a < 3.141f) u = -.5f; if (u > .5f && a < 3.141f) u = .5f; u = u - .5f; if (i > 0) { float delta = Math.abs(u - tU[i - 1]); if (delta > .5f) { u = 1f - u; } } float v = tV[i]; v = (float) (v / Math.PI); if (v < -.5f) v = -.5f; if (v > .5f) v = .5f; v = .5f - v; if (i > 0) { float delta = Math.abs(v - tV[i - 1]); if (delta > .5f) { v = 1f - v; } } tU[i] = u; tV[i] = v; result[r] = u; result[r + 1] = v; } } if (id != null && !uvCache.containsKey(id)) { uvCache.put(id, new UV(tU, tV)); } return result; } public void dispose(OpenGLRenderer renderer) { if (openGlDisposed.containsKey(renderer)) { boolean disposed = openGlDisposed.get(renderer); int id = openGlId.get(renderer); int idGlossmap = openGlIdGlossmap.get(renderer); int idCubemap = openGlIdCubemap.get(renderer); int idCubemapMatte = openGlIdCubemapMatte.get(renderer); int isCubemapMetal = openGlIdCubemapMetal.get(renderer); if (!disposed) { uvCache.clear(); cacheUsage.clear(); if (id != -1) GL11.glDeleteTextures(id); if (idGlossmap != -1) GL11.glDeleteTextures(idGlossmap); if (renderer.containsOnlyCubeMaps() && renderer.getC3D().getRenderMode() != 5) { if (idCubemap != -1) GL11.glDeleteTextures(idCubemap); if (idCubemapMatte != -1) GL11.glDeleteTextures(idCubemapMatte); if (isCubemapMetal != -1) GL11.glDeleteTextures(isCubemapMetal); } openGlDisposed.put(renderer, true); openGlId.put(renderer, -1); openGlIdGlossmap.put(renderer, -1); openGlIdCubemap.put(renderer, -1); openGlIdCubemapMatte.put(renderer, -1); openGlIdCubemapMetal.put(renderer, -1); } } } void refreshCache() { if (!cacheUsage.isEmpty()) { Set<GData> isolatedIDs = new HashSet<>(uvCache.keySet()); isolatedIDs.removeAll(cacheUsage); for (GData ID : isolatedIDs) { uvCache.remove(ID); } cacheUsage.clear(); } } void bind(boolean drawSolidMaterials, boolean normalSwitch, boolean lightOn, OpenGLRenderer20 renderer, int useCubeMap) { int id = -1; int idGlossmap = -1; int idCubemap = -1; int idCubemapMatte = -1; int idCubemapMetal = -1; boolean disposed = true; if (openGlDisposed.containsKey(renderer)) { disposed = openGlDisposed.get(renderer); id = openGlId.get(renderer); idGlossmap = openGlIdGlossmap.get(renderer); idCubemap = openGlIdCubemap.get(renderer); idCubemapMatte = openGlIdCubemapMatte.get(renderer); idCubemapMetal = openGlIdCubemapMetal.get(renderer); } else { openGlDisposed.put(renderer, true); } if (disposed) { DatFile df = renderer.getC3D().getLockableDatFileReference(); id = loadPNGTexture(texture, GL13.GL_TEXTURE0, df); if (glossy) idGlossmap = loadPNGTexture(glossmap, GL13.GL_TEXTURE1, df); if (cubeMapIndex > 0) { switch (cubeMapIndex) { case 1: idCubemap = loadPNGTexture("cmap.png", GL13.GL_TEXTURE2, df ); //$NON-NLS-1$ break; case 2: idCubemapMatte = loadPNGTexture("matte_metal.png", GL13.GL_TEXTURE3, df); //$NON-NLS-1$ break; case 3: idCubemapMetal = loadPNGTexture("metal.png", GL13.GL_TEXTURE4, df); //$NON-NLS-1$ break; default: break; } } openGlDisposed.put(renderer, false); renderer.registerTexture(this); openGlId.put(renderer, id); openGlIdGlossmap.put(renderer, idGlossmap); openGlIdCubemap.put(renderer, idCubemap); openGlIdCubemapMatte.put(renderer, idCubemapMatte); openGlIdCubemapMetal.put(renderer, idCubemapMetal); } else if (id != -1) { accessTime = System.currentTimeMillis(); GL13.glActiveTexture(GL13.GL_TEXTURE0 + 0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, id); GL20.glUniform1f(renderer.getAlphaSwitchLoc(), drawSolidMaterials ? 1f : 0f); // Draw transparent GL20.glUniform1f(renderer.getNormalSwitchLoc(), normalSwitch ? 1f : 0f); // Draw transparent GL20.glUniform1i(renderer.getBaseImageLoc(), 0); // Texture unit 0 is for base images. GL20.glUniform1f(renderer.getNoTextureSwitch(), 0f); GL20.glUniform1f(renderer.getNoLightSwitch(), lightOn ? 0f : 1f); GL20.glUniform1f(renderer.getCubeMapSwitch(), useCubeMap); if (glossy) { GL13.glActiveTexture(GL13.GL_TEXTURE0 + 2); GL11.glBindTexture(GL11.GL_TEXTURE_2D, idGlossmap); GL20.glUniform1i(renderer.getGlossMapLoc(), 2); // Texture unit 2 is for gloss maps. GL20.glUniform1f(renderer.getNoGlossMapSwitch(), 0f); } else { GL20.glUniform1f(renderer.getNoGlossMapSwitch(), 1f); } if (cubeMapIndex > 0) { switch (cubeMapIndex) { case 1: GL13.glActiveTexture(GL13.GL_TEXTURE0 + 4); GL11.glBindTexture(GL11.GL_TEXTURE_2D, idCubemap); GL20.glUniform1i(renderer.getCubeMapLoc(), 4); // Texture unit 4 is for cube maps. break; case 2: GL13.glActiveTexture(GL13.GL_TEXTURE0 + 8); GL11.glBindTexture(GL11.GL_TEXTURE_2D, idCubemapMatte); GL20.glUniform1i(renderer.getCubeMapMatteLoc(), 8); // Texture unit 8 is for cube maps. break; case 3: GL13.glActiveTexture(GL13.GL_TEXTURE0 + 16); GL11.glBindTexture(GL11.GL_TEXTURE_2D, idCubemapMetal); GL20.glUniform1i(renderer.getCubeMapMetalLoc(), 16); // Texture unit 16 is for cube maps. break; default: break; } } } } void bindGL33(OpenGLRenderer renderer, GLShader shader) { int id = -1; int idGlossmap = -1; int idCubemap = -1; int idCubemapMatte = -1; int idCubemapMetal = -1; boolean disposed = true; if (openGlDisposed.containsKey(renderer)) { disposed = openGlDisposed.get(renderer); id = openGlId.get(renderer); idGlossmap = openGlIdGlossmap.get(renderer); idCubemap = openGlIdCubemap.get(renderer); idCubemapMatte = openGlIdCubemapMatte.get(renderer); idCubemapMetal = openGlIdCubemapMetal.get(renderer); } else { openGlDisposed.put(renderer, true); } if (disposed) { DatFile df = renderer.getC3D().getLockableDatFileReference(); id = loadPNGTexture(texture, GL13.GL_TEXTURE0, df); if (cubeMapIndex > 0) { switch (cubeMapIndex) { case 1: idCubemap = loadPNGTexture("cmap.png", GL13.GL_TEXTURE2, df ); //$NON-NLS-1$ break; case 2: idCubemapMatte = loadPNGTexture("matte_metal.png", GL13.GL_TEXTURE3, df); //$NON-NLS-1$ break; case 3: idCubemapMetal = loadPNGTexture("metal.png", GL13.GL_TEXTURE4, df); //$NON-NLS-1$ break; default: break; } } openGlDisposed.put(renderer, false); renderer.registerTexture(this); openGlId.put(renderer, id); openGlIdGlossmap.put(renderer, idGlossmap); openGlIdCubemap.put(renderer, idCubemap); openGlIdCubemapMatte.put(renderer, idCubemapMatte); openGlIdCubemapMetal.put(renderer, idCubemapMetal); } else if (id != -1) { accessTime = System.currentTimeMillis(); GL13.glActiveTexture(GL13.GL_TEXTURE0 + 0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, id); GL20.glUniform1i(shader.getUniformLocation("ldpePngSampler"), 0); // Texture unit 0 is for base images. //$NON-NLS-1$ if (cubeMapIndex > 0) { switch (cubeMapIndex) { case 1: GL13.glActiveTexture(GL13.GL_TEXTURE0 + 4); GL11.glBindTexture(GL11.GL_TEXTURE_2D, idCubemap); GL20.glUniform1i(shader.getUniformLocation("cubeMap"), 4); // Texture unit 4 is for cube maps. //$NON-NLS-1$ break; case 2: GL13.glActiveTexture(GL13.GL_TEXTURE0 + 8); GL11.glBindTexture(GL11.GL_TEXTURE_2D, idCubemapMatte); GL20.glUniform1i(shader.getUniformLocation("cubeMapMatte"), 8); // Texture unit 8 is for cube maps. //$NON-NLS-1$ break; case 3: GL13.glActiveTexture(GL13.GL_TEXTURE0 + 16); GL11.glBindTexture(GL11.GL_TEXTURE_2D, idCubemapMetal); GL20.glUniform1i(shader.getUniformLocation("cubeMapMetal"), 16); // Texture unit 16 is for cube maps. //$NON-NLS-1$ break; default: break; } } } } public boolean isTooOld() { return System.currentTimeMillis() - accessTime > 10000; } /** * * @param filename * @param textureUnit * e.g. GL13.GL_TEXTURE0 * @return */ private int loadPNGTexture(String filename, int textureUnit, DatFile datFile) { int max = GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE); ByteBuffer buf = null; int tWidth = 1; int tHeight = 1; if ("".equals(filename)) { //$NON-NLS-1$ buf = ByteBuffer.allocateDirect(4); final byte[] bytes = new byte[] { 0, 0, 0, -1 }; buf.put(bytes); buf.flip(); } else { // Check folders File fileToOpen; String oTex = WorkbenchManager.getUserSettingState().getLdrawFolderPath() + File.separator + filename; String oTexU = WorkbenchManager.getUserSettingState().getLdrawFolderPath() + File.separator + "TEXTURES" + File.separator + filename; //$NON-NLS-1$ String oTexL = WorkbenchManager.getUserSettingState().getLdrawFolderPath() + File.separator + "textures" + File.separator + filename; //$NON-NLS-1$ String uTex = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + filename; String uTexU = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "TEXTURES" + File.separator + filename; //$NON-NLS-1$ String uTexL = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "textures" + File.separator + filename; //$NON-NLS-1$ String pTex = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + filename; String pTexU = Project.getProjectPath() + File.separator + "TEXTURES" + File.separator + filename; //$NON-NLS-1$ String pTexL = Project.getProjectPath() + File.separator + "textures" + File.separator + filename; //$NON-NLS-1$ String fTex = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + filename; String fTexU = Project.getProjectPath() + File.separator + "TEXTURES" + File.separator + filename; //$NON-NLS-1$ String fTexL = Project.getProjectPath() + File.separator + "textures" + File.separator + filename; //$NON-NLS-1$ if (datFile != null && !datFile.isProjectFile() && !View.DUMMY_DATFILE.equals(datFile)) { File dff = new File(datFile.getOldName()).getParentFile(); if (dff != null && dff.exists() && dff.isDirectory()) { String ap = dff.getAbsolutePath(); fTex = ap + File.separator + filename; fTexU = ap + File.separator + "TEXTURES" + File.separator + filename; //$NON-NLS-1$ fTexL = ap + File.separator + "textures" + File.separator + filename; //$NON-NLS-1$ } } String tex = filename; File officialTexture = new File(oTex); File officialTextureU = new File(oTexU); File officialTextureL = new File(oTexL); File unofficialTexture = new File(uTex); File unofficialTextureU = new File(uTexU); File unofficialTextureL = new File(uTexL); File projectTexture = new File(pTex); File projectTextureU = new File(pTexU); File projectTextureL = new File(pTexL); File localTexture = new File(fTex); File localTextureU = new File(fTexU); File localTextureL = new File(fTexL); File textureFile = new File(tex); boolean fileExists = ( (fileToOpen = FileHelper.exist(localTexture)) != null || (fileToOpen = FileHelper.exist(localTextureU)) != null || (fileToOpen = FileHelper.exist(localTextureL)) != null || (fileToOpen = FileHelper.exist(projectTexture)) != null || (fileToOpen = FileHelper.exist(projectTextureU)) != null || (fileToOpen = FileHelper.exist(projectTextureL)) != null || (fileToOpen = FileHelper.exist(unofficialTexture)) != null || (fileToOpen = FileHelper.exist(unofficialTextureU)) != null || (fileToOpen = FileHelper.exist(unofficialTextureL)) != null || (fileToOpen = FileHelper.exist(officialTexture)) != null || (fileToOpen = FileHelper.exist(officialTextureU)) != null || (fileToOpen = FileHelper.exist(officialTextureL)) != null || (fileToOpen = FileHelper.exist(textureFile)) != null) && fileToOpen.isFile(); InputStream in = null; try { // Try to download the png file from the parts tracker if part review mode is enabled if (Editor3DWindow.getWindow().isReviewingAPart()) { try { final URL url = new URL("https://www.ldraw.org/library/unofficial/parts/textures/" + filename); //$NON-NLS-1$ in = url.openStream(); } catch (IOException ioe) { NLogger.debug(GTexture.class, ioe); } } if (in == null) { if (fileExists) { // Open the PNG file as an FileInputStream filename = fileToOpen.getAbsolutePath(); in = new FileInputStream(filename); } else { // Try to get PNG file from org.nschmidt.ldparteditor.opengl in = GLShader.class.getResourceAsStream(filename); if (in == null) { return -1; } } } // Link the PNG decoder to this stream PNGDecoder decoder = new PNGDecoder(in); // Get the width and height of the texture tWidth = decoder.getWidth(); tHeight = decoder.getHeight(); this.width = tWidth; this.height = tHeight; if (tWidth > max) throw new OutOfMemoryError(); if (tHeight > max) throw new OutOfMemoryError(); // Decode the PNG file in a ByteBuffer buf = ByteBuffer.allocateDirect(4 * tWidth * tHeight); decoder.decode(buf, tWidth * 4, Format.RGBA); buf.flip(); final List<Byte> bytes; { final byte[] tbytes = new byte[buf.remaining()]; buf.get(tbytes); bytes = new ArrayList<>(tbytes.length); for (final byte bt : tbytes) { bytes.add(bt); } } // TODO angle dependent adjustment (alpha fill) if (textureUnit != GL13.GL_TEXTURE2 && textureUnit != GL13.GL_TEXTURE3 && textureUnit != GL13.GL_TEXTURE4 && (type == TexType.CYLINDRICAL || type == TexType.SPHERICAL)) { int delta = (int) (tWidth * (Math.PI / a - 1f) / 2f); if (tWidth + delta > max || delta / a > max) throw new OutOfMemoryError(); List<Byte> stride = new ArrayList<>(tWidth); final int strideLength = tWidth * 4; for (int j = 0; j < delta; j++) { stride.add((byte) 0x00); stride.add((byte) 0x00); stride.add((byte) 0x00); stride.add((byte) 0x00); } final int strideLength2 = stride.size(); int index = 0; for (int i = 0; i < tHeight && index + 1 <= bytes.size(); i++) { bytes.addAll(index, stride); index += strideLength + strideLength2; if (index + 1 > bytes.size()) { if (index == bytes.size()) { bytes.addAll(stride); } else { break; } } else { bytes.addAll(index, stride); } index += strideLength2; } tWidth = tWidth + delta * 2; if (type == TexType.SPHERICAL) { int delta2 = (int) (tHeight * (Math.PI / (b * 2f) - 1f) / 2f); if (tHeight + delta2 > max || delta2 / b > max) throw new OutOfMemoryError(); stride.clear(); for (int j = 0; j < tWidth; j++) { stride.add((byte) 0x00); stride.add((byte) 0x00); stride.add((byte) 0x00); stride.add((byte) 0x00); } for (int i = 0; i < delta2; i++) { bytes.addAll(0, stride); bytes.addAll(stride); } tHeight = tHeight + delta2 * 2; } } int c = 0; final int as = bytes.size(); for (int i = 0; i < as; i++) { c++; byte bt = bytes.get(i); if (c < 4) { if (bt == (byte) 0xFF) bytes.set(i, (byte) 0xFE); if (bt == (byte) 0x01) bytes.set(i, (byte) 0x02); if (bt == (byte) 0x00) bytes.set(i, (byte) 0x02); } else { c = 0; } } { byte[] tmp = new byte[bytes.size()]; c = 0; for (final byte bt : bytes) { tmp[c] = bt; c++; } buf = ByteBuffer.allocateDirect(4 * tWidth * tHeight); buf.put(tmp); buf.flip(); } in.close(); } catch (OutOfMemoryError | BufferOverflowException e) { tWidth = 1; tHeight = 1; buf = ByteBuffer.allocateDirect(4); final byte[] bytes = new byte[] { 0, 0, 0, -1 }; buf.put(bytes); buf.flip(); try { in.close(); } catch (Exception ex) { } } catch (IOException e) { try { in.close(); } catch (Exception ex) { } return -1; } } // Create a new texture object in memory and bind it int texId = GL11.glGenTextures(); GL13.glActiveTexture(textureUnit); GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId); // All RGB bytes are aligned to each other and each component is 1 byte GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); // Upload the texture data GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, tWidth, tHeight, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf); // Setup the ST coordinate system GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); // Setup what to do when the texture has to be scaled GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); return texId; } public float getWidth() { return width; } public void setWidth(float width) { this.width = width; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public TexType getType() { return type; } public Vector4f getPoint1() { return new Vector4f(point1.x, point1.y, point1.z, 1f); } public Vector4f getPoint2() { return new Vector4f(point2.x, point2.y, point2.z, 1f); } public Vector4f getPoint3() { return new Vector4f(point3.x, point3.y, point3.z, 1f); } public int getCubeMapIndex() { return cubeMapIndex; } }
mit
east-sussex-county-council/Escc.Umbraco.Inception
Umbraco.Inception/Attributes/UmbracoDataTypeAttribute.cs
1463
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Inception.BL; namespace Umbraco.Inception.Attributes { [AttributeUsage(AttributeTargets.Class)] public class UmbracoDataTypeAttribute : Attribute { public string DataTypeName { get; set; } public string PropertyEditorAlias { get; set; } public Type PreValues { get; set; } public DataTypeDatabaseType DatabaseType { get; set; } /// <summary> /// Add on the class that represents your custom data type, so that the custom data type is inserted into the database. /// </summary> /// <param name="dataTypeName">Friendly name of the data type</param> /// <param name="propertyEditorAlias">Alias of the data type</param> /// <param name="preValues">The <c>System.Type</c> of a class which implements <see cref="IPreValueProvider" /></param> /// <param name="dataTypeDatabaseType">Type of the data type database.</param> public UmbracoDataTypeAttribute(string dataTypeName, string propertyEditorAlias, Type preValues, DataTypeDatabaseType dataTypeDatabaseType) { DataTypeName = dataTypeName; PropertyEditorAlias = propertyEditorAlias; PreValues = preValues; DatabaseType = dataTypeDatabaseType; } } }
mit
Useurmind/Eventualize
Eventualize.Projection/FluentProjection/EventHandlerContext.cs
559
using System; using System.Linq; using Eventualize.Projection.ProjectionMetaModel; namespace Eventualize.Projection.FluentProjection { public class EventHandlerContext { private Action<ProjectionEventHandler> onAddEventHandler; public EventHandlerContext(Action<ProjectionEventHandler> onAddEventHandler) { this.onAddEventHandler = onAddEventHandler; } public void AddEventHandler(ProjectionEventHandler eventHandler) { this.onAddEventHandler(eventHandler); } } }
mit
eddiebueno/phase-0
week-4/variables-methods.rb
1665
print "What's your first name? " first_name = gets.chomp first_name.capitalize! print "What's your last name? " last_name = gets.chomp last_name.capitalize! print "What's your middle name'? " middle_name = gets.chomp middle_name.capitalize! puts "Hello #{first_name} #{middle_name} #{last_name}! How are you? " print "What is your favorite number? " fav_number = gets.chomp print "Now let's make it BIGGER and BETTER! ANNNNND KABAM!!! #{fav_number +1}. Now this is a bigger and better number" # How do you define a local variable? # You assign an object to a local variable. You do this by naming your local variable and writing = to an object. # How do you define a method? # You define a method by saying def and the name of the method. You then assign the number of inputs. Then there is the body and then an output. You close it off with an end. # What is the difference between a local variable and a method? # A local variable only applies in the local workspace. A method can be used over and over again. # How do you run a ruby program from the command line? # You can run a ruby program by typing ruby and then the file name. # How do you run an RSpec file from the command line? # You can runan rspen file from the command line by typin rspec and then the rspec file name. # What was confusing about this material? What made sense? # The material was pretty straight forward. Everything made sense there was no part that was difficult to understand. Links to sections: 4.3.1: https://github.com/eddiebueno/phase-0/blob/master/week-4/address/my_solution.rb 4.3.2: https://github.com/eddiebueno/phase-0/blob/master/week-4/math/my_solution.rb
mit
stylelint/stylelint
lib/rules/value-list-comma-newline-after/__tests__/index.js
4884
'use strict'; const { messages, ruleName } = require('..'); testRule({ ruleName, config: ['always'], fix: true, accept: [ { code: 'a { background-size: 0,\n0; }', }, { code: 'a { background-size: 0,\n\n0; }', }, { code: 'a { background-size: 0 ,\n 0; }', }, { code: 'a { background-size: 0 ,\r\n 0; }', description: 'CRLF', }, { code: 'a { background-size: 0 ,\r\n\r\n 0; }', description: 'Double CRLF', }, { code: 'a::before { content: "foo,bar,baz"; }', description: 'string', }, { code: 'a { transform: translate(1,1); }', description: 'ignores function', }, { code: '$grid-breakpoints: (\n(xs),\n(sm, 768px)\n) !default;', description: 'ignores scss maps', }, { code: 'a { background-size: 0, //\n0; }', description: 'ignores single line comments', }, { code: 'a { background-size: 0, /**/\n0; }', description: 'ignores multi line comments', }, ], reject: [ { code: 'a { background-size: 0, 0; }', fixed: 'a { background-size: 0,\n 0; }', message: messages.expectedAfter(), line: 1, column: 23, }, { code: 'a { background-size: 0, 0; }', fixed: 'a { background-size: 0,\n 0; }', message: messages.expectedAfter(), line: 1, column: 23, }, { code: 'a { background-size: 0,\t0; }', fixed: 'a { background-size: 0,\n\t0; }', message: messages.expectedAfter(), line: 1, column: 23, }, { code: 'a { background-size: 0, /**/0; }', fixed: 'a { background-size: 0, /**/\n0; }', message: messages.expectedAfter(), description: 'ignores multi line comments', line: 1, column: 28, }, ], }); testRule({ ruleName, config: ['always-multi-line'], fix: true, accept: [ { code: 'a { background-size: 0,\n0,\n0; }', }, { code: 'a { background-size: 0, //\n0, /**/\n0; }', description: 'with comments', }, { code: 'a { background-size: 0 ,\n 0,\n0; }', }, { code: 'a { background-size: 0 ,\r\n 0,\r\n0; }', description: 'CRLF', }, { code: 'a { background-size: 0, 0; }', description: 'ignores single-line', }, { code: 'a { background-size: 0, 0;\n}', description: 'ignores single-line list, multi-line block', }, { code: 'a { background-size: 0, 0;\r\n}', description: 'ignores single-line list, multi-line block with CRLF', }, { code: 'a { background-size: 0, /**/ 0; }', description: 'ignores single-line list, multi-line block with comment', }, ], reject: [ { code: 'a { background-size: 0,\n0, 0; }', fixed: 'a { background-size: 0,\n0,\n 0; }', message: messages.expectedAfterMultiLine(), line: 2, column: 2, }, { code: 'a { background-size: 0, //\n0, /**/0; }', fixed: 'a { background-size: 0, //\n0, /**/\n0; }', description: 'with comments', message: messages.expectedAfterMultiLine(), line: 2, column: 7, }, { code: 'a { background-size: 0,\n0, 0; }', fixed: 'a { background-size: 0,\n0,\n 0; }', message: messages.expectedAfterMultiLine(), line: 2, column: 2, }, { code: 'a { background-size: 0,\n0,\t0; }', fixed: 'a { background-size: 0,\n0,\n\t0; }', message: messages.expectedAfterMultiLine(), line: 2, column: 2, }, { code: 'a { background-size: 0,\r\n0,\t0; }', fixed: 'a { background-size: 0,\r\n0,\r\n\t0; }', description: 'CRLF', message: messages.expectedAfterMultiLine(), line: 2, column: 2, }, ], }); testRule({ ruleName, config: ['never-multi-line'], fix: true, accept: [ { code: 'a { background-size: 0\n,0\n,0; }', }, { code: 'a { background-size: 0 //\n,0 /**/\n,0; }', description: 'with comments', }, { code: 'a { background-size: 0\r\n,0\r\n,0; }', description: 'CRLF', }, { code: 'a { background-size: 0, 0; }', description: 'ignores single-line', }, { code: 'a { background-size: 0, 0;\n}', description: 'ignores single-line list, multi-line block', }, { code: 'a { background-size: 0, 0;\r\n}', description: 'ignores single-line list, multi-line block with CRLF', }, ], reject: [ { code: 'a { background-size: 0\n,0\n, 0; }', fixed: 'a { background-size: 0\n,0\n,0; }', message: messages.rejectedAfterMultiLine(), line: 3, column: 1, }, { code: 'a { background-size: 0\n,0\n, 0; }', fixed: 'a { background-size: 0\n,0\n,0; }', message: messages.rejectedAfterMultiLine(), line: 3, column: 1, }, { code: 'a { background-size: 0\r\n,0\r\n, 0; }', fixed: 'a { background-size: 0\r\n,0\r\n,0; }', description: 'CRLF', message: messages.rejectedAfterMultiLine(), line: 3, column: 1, }, { code: 'a { background-size: 0\n,0\n,\t0; }', fixed: 'a { background-size: 0\n,0\n,0; }', message: messages.rejectedAfterMultiLine(), line: 3, column: 1, }, ], });
mit
shime/smoke-and-mirrors
addon/mixins/magic-array.js
2828
import Ember from "ember"; import SmartObjectProxy from "../utils/smart-object-proxy"; const { computed, ArrayProxy } = Ember; function computeProxiedArray() { var proxied = this.get('content'); var key = this.get('keyForId'); var content = this.get('__proxyContent'); var newLength; var newObjects = Ember.A(); var diff; // play nice with arrays that are already proxied if (proxied.get && proxied.get('content')) { proxied = proxied.get('content'); } this.beginPropertyChanges(); // create a new array object if we don't have one yet if (proxied) { // handle additions to the beginning of the array if (this._changeIsPrepend(proxied, content, key)) { newLength = Ember.get(proxied, 'length'); diff = newLength - content.get('length'); for (var i = 0; i < diff; i++) { newObjects.push(SmartObjectProxy.create({content: proxied[i], __indexPath: key})); } if (newObjects.length) { content.replace(0, 0, newObjects); } // handle additions and inline changes } else { proxied.forEach(function(item, index) { var proxiedObject = content.objectAt(index); if (proxiedObject) { proxiedObject.__update(item); } else { newObjects.push(SmartObjectProxy.create({content: item, __indexPath: key})); } }); if (newObjects.length) { content.pushObjects(newObjects); } } } newLength = proxied ? Ember.get(proxied, 'length') : 0; if (newLength < content.get('length')) { diff = content.get('length') - newLength; content.removeAt(newLength, diff); } this.endPropertyChanges(); return content; } var Mixin = Ember.Mixin.create({ keyForId: null, content: null, _proxyContentTo: '__content', __proxyContent: null, _changeIsPrepend: function(newArray, proxiedArray, key) { var lengthDifference = proxiedArray.get('length') - Ember.get(newArray, 'length'); // if either array is empty or the new array is not longer, do not treat as prepend if (!proxiedArray.get('length') || !Ember.get(newArray, 'length') || lengthDifference >= 0) { return false; } // if the object at the right key is the same, this is a prepend var oldInitialItem = proxiedArray.objectAt(0).get('__key'); var newInitialItem = Ember.get(newArray[-lengthDifference], key); return oldInitialItem === newInitialItem; }, _initializeMagicArray: function() { var dest = this.get('_proxyContentTo'); this.set('__proxyContent', ArrayProxy.create({ content: Ember.A() })); this.set(dest, computed('content', 'content.@each', computeProxiedArray)); }, init: function() { this._initializeMagicArray(); this._super.apply(this, arguments); } }); export default Mixin;
mit
quwahara/Nana
NanaLib/Infr/Tuple.cs
1980
/* * Copyright (C) 2011 Mitsuaki Kuwahara * Released under the MIT License. */ using System; using System.Collections.Generic; using System.Text; namespace Nana.Infr { public class Tuple2<T1, T2> { public T1 F1; public T2 F2; public Tuple2() { } public Tuple2(T1 f1, T2 f2) { F1 = f1; F2 = f2; } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { if (null == obj) { return false; } if (obj.GetType() != typeof(Tuple2<T1, T2>)) { return false; } Tuple2<T1, T2> t = (Tuple2<T1, T2>)obj; if (null != F1) /**/ { if (false == F1.Equals(t.F1)) { return false; } } else /**/ { if (null != t.F1) { return false; } } if (null != F2) /**/ { if (false == F2.Equals(t.F2)) { return false; } } else /**/ { if (null != t.F2) { return false; } } return true; } public static bool operator ==(Tuple2<T1, T2> a, Tuple2<T1, T2> b) { if (null == (object)a && null == (object)b) { return true; } if (null == (object)a) { return false; } return a.Equals(b); } public static bool operator !=(Tuple2<T1, T2> a, Tuple2<T1, T2> b) { if (null == (object)a && null == (object)b) { return false; } if (null == (object)a) { return true; } return false == a.Equals(b); } } public class Tuple3<T1, T2, T3> { public Tuple3() { } public Tuple3(T1 f1, T2 f2, T3 f3) { F1 = f1; F2 = f2; F3 = f3; } public T1 F1; public T2 F2; public T3 F3; } public class Tuple4<T1, T2, T3, T4> { public Tuple4() { } public Tuple4(T1 f1, T2 f2, T3 f3, T4 f4) { F1 = f1; F2 = f2; F3 = f3; F4 = f4; } public T1 F1; public T2 F2; public T3 F3; public T4 F4; } }
mit
thaihungle/deepexp
gan/vae.py
11214
import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights""" # https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow low = -constant*np.sqrt(6.0/(fan_in + fan_out)) high = constant*np.sqrt(6.0/(fan_in + fan_out)) return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high, dtype=tf.float32) class VariationalAutoencoder(object): """ Variation Autoencoder (VAE) with an sklearn-like interface implemented using TensorFlow. This implementation uses probabilistic encoders and decoders using Gaussian distributions and realized by multi-layer perceptrons. The VAE can be learned end-to-end. See "Auto-Encoding Variational Bayes" by Kingma and Welling for more details. """ def __init__(self, network_architecture, transfer_fct=tf.nn.softplus, learning_rate=0.001, batch_size=100): self.network_architecture = network_architecture self.transfer_fct = transfer_fct self.learning_rate = learning_rate self.batch_size = batch_size # tf Graph input self.x = tf.placeholder(tf.float32, [None, network_architecture["n_input"]]) # Create autoencoder network self._create_network() # Define loss function based variational upper-bound and # corresponding optimizer self._create_loss_optimizer() # Initializing the tensor flow variables init = tf.global_variables_initializer() # Launch the session self.sess = tf.InteractiveSession() self.sess.run(init) def _create_network(self): # Initialize autoencode network weights and biases network_weights = self._initialize_weights(**self.network_architecture) # Use recognition network to determine mean and # (log) variance of Gaussian distribution in latent # space self.z_mean, self.z_log_sigma_sq = \ self._recognition_network(network_weights["weights_recog"], network_weights["biases_recog"]) # Draw one sample z from Gaussian distribution n_z = self.network_architecture["n_z"] eps = tf.random_normal((self.batch_size, n_z), 0, 1, dtype=tf.float32) # z = mu + sigma*epsilon self.z = tf.add(self.z_mean, tf.mul(tf.sqrt(tf.exp(self.z_log_sigma_sq)), eps)) # Use generator to determine mean of # Bernoulli distribution of reconstructed input self.x_reconstr_mean = \ self._generator_network(network_weights["weights_gener"], network_weights["biases_gener"]) @staticmethod def _initialize_weights(n_hidden_recog_1, n_hidden_recog_2, n_hidden_gener_1, n_hidden_gener_2, n_input, n_z): all_weights = dict() all_weights['weights_recog'] = { 'h1': tf.Variable(xavier_init(n_input, n_hidden_recog_1)), 'h2': tf.Variable(xavier_init(n_hidden_recog_1, n_hidden_recog_2)), 'out_mean': tf.Variable(xavier_init(n_hidden_recog_2, n_z)), 'out_log_sigma': tf.Variable(xavier_init(n_hidden_recog_2, n_z))} all_weights['biases_recog'] = { 'b1': tf.Variable(tf.zeros([n_hidden_recog_1], dtype=tf.float32)), 'b2': tf.Variable(tf.zeros([n_hidden_recog_2], dtype=tf.float32)), 'out_mean': tf.Variable(tf.zeros([n_z], dtype=tf.float32)), 'out_log_sigma': tf.Variable(tf.zeros([n_z], dtype=tf.float32))} all_weights['weights_gener'] = { 'h1': tf.Variable(xavier_init(n_z, n_hidden_gener_1)), 'h2': tf.Variable(xavier_init(n_hidden_gener_1, n_hidden_gener_2)), 'out_mean': tf.Variable(xavier_init(n_hidden_gener_2, n_input)), 'out_log_sigma': tf.Variable(xavier_init(n_hidden_gener_2, n_input))} all_weights['biases_gener'] = { 'b1': tf.Variable(tf.zeros([n_hidden_gener_1], dtype=tf.float32)), 'b2': tf.Variable(tf.zeros([n_hidden_gener_2], dtype=tf.float32)), 'out_mean': tf.Variable(tf.zeros([n_input], dtype=tf.float32)), 'out_log_sigma': tf.Variable(tf.zeros([n_input], dtype=tf.float32))} return all_weights def _recognition_network(self, weights, biases): # Generate probabilistic encoder (recognition network), which # maps inputs onto a normal distribution in latent space. # The transformation is parametrized and can be learned. layer_1 = self.transfer_fct(tf.add(tf.matmul(self.x, weights['h1']), biases['b1'])) layer_2 = self.transfer_fct(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])) z_mean = tf.add(tf.matmul(layer_2, weights['out_mean']), biases['out_mean']) z_log_sigma_sq = \ tf.add(tf.matmul(layer_2, weights['out_log_sigma']), biases['out_log_sigma']) return z_mean, z_log_sigma_sq def _generator_network(self, weights, biases): # Generate probabilistic decoder (decoder network), which # maps points in latent space onto a Bernoulli distribution in data space. # The transformation is parametrized and can be learned. layer_1 = self.transfer_fct(tf.add(tf.matmul(self.z, weights['h1']), biases['b1'])) layer_2 = self.transfer_fct(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])) x_reconstr_mean = \ tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weights['out_mean']), biases['out_mean'])) return x_reconstr_mean def _create_loss_optimizer(self): # The loss is composed of two terms: # 1.) The reconstruction loss (the negative log probability # of the input under the reconstructed Bernoulli distribution # induced by the decoder in the data space). # This can be interpreted as the number of "nats" required # for reconstructing the input when the activation in latent # is given. # Adding 1e-10 to avoid evaluation of log(0.0) reconstr_loss = \ -tf.reduce_sum(self.x * tf.log(1e-10 + self.x_reconstr_mean) + (1 - self.x) * tf.log(1e-10 + 1 - self.x_reconstr_mean), 1) # 2.) The latent loss, which is defined as the Kullback Leibler divergence ## between the distribution in latent space induced by the encoder on # the data and some prior. This acts as a kind of regularizer. # This can be interpreted as the number of "nats" required # for transmitting the the latent space distribution given # the prior. latent_loss = -0.5 * tf.reduce_sum(1 + self.z_log_sigma_sq - tf.square(self.z_mean) - tf.exp(self.z_log_sigma_sq), 1) self.cost = tf.reduce_mean(reconstr_loss + latent_loss) # average over batch # Use ADAM optimizer self.optimizer = \ tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.cost) def partial_fit(self, X): """Train model based on mini-batch of input data. Return cost of mini-batch. """ opt, cost = self.sess.run((self.optimizer, self.cost), feed_dict={self.x: X}) return cost def transform(self, X): """Transform data by mapping it into the latent space.""" # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.z_mean, feed_dict={self.x: X}) def generate(self, z_mu=None): """ Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space. """ if z_mu is None: z_mu = np.random.normal(size=self.network_architecture["n_z"]) # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.x_reconstr_mean, feed_dict={self.z: z_mu}) def reconstruct(self, X): """ Use VAE to reconstruct given data. """ return self.sess.run(self.x_reconstr_mean, feed_dict={self.x: X}) def train_mnist(network_architecture, mnist, learning_rate=0.001, batch_size=100, training_epochs=10, display_step=5): vae = VariationalAutoencoder(network_architecture, learning_rate=learning_rate, batch_size=batch_size) n_samples = mnist.train.num_examples # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(n_samples / batch_size) # Loop over all batches for i in range(total_batch): batch_xs, _ = mnist.train.next_batch(batch_size) # Fit training using batch data cost = vae.partial_fit(batch_xs) # Compute average loss avg_cost += cost / n_samples * batch_size # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) return vae def run_mnist(): np.random.seed(0) tf.set_random_seed(0) mnist = input_data.read_data_sets('mnist', one_hot=True) n_samples = mnist.train.num_examples print(n_samples) network_architecture = \ dict(n_hidden_recog_1=500, # 1st layer encoder neurons n_hidden_recog_2=500, # 2nd layer encoder neurons n_hidden_gener_1=500, # 1st layer decoder neurons n_hidden_gener_2=500, # 2nd layer decoder neurons n_input=784, # MNIST data input (img shape: 28*28) n_z=20) # dimensionality of latent space vae = train_mnist(network_architecture, mnist, training_epochs=75) x_sample = mnist.test.next_batch(100)[0] x_reconstruct = vae.reconstruct(x_sample) plt.figure(figsize=(8, 12)) for i in range(5): plt.subplot(5, 2, 2 * i + 1) plt.imshow(x_sample[i].reshape(28, 28), vmin=0, vmax=1, cmap="gray") plt.title("Test input") plt.colorbar() plt.subplot(5, 2, 2 * i + 2) plt.imshow(x_reconstruct[i].reshape(28, 28), vmin=0, vmax=1, cmap="gray") plt.title("Reconstruction") plt.colorbar() plt.tight_layout() if __name__ == '__main__': run_mnist()
mit
aldeed/autoform-demo
client/views/insertaf/insertaf.js
75
Template.insertaf.helpers({ people() { return People.find(); } });
mit
mrizkir/portalekampus
protected/logic/Logic_ReportNilai.php
137049
<?php prado::using ('Application.logic.Logic_Report'); class Logic_ReportNilai extends Logic_Report { public function __construct ($db) { parent::__construct ($db); } /** * digunakan untuk memprint KHS * @param type $objNilai object */ public function printKHS ($objNilai,$withsignature=false) { $nim=$this->dataReport['nim']; $ta=$this->dataReport['ta']; $semester=$this->dataReport['semester']; $nama_tahun=$this->dataReport['nama_tahun']; $nama_semester=$this->dataReport['nama_semester']; switch ($this->getDriver()) { case 'excel2003': case 'excel2007': // $this->printOut("khs_$nim"); break; case 'pdf' : $rpt=$this->rpt; $rpt->setTitle('KHS Mahasiswa'); $rpt->setSubject('KHS Mahasiswa'); $rpt->AddPage(); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'KARTU HASIL STUDI (KHS)',0,0,'C'); $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Nama Mahasiswa (L/P)'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_mhs'].' ('.$this->dataReport['jk'].')'); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'P.S / Jenjang'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_ps'].' / S-1'); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Penasihat Akademik'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_dosen']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'NIM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,": $nim"); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Semester/TA'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,": $nama_semester / $ta"); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'NIRM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nirm']); $row+=20; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(13, 5, 'NO', 1, 0, 'C'); $rpt->Cell(15, 5, 'KODE', 1, 0, 'C'); $rpt->Cell(80, 5, 'MATAKULIAH', 1, 0, 'C'); $rpt->Cell(10, 5, 'HM', 1, 0, 'C'); $rpt->Cell(10, 5, 'SKS', 1, 0, 'C'); $rpt->Cell(10, 5, 'NM', 1, 0, 'C'); $rpt->Cell(47, 5, 'KETERANGAN', 1, 0, 'C'); $objNilai->setDataMHS(array('nim'=>$nim)); $dn=$objNilai->getKHS($ta,$semester); $totalSks=0; $totalNm=0; $row+=5; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',8); while (list($k,$v)=each($dn)) { $rpt->setXY(3,$row); $rpt->Cell(13, 5, $v['no'], 1, 0, 'C'); $rpt->Cell(15, 5, $v['kmatkul'], 1, 0, 'C'); $rpt->Cell(80, 5, $v['nmatkul'], 1, 0, 'L'); $n_kual=$v['n_kual']==''?'-':$v['n_kual']; $sks=$v['sks']; $m=$v['m']; $rpt->Cell(10, 5, $n_kual, 1, 0, 'C'); $rpt->Cell(10, 5, $sks, 1, 0, 'C'); $rpt->Cell(10, 5, $m, 1, 0, 'C'); $rpt->Cell(47, 5, '', 1, 0, 'C'); $totalSks+=$sks; $totalNm+=$m; $row+=5; } $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Kredit',0); $rpt->Cell(10, 5, $totalSks, 1, 0, 'C'); $rpt->Cell(10, 5, $totalNm, 1, 0, 'C'); $ip=@ bcdiv($totalNm,$totalSks,2); $rpt->Cell(47, 5, "IPS : $ip", 1, 0, 'C'); $row+=5; $nilaisemesterlalu=$objNilai->getKumulatifSksDanNmSemesterLalu($ta,$semester); $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Kumulatif Semester Lalu (JKSL)'); $rpt->Cell(10, 5, $nilaisemesterlalu['total_sks'], 1, 0, 'C'); $rpt->Cell(10, 5, $nilaisemesterlalu['total_nm'], 1, 0, 'C'); $rpt->Cell(47, 5, '', 1, 0, 'C'); $nilaisemestersekarang=$objNilai->getIPKSampaiTASemester($ta,$semester,'ipksksnm'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Kumulatif Semester Ini (JKSI)'); $rpt->Cell(10, 5, $nilaisemestersekarang['sks'], 1, 0, 'C'); $rpt->Cell(10, 5, $nilaisemestersekarang['nm'], 1, 0, 'C'); $ipk=$nilaisemestersekarang['ipk']; $rpt->Cell(47, 5, "IPK : $ipk", 1, 0, 'C'); $row+=5; $nextsemeserandta=$objNilai->getNextSemesterAndTa ($ta,$semester); $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Maksimum Kredit yang dapat diambil'); $rpt->Cell(67, 8, $this->setup->getSksNextSemester($ip), 1, 0, 'C'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Pada semester '.$nextsemeserandta['semester'].' Tahun Akademik '.$nextsemeserandta['ta']); if ($withsignature) { $row+=5; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(31,$row); $rpt->Cell(60, 5, 'Mengetahui',0,0,'C'); $tanggal=$this->tgl->tanggal('l, j F Y'); $rpt->Cell(80, 5, $this->setup->getSettingValue('kota_pt').", $tanggal",0,0,'C'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(60, 5, 'A.n. Ketua '.$this->dataReport['nama_pt_alias'],0,0,'C'); $rpt->Cell(80, 5, "Ketua Program Studi",0,0,'C'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(60, 5, $this->dataReport['nama_jabatan_khs'],0,0,'C'); $nama_ps=$this->dataReport['nama_ps']; $rpt->Cell(80, 5, $nama_ps,0,0,'C'); $row+=20; $rpt->setXY(31,$row); $rpt->Cell(60, 5,$this->dataReport['nama_penandatangan_khs'],0,0,'C'); $rpt->Cell(80, 5,$this->dataReport['nama_kaprodi'],0,0,'C'); $row+=5; $rpt->setXY(31,$row); $nama_jabatan=strtoupper($this->dataReport['jabfung_penandatangan_khs']); $nidn=$this->dataReport['nidn_penandatangan_khs']; $rpt->Cell(60, 5, "$nama_jabatan NIDN : $nidn",0,0,'C'); $rpt->Cell(80, 5, strtoupper($this->dataReport['jabfung_kaprodi']). ' NIDN : '.$this->dataReport['nidn_kaprodi'],0,0,'C'); } $this->printOut("khs_$nim"); break; } $this->setLink($this->dataReport['linkoutput'],"Kartu Hasil Studi T.A $nama_tahun Semester $nama_semester"); } /** * digunakan untuk memprint seluruh KHS dalam Semester dan T.A * @param type $objNilai object */ public function printKHSAll ($objNilai,$objDMaster,$repeater,$withsignature=false) { $awal=$this->dataReport['awal']; $akhir=$this->dataReport['akhir']; $ta=$this->dataReport['ta']; $semester=$this->dataReport['semester']; $nama_tahun=$this->dataReport['nama_tahun']; $nama_semester=$this->dataReport['nama_semester']; switch ($this->getDriver()) { case 'excel2003': case 'excel2007': // $this->printOut("khs_$nim"); break; case 'pdf' : $rpt=$this->rpt; $rpt->setTitle('KHS Mahasiswa'); $rpt->setSubject('KHS Mahasiswa'); foreach ($repeater->Items as $inputan) { if ($inputan->btnPrintOutR->Enabled) { $item=$inputan->btnPrintOutR->getNamingContainer(); $idkrs=$repeater->DataKeys[$item->getItemIndex()]; $str = "SELECT vdm.nim,vdm.nirm,vdm.nama_mhs,vdm.jk,vdm.kjur,vdm.nama_ps,vdm.idkonsentrasi,k.nama_konsentrasi,iddosen_wali FROM krs LEFT JOIN v_datamhs vdm ON (krs.nim=vdm.nim) LEFT JOIN konsentrasi k ON (vdm.idkonsentrasi=k.idkonsentrasi) WHERE krs.idkrs=$idkrs"; $this->db->setFieldTable(array('nim','nirm','nama_mhs','jk','kjur','nama_ps','idkonsentrasi','nama_konsentrasi','iddosen_wali')); $r=$this->db->getRecord($str); $dataMhs=$r[1]; $nim=$dataMhs['nim']; $rpt->AddPage(); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'KARTU HASIL STUDI (KHS)',0,0,'C'); $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Nama Mahasiswa (L/P)'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$dataMhs['nama_mhs'].' ('.$dataMhs['jk'].')'); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'P.S / Jenjang'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$dataMhs['nama_ps'].' / S-1'); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Penasihat Akademik'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $nama_dosen=$objDMaster->getNamaDosenWaliByID ($dataMhs['iddosen_wali']); $rpt->Cell(0,$row,": $nama_dosen"); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'NIM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,": $nim"); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Semester/TA'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,": $nama_semester / $ta"); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'NIRM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$dataMhs['nirm']); $row+=20; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(13, 5, 'NO', 1, 0, 'C'); $rpt->Cell(15, 5, 'KODE', 1, 0, 'C'); $rpt->Cell(80, 5, 'MATAKULIAH', 1, 0, 'C'); $rpt->Cell(10, 5, 'HM', 1, 0, 'C'); $rpt->Cell(10, 5, 'SKS', 1, 0, 'C'); $rpt->Cell(10, 5, 'NM', 1, 0, 'C'); $rpt->Cell(47, 5, 'KETERANGAN', 1, 0, 'C'); $objNilai->setDataMHS(array('nim'=>$nim)); $dn=$objNilai->getKHS($ta,$semester); $totalSks=0; $totalNm=0; $row+=5; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',8); while (list($k,$v)=each($dn)) { $rpt->setXY(3,$row); $rpt->Cell(13, 5, $v['no'], 1, 0, 'C'); $rpt->Cell(15, 5, $v['kmatkul'], 1, 0, 'C'); $rpt->Cell(80, 5, $v['nmatkul'], 1, 0, 'L'); $n_kual=$v['n_kual']==''?'-':$v['n_kual']; $sks=$v['sks']; $m=$v['m']; $rpt->Cell(10, 5, $n_kual, 1, 0, 'C'); $rpt->Cell(10, 5, $sks, 1, 0, 'C'); $rpt->Cell(10, 5, $m, 1, 0, 'C'); $rpt->Cell(47, 5, '', 1, 0, 'C'); $totalSks+=$sks; $totalNm+=$m; $row+=5; } $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Kredit',0); $rpt->Cell(10, 5, $totalSks, 1, 0, 'C'); $rpt->Cell(10, 5, $totalNm, 1, 0, 'C'); $ip=@ bcdiv($totalNm,$totalSks,2); $rpt->Cell(47, 5, "IPS : $ip", 1, 0, 'C'); $row+=5; $nilaisemesterlalu=$objNilai->getKumulatifSksDanNmSemesterLalu($ta,$semester); $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Kumulatif Semester Lalu (JKSL)'); $rpt->Cell(10, 5, $nilaisemesterlalu['total_sks'], 1, 0, 'C'); $rpt->Cell(10, 5, $nilaisemesterlalu['total_nm'], 1, 0, 'C'); $rpt->Cell(47, 5, '', 1, 0, 'C'); $nilaisemestersekarang=$objNilai->getIPKSampaiTASemester($ta,$semester,'ipksksnm'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Kumulatif Semester Ini (JKSI)'); $rpt->Cell(10, 5, $nilaisemestersekarang['sks'], 1, 0, 'C'); $rpt->Cell(10, 5, $nilaisemestersekarang['nm'], 1, 0, 'C'); $ipk=$nilaisemestersekarang['ipk']; $rpt->Cell(47, 5, "IPK : $ipk", 1, 0, 'C'); $row+=5; $nextsemeserandta=$objNilai->getNextSemesterAndTa ($ta,$semester); $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Jumlah Maksimum Kredit yang dapat diambil'); $rpt->Cell(67, 8, $this->setup->getSksNextSemester($ip), 1, 0, 'C'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(90, 5, 'Pada semester '.$nextsemeserandta['semester'].' Tahun Akademik '.$nextsemeserandta['ta']); if ($withsignature) { $row+=5; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(31,$row); $rpt->Cell(60, 5, 'Mengetahui',0,0,'C'); $tanggal=$this->tgl->tanggal('l, j F Y'); $rpt->Cell(80, 5, $this->setup->getSettingValue('kota_pt').", $tanggal",0,0,'C'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(60, 5, 'A.n. Ketua '.$this->dataReport['nama_pt_alias'],0,0,'C'); $rpt->Cell(80, 5, "Ketua Program Studi",0,0,'C'); $row+=5; $rpt->setXY(31,$row); $rpt->Cell(60, 5, $this->dataReport['nama_jabatan_khs'],0,0,'C'); $nama_ps=$this->dataReport['nama_ps']; $rpt->Cell(80, 5, $nama_ps,0,0,'C'); $row+=20; $rpt->setXY(31,$row); $rpt->Cell(60, 5,$this->dataReport['nama_penandatangan_khs'],0,0,'C'); $rpt->Cell(80, 5,$this->dataReport['nama_kaprodi'],0,0,'C'); $row+=5; $rpt->setXY(31,$row); $nama_jabatan=strtoupper($this->dataReport['jabfung_penandatangan_khs']); $nidn=$this->dataReport['nidn_penandatangan_khs']; $rpt->Cell(60, 5, "$nama_jabatan NIDN : $nidn",0,0,'C'); $rpt->Cell(80, 5, strtoupper($this->dataReport['jabfung_kaprodi']). ' NIDN : '.$this->dataReport['nidn_kaprodi'],0,0,'C'); } } } $this->printOut('seluruh_khs_dari_'.$awal.'_'.$akhir); break; } $this->setLink($this->dataReport['linkoutput'],"Kartu Hasil Studi T.A $nama_tahun Semester $nama_semester"); } /** * digunakan untuk memprint KHS * @param type $objNilai object * @param type $objDMaster object */ public function printSummaryKHS ($objNilai,$objDMaster,$withsignature=false) { $ta=$this->dataReport['ta']; $tahun_masuk=$this->dataReport['tahun_masuk']; $semester=$this->dataReport['semester']; $kjur=$this->dataReport['kjur']; $nama_tahun=$this->dataReport['nama_tahun']; $nama_semester=$this->dataReport['nama_semester']; $nama_ps = $this->dataReport['nama_ps']; switch ($this->getDriver()) { case 'excel2003': case 'excel2007': $this->setHeaderPT('L'); $sheet=$this->rpt->getActiveSheet(); $this->rpt->getDefaultStyle()->getFont()->setName('Arial'); $this->rpt->getDefaultStyle()->getFont()->setSize('9'); $sheet->mergeCells("A7:L7"); $sheet->getRowDimension(7)->setRowHeight(20); $sheet->setCellValue("A7","SUMMARY KHS T.A $nama_tahun SEMESTER $nama_semester"); $sheet->mergeCells("A8:L8"); $sheet->setCellValue("A8","PROGRAM STUDI $nama_ps"); $sheet->getRowDimension(8)->setRowHeight(20); $styleArray=array( 'font' => array('bold' => true, 'size' => 16), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER) ); $sheet->getStyle("A7:L8")->applyFromArray($styleArray); $sheet->getRowDimension(10)->setRowHeight(25); $sheet->getColumnDimension('B')->setWidth(15); $sheet->getColumnDimension('C')->setWidth(18); $sheet->getColumnDimension('D')->setWidth(35); $sheet->getColumnDimension('E')->setWidth(10); $sheet->getColumnDimension('I')->setWidth(10); $sheet->getColumnDimension('G')->setWidth(10); $sheet->getColumnDimension('H')->setWidth(10); $sheet->getColumnDimension('I')->setWidth(15); $sheet->getColumnDimension('J')->setWidth(15); $sheet->getColumnDimension('K')->setWidth(14); $sheet->getColumnDimension('L')->setWidth(18); $sheet->setCellValue('A10','NO'); $sheet->setCellValue('B10','NIM'); $sheet->setCellValue('C10','NIRM'); $sheet->setCellValue('D10','NAMA'); $sheet->setCellValue('E10','JK'); $sheet->setCellValue('F10','ANGK.'); $sheet->setCellValue('G10','IPS'); $sheet->setCellValue('H10','IPK'); $sheet->setCellValue('I10','SKS SEMESTER'); $sheet->setCellValue('J10','SKS TOTAL'); $sheet->setCellValue('K10','SKS KONVERSI DI AKUI'); $sheet->setCellValue('L10','KELAS'); $styleArray=array( 'font' => array('bold' => true), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A10:L10")->applyFromArray($styleArray); $sheet->getStyle("A10:L10")->getAlignment()->setWrapText(true); $str_tahun_masuk=$tahun_masuk == 'none' ?'':"AND vdm.tahun_masuk=$tahun_masuk"; $str = "SELECT k.idkrs,k.tgl_krs,k.nim,nirm,vdm.nama_mhs,vdm.jk,vdm.kjur,vdm.idkelas,vdm.tahun_masuk,vdm.semester_masuk,dk.iddata_konversi FROM krs k JOIN v_datamhs vdm ON (k.nim=vdm.nim) LEFT JOIN data_konversi dk ON (dk.nim=vdm.nim) WHERE tahun='$ta' AND idsmt='$semester' AND kjur=$kjur AND k.sah=1 $str_tahun_masuk ORDER BY vdm.tahun_masuk ASC,vdm.idkelas ASC,vdm.nama_mhs ASC"; $this->db->setFieldTable(array('idkrs','tgl_krs','nim','nirm','nama_mhs','jk','kjur','idkelas','tahun_masuk','semester_masuk','iddata_konversi')); $r=$this->db->getRecord($str); $row=11; while (list($k,$v)=each($r)) { $nim=$v['nim']; $objNilai->setDataMHS(array('nim'=>$nim)); $objNilai->getKHS($_SESSION['ta'],$_SESSION['semester']); $ip=$objNilai->getIPS (); $sks=$objNilai->getTotalSKS (); $dataipk=$objNilai->getIPKSampaiTASemester($ta,$semester,'ipksks'); $sheet->setCellValue("A$row",$v['no']); $sheet->setCellValueExplicit("B$row",$v['nim'],PHPExcel_Cell_DataType::TYPE_STRING); $sheet->setCellValueExplicit("C$row",$v['nirm'],PHPExcel_Cell_DataType::TYPE_STRING); $sheet->setCellValue("D$row",$v['nama_mhs']); $sheet->setCellValue("E$row",$v['jk']); $sheet->setCellValue("F$row",$v['tahun_masuk']); $sheet->setCellValue("G$row",$ip); $sheet->setCellValue("H$row",$dataipk['ipk']); $sheet->setCellValue("I$row",$sks); $sheet->setCellValue("J$row",$dataipk['sks']); $iddata_konversi = $v['iddata_konversi']; $jumlah_sks=0; if ($iddata_konversi > 0) { $jumlah_sks=$this->db->getSumRowsOfTable ('sks',"v_konversi2 WHERE iddata_konversi=$iddata_konversi"); } $sheet->setCellValue("K$row",$jumlah_sks); $sheet->setCellValue("L$row",$objDMaster->getNamaKelasByID($v['idkelas'])); $row+=1; } $row-=1; $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A11:L$row")->applyFromArray($styleArray); $sheet->getStyle("A11:L$row")->getAlignment()->setWrapText(true); $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER) ); $sheet->getStyle("A11:C$row")->applyFromArray($styleArray); $sheet->getStyle("E11:L$row")->applyFromArray($styleArray); if ($withsignature) { $row+=3; $row_awal=$row; $sheet->mergeCells("C$row:D$row"); $sheet->setCellValue("C$row",'Mengetahui'); $sheet->mergeCells("F$row:I$row"); $tanggal=$this->tgl->tanggal('l, j F Y'); $sheet->setCellValue("F$row",$this->setup->getSettingValue('kota_pt').", $tanggal"); $row+=1; $sheet->mergeCells("C$row:D$row"); $sheet->setCellValue("C$row",'A.n. Ketua '.$this->dataReport['nama_pt_alias']); $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",'Ketua Program Studi'); $row+=1; $sheet->mergeCells("C$row:D$row"); $sheet->setCellValue("C$row",$this->dataReport['nama_jabatan_khs']); $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",$nama_ps); $row+=5; $sheet->mergeCells("C$row:D$row"); $sheet->setCellValue("C$row",$this->dataReport['nama_penandatangan_khs']); $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",$this->dataReport['nama_kaprodi']); $row+=1; $sheet->mergeCells("C$row:D$row"); $nama_jabatan=strtoupper($this->dataReport['jabfung_penandatangan_khs']); $nidn=$this->dataReport['nidn_penandatangan_khs']; $sheet->setCellValue("C$row","$nama_jabatan NIDN : $nidn"); $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",strtoupper($this->dataReport['jabfung_kaprodi']). ' NIDN : '.$this->dataReport['nidn_kaprodi']); $styleArray=array( 'font' => array('bold' => true), ); $sheet->getStyle("A$row_awal:L$row")->applyFromArray($styleArray); $sheet->getStyle("A$row_awal:L$row")->getAlignment()->setWrapText(true); } $this->printOut("summarykhs"); break; } $this->setLink($this->dataReport['linkoutput'],"Summary KHS T.A $nama_tahun Semester $nama_semester"); } /** * digunakan untuk memprint Transkrip Kurikulum * @param type $objNilai object */ public function printTranskripKurikulum ($objNilai,$withsignature=false) { $biodata=$this->dataReport; $nim=$biodata['nim']; $objNilai->setDataMHS($biodata); $smt=Logic_Akademik::$SemesterMatakuliahRomawi; switch ($this->getDriver()) { case 'excel2003': case 'excel2007': // $this->printOut("khs_$nim"); break; case 'pdf' : $rpt=$this->rpt; $rpt->setTitle('Transkriprip Nilai Kurikulum'); $rpt->setSubject('Transkrip Nilai Kurikulum'); $rpt->AddPage(); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'TRANSKRIP NILAI KURIKULUM',0,0,'C'); $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Nama Mahasiswa'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nama_mhs']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Program Studi'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['nama_ps']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Tempat, tanggal lahir'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['tempat_lahir'].', '.$this->tgl->tanggal('j F Y',$biodata['tanggal_lahir'])); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Konsentrasi'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['nama_konsentrasi']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'NIM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nim']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Jenjang'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': Starta 1 (satu)'); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'NIRM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nirm']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Angk. Th. Akad'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['tahun_masuk']); //field of column ganjil $row+=20; $rpt->setXY(3,$row); $rpt->Cell(7,8,'SMT',1,0,'C'); $rpt->Cell(6,8,'NO',1,0,'C'); $rpt->Cell(11,4,'KODE',1,0,'C'); $rpt->Cell(54,8,'MATA KULIAH',1,0,'C'); $rpt->Cell(8,8,'SKS',1,0,'C'); $rpt->Cell(8,8,'NM',1,0,'C'); $rpt->Cell(8,8,'AM',1,0,'C'); $rpt->Cell(1,8,''); //field of column genap $rpt->Cell(7,8,'SMT',1,0,'C'); $rpt->Cell(6,8,'NO',1,0,'C'); $rpt->Cell(11,4,'KODE',1,0,'C'); $rpt->Cell(54,8,'MATA KULIAH',1,0,'C'); $rpt->Cell(8,8,'SKS',1,0,'C'); $rpt->Cell(8,8,'NM',1,0,'C'); $rpt->Cell(8,8,'AM',1,0,'C'); $row+=4; $rpt->setXY(16,$row); $rpt->Cell(11,4,'MK',1,0,'C'); $rpt->setXY(119,$row); $rpt->Cell(11,4,'MK',1,0,'C'); $n=$objNilai->getTranskripNilaiKurikulum($this->dataReport['cek_isikuesioner']); $totalSks=0; $totalM=0; $row+=4; $row_ganjil=$row; $row_genap = $row; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',6); $tambah_ganjil_row=false; $tambah_genap_row=false; for ($i = 1; $i <= 8; $i++) { $no_semester=1; if ($i%2==0) {//genap $tambah_genap_row=true; $genap_total_m=0; $genap_total_sks=0; foreach ($n as $v) { if ($v['semester']==$i) { $n_kual=$v['n_kual']; $sks=$v['sks']; $m=($n_kual=='-')?'-':$v['m']; $rpt->setXY(106,$row_genap); $rpt->Cell(7,4,$smt[$i],1,0,'C'); $rpt->Cell(6,4,$no_semester,1,0,'C'); $rpt->Cell(11,4,$objNilai->getKMatkul($v['kmatkul']),1,0,'C'); $rpt->Cell(54,4,$v['nmatkul'],1,0,'L'); $rpt->Cell(8,4,$sks,1,0,'C'); $rpt->Cell(8,4,$n_kual,1,0,'C'); $rpt->Cell(8,4,$m,1,0,'C'); $genap_total_sks += $sks; if ($n_kual!='-') { $genap_total_m += $m; $totalSks+=$sks; $totalM+=$m; } $row_genap+=4; $no_semester++; } } $ipk_genap=@ bcdiv($totalM,$totalSks,2); $ipk_genap=$ipk_genap==''?'0.00':$ipk_genap; }else {//ganjil $tambah_ganjil_row=true; $ganjil_total_m=0; $ganjil_total_sks=0; foreach ($n as $s) { if ($s['semester']==$i) { $n_kual=$s['n_kual']; $sks=$s['sks']; $m=($n_kual=='-')?'-':$s['m']; $rpt->setXY(3,$row_ganjil); $rpt->Cell(7,4,$smt[$i],1,0,'C'); $rpt->Cell(6,4,$no_semester,1,0,'C'); $rpt->Cell(11,4,$objNilai->getKMatkul($s['kmatkul']),1,0,'C'); $rpt->Cell(54,4,$s['nmatkul'],1,0,'L'); $rpt->Cell(8,4,$sks,1,0,'C'); $rpt->Cell(8,4,$n_kual,1,0,'C'); $rpt->Cell(8,4,$m,1,0,'C'); $ganjil_total_sks += $sks; if ($n_kual != '-') { $ganjil_total_m += $m; $totalSks+=$sks; $totalM+=$m; } $row_ganjil+=4; $no_semester++; } } $ipk_ganjil=@ bcdiv($totalM,$totalSks,2); $ipk_ganjil=$ipk_ganjil==''?'0.00':$ipk_ganjil; } if ($tambah_ganjil_row && $tambah_genap_row) { $tambah_ganjil_row=false; $tambah_genap_row=false; if ($row_ganjil < $row_genap){ // berarti tambah row yang ganjil $sisa=$row_ganjil + ($row_genap-$row_ganjil); for ($c=$row_ganjil;$c <= $row_genap;$c+=4) { $rpt->setXY(3,$c); $rpt->Cell(102,4,'',1,0); } $row_ganjil=$sisa; }else{ // berarti tambah row yang genap $sisa=$row_genap + ($row_ganjil-$row_genap); for ($c=$row_genap;$c < $row_ganjil;$c+=4) { $rpt->setXY(106,$c); $rpt->Cell(102,4,'',1,0); } $row_genap=$sisa; } //ganjil $rpt->setXY(16,$row_ganjil); $rpt->Cell(65,4,'Jumlah',1,0,'L'); $rpt->Cell(8,4,$ganjil_total_sks,1,0,'C'); $rpt->Cell(8,4,'',1,0,'L'); $rpt->Cell(8,4,$ganjil_total_m,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(81,4,'Indeks Prestasi Semester',1,0,'L'); $ip=@ bcdiv($ganjil_total_m,$ganjil_total_sks,2); $rpt->Cell(8,4,$ip,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(81,4,'Indeks Prestasi Kumulatif',1,0,'L'); $ipk_ganjil=$ip == '0.00'?'0.00':$ipk_ganjil; $rpt->Cell(8,4,$ipk_ganjil,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(8,4,' ',0,0,'C'); $row_ganjil+=1; //genap $rpt->setXY(119,$row_genap); $rpt->Cell(65,4,'Jumlah',1,0,'L'); $rpt->Cell(8,4,$genap_total_sks,1,0,'C'); $rpt->Cell(8,4,'',1,0,'L'); $rpt->Cell(8,4,$genap_total_m,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(81,4,'Indeks Prestasi Semester',1,0,'L'); $ip=@ bcdiv($genap_total_m,$genap_total_sks,2); $rpt->Cell(8,4,$ip,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(81,4,'Indeks Prestasi Kumulatif',1,0,'L'); $ipk_genap=$ip == '0.00'?'0.00':$ipk_genap; $rpt->Cell(8,4,$ipk_genap,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(8,4,' ',0,0,'C'); $row_genap+=1; } } $rpt->SetFont ('helvetica','B',6); $row=$row_genap+4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Total Kredit Kumulatif',0,0,'L'); $rpt->Cell(8,4,$totalSks,0,0,'C'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Jumlah Nilai Kumulatif',0,0,'L'); $rpt->Cell(8,4,$totalM,0,0,'C'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Indeks Prestasi Kumulatif',0,0,'L'); $ipk=@ bcdiv($totalM,$totalSks,2); $ipk=$ipk==''?'0.00':$ipk; $rpt->Cell(8,4,$ipk,0,0,'C'); if ($withsignature) { $row+=8; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->setup->getSettingValue('kota_pt').', '.$this->tgl->tanggal('j F Y'),0,0,'L'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->dataReport['nama_jabatan_transkrip'],0,0,'L'); $row+=14; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->dataReport['nama_penandatangan_transkrip'],0,0,'L'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,strtoupper($this->dataReport['jabfung_penandatangan_transkrip']). ' NIDN '.$this->dataReport['nidn_penandatangan_transkrip'],0,0,'L'); } $this->printOut("transkripkurikulum_$nim"); break; } $this->setLink($this->dataReport['linkoutput'],"Transkrip Kurikulum"); } /** * digunakan untuk memprint Transkrip Kurikulum All * @param type $objNilai object */ public function printTranskripKurikulumAll ($objNilai,$withsignature=false,$outputcompress,$level=0) { $biodata=$this->dataReport; $nim=$biodata['nim']; $objNilai->setDataMHS($biodata); $smt=Logic_Akademik::$SemesterMatakuliahRomawi; switch ($this->getDriver()) { case 'excel2003': case 'excel2007': // $this->printOut("khs_$nim"); break; case 'pdf' : $rpt=$this->rpt; $rpt->setTitle('Transkriprip Nilai Kurikulum'); $rpt->setSubject('Transkriprip Nilai Kurikulum'); $rpt->AddPage(); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'TRANSKRIP NILAI KURIKULUM',0,0,'C'); $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Nama Mahasiswa'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nama_mhs']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Program Studi'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['nama_ps']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Tempat, tanggal lahir'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['tempat_lahir'].', '.$this->tgl->tanggal('j F Y',$biodata['tanggal_lahir'])); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Konsentrasi'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['nama_konsentrasi']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'NIM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nim']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Jenjang'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': Starta 1 (satu)'); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'NIRM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nirm']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Angk. Th. Akad'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['tahun_masuk']); //field of column ganjil $row+=20; $rpt->setXY(3,$row); $rpt->Cell(7,8,'SMT',1,0,'C'); $rpt->Cell(6,8,'NO',1,0,'C'); $rpt->Cell(11,4,'KODE',1,0,'C'); $rpt->Cell(54,8,'MATA KULIAH',1,0,'C'); $rpt->Cell(8,8,'SKS',1,0,'C'); $rpt->Cell(8,8,'NM',1,0,'C'); $rpt->Cell(8,8,'AM',1,0,'C'); $rpt->Cell(1,8,''); //field of column genap $rpt->Cell(7,8,'SMT',1,0,'C'); $rpt->Cell(6,8,'NO',1,0,'C'); $rpt->Cell(11,4,'KODE',1,0,'C'); $rpt->Cell(54,8,'MATA KULIAH',1,0,'C'); $rpt->Cell(8,8,'SKS',1,0,'C'); $rpt->Cell(8,8,'NM',1,0,'C'); $rpt->Cell(8,8,'AM',1,0,'C'); $row+=4; $rpt->setXY(16,$row); $rpt->Cell(11,4,'MK',1,0,'C'); $rpt->setXY(119,$row); $rpt->Cell(11,4,'MK',1,0,'C'); $n=$objNilai->getTranskripNilaiKurikulum(); $totalSks=0; $totalM=0; $row+=4; $row_ganjil=$row; $row_genap = $row; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',6); $tambah_ganjil_row=false; $tambah_genap_row=false; for ($i = 1; $i <= 8; $i++) { $no_semester=1; if ($i%2==0) {//genap $tambah_genap_row=true; $genap_total_m=0; $genap_total_sks=0; foreach ($n as $v) { if ($v['semester']==$i) { $n_kual=$v['n_kual']; $sks=$v['sks']; $m=($n_kual=='-')?'-':$v['m']; $rpt->setXY(106,$row_genap); $rpt->Cell(7,4,$smt[$i],1,0,'C'); $rpt->Cell(6,4,$no_semester,1,0,'C'); $rpt->Cell(11,4,$objNilai->getKMatkul($v['kmatkul']),1,0,'C'); $rpt->Cell(54,4,$v['nmatkul'],1,0,'L'); $rpt->Cell(8,4,$sks,1,0,'C'); $rpt->Cell(8,4,$n_kual,1,0,'C'); $rpt->Cell(8,4,$m,1,0,'C'); $genap_total_sks += $sks; if ($n_kual!='-') { $genap_total_m += $m; $totalSks+=$sks; $totalM+=$m; } $row_genap+=4; $no_semester++; } } $ipk_genap=@ bcdiv($totalM,$totalSks,2); $ipk_genap=$ipk_genap==''?'0.00':$ipk_genap; }else {//ganjil $tambah_ganjil_row=true; $ganjil_total_m=0; $ganjil_total_sks=0; foreach ($n as $s) { if ($s['semester']==$i) { $n_kual=$s['n_kual']; $sks=$s['sks']; $m=($n_kual=='-')?'-':$s['m']; $rpt->setXY(3,$row_ganjil); $rpt->Cell(7,4,$smt[$i],1,0,'C'); $rpt->Cell(6,4,$no_semester,1,0,'C'); $rpt->Cell(11,4,$objNilai->getKMatkul($s['kmatkul']),1,0,'C'); $rpt->Cell(54,4,$s['nmatkul'],1,0,'L'); $rpt->Cell(8,4,$sks,1,0,'C'); $rpt->Cell(8,4,$n_kual,1,0,'C'); $rpt->Cell(8,4,$m,1,0,'C'); $ganjil_total_sks += $sks; if ($n_kual != '-') { $ganjil_total_m += $m; $totalSks+=$sks; $totalM+=$m; } $row_ganjil+=4; $no_semester++; } } $ipk_ganjil=@ bcdiv($totalM,$totalSks,2); $ipk_ganjil=$ipk_ganjil==''?'0.00':$ipk_ganjil; } if ($tambah_ganjil_row && $tambah_genap_row) { $tambah_ganjil_row=false; $tambah_genap_row=false; if ($row_ganjil < $row_genap){ // berarti tambah row yang ganjil $sisa=$row_ganjil + ($row_genap-$row_ganjil); for ($c=$row_ganjil;$c <= $row_genap;$c+=4) { $rpt->setXY(3,$c); $rpt->Cell(102,4,'',1,0); } $row_ganjil=$sisa; }else{ // berarti tambah row yang genap $sisa=$row_genap + ($row_ganjil-$row_genap); for ($c=$row_genap;$c < $row_ganjil;$c+=4) { $rpt->setXY(106,$c); $rpt->Cell(102,4,'',1,0); } $row_genap=$sisa; } //ganjil $rpt->setXY(16,$row_ganjil); $rpt->Cell(65,4,'Jumlah',1,0,'L'); $rpt->Cell(8,4,$ganjil_total_sks,1,0,'C'); $rpt->Cell(8,4,'',1,0,'L'); $rpt->Cell(8,4,$ganjil_total_m,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(81,4,'Indeks Prestasi Semester',1,0,'L'); $ip=@ bcdiv($ganjil_total_m,$ganjil_total_sks,2); $rpt->Cell(8,4,$ip,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(81,4,'Indeks Prestasi Kumulatif',1,0,'L'); $ipk_ganjil=$ip == '0.00'?'0.00':$ipk_ganjil; $rpt->Cell(8,4,$ipk_ganjil,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(8,4,' ',0,0,'C'); $row_ganjil+=1; //genap $rpt->setXY(119,$row_genap); $rpt->Cell(65,4,'Jumlah',1,0,'L'); $rpt->Cell(8,4,$genap_total_sks,1,0,'C'); $rpt->Cell(8,4,'',1,0,'L'); $rpt->Cell(8,4,$genap_total_m,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(81,4,'Indeks Prestasi Semester',1,0,'L'); $ip=@ bcdiv($genap_total_m,$genap_total_sks,2); $rpt->Cell(8,4,$ip,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(81,4,'Indeks Prestasi Kumulatif',1,0,'L'); $ipk_genap=$ip == '0.00'?'0.00':$ipk_genap; $rpt->Cell(8,4,$ipk_genap,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(8,4,' ',0,0,'C'); $row_genap+=1; } } $rpt->SetFont ('helvetica','B',6); $row=$row_genap+4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Total Kredit Kumulatif',0,0,'L'); $rpt->Cell(8,4,$totalSks,0,0,'C'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Jumlah Nilai Kumulatif',0,0,'L'); $rpt->Cell(8,4,$totalM,0,0,'C'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Indeks Prestasi Kumulatif',0,0,'L'); $ipk=@ bcdiv($totalM,$totalSks,2); $ipk=$ipk==''?'0.00':$ipk; $rpt->Cell(8,4,$ipk,0,0,'C'); if ($withsignature) { $row+=8; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->setup->getSettingValue('kota_pt').', '.$this->tgl->tanggal('j F Y'),0,0,'L'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->dataReport['nama_jabatan_transkrip'],0,0,'L'); $row+=14; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->dataReport['nama_penandatangan_transkrip'],0,0,'L'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,strtoupper($this->dataReport['jabfung_penandatangan_transkrip']). ' NIDN '.$this->dataReport['nidn_penandatangan_transkrip'],0,0,'L'); } $this->printOut("transkripsementara_$nim"); break; } $this->setLink($this->dataReport['linkoutput'],"Transkrip Kurikulum"); } /** * digunakan untuk memprint Transkrip KRS * @param type $objNilai object */ public function printTranskripKRS ($objNilai,$withsignature=false) { $biodata=$this->dataReport; $nim=$biodata['nim']; $objNilai->setDataMHS($biodata); $smt=Logic_Akademik::$SemesterMatakuliahRomawi; switch ($this->getDriver()) { case 'excel2003': case 'excel2007': // $this->printOut("khs_$nim"); break; case 'pdf' : $rpt=$this->rpt; $rpt->setTitle('Transkriprip Nilai KRS'); $rpt->setSubject('Transkriprip Nilai KRS'); $rpt->AddPage(); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'TRANSKRIP NILAI KURIKULUM',0,0,'C'); $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Nama Mahasiswa'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nama_mhs']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Program Studi'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['nama_ps']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Tempat, tanggal lahir'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['tempat_lahir'].', '.$this->tgl->tanggal('j F Y',$biodata['tanggal_lahir'])); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Konsentrasi'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['nama_konsentrasi']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'NIM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nim']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Jenjang'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': Starta 1 (satu)'); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'NIRM'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$biodata['nirm']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Angk. Th. Akad'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$biodata['tahun_masuk']); $n=$objNilai->getTranskripFromKRS($this->dataReport['cek_isikuesioner']); $tampil_column_ganjil=false; $tampil_column_genap=false; for ($i = 1; $i <= 8; $i++) { $no_semester=1; if ($i%2==0) {//genap foreach ($n as $v) { if ($v['semester']==$i) { $tampil_column_genap=true; break; } } }else{ foreach ($n as $s) { if ($s['semester']==$i) { $tampil_column_ganjil=true; break; } } } if ($tampil_column_ganjil & $tampil_column_genap) { break; } } //field of column ganjil $row+=20; $rpt->setXY(3,$row); if ($tampil_column_ganjil) { $rpt->Cell(7,8,'SMT',1,0,'C'); $rpt->Cell(6,8,'NO',1,0,'C'); $rpt->Cell(11,4,'KODE',1,0,'C'); $rpt->Cell(54,8,'MATA KULIAH',1,0,'C'); $rpt->Cell(8,8,'SKS',1,0,'C'); $rpt->Cell(8,8,'NM',1,0,'C'); $rpt->Cell(8,8,'AM',1,0,'C'); $rpt->Cell(1,8,''); }else{ $rpt->setXY(106,$row); } if ($tampil_column_genap) { //field of column genap $rpt->Cell(7,8,'SMT',1,0,'C'); $rpt->Cell(6,8,'NO',1,0,'C'); $rpt->Cell(11,4,'KODE',1,0,'C'); $rpt->Cell(54,8,'MATA KULIAH',1,0,'C'); $rpt->Cell(8,8,'SKS',1,0,'C'); $rpt->Cell(8,8,'NM',1,0,'C'); $rpt->Cell(8,8,'AM',1,0,'C'); $row+=4; if ($tampil_column_ganjil) { $rpt->setXY(16,$row); $rpt->Cell(11,4,'MK',1,0,'C'); } $rpt->setXY(119,$row); $rpt->Cell(11,4,'MK',1,0,'C'); }else { $row+=4; $rpt->setXY(16,$row); $rpt->Cell(11,4,'MK',1,0,'C'); } $totalSks=0; $totalM=0; $row+=4; $row_ganjil=$row; $row_genap = $row; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',6); $tambah_ganjil_row=false; $tambah_genap_row=false; $bool_khs_genap = false; $bool_khs_ganjil = false; for ($i = 1; $i <= 8; $i++) { $no_semester=1; if ($i%2==0) {//genap $tambah_genap_row=true; $genap_total_m=0; $genap_total_sks=0; $tampil_border_genap=false; foreach ($n as $v) { if ($v['semester']==$i) { $n_kual=$v['n_kual']; $sks=$v['sks']; $m=($n_kual=='-')?'-':$v['m']; $rpt->setXY(106,$row_genap); $rpt->Cell(7,4,$smt[$i],1,0,'C'); $rpt->Cell(6,4,$no_semester,1,0,'C'); $rpt->Cell(11,4,$objNilai->getKMatkul($v['kmatkul']),1,0,'C'); $rpt->Cell(54,4,$v['nmatkul'],1,0,'L'); $rpt->Cell(8,4,$sks,1,0,'C'); $rpt->Cell(8,4,$n_kual,1,0,'C'); $rpt->Cell(8,4,$m,1,0,'C'); $genap_total_sks += $sks; if ($n_kual!='-') { $genap_total_m += $m; $totalSks+=$sks; $totalM+=$m; } $row_genap+=4; $no_semester++; $bool_khs_genap = true; $tampil_border_genap=true; } } $ipk_genap=@ bcdiv($totalM,$totalSks,2); $ipk_genap=$ipk_genap==''?'0.00':$ipk_genap; }else {//ganjil $tambah_ganjil_row=true; $ganjil_total_m=0; $ganjil_total_sks=0; $tampil_border_ganjil=false; foreach ($n as $s) { if ($s['semester']==$i) { $n_kual=$s['n_kual']; $sks=$s['sks']; $m=($n_kual=='-')?'-':$s['m']; $rpt->setXY(3,$row_ganjil); $rpt->Cell(7,4,$smt[$i],1,0,'C'); $rpt->Cell(6,4,$no_semester,1,0,'C'); $rpt->Cell(11,4,$objNilai->getKMatkul($s['kmatkul']),1,0,'C'); $rpt->Cell(54,4,$s['nmatkul'],1,0,'L'); $rpt->Cell(8,4,$sks,1,0,'C'); $rpt->Cell(8,4,$n_kual,1,0,'C'); $rpt->Cell(8,4,$m,1,0,'C'); $ganjil_total_sks += $sks; if ($n_kual != '-') { $ganjil_total_m += $m; $totalSks+=$sks; $totalM+=$m; } $row_ganjil+=4; $no_semester++; $bool_khs_ganjil = true; $tampil_border_ganjil=true; } } $ipk_ganjil=@ bcdiv($totalM,$totalSks,2); $ipk_ganjil=$ipk_ganjil==''?'0.00':$ipk_ganjil; } if ($tambah_ganjil_row && $tambah_genap_row) { $tambah_ganjil_row=false; $tambah_genap_row=false; if ($row_ganjil < $row_genap){ // berarti tambah row yang ganjil $sisa=$row_ganjil + ($row_genap-$row_ganjil); if ($tampil_border_ganjil){ for ($c=$row_ganjil;$c <= $row_genap;$c+=4) { $rpt->setXY(3,$c); $rpt->Cell(102,4,'',1,0); } } $row_ganjil=$sisa; }else{ // berarti tambah row yang genap $sisa=$row_genap + ($row_ganjil-$row_genap); if ($tampil_border_genap){ for ($c=$row_genap;$c < $row_ganjil;$c+=4) { $rpt->setXY(106,$c); $rpt->Cell(102,4,'',1,0); } } $row_genap=$sisa; } if ($bool_khs_ganjil) { //ganjil $rpt->setXY(16,$row_ganjil); $rpt->Cell(65,4,'Jumlah',1,0,'L'); $rpt->Cell(8,4,$ganjil_total_sks,1,0,'C'); $rpt->Cell(8,4,'',1,0,'L'); $rpt->Cell(8,4,$ganjil_total_m,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(81,4,'Indeks Prestasi Semester',1,0,'L'); $ip=@ bcdiv($ganjil_total_m,$ganjil_total_sks,2); $rpt->Cell(8,4,$ip,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(81,4,'Indeks Prestasi Kumulatif',1,0,'L'); $ipk_ganjil=$ip == '0.00'?'0.00':$ipk_ganjil; $rpt->Cell(8,4,$ipk_ganjil,1,0,'C'); $row_ganjil+=4; $rpt->setXY(16,$row_ganjil); $rpt->Cell(8,4,' ',0,0,'C'); $row_ganjil+=1; } if ($bool_khs_genap) { //genap $rpt->setXY(119,$row_genap); $rpt->Cell(65,4,'Jumlah',1,0,'L'); $rpt->Cell(8,4,$genap_total_sks,1,0,'C'); $rpt->Cell(8,4,'',1,0,'L'); $rpt->Cell(8,4,$genap_total_m,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(81,4,'Indeks Prestasi Semester',1,0,'L'); $ip=@ bcdiv($genap_total_m,$genap_total_sks,2); $rpt->Cell(8,4,$ip,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(81,4,'Indeks Prestasi Kumulatif',1,0,'L'); $ipk_genap=$ip == '0.00'?'0.00':$ipk_genap; $rpt->Cell(8,4,$ipk_genap,1,0,'C'); $row_genap+=4; $rpt->setXY(119,$row_genap); $rpt->Cell(8,4,' ',0,0,'C'); $row_genap+=1; } $bool_khs_genap = false; $bool_khs_ganjil = false; } } $rpt->SetFont ('helvetica','B',6); $row=$row_genap+4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Total Kredit Kumulatif',0,0,'L'); $rpt->Cell(8,4,$totalSks,0,0,'C'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Jumlah Nilai Kumulatif',0,0,'L'); $rpt->Cell(8,4,$totalM,0,0,'C'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,'Indeks Prestasi Kumulatif',0,0,'L'); $ipk=@ bcdiv($totalM,$totalSks,2); $ipk=$ipk==''?'0.00':$ipk; $rpt->Cell(8,4,$ipk,0,0,'C'); if ($withsignature) { $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->setup->getSettingValue('kota_pt').', '.$this->tgl->tanggal('j F Y'),0,0,'L'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->dataReport['nama_jabatan_transkrip'],0,0,'L'); $row+=14; $rpt->setXY(105,$row); $rpt->Cell(65,4,$this->dataReport['nama_penandatangan_transkrip'],0,0,'L'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(65,4,strtoupper($this->dataReport['jabfung_penandatangan_transkrip']). ' NIDN '.$this->dataReport['nidn_penandatangan_transkrip'],0,0,'L'); } $this->printOut("transkripkrs_$nim"); break; } $this->setLink($this->dataReport['linkoutput'],"Transkrip KRS"); } /** * digunakan untuk memprint Transkrip Final * @param type $objNilai object */ public function printTranskripFinal ($objNilai) { $biodata=$this->dataReport; $nim=$biodata['nim']; $objNilai->setDataMHS (array('nim'=>$nim)); $n=$objNilai->getTranskrip(false); switch ($this->getDriver()) { case 'excel2003': case 'excel2007': // $this->printOut("khs_$nim"); break; case 'pdf' : $rpt=$this->rpt; $rpt->setTitle('Transkrip Nilai Final'); $rpt->setSubject('Transkrip Nilai Final'); $rpt->AddPage('P','F4'); $row=43; $rpt->SetFont ('helvetica','',8); $rpt->setXY(3,$row); $rpt->Cell(0,5,'Nomor Ijazah: '.$biodata['dataTranskrip']['nomor_ijazah'],0,0,'R'); $row+=6; $rpt->SetFont ('helvetica','BU',12); $rpt->setXY(3,$row); $rpt->Cell(0,5,'TRANSKRIP AKADEMIK',0,0,'C'); $row+=4; $rpt->SetFont ('helvetica','B',10); $rpt->setXY(3,$row); $rpt->Cell(0,5,'Nomor : '.$biodata['dataTranskrip']['nomor_transkrip'],0,0,'C'); $row+=8; $rpt->SetFont ('helvetica','',8); $rpt->setXY(3,$row); $rpt->Cell(44,5,'NAMA'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$biodata['nama_mhs']); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'NIM'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$biodata['nim']); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'NIRM'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$biodata['nirm']); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'TEMPAT, TGL. LAHIR'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$biodata['tempat_lahir']. ', '.$this->tgl->tanggal('j F Y',$biodata['tanggal_lahir'])); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'PROGRAM STUDI'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$biodata['nama_ps']); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'KONSENTRASI'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5, strtoupper($biodata['nama_konsentrasi'])); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'INDEKS PRESTASI KUMULATIF'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$objNilai->getIPKAdaNilai()); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'PREDIKAT KELULUSAN'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$biodata['dataTranskrip']['predikat_kelulusan']); $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'TANGGAL LULUS'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,$this->tgl->tanggal('j F Y',$biodata['dataTranskrip']['tanggal_lulus'])); $row+=4; $nama_pembimbing1=$biodata['dataTranskrip']['nama_pembimbing1']; $rpt->setXY(3,$row); $rpt->Cell(44,5,'PEMBIMBING SKRIPSI'); $rpt->Cell(1.5,5,':'); $rpt->Cell(150,5,"1. $nama_pembimbing1"); $nama_pembimbing2=$biodata['dataTranskrip']['nama_pembimbing2']; if ($nama_pembimbing2!='') { $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,''); $rpt->Cell(1.5,5,''); $rpt->Cell(150,5,"2. $nama_pembimbing2"); } $row+=4; $rpt->setXY(3,$row); $rpt->Cell(44,5,'JUDUL SKRIPSI'); $rpt->Cell(1.5,5,':'); $row+=0.5; $rpt->setXY(3,$row); $rpt->Cell(44,5,''); $rpt->Cell(1.5,5,''); $rpt->MultiCell(150,11,$biodata['dataTranskrip']['judul_skripsi'],0,'L',false,0,'',''); //field of column ganjil $row+=12; $rpt->setXY(3,$row); $rpt->Cell(205,3,' ','T',0,'C'); $row+=0.7; $rpt->setXY(3,$row); $rpt->Cell(15,5,'KODE','TBR',0,'C'); $rpt->Cell(60,5,'MATA KULIAH',1,0,'C'); $rpt->Cell(9,5,'SKS',1,0,'C'); $rpt->Cell(9,5,'AM',1,0,'C'); $rpt->Cell(9,5,'NM',1,0,'C'); $rpt->Cell(1,5,''); //field of column genap $rpt->Cell(15,5,'KODE',1,0,'C'); $rpt->Cell(60,5,'MATA KULIAH',1,0,'C'); $rpt->Cell(9,5,'SKS',1,0,'C'); $rpt->Cell(9,5,'AM',1,0,'C'); $rpt->Cell(9,5,'NM','TBL',0,'C'); $row+=5; $totalSks=0; $totalM=0; $row_ganjil=$row; $row_genap = $row; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',6); $tambah_ganjil_row=false; $tambah_genap_row=false; for ($i = 1; $i <= 8; $i++) { if ($i%2==0) {//genap $tambah_genap_row=true; $rpt->setXY(106,$row_genap); $rpt->Cell(102,4,"SEMESTER $i",'L',0,'C'); $row_genap+=4; foreach ($n as $v) { if ($v['semester']==$i) { $n_kual=$v['n_kual']; $n_kual=($n_kual=='-'||$n_kual=='')?'-':$n_kual; $sks=$v['sks']; $totalSks+=$sks; $rpt->setXY(106,$row_genap); $rpt->Cell(15,4,$objNilai->getKMatkul($v['kmatkul']),'L',0,'C'); $rpt->Cell(60,4,$v['nmatkul'],0,0,'L'); $rpt->Cell(9,4,$sks,0,0,'C'); $rpt->Cell(9,4,$objNilai->getAngkaMutu($n_kual),0,0,'C'); $rpt->Cell(9,4,$n_kual,0,0,'C'); $row_genap+=4; } } }else {//ganjil $tambah_ganjil_row=true; $rpt->setXY(3,$row_genap); $rpt->Cell(102,4,"SEMESTER $i",'R',0,'C'); $row_ganjil+=4; foreach ($n as $s) { if ($s['semester']==$i) { $n_kual=$s['n_kual']; $n_kual=($n_kual=='-'||$n_kual=='')?'-':$n_kual; $sks=$s['sks']; $totalSks+=$sks; $rpt->setXY(3,$row_ganjil); $rpt->Cell(15,4,$objNilai->getKMatkul($s['kmatkul']),0,0,'C'); $rpt->Cell(60,4,$s['nmatkul'],0,0,'L'); $rpt->Cell(9,4,$sks,0,0,'C'); $rpt->Cell(9,4,$objNilai->getAngkaMutu($n_kual),0,0,'C'); $rpt->Cell(9,4,$n_kual,'R',0,'C'); $row_ganjil+=4; } } } if ($tambah_ganjil_row && $tambah_genap_row) { $tambah_ganjil_row=false; $tambah_genap_row=false; if ($row_ganjil < $row_genap){ // berarti tambah row yang ganjil $sisa=$row_ganjil + ($row_genap-$row_ganjil); for ($c=$row_ganjil;$c <= $row_genap;$c+=4) { $rpt->setXY(3,$c); $rpt->Cell(15,4,'',0,0,'C'); $rpt->Cell(60,4,'',0,0,'L'); $rpt->Cell(9,4,'',0,0,'C'); $rpt->Cell(9,4,'',0,0,'C'); $rpt->Cell(9,4,'','R',0,'C'); } $row_ganjil=$sisa; }else{ // berarti tambah row yang genap $sisa=$row_genap + ($row_ganjil-$row_genap); for ($c=$row_genap;$c < $row_ganjil;$c+=4) { $rpt->setXY(106,$c); $rpt->Cell(15,4,'','L',0,'C'); $rpt->Cell(60,4,'',0,0,'L'); $rpt->Cell(9,4,'',0,0,'C'); $rpt->Cell(9,4,'',0,0,'C'); $rpt->Cell(9,4,'',0,0,'C'); } $row_genap=$sisa; } } } $row=$row_genap; $rpt->setXY(3,$row); $rpt->Cell(102,4,'','T',0); $rpt->Cell(1,4,'',0,0); $rpt->Cell(102,4,'','T',0); $row=$row_genap+0.7; $rpt->setXY(3,$row); $rpt->Cell(205,1,' ','T',0); $row+=1; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(7,$row); $rpt->Cell(65,4,'Jumlah SKS Kumulatif',0); $rpt->SetFont ('helvetica',''); $rpt->Cell(4,4,': ',0); $rpt->SetFont ('helvetica','B'); $rpt->Cell(130,4,"$totalSks",0); $row+=4; $rpt->setXY(7,$row); $rpt->Cell(65,4,'Keterangan',0); $rpt->SetFont ('helvetica',''); $rpt->Cell(4,4,': ',0); $rpt->Cell(45,4,'A = 4 (Sangat Baik)',0); $rpt->Cell(85,4,': B = 3 (Baik) : C = 2 (Cukup)',0); $row+=4; $rpt->setXY(7,$row); $rpt->Cell(65,4,' ',0); $rpt->Cell(4,4,' ',0); $rpt->Cell(45,4,'D = 1 (Kurang)',0); $rpt->Cell(85,4,': E = 0 (Tidak Lulus)',0); $row+=6; $rpt->setXY(20,$row); $rpt->Cell(25,30,'',1); $row+=2; $rpt->setXY(40,$row); $rpt->Cell(65,4,'',0,0,'C'); $rpt->Cell(90,4,$this->setup->getSettingValue('kota_pt').', '.$this->tgl->tanggal('j F Y',$biodata['tanggalterbit']),0,0,'C'); $row+=4; $rpt->setXY(40,$row); $rpt->Cell(65,4,$biodata['nama_jabatan_transkrip'].',',0,0,'C'); $rpt->Cell(90,4,'KETUA PROGRAM STUDI,',0,0,'C'); $row+=4; $rpt->setXY(105,$row); $rpt->Cell(90,4,$biodata['nama_ps'],0,0,'C'); $row+=17; $rpt->setXY(40,$row); $rpt->SetFont ('helvetica','B'); $rpt->Cell(65,4,$biodata['nama_penandatangan_transkrip'],0,0,'C'); $rpt->Cell(90,4,$biodata['nama_kaprodi'],0,0,'C'); $row+=4; $rpt->setXY(40,$row); $rpt->SetFont ('helvetica',''); $rpt->Cell(65,4,strtoupper($biodata['jabfung_penandatangan_transkrip']). ' NIDN '.$biodata['nidn_penandatangan_transkrip'],0,0,'C'); $rpt->Cell(90,4,strtoupper($biodata['jabfung_kaprodi']). ' NIDN '.$biodata['nidn_kaprodi'],0,0,'C'); $this->printOut("transkripfinal_$nim"); break; } $this->setLink($this->dataReport['linkoutput'],"Transkrip Final"); } /** * digunakan untuk memprint DPNA * @param type $objNilai object */ public function printDPNA ($objNilai) { $kmatkul=$this->dataReport['kmatkul']; $idkelas_mhs=$this->dataReport['idkelas_mhs']; $kaprodi=$objNilai->getKetuaPRODI($this->dataReport['kjur']); switch ($this->getDriver()) { case 'excel2003': case 'excel2007': $this->setHeaderPT('K'); $sheet=$this->rpt->getActiveSheet(); $this->rpt->getDefaultStyle()->getFont()->setName('Arial'); $this->rpt->getDefaultStyle()->getFont()->setSize('9'); $sheet->mergeCells("A7:K7"); $sheet->getRowDimension(7)->setRowHeight(20); $sheet->setCellValue("A7",'DAFTAR PESERTA DAN NILAI AKHIR'); $styleArray=array( 'font' => array('bold' => true, 'size' => 16), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER) ); $sheet->getStyle("A7:K8")->applyFromArray($styleArray); $sheet->getColumnDimension('A')->setWidth(8); $sheet->getColumnDimension('B')->setWidth(11); $sheet->getColumnDimension('C')->setWidth(25); $sheet->getColumnDimension('D')->setWidth(15); $sheet->getColumnDimension('F')->setWidth(12); $sheet->getColumnDimension('G')->setWidth(20); $sheet->getColumnDimension('K')->setWidth(15); if ($idkelas_mhs == 'none'){ $sheet->mergeCells('A10:B10'); $sheet->setCellValue("A10",'Matakuliah'); $sheet->setCellValue("C10",': '.$this->dataReport['nmatkul']); $sheet->mergeCells('A11:B11'); $sheet->setCellValue("A11",'Kode / SKS'); $sheet->setCellValue("C11",': '.$this->dataReport['kmatkul'].' / '.$this->dataReport['sks']); $sheet->mergeCells('A12:B12'); $sheet->setCellValue("A12",'P.S / Jenjang'); $sheet->setCellValue("C12",': '.$this->dataReport['nama_ps']); $sheet->mergeCells('E13:F13'); $sheet->setCellValue("E12",'Dosen Pengampu'); $sheet->setCellValue("G12",': '.$this->dataReport['nama_dosen_pengampu']); $sheet->mergeCells('A13:B13'); $sheet->setCellValue("A13",'Semester'); $sheet->setCellValue("C13",': '.$this->dataReport['nama_semester']); $sheet->mergeCells('E13:F13'); $sheet->setCellValue("E13",'T.A'); $sheet->setCellValue("G13",': '.$this->dataReport['ta']); $idpenyelenggaraan=$this->dataReport['idpenyelenggaraan']; $str ="SELECT vdm.nim,vdm.nirm,vdm.nama_mhs,vdm.jk,n.n_kuan,n.n_kual FROM v_krsmhs vkm JOIN v_datamhs vdm ON(vdm.nim=vkm.nim) LEFT JOIN nilai_matakuliah n ON (n.idkrsmatkul=vkm.idkrsmatkul) WHERE vkm.idpenyelenggaraan=$idpenyelenggaraan AND vkm.sah=1 AND vkm.batal=0 ORDER BY vdm.nama_mhs ASC"; $this->db->setFieldTable(array('nim','nirm','nama_mhs','jk','n_kuan','n_kual')); }else{ $sheet->mergeCells('A10:B10'); $sheet->setCellValue("A10",'Matakuliah'); $sheet->setCellValue("C10",': '.$this->dataReport['nmatkul']); $sheet->mergeCells('A11:B11'); $sheet->setCellValue("A11",'Kode / SKS'); $sheet->setCellValue("C11",': '.$this->dataReport['kmatkul'].' / '.$this->dataReport['sks']); $sheet->mergeCells('A12:B12'); $sheet->setCellValue("A12",'P.S / Jenjang'); $sheet->setCellValue("C12",': '.$this->dataReport['nama_ps']); $sheet->mergeCells('E13:F13'); $sheet->setCellValue("E12",'Dosen Pengampu'); $sheet->setCellValue("G12",': '.$this->dataReport['nama_dosen_pengampu']); $sheet->mergeCells('A13:B13'); $sheet->setCellValue("A13",'Semester'); $sheet->setCellValue("C13",': '.$this->dataReport['nama_semester']); $sheet->mergeCells('E13:F13'); $sheet->setCellValue("E13",'T.A'); $sheet->setCellValue("G13",': '.$this->dataReport['ta']); $sheet->mergeCells('A13:B13'); $sheet->setCellValue("A13",'Kelas'); $sheet->setCellValue("C13",': '.$this->dataReport['namakelas']); $sheet->mergeCells('E13:F13'); $sheet->setCellValue("E13",'Hari / Jam'); $sheet->setCellValue("G13",': '.$this->dataReport['hari'].', '.$this->dataReport['jam_masuk'].'-'.$this->dataReport['jam_keluar']); $idkelas=$this->dataReport['idkelas_mhs']; $itemcount=$this->db->getCountRowsOfTable("kelas_mhs_detail kmd JOIN v_krsmhs vkm ON (vkm.idkrsmatkul=kmd.idkrsmatkul) JOIN v_datamhs vdm ON (vkm.nim=vdm.nim) WHERE kmd.idkelas_mhs=$idkelas AND vkm.sah=1 AND vkm.batal=0",'vkm.nim'); $pagesize=40; $jumlahpage=ceil($itemcount/$pagesize); $str ="SELECT vdm.nim,vdm.nirm,vdm.nama_mhs,vdm.jk,n.n_kual,n.n_kuan FROM kelas_mhs_detail kmd LEFT JOIN nilai_matakuliah n ON (n.idkrsmatkul=kmd.idkrsmatkul) JOIN v_krsmhs vkm ON (vkm.idkrsmatkul=kmd.idkrsmatkul) JOIN v_datamhs vdm ON (vkm.nim=vdm.nim) WHERE kmd.idkelas_mhs=$idkelas AND vkm.sah=1 AND vkm.batal=0 ORDER BY vdm.nama_mhs ASC"; $this->db->setFieldTable(array('nim','nirm','nama_mhs','jk','n_kual','n_kuan')); } $sheet->mergeCells('A15:A16'); $sheet->setCellValue('A15','NO'); $sheet->mergeCells('B15:D16'); $sheet->setCellValue('B15','NAMA'); $sheet->mergeCells('E15:E16'); $sheet->setCellValue('E15','JK'); $sheet->mergeCells('F15:F16'); $sheet->setCellValue('F15','NIM'); $sheet->mergeCells('G15:G16'); $sheet->setCellValue('G15','NIRM'); $sheet->mergeCells('H15:J15'); $sheet->setCellValue('H15','NILAI'); $sheet->mergeCells('K15:K16'); $sheet->setCellValue('K15','KETERANGAN'); $sheet->setCellValue('H16','ANGKA'); $sheet->setCellValue('I16','AM'); $sheet->setCellValue('J16','HM'); $styleArray=array( 'font' => array('bold' => true), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A15:K16")->applyFromArray($styleArray); $sheet->getStyle("A15:K6")->getAlignment()->setWrapText(true); $row=17; $r=$this->db->getRecord($str); while (list($k,$v)=each ($r) ){ $sheet->setCellValue("A$row",$v['no']); $sheet->mergeCells("B$row:D$row"); $sheet->setCellValue("B$row",$v['nama_mhs']); $sheet->setCellValue("E$row",$v['jk']); $sheet->setCellValueExplicit("F$row",$v['nim'],PHPExcel_Cell_DataType::TYPE_STRING); $sheet->setCellValueExplicit("G$row",$v['nirm'],PHPExcel_Cell_DataType::TYPE_STRING); $sheet->setCellValue("H$row",$v['n_kuan']); $am=$v['n_kual']==''?'-':$objNilai->getAngkaMutu($v['n_kual']); $hm=$v['n_kual']==''?'-':$v['n_kual']; $sheet->setCellValue("I$row",$am); $sheet->setCellValue("J$row",$hm); $sheet->setCellValue("K$row",'-'); $row+=1; } $row-=1; $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A17:K$row")->applyFromArray($styleArray); $sheet->getStyle("A17:K$row")->getAlignment()->setWrapText(true); $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER) ); $sheet->getStyle("A17:A$row")->applyFromArray($styleArray); $sheet->getStyle("E17:K$row")->applyFromArray($styleArray); $row+=3; $row_awal=$row; $tanggal=$this->tgl->tanggal('l, j F Y'); $sheet->setCellValue("H$row",$this->setup->getSettingValue('kota_pt').", $tanggal"); $row+=2; $sheet->setCellValue("C$row",'A.N. KETUA'); $sheet->setCellValue("F$row","KETUA PROGRAM STUDI"); $sheet->setCellValue("H$row","DOSEN PENGAJAR"); $row+=1; $sheet->setCellValue("C$row",$this->dataReport['nama_jabatan_dpna']); $sheet->setCellValue("F$row",$this->dataReport['nama_ps']); $sheet->setCellValue("H$row",'MATAKULIAH'); $row+=5; $sheet->setCellValue("C$row",$this->dataReport['nama_penandatangan_dpna']); $kaprodi=$objNilai->getKetuaPRODI($this->dataReport['kjur']); $sheet->setCellValue("F$row",$kaprodi['nama_dosen']); $nama_dosen_ttd=$this->dataReport['nama_dosen_pengampu']; $nidn_jabatan_dosen_ttd=$this->dataReport['nama_jabatan_dosen_pengampu']. ' NIDN '.$this->dataReport['nidn_dosen_pengampu']; if ($this->dataReport['idjabatan_dosen_pengajar'] > 0) { $nama_dosen_ttd=$this->dataReport['nama_dosen_pengajar']; $nidn_jabatan_dosen_ttd=$this->dataReport['nama_jabatan_dosen_pengajar']. ' NIDN '.$this->dataReport['nidn_dosen_pengajar']; } $sheet->setCellValue("H$row",$nama_dosen_ttd); $row+=1; $sheet->setCellValue("C$row",strtoupper($this->dataReport['jabfung_penandatangan_dpna']). ' NIDN '.$this->dataReport['nidn_penandatangan_dpna']); $sheet->setCellValue("F$row",$kaprodi['nama_jabatan']. ' NIDN '.$kaprodi['nidn']); $sheet->setCellValue("H$row",$nidn_jabatan_dosen_ttd); $this->printOut("dpna_$kmatkul"); break; case 'pdf' : $rpt=$this->rpt; $rpt->setTitle('Daftar Peserta dan Nilai Akhir'); $rpt->setSubject('Daftar Peserta dan Nilai Akhir'); $rpt->setAutoPageBreak(true,PDF_MARGIN_BOTTOM); $idkelas_mhs=$this->dataReport['idkelas_mhs']; $rpt->AddPage('P','F4'); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'DAFTAR PESERTA DAN NILAI AKHIR',0,0,'C'); if ($idkelas_mhs == 'none'){ $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Matakuliah'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nmatkul']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Kode / SKS'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['kmatkul'].' / '.$this->dataReport['sks']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'P.S / Jenjang'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_ps']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Dosen Pengampu'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_dosen_pengampu']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Semester'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_semester']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'T.A'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$this->dataReport['ta']); $idpenyelenggaraan=$this->dataReport['idpenyelenggaraan']; $itemcount=$this->db->getCountRowsOfTable("v_krsmhs vkm JOIN v_datamhs vdm ON(vdm.nim=vkm.nim) WHERE vkm.idpenyelenggaraan=$idpenyelenggaraan AND vkm.sah=1 AND vkm.batal=0",'vkm.nim'); $pagesize=39; $jumlahpage=ceil($itemcount/$pagesize); $str ="SELECT vdm.nim,vdm.nirm,vdm.nama_mhs,vdm.jk,n.n_kual FROM v_krsmhs vkm JOIN v_datamhs vdm ON(vdm.nim=vkm.nim) LEFT JOIN nilai_matakuliah n ON (n.idkrsmatkul=vkm.idkrsmatkul) WHERE vkm.idpenyelenggaraan=$idpenyelenggaraan AND vkm.sah=1 AND vkm.batal=0 ORDER BY vdm.nama_mhs ASC"; $this->db->setFieldTable(array('nim','nirm','nama_mhs','jk','n_kual')); }else{ $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Matakuliah'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nmatkul']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'Kode / SKS'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['kmatkul'].' / '.$this->dataReport['sks']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Dosen Pengampu'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_dosen_pengampu']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'P.S / Jenjang'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_ps']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Dosen Pengajar'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_dosen_pengajar']); $row+=3; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','B',8); $rpt->Cell(0,$row,'T.A / SMT / Kelas'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(38,$row); $rpt->Cell(0,$row,': '.$this->dataReport['ta'].' '.$this->dataReport['nama_semester'].' '.$this->dataReport['namakelas']); $rpt->SetFont ('helvetica','B',8); $rpt->setXY(105,$row); $rpt->Cell(0,$row,'Hari / Jam'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(130,$row); $rpt->Cell(0,$row,': '.$this->dataReport['hari'].', '.$this->dataReport['jam_masuk'].'-'.$this->dataReport['jam_keluar']); $idkelas=$this->dataReport['idkelas_mhs']; $itemcount=$this->db->getCountRowsOfTable("kelas_mhs_detail kmd JOIN v_krsmhs vkm ON (vkm.idkrsmatkul=kmd.idkrsmatkul) JOIN v_datamhs vdm ON (vkm.nim=vdm.nim) WHERE kmd.idkelas_mhs=$idkelas AND vkm.sah=1 AND vkm.batal=0",'vkm.nim'); $pagesize=39; $jumlahpage=ceil($itemcount/$pagesize); $str ="SELECT vdm.nim,vdm.nirm,vdm.nama_mhs,vdm.jk,n.n_kual FROM kelas_mhs_detail kmd LEFT JOIN nilai_matakuliah n ON (n.idkrsmatkul=kmd.idkrsmatkul) JOIN v_krsmhs vkm ON (vkm.idkrsmatkul=kmd.idkrsmatkul) JOIN v_datamhs vdm ON (vkm.nim=vdm.nim) WHERE kmd.idkelas_mhs=$idkelas AND vkm.sah=1 AND vkm.batal=0 ORDER BY vdm.nama_mhs ASC"; $this->db->setFieldTable(array('nim','nirm','nama_mhs','jk','n_kual')); } $row+=23; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(13, 8, 'NO', 1, 0, 'C'); $rpt->Cell(70, 8, 'NAMA', 1, 0, 'C'); $rpt->Cell(10, 8, 'JK', 1, 0, 'C'); $rpt->Cell(20, 8, 'NIM', 1, 0, 'C'); $rpt->Cell(30, 8, 'NIRM', 1, 0, 'C'); $rpt->Cell(20, 4, 'NILAI', 1, 0, 'C'); $rpt->Cell(30, 8, 'KETERANGAN', 1, 0, 'C'); $row+=4; $rpt->setXY(146,$row); $rpt->Cell(10, 4, 'AM', 1, 0, 'C'); $rpt->Cell(10, 4, 'HM', 1, 0, 'C'); $row+=4; $rpt->setXY(3,$row); $rpt->setFont ('helvetica','',8); for ($i=0;$i < $jumlahpage;$i++) { $offset=$i*$pagesize; $limit=$pagesize; if ($offset+$limit>$itemcount) { $limit=$itemcount-$offset; } $r=$this->db->getRecord("$str LIMIT $offset,$limit",$offset+1); while (list($k,$v)=each ($r) ){ $rpt->setXY(3,$row); $rpt->Cell(13, 5, $v['no'], 1, 0, 'C'); $rpt->Cell(70, 5, $v['nama_mhs'], 1, 0); $rpt->Cell(10, 5, $v['jk'], 1, 0, 'C'); $rpt->Cell(20, 5, $v['nim'], 1, 0, 'C'); $rpt->Cell(30, 5, $v['nirm'], 1, 0, 'C'); $am=$v['n_kual']==''?'-':$objNilai->getAngkaMutu($v['n_kual']); $hm=$v['n_kual']==''?'-':$v['n_kual']; $rpt->Cell(10, 5, $am, 1, 0, 'C'); $rpt->Cell(10, 5, $hm, 1, 0, 'C'); $rpt->Cell(30, 5, '', 1, 0, 'C'); $row+=5; } $row+=5; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $tanggal=$this->tgl->tanggal('l, j F Y'); $rpt->Cell(192, 5, $this->setup->getSettingValue('kota_pt').", $tanggal",0,0,'R'); $row+=5; $rpt->setXY(3,$row); $rpt->Cell(64, 5, 'A.N. KETUA',0,0,'C'); $rpt->Cell(64, 5, "KETUA PROGRAM STUDI",0,0,'C'); $rpt->Cell(64, 5, "DOSEN PENGAJAR",0,0,'C'); $row+=5; $rpt->setXY(3,$row); $rpt->Cell(64, 5, $this->dataReport['nama_jabatan_dpna'],0,0,'C'); $rpt->Cell(64, 5, $this->dataReport['nama_ps'],0,0,'C'); $rpt->Cell(64, 5, 'MATAKULIAH',0,0,'C'); $row+=18; $rpt->setXY(3,$row); $rpt->Cell(64, 5,$this->dataReport['nama_penandatangan_dpna'],0,0,'C'); $rpt->Cell(64, 5,$kaprodi['nama_dosen'],0,0,'C'); $nama_dosen_ttd=$this->dataReport['nama_dosen_pengampu']; $nidn_jabatan_dosen_ttd=$this->dataReport['nama_jabatan_dosen_pengampu']. ' NIDN '.$this->dataReport['nidn_dosen_pengampu']; if ($this->dataReport['idjabatan_dosen_pengajar'] > 0) { $nama_dosen_ttd=$this->dataReport['nama_dosen_pengajar']; $nidn_jabatan_dosen_ttd=$this->dataReport['nama_jabatan_dosen_pengajar']. ' NIDN '.$this->dataReport['nidn_dosen_pengajar']; } $rpt->Cell(64, 5,$nama_dosen_ttd,0,0,'C'); $row+=5; $rpt->setXY(3,$row); $rpt->Cell(64, 5, strtoupper($this->dataReport['jabfung_penandatangan_dpna']). ' NIDN '.$this->dataReport['nidn_penandatangan_dpna'],0,0,'C'); $rpt->Cell(64, 5, $kaprodi['nama_jabatan']. ' NIDN '.$kaprodi['nidn'],0,0,'C'); $rpt->Cell(64, 5,$nidn_jabatan_dosen_ttd,0,0,'C'); if ($i < ($jumlahpage-1)) { $rpt->AddPage('P','F4'); $row=5; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(13, 8, 'NO', 1, 0, 'C'); $rpt->Cell(70, 8, 'NAMA', 1, 0, 'C'); $rpt->Cell(10, 8, 'JK', 1, 0, 'C'); $rpt->Cell(20, 8, 'NIM', 1, 0, 'C'); $rpt->Cell(30, 8, 'NIRM', 1, 0, 'C'); $rpt->Cell(20, 4, 'NILAI', 1, 0, 'C'); $rpt->Cell(30, 8, 'KETERANGAN', 1, 0, 'C'); $row+=4; $rpt->setXY(146,$row); $rpt->Cell(10, 4, 'AM', 1, 0, 'C'); $rpt->Cell(10, 4, 'HM', 1, 0, 'C'); $row+=4; $rpt->setXY(3,$row); $rpt->setFont ('helvetica','',8); } } $this->printOut("dpna_$kmatkul"); break; } $this->setLink($this->dataReport['linkoutput'],"<br/>Daftar Peserta dan Nilai Akhir"); } /** * digunakan untuk memprint Konversi Matakuliah * @param type $objNilai object */ public function printKonversiMatakuliah ($objNilai) { switch ($this->getDriver()) { case 'pdf': $rpt=$this->rpt; $rpt->setTitle('Konversi Nilai'); $rpt->setSubject('Konversi Nilai'); $rpt->AddPage('P', 'LETTER'); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'TABEL KONVERSI',0,0,'C'); $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Nama Lengkap'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama']); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Tempat / Tanggal Lahir'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': - '); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Perguruan Tinggi Asal'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_pt_asal']); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Jenjang / Program Studi (LAMA)'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_ps_asal'].' ('.$this->dataReport['kode_ps_asal'].') '.$this->dataReport['njenjang']); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Jenjang / Program Studi (BARU)'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_ps']); $row+=24; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(10, 5, 'NO', 1, 0, 'C'); $rpt->Cell(70, 5, 'MATAKULIAH ASAL', 1, 0, 'C'); $rpt->Cell(13, 5, 'SKS', 1, 0, 'C'); $rpt->Cell(15, 5, 'KODE', 1, 0, 'C'); $rpt->Cell(80, 5, 'MATAKULIAH', 1, 0, 'C'); $rpt->Cell(10, 5, 'SKS', 1, 0, 'C'); $rpt->Cell(10, 5, 'NH', 1, 0, 'C'); $nilai=$objNilai->getNilaiKonversi($this->dataReport['iddata_konversi'],$this->dataReport['idkur']); $jumlah_sks=0; $jumlah_matkul=0; $row+=5; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',8); $i = 1; while (list($k,$v)=each($nilai)) { $rpt->setXY(3,$row); $rpt->Cell(10, 5, $v['no'], 1, 0, 'C'); $rpt->Cell(70, 5, $v['matkul_asal'], 1, 0, 'L'); $rpt->Cell(13, 5, $v['sks_asal'], 1, 0, 'C'); $rpt->Cell(15, 5, $objNilai->getKMatkul($v['kmatkul']), 1, 0, 'C'); $rpt->Cell(80, 5, $v['nmatkul'], 1, 0, 'L'); $rpt->Cell(10, 5, $v['sks'], 1, 0, 'C'); $rpt->Cell(10, 5, $v['n_kual'], 1, 0, 'C'); if ($i > 37) { $rpt->AddPage('P', 'LETTER'); $row=6; $i = 1; } if ($v['n_kual'] != '') { $jumlah_sks+=$v['sks']; $jumlah_matkul++; } $row+=5; $i+=1; } $this->printOut("konvesrsi_nilai_$nim"); break; case 'excel2003': case 'excel2007': $this->setHeaderPT('J'); $sheet=$this->rpt->getActiveSheet(); $this->rpt->getDefaultStyle()->getFont()->setName('Arial'); $this->rpt->getDefaultStyle()->getFont()->setSize('9'); $sheet->mergeCells("A7:J7"); $sheet->getRowDimension(7)->setRowHeight(20); $sheet->setCellValue("A7","TABEL KONVERSI"); $styleArray=array( 'font' => array('bold' => true, 'size' => 16), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER) ); $sheet->getStyle("A7:J7")->applyFromArray($styleArray); $sheet->mergeCells('B9:D9'); $sheet->setCellValue('B9','Nama Lengkap :'); $sheet->mergeCells('E9:H9'); $sheet->setCellValue('E9',$this->dataReport['nama']); $sheet->mergeCells('B10:D10'); $sheet->setCellValue('B10','Tempat / Tanggal Lahir :'); $sheet->mergeCells('E10:H10'); $sheet->setCellValue('E10','-'); $sheet->mergeCells('B11:D11'); $sheet->setCellValue('B11','Perguruan Tinggi Asal :'); $sheet->mergeCells('E11:H11'); $sheet->setCellValue('E11',$this->dataReport['nama_pt_asal'].' ('.$this->dataReport['kode_pt_asal'].')'); $sheet->mergeCells('B12:D12'); $sheet->setCellValue('B12','Jenjang / Program Studi (LAMA) :'); $sheet->mergeCells('E12:H12'); $sheet->setCellValue('E12',$this->dataReport['nama_ps_asal'].' ('.$this->dataReport['kode_ps_asal'].') '.$this->dataReport['njenjang']); $sheet->mergeCells('B13:D13'); $sheet->setCellValue('B13','Jenjang / Program Studi (BARU) :'); $sheet->mergeCells('E13:H13'); $sheet->setCellValue('E13',$this->dataReport['nama_ps']); $sheet->getRowDimension(16)->setRowHeight(25); $sheet->getColumnDimension('B')->setWidth(12); $sheet->getColumnDimension('C')->setWidth(40); $sheet->getColumnDimension('G')->setWidth(40); $sheet->getColumnDimension('F')->setWidth(12); $sheet->mergeCells('A15:A16'); $sheet->setCellValue('A15','NO'); $sheet->mergeCells('B15:E15'); $sheet->setCellValue('B15','NILAI PT ASAL '); $sheet->setCellValue('B16','KODE MK'); $sheet->setCellValue('C16','NAMA MK'); $sheet->setCellValue('D16','SKS'); $sheet->setCellValue('E16','NILAI HURUF'); $sheet->mergeCells('F15:J15'); $sheet->setCellValue('F15','KONVERSI NILAI PT BARU (DIAKUI)'); $sheet->setCellValue('F16','KODE MK'); $sheet->setCellValue('G16','NAMA MK'); $sheet->setCellValue('H16','SKS'); $sheet->setCellValue('I16','NILAI HURUF'); $sheet->setCellValue('J16','NILAI ANGKA'); $styleArray=array( 'font' => array('bold' => true), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A15:J16")->applyFromArray($styleArray); $sheet->getStyle("A15:J16")->getAlignment()->setWrapText(true); $nilai=$objNilai->getNilaiKonversi($this->dataReport['iddata_konversi'],$this->dataReport['idkur']); $row=17; $jumlah_sks=0; $jumlah_matkul=0; while (list($k,$v)=each($nilai)) { $sheet->setCellValue("A$row",$v['no']); $sheet->setCellValue("B$row",$v['kmatkul_asal']); $sheet->setCellValue("C$row",$v['matkul_asal']); $sheet->setCellValue("D$row",$v['sks_asal']); $sheet->setCellValue("E$row",$v['n_kual']); $sheet->setCellValue("F$row",$objNilai->getKMatkul($v['kmatkul'])); $sheet->setCellValue("G$row",$v['nmatkul']); $sheet->setCellValue("H$row",$v['sks']); $sheet->setCellValue("I$row",$v['n_kual']); $sheet->setCellValue("J$row",$objNilai->getAngkaMutu($v['n_kual'])); if ($v['n_kual'] != '') { $jumlah_sks+=$v['sks']; $jumlah_matkul++; } $sheet->getRowDimension($row)->setRowHeight(22); $row+=1; } $row-=1; $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A17:J$row")->applyFromArray($styleArray); $sheet->getStyle("A17:J$row")->getAlignment()->setWrapText(true); $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT) ); $sheet->getStyle("C17:C$row")->applyFromArray($styleArray); $sheet->getStyle("G17:G$row")->applyFromArray($styleArray); $row_awal=$row; $row+=2; $sheet->mergeCells("A$row:D$row"); $sheet->setCellValue('A'.$row,'Jumlah Matakuliah yang Terkonversi'); $sheet->setCellValue("E$row",$jumlah_matkul); $row+=1; $sheet->mergeCells("A$row:D$row"); $sheet->setCellValue("A$row",'Jumlah SKS yang Terkonversi'); $sheet->setCellValue("E$row",$jumlah_sks); $row+=4; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",'TANJUNGPINANG, '.$this->tgl->tanggal('j F Y')); $row+=1; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",'KETUA PROGRAM STUDI'); $row+=1; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",$this->dataReport['nama_ps']); $row+=5; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue('F'.$row,$this->dataReport['nama_kaprodi']); $row+=1; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",'NIDN : '.$this->dataReport['nidn_kaprodi']); $this->printOut("konversimatakuliah"); break; } $this->setLink($this->dataReport['linkoutput'],"<br/>Konversi Matakuliah"); } /** * digunakan untuk memprint Konversi Matakuliah * @param type $objNilai object */ public function printRPL ($objNilai) { switch ($this->getDriver()) { case 'pdf': $rpt=$this->rpt; $rpt->setTitle('Konversi Nilai'); $rpt->setSubject('Konversi Nilai'); $rpt->AddPage('P', 'LETTER'); $this->setHeaderPT(); $row=$this->currentRow; $row+=6; $rpt->SetFont ('helvetica','B',12); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'TABEL KONVERSI',0,0,'C'); $row+=6; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Nama Lengkap'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama']); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Tempat / Tanggal Lahir'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': - '); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Perguruan Tinggi Asal'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_pt_asal']); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Jenjang / Program Studi (LAMA)'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_ps_asal'].' ('.$this->dataReport['kode_ps_asal'].') '.$this->dataReport['njenjang']); $row+=3; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(0,$row,'Jenjang / Program Studi (BARU)'); $rpt->SetFont ('helvetica','',8); $rpt->setXY(50,$row); $rpt->Cell(0,$row,': '.$this->dataReport['nama_ps']); $row+=24; $rpt->SetFont ('helvetica','B',8); $rpt->setXY(3,$row); $rpt->Cell(10, 5, 'NO', 1, 0, 'C'); $rpt->Cell(70, 5, 'PENGALAMAN KERJA/KOMPETENSI', 1, 0, 'C'); $rpt->Cell(13, 5, 'SKS', 1, 0, 'C'); $rpt->Cell(15, 5, 'KODE', 1, 0, 'C'); $rpt->Cell(80, 5, 'MATAKULIAH', 1, 0, 'C'); $rpt->Cell(10, 5, 'SKS', 1, 0, 'C'); $rpt->Cell(10, 5, 'NH', 1, 0, 'C'); $nilai=$objNilai->getNilaiKonversi($this->dataReport['iddata_konversi'],$this->dataReport['idkur']); $jumlah_sks=0; $jumlah_matkul=0; $row+=5; $rpt->setXY(3,$row); $rpt->SetFont ('helvetica','',8); $i = 1; while (list($k,$v)=each($nilai)) { $rpt->setXY(3,$row); $rpt->Cell(10, 5, $v['no'], 1, 0, 'C'); $rpt->Cell(70, 5, $v['matkul_asal'], 1, 0, 'L'); $rpt->Cell(13, 5, $v['sks_asal'], 1, 0, 'C'); $rpt->Cell(15, 5, $objNilai->getKMatkul($v['kmatkul']), 1, 0, 'C'); $rpt->Cell(80, 5, $v['nmatkul'], 1, 0, 'L'); $rpt->Cell(10, 5, $v['sks'], 1, 0, 'C'); $rpt->Cell(10, 5, $v['n_kual'], 1, 0, 'C'); if ($i > 37) { $rpt->AddPage('P', 'LETTER'); $row=6; $i = 1; } if ($v['n_kual'] != '') { $jumlah_sks+=$v['sks']; $jumlah_matkul++; } $row+=5; $i+=1; } $this->printOut("konvesrsi_nilai_$nim"); break; case 'excel2003': case 'excel2007': $this->setHeaderPT('J'); $sheet=$this->rpt->getActiveSheet(); $this->rpt->getDefaultStyle()->getFont()->setName('Arial'); $this->rpt->getDefaultStyle()->getFont()->setSize('9'); $sheet->mergeCells("A7:J7"); $sheet->getRowDimension(7)->setRowHeight(20); $sheet->setCellValue("A7","TABEL KONVERSI"); $styleArray=array( 'font' => array('bold' => true, 'size' => 16), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER) ); $sheet->getStyle("A7:J7")->applyFromArray($styleArray); $sheet->mergeCells('B9:D9'); $sheet->setCellValue('B9','Nama Lengkap :'); $sheet->mergeCells('E9:H9'); $sheet->setCellValue('E9',$this->dataReport['nama']); $sheet->mergeCells('B10:D10'); $sheet->setCellValue('B10','Tempat / Tanggal Lahir :'); $sheet->mergeCells('E10:H10'); $sheet->setCellValue('E10','-'); $sheet->mergeCells('B11:D11'); $sheet->setCellValue('B11','Perguruan Tinggi Asal :'); $sheet->mergeCells('E11:H11'); $sheet->setCellValue('E11',$this->dataReport['nama_pt_asal'].' ('.$this->dataReport['kode_pt_asal'].')'); $sheet->mergeCells('B12:D12'); $sheet->setCellValue('B12','Jenjang / Program Studi (LAMA) :'); $sheet->mergeCells('E12:H12'); $sheet->setCellValue('E12',$this->dataReport['nama_ps_asal'].' ('.$this->dataReport['kode_ps_asal'].') '.$this->dataReport['njenjang']); $sheet->mergeCells('B13:D13'); $sheet->setCellValue('B13','Jenjang / Program Studi (BARU) :'); $sheet->mergeCells('E13:H13'); $sheet->setCellValue('E13',$this->dataReport['nama_ps']); $sheet->getRowDimension(16)->setRowHeight(25); $sheet->getColumnDimension('B')->setWidth(12); $sheet->getColumnDimension('C')->setWidth(40); $sheet->getColumnDimension('G')->setWidth(40); $sheet->getColumnDimension('F')->setWidth(12); $sheet->mergeCells('A15:A16'); $sheet->setCellValue('A15','NO'); $sheet->mergeCells('B15:E15'); $sheet->setCellValue('B15','NILAI PT ASAL '); $sheet->setCellValue('B16','KODE'); $sheet->setCellValue('C16','PENGALAMAN KERJA/KOMPETENSI'); $sheet->setCellValue('D16','SKS'); $sheet->setCellValue('E16','NILAI HURUF'); $sheet->mergeCells('F15:J15'); $sheet->setCellValue('F15','KONVERSI NILAI PT BARU (DIAKUI)'); $sheet->setCellValue('F16','KODE MK'); $sheet->setCellValue('G16','NAMA MK'); $sheet->setCellValue('H16','SKS'); $sheet->setCellValue('I16','NILAI HURUF'); $sheet->setCellValue('J16','NILAI ANGKA'); $styleArray=array( 'font' => array('bold' => true), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A15:J16")->applyFromArray($styleArray); $sheet->getStyle("A15:J16")->getAlignment()->setWrapText(true); $nilai=$objNilai->getNilaiKonversi($this->dataReport['iddata_konversi'],$this->dataReport['idkur']); $row=17; $jumlah_sks=0; $jumlah_matkul=0; while (list($k,$v)=each($nilai)) { $sheet->setCellValue("A$row",$v['no']); $sheet->setCellValue("B$row",$v['kmatkul_asal']); $sheet->setCellValue("C$row",$v['matkul_asal']); $sheet->setCellValue("D$row",$v['sks_asal']); $sheet->setCellValue("E$row",$v['n_kual']); $sheet->setCellValue("F$row",$objNilai->getKMatkul($v['kmatkul'])); $sheet->setCellValue("G$row",$v['nmatkul']); $sheet->setCellValue("H$row",$v['sks']); $sheet->setCellValue("I$row",$v['n_kual']); $sheet->setCellValue("J$row",$objNilai->getAngkaMutu($v['n_kual'])); if ($v['n_kual'] != '') { $jumlah_sks+=$v['sks']; $jumlah_matkul++; } $sheet->getRowDimension($row)->setRowHeight(22); $row+=1; } $row-=1; $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A17:J$row")->applyFromArray($styleArray); $sheet->getStyle("A17:J$row")->getAlignment()->setWrapText(true); $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT) ); $sheet->getStyle("C17:C$row")->applyFromArray($styleArray); $sheet->getStyle("G17:G$row")->applyFromArray($styleArray); $row_awal=$row; $row+=2; $sheet->mergeCells("A$row:D$row"); $sheet->setCellValue('A'.$row,'Jumlah Matakuliah yang Terkonversi'); $sheet->setCellValue("E$row",$jumlah_matkul); $row+=1; $sheet->mergeCells("A$row:D$row"); $sheet->setCellValue("A$row",'Jumlah SKS yang Terkonversi'); $sheet->setCellValue("E$row",$jumlah_sks); $row+=4; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",'TANJUNGPINANG, '.$this->tgl->tanggal('j F Y')); $row+=1; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",'KETUA PROGRAM STUDI'); $row+=1; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",$this->dataReport['nama_ps']); $row+=5; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue('F'.$row,$this->dataReport['nama_kaprodi']); $row+=1; $sheet->mergeCells("F$row:I$row"); $sheet->setCellValue("F$row",'NIDN : '.$this->dataReport['nidn_kaprodi']); $this->printOut("konversimatakuliah"); break; } $this->setLink($this->dataReport['linkoutput'],"<br/>Konversi Matakuliah"); } /** * digunakan untuk mencetak daftar peserta kelas mahasiswa untuk mengimport nilai * @return type void */ public function printPesertaImportNilai () { switch ($this->getDriver()) { case 'excel2003': case 'excel2007': $sheet=$this->rpt->getActiveSheet(); $idkelas_mhs=$this->dataReport['idkelas_mhs']; $sheet->setCellValue('A1','ID'); $sheet->setCellValue('B1','NAMA MHS'); $sheet->setCellValue('C1','NIM'); $sheet->setCellValue('D1','PR/QUIZ'); $sheet->setCellValue('E1','TUGAS'); $sheet->setCellValue('F1','UTS'); $sheet->setCellValue('G1','UAS'); $sheet->setCellValue('H1','ABSEN'); $styleArray=array( 'font' => array('bold' => true), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A1:H1")->applyFromArray($styleArray); $sheet->getStyle("A1:H1")->getAlignment()->setWrapText(true); $str = "SELECT kmd.idkrsmatkul,vdm.nim,vdm.nama_mhs FROM kelas_mhs_detail kmd JOIN krsmatkul km ON (kmd.idkrsmatkul=km.idkrsmatkul) JOIN krs k ON (km.idkrs=k.idkrs) JOIN v_datamhs vdm ON (k.nim=vdm.nim) LEFT JOIN nilai_matakuliah nm ON (km.idkrsmatkul=nm.idkrsmatkul) WHERE kmd.idkelas_mhs=$idkelas_mhs AND km.batal=0 AND nm.idkrsmatkul IS NULL ORDER BY vdm.nama_mhs ASC"; $this->db->setFieldTable(array('idkrsmatkul','nim','nama_mhs')); $r=$this->db->getRecord($str); $row_awal=2; $row=2; $sheet->getColumnDimension('A')->setWidth(10); $sheet->getColumnDimension('B')->setWidth(40); $sheet->getColumnDimension('C')->setWidth(15); while (list($k,$v)=each($r)) { $sheet->setCellValue("A$row",$v['idkrsmatkul']); $sheet->setCellValue("B$row",$v['nama_mhs']); $sheet->setCellValueExplicit("C$row",$v['nim'],PHPExcel_Cell_DataType::TYPE_STRING); $row+=1; } $row=$row-1; $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A$row_awal:H$row")->applyFromArray($styleArray); $sheet->getStyle("A$row_awal:H$row")->getAlignment()->setWrapText(true); $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT) ); $sheet->getStyle("B$row_awal:B$row")->applyFromArray($styleArray); $this->printOut('daftarisiannilai_'.$this->dataReport['kmatkul'].'_'.$this->dataReport['nama_kelas']); break; } $this->setLink($this->dataReport['linkoutput'],"Daftar Isian Nilai Mahasiswa"); } /** * digunakan untuk memprint Konversi Matakuliah * @param type $objNilai object */ public function printFormatEvaluasiHasilBelajar ($objNilai) { $idkelas_mhs=$this->dataReport['idkelas_mhs']; switch ($this->getDriver()) { case 'excel2003': case 'excel2007': $this->setHeaderPT('J'); $sheet=$this->rpt->getActiveSheet(); $this->rpt->getDefaultStyle()->getFont()->setName('Arial'); $this->rpt->getDefaultStyle()->getFont()->setSize('9'); $sheet->mergeCells("A7:T7"); $sheet->getRowDimension(7)->setRowHeight(20); $sheet->setCellValue("A7","FORMAT EVALUASI HASIL BELAJAR"); $styleArray=array( 'font' => array('bold' => true, 'size' => 16), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER) ); $sheet->getStyle("A7:T7")->applyFromArray($styleArray); $sheet->mergeCells('E9:F9'); $sheet->setCellValue('E9','Kode Matakuliah'); $sheet->setCellValue('G9',': '.$this->dataReport['kmatkul']); $sheet->mergeCells('E10:F10'); $sheet->setCellValue('E10','Nama Matakuliah'); $sheet->setCellValue('G10',': '.$this->dataReport['nmatkul']); $sheet->mergeCells('E11:F11'); $sheet->setCellValue('E11','SKS'); $sheet->setCellValueExplicit("G11",': '.$this->dataReport['sks'],PHPExcel_Cell_DataType::TYPE_STRING); $sheet->mergeCells('E12:F12'); $sheet->setCellValue('E12','T.A / Semester'); $sheet->setCellValue('G12',': '.$this->dataReport['tahun'].' / '.$this->dataReport['nama_semester']); $sheet->mergeCells('E13:F13'); $sheet->setCellValue('E13','Dosen Pengampu'); $sheet->setCellValue('G13',': '.$this->dataReport['nama_dosen_matakuliah'].' ['.$this->dataReport['nidn_dosen_matakuliah'].') '); $sheet->mergeCells('E14:F14'); $sheet->setCellValue('E14','Dosen Pengajar'); $sheet->setCellValue('G14',': '.$this->dataReport['nama_dosen'].' ['.$this->dataReport['nidn'].') '); $sheet->mergeCells('E15:F15'); $sheet->setCellValue('E15','Kelas'); $sheet->setCellValue('G15',': '.$this->dataReport['namakelas']); $sheet->mergeCells('A17:A18'); $sheet->setCellValue('A17','NO'); $sheet->mergeCells('B17:E18'); $sheet->setCellValue('B17','NAMA'); $sheet->mergeCells('F17:F18'); $sheet->setCellValue('F17','JK'); $sheet->mergeCells('G17:G18'); $sheet->setCellValue('G17','NIM'); $sheet->mergeCells('H17:H18'); $sheet->setCellValue('H17','NIRM'); $sheet->mergeCells('I17:J17'); $sheet->setCellValue('I17','QUIZ ('.$this->dataReport['persen_quiz'].'%)'); $sheet->mergeCells('K17:L17'); $sheet->setCellValue('K17','TUGAS ('.$this->dataReport['persen_tugas'].'%)'); $sheet->mergeCells('M17:N17'); $sheet->setCellValue('M17','UTS ('.$this->dataReport['persen_uts'].'%)'); $sheet->mergeCells('O17:P17'); $sheet->setCellValue('O17','UAS ('.$this->dataReport['persen_uas'].'%)'); $sheet->mergeCells('Q17:R17'); $sheet->setCellValue('Q17','ABSEN ('.$this->dataReport['persen_absen'].'%)'); $sheet->mergeCells('S17:T17'); $sheet->setCellValue('S17','NILAI AKHIR'); $sheet->setCellValue('I18','NA'); $sheet->setCellValue('J18','%'); $sheet->setCellValue('K18','NA'); $sheet->setCellValue('L18','%'); $sheet->setCellValue('M18','NA'); $sheet->setCellValue('N18','%'); $sheet->setCellValue('O18','NA'); $sheet->setCellValue('P18','%'); $sheet->setCellValue('Q18','NA'); $sheet->setCellValue('R18','%'); $sheet->setCellValue('S18','AM'); $sheet->setCellValue('T18','HM'); $sheet->getColumnDimension('A')->setWidth(10); $sheet->getColumnDimension('H')->setWidth(17); $sheet->getColumnDimension('I')->setWidth(6); $sheet->getColumnDimension('J')->setWidth(6); $sheet->getColumnDimension('K')->setWidth(6); $sheet->getColumnDimension('L')->setWidth(6); $sheet->getColumnDimension('M')->setWidth(6); $sheet->getColumnDimension('N')->setWidth(6); $sheet->getColumnDimension('O')->setWidth(6); $sheet->getColumnDimension('P')->setWidth(6); $sheet->getColumnDimension('Q')->setWidth(6); $sheet->getColumnDimension('R')->setWidth(6); $sheet->getColumnDimension('S')->setWidth(8); $sheet->getColumnDimension('T')->setWidth(8); $styleArray=array( 'font' => array('bold' => true), 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A17:T18")->applyFromArray($styleArray); $sheet->getStyle("A17:T18")->getAlignment()->setWrapText(true); $str = "SELECT vkm.idkrsmatkul,vdm.nim,vdm.nirm,vdm.nama_mhs,vdm.jk,n.persentase_quiz, n.persentase_tugas, n.persentase_uts, n.persentase_uas, n.persentase_absen, n.nilai_quiz, n.nilai_tugas, n.nilai_uts, n.nilai_uas, n.nilai_absen, n.n_kuan,n.n_kual FROM kelas_mhs_detail kmd LEFT JOIN nilai_matakuliah n ON (n.idkrsmatkul=kmd.idkrsmatkul) JOIN v_krsmhs vkm ON (vkm.idkrsmatkul=kmd.idkrsmatkul) JOIN v_datamhs vdm ON (vkm.nim=vdm.nim) WHERE kmd.idkelas_mhs=$idkelas_mhs AND vkm.sah=1 AND vkm.batal=0 ORDER BY vdm.nama_mhs ASC"; $this->db->setFieldTable(array('idkrsmatkul','nim','nirm','nama_mhs','jk','persentase_quiz', 'persentase_tugas', 'persentase_uts', 'persentase_uas', 'persentase_absen', 'nilai_quiz', 'nilai_tugas', 'nilai_uts', 'nilai_uas', 'nilai_absen','n_kuan','n_kual')); $r=$this->db->getRecord($str); $row_awal=19; $row=19; while (list($k,$v)=each($r)) { $sheet->setCellValue("A$row",$v['no']); $sheet->mergeCells("B$row:E$row"); $sheet->setCellValue("B$row",$v['nama_mhs']); $sheet->setCellValue("F$row",$v['jk']); $sheet->setCellValueExplicit("G$row",$v['nim'],PHPExcel_Cell_DataType::TYPE_STRING); $sheet->setCellValueExplicit("H$row",$v['nirm'],PHPExcel_Cell_DataType::TYPE_STRING); $sheet->setCellValue("I$row",$v['nilai_quiz']); $sheet->setCellValue("J$row",($v['persentase_quiz'] > 0 || $v['nilai_quiz']!='') ? $v['persentase_quiz']*$v['nilai_quiz']:''); $sheet->setCellValue("K$row",$v['nilai_tugas']); $sheet->setCellValue("L$row",($v['persentase_tugas'] > 0 || $v['nilai_tugas']!='') ? $v['persentase_tugas']*$v['nilai_tugas']:''); $sheet->setCellValue("M$row",$v['nilai_uts']); $sheet->setCellValue("N$row",($v['persentase_uts'] > 0 || $v['nilai_uts']!='') ? $v['persentase_uts']*$v['nilai_uts']:''); $sheet->setCellValue("O$row",$v['nilai_uas']); $sheet->setCellValue("P$row",($v['persentase_uas'] > 0 || $v['nilai_uas']!='') ? $v['persentase_uas']*$v['nilai_uas'] :''); $sheet->setCellValue("Q$row",$v['nilai_absen']); $sheet->setCellValue("R$row",($v['persentase_absen'] > 0 || $v['nilai_absen']!='') ? $v['persentase_absen']*$v['nilai_absen'] :''); $sheet->setCellValue("S$row",$v['n_kuan']); $sheet->setCellValue("T$row",$v['n_kual']); $row+=1; } $row=$row-1; $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)) ); $sheet->getStyle("A$row_awal:T$row")->applyFromArray($styleArray); $sheet->getStyle("A$row_awal:T$row")->getAlignment()->setWrapText(true); $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT) ); $sheet->getStyle("B$row_awal:B$row")->applyFromArray($styleArray); $row+=3; $row_awaL=$row; $sheet->setCellValue("B$row",'Nilai Angka (NA)'); $sheet->setCellValue("D$row",'Huruf Mutu (HM)'); $sheet->setCellValue("F$row",'Angka Mutu (AM)'); $sheet->setCellValue("N$row",$this->setup->getSettingValue('kota_pt').', '.$this->tgl->tanggal('d F Y')); $row+=1; $sheet->setCellValue("B$row",'85-100'); $sheet->setCellValue("D$row",'A'); $sheet->setCellValue("F$row",'4'); $sheet->setCellValue("N$row",'Dosen Matakuliah'); $row+=1; $sheet->setCellValue("B$row",'70-84'); $sheet->setCellValue("D$row",'B'); $sheet->setCellValue("F$row",'3'); $row+=1; $sheet->setCellValue("B$row",'55-69'); $sheet->setCellValue("D$row",'C'); $sheet->setCellValue("F$row",'2'); $row+=1; $sheet->setCellValue("B$row",'40-54'); $sheet->setCellValue("D$row",'D'); $sheet->setCellValue("F$row",'1'); $row+=1; $sheet->setCellValue("B$row",'0-39'); $sheet->setCellValue("D$row",'E'); $sheet->setCellValue("F$row",'0'); $sheet->setCellValue("N$row",$this->dataReport['nama_dosen']); $styleArray=array( 'alignment' => array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT) ); $sheet->getStyle("F$row_awal:F$row")->applyFromArray($styleArray); $this->printOut('formatevaluasihasilbelajar'); break; } $this->setLink($this->dataReport['linkoutput'],"Format Evaluasi Hasil Belajar"); } }
mit
uhef/Oskari-Routing
service-wfs/src/main/java/fi/nls/oskari/wfs/util/XMLHelper.java
4134
package fi.nls.oskari.wfs.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.InputStream; import java.io.UnsupportedEncodingException; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import fi.nls.oskari.log.LogFactory; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.xsd.XSDSchema; import org.eclipse.xsd.util.XSDResourceImpl; import org.w3c.dom.Node; import fi.nls.oskari.log.Logger; /** * XML helper methods */ public class XMLHelper { private static final Logger log = LogFactory.getLogger(XMLHelper.class); /** * Creates XML builder for reading XML * * @param xml * @return builder */ public static StAXOMBuilder createBuilder(String xml) { StringReader reader = new StringReader(xml); return createBuilder(reader); } /** * Creates XML builder for reading XML * * @param reader * @return builder */ public static StAXOMBuilder createBuilder(Reader reader) { XMLStreamReader xmlStreamReader = null; StAXOMBuilder stAXOMBuilder = null; try { xmlStreamReader = XMLInputFactory.newInstance() .createXMLStreamReader(reader); } catch (XMLStreamException e) { log.error(e, "XML Stream error"); } catch (FactoryConfigurationError e) { log.error(e, "XMLInputFactory configuration error"); } if (xmlStreamReader != null) { stAXOMBuilder = new StAXOMBuilder(xmlStreamReader); } return stAXOMBuilder; } /** * Transforms from XSDSchema to String * * @param schema * @return xsd */ public static String XSDSchemaToString(XSDSchema schema) { Node el = schema.getElement(); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = transFactory.newTransformer(); } catch (TransformerConfigurationException e) { log.error(e, "Transformer couldn't be configured"); } StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.INDENT, "no"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); try { transformer.transform(new DOMSource(el), new StreamResult(buffer)); } catch (TransformerException e) { log.error(e, "Transform error"); } buffer.flush(); return buffer.toString(); } /** * Transforms from String to XSDSchema * * @param str * @return xsd */ public static XSDSchema StringToXSDSchema(String str) { InputStream stream = null; try { if(str != null) { stream = new ByteArrayInputStream(str.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { log.error(e, "Encoding error"); } catch (Exception e) { log.error(e, "Stream error"); } if(stream != null) { return InputStreamToXSDSchema(stream); } return null; } /** * Transforms from InputStream to XSDSchema * * @param stream * @return xsd */ public static XSDSchema InputStreamToXSDSchema(InputStream stream) { ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xsd", new org.eclipse.xsd.util.XSDResourceFactoryImpl()); XSDResourceImpl xsdMainResource = (XSDResourceImpl) resourceSet.createResource(URI.createURI(".xsd")); try { if(stream != null) { xsdMainResource.load(stream, resourceSet.getLoadOptions()); } } catch (IOException e) { log.error(e, "IO error"); } return xsdMainResource.getSchema(); } }
mit
JoseLuisPucChan/Proyecto4Cuatrimestre
Prácticas/PracticasCuartoParcial/Practica1Postales/Practica1Postales/Properties/AssemblyInfo.cs
1552
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("Practica1Postales")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Practica1Postales")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("14b1427d-1e8a-4b26-b10e-d79573f8928b")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
salespaulo/nota-fiscal-api
src/main/resources/static/app.js
296
'use strict'; angular.module('app', [ 'ngRoute', 'app.home', 'app.mercadoria', 'app.notafiscal' ]) .config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $locationProvider.hashPrefix('!'); $routeProvider.otherwise({redirectTo: '/home'}); }]);
mit
Geodan/gost
configuration/constants.go
368
package configuration const ( // ServerVersion specifies the current GOST Server version ServerVersion string = "v0.5" // SensorThingsAPIVersion specifies the supported SensorThings API version SensorThingsAPIVersion string = "v1.0" // DefaultMaxEntries is used when config maxEntries is empty or $top exceeds this default value DefaultMaxEntries int = 200 )
mit
sagamors/Perspex
Windows/Perspex.Direct2D1/Media/StreamGeometryImpl.cs
2485
// ----------------------------------------------------------------------- // <copyright file="StreamGeometryImpl.cs" company="Steven Kirk"> // Copyright 2015 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Direct2D1.Media { using Perspex.Media; using Perspex.Platform; using SharpDX.Direct2D1; using Splat; using D2DGeometry = SharpDX.Direct2D1.Geometry; /// <summary> /// A Direct2D implementation of a <see cref="StreamGeometry"/>. /// </summary> public class StreamGeometryImpl : GeometryImpl, IStreamGeometryImpl { private PathGeometry path; /// <summary> /// Initializes a new instance of the <see cref="StreamGeometryImpl"/> class. /// </summary> public StreamGeometryImpl() { Factory factory = Locator.Current.GetService<Factory>(); this.path = new PathGeometry(factory); } /// <summary> /// Initializes a new instance of the <see cref="StreamGeometryImpl"/> class. /// </summary> /// <param name="geometry">An existing Direct2D <see cref="PathGeometry"/>.</param> protected StreamGeometryImpl(PathGeometry geometry) { this.path = geometry; } /// <inheritdoc/> public override Rect Bounds { get { return this.path.GetBounds().ToPerspex(); } } /// <inheritdoc/> public override D2DGeometry DefiningGeometry { get { return this.path; } } /// <summary> /// Clones the geometry. /// </summary> /// <returns>A cloned geometry.</returns> public IStreamGeometryImpl Clone() { Factory factory = Locator.Current.GetService<Factory>(); var result = new PathGeometry(factory); var sink = result.Open(); this.path.Stream(sink); sink.Close(); return new StreamGeometryImpl(result); } /// <summary> /// Opens the geometry to start defining it. /// </summary> /// <returns> /// A <see cref="StreamGeometryContext"/> which can be used to define the geometry. /// </returns> public IStreamGeometryContextImpl Open() { return new StreamGeometryContextImpl(this.path.Open()); } } }
mit
ashimusmani/trinity-core
src/main/java/org/zigmoi/trinity/core/controller/DemoController.java
2083
package org.zigmoi.trinity.core.controller; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * Handles requests for the Demo JSP home page, offers connection testing, GET and POST demos. */ @Controller public class DemoController { /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate ); return "home"; } @RequestMapping(value = "/testconnection", method = RequestMethod.GET) public @ResponseBody String testConnection() { return "TRINITY UP & RUNNING!"; } @RequestMapping(value = "/postrequestdemo", method = RequestMethod.POST) public @ResponseBody String postRequestDemo(@RequestBody TestData inp) { // To process post data you need create a java class to convert that json object to java object. // Code processing the input parameters // request data should be like this when passed in javascript var data ={inp1:"ashim",inp2:"usmani"}; return "POST data recieved, Mirrored Data follows:"+ inp.getInp1()+ inp.getInp2(); } @RequestMapping(value = "/getrequestdemo", method = RequestMethod.GET) public @ResponseBody String getRequestDemo(@RequestParam(value="inp1") String input1,@RequestParam(value="inp2") String input2) { //@RequestParam is for values passed in query string. return "GET data recieved, Mirrored Data follows:"+ input1+input2; } }
mit
drongo-framework/drongo-nest
nest/parsers/body/body.py
893
from .multipart import MultipartParser from .raw import RawParser from .urlencoded import UrlEncodedParser __all__ = ['BodyParser'] class BodyParser(object): __slots__ = ['_buffer', '_parser', 'complete'] RETAIN_KEYS = set(['CONTENT_TYPE', 'CONTENT_LENGTH']) def __init__(self): self._buffer = b'' self.complete = False self._parser = None def feed(self, data, env): if self._parser is None: if env['CONTENT_TYPE'].startswith( 'application/x-www-form-urlencoded'): self._parser = UrlEncodedParser() elif env['CONTENT_TYPE'].startswith('multipart/form-data'): self._parser = MultipartParser() else: self._parser = RawParser() res = self._parser.feed(data, env) self.complete = self._parser.complete return res
mit
vienbk91/fuelphp17
fuel/core/tests/database/query/builder/insert.php
442
<?php /** * Part of the Fuel framework. * * @package Fuel * @version 1.6 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2013 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Core; /** * Database_Query_Builder_Insert class tests * * @group Core * @group Database */ class Test_Database_Query_Builder_Insert extends TestCase { public function test_foo() { } }
mit
longde123/MultiversePlatform
server/src/multiverse/server/engine/WorldFileLoader.java
18338
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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 multiverse.server.engine; import javax.xml.parsers.*; import org.xml.sax.SAXException; import org.w3c.dom.*; import java.io.IOException; import java.io.File; import java.util.List; import java.util.LinkedList; import multiverse.server.util.Log; import multiverse.server.util.XMLHelper; import multiverse.server.objects.*; import multiverse.server.math.*; import multiverse.server.pathing.*; import multiverse.server.engine.TerrainConfig; import multiverse.msgsys.Message; import multiverse.server.plugins.WorldManagerClient; public class WorldFileLoader { public WorldFileLoader(Instance instance, String worldFileName, WorldLoaderOverride override) { this.instance = instance; this.worldFileName = worldFileName; this.worldLoaderOverride = override; } public void setWorldLoaderOverride(WorldLoaderOverride override) { worldLoaderOverride = override; } public WorldLoaderOverride getWorldLoaderOverride() { return worldLoaderOverride; } public boolean load() { if (! parse()) return false; return generate(); } public boolean parse() { try { DocumentBuilder builder = XMLHelper.makeDocBuilder(); File xmlFile = new File(worldFileName); worldFileBasePath = xmlFile.getParent(); worldDoc = builder.parse(xmlFile); } catch (IOException e) { Log.exception("WorldFileLoader.parse("+worldFileName+")", e); return false; } catch (SAXException e) { Log.exception("WorldFileLoader.parse("+worldFileName+")", e); return false; } return true; } public boolean generate() { Node worldNode = XMLHelper.getMatchingChild(worldDoc, "World"); if (worldNode == null) { Log.error("No <World> node in file "+worldFileName); return false; } String worldName = XMLHelper.getAttribute(worldNode, "Name"); if (worldName == null) { Log.error("No world name in file "+worldFileName); return false; } if (Log.loggingDebug) Log.debug("world name=" + worldName + " (file "+worldFileName+")"); String fileVersion = XMLHelper.getAttribute(worldNode, "Version"); if (fileVersion == null) { Log.error("No world file version"); return false; } if (Log.loggingDebug) Log.debug("world file version=" + fileVersion); if (! fileVersion.equals("2")) { Log.error("Unsupported world file version in file " + worldFileName); return false; } // get the skybox Node skyboxNode = XMLHelper.getMatchingChild(worldNode, "Skybox"); if (skyboxNode == null) { Log.debug("No <Skybox> node in file " + worldFileName); } else { String skybox = XMLHelper.getAttribute(skyboxNode, "Name"); if (Log.loggingDebug) Log.debug("Global skybox=" + skybox); instance.setGlobalSkybox(skybox); } // get global fog Node globalFogNode = XMLHelper.getMatchingChild(worldNode, "GlobalFog"); if (globalFogNode != null) { String near = XMLHelper.getAttribute(globalFogNode, "Near"); String far = XMLHelper.getAttribute(globalFogNode, "Far"); Color fogColor = getColor( XMLHelper.getMatchingChild(globalFogNode, "Color")); Fog fog = new Fog("global fog"); fog.setStart((int)Float.parseFloat(near)); fog.setEnd((int)Float.parseFloat(far)); fog.setColor(fogColor); instance.setGlobalFog(fog); if (Log.loggingDebug) Log.debug("Global fog: " + fog); } // get global ambient light Node globalAmbientLightNode = XMLHelper.getMatchingChild(worldNode, "GlobalAmbientLight"); if (globalAmbientLightNode != null) { Color lightColor = getColor( XMLHelper.getMatchingChild(globalAmbientLightNode,"Color")); instance.setGlobalAmbientLight(lightColor); if (Log.loggingDebug) Log.debug("Global ambient light: " + lightColor); } // get global directional light Node globalDirectionalLightNode = XMLHelper.getMatchingChild(worldNode, "GlobalDirectionalLight"); if (globalDirectionalLightNode != null) { Color diffuseColor = getColor(XMLHelper.getMatchingChild(globalDirectionalLightNode, "Diffuse")); Color specularColor = getColor(XMLHelper.getMatchingChild(globalDirectionalLightNode, "Specular")); MVVector lightDir = getVector(XMLHelper.getMatchingChild(globalDirectionalLightNode, "Direction")); LightData lightData = new LightData(); lightData.setName("globalDirLight"); lightData.setDiffuse(diffuseColor); lightData.setSpecular(specularColor); lightData.setAttenuationRange(1000000); lightData.setAttenuationConstant(1); Quaternion q = MVVector.UnitZ.getRotationTo(lightDir); if (q == null) { if (Log.loggingDebug) Log.debug("global light orient is near inverse, dir=" + lightDir); q = new Quaternion(0,1,0,0); } lightData.setOrientation(q); instance.setGlobalDirectionalLight(lightData); if (Log.loggingDebug) Log.debug("Global directional light: " + lightData); } Node pathObjectTypesNode = XMLHelper.getMatchingChild(worldNode, "PathObjectTypes"); if (pathObjectTypesNode != null) { List<Node> pathObjectTypeNodes = XMLHelper.getMatchingChildren( pathObjectTypesNode, "PathObjectType"); for (Node pathObjectTypeNode : pathObjectTypeNodes) { String potName = XMLHelper.getAttribute(pathObjectTypeNode, "name"); float potHeight = Float.parseFloat(XMLHelper.getAttribute(pathObjectTypeNode, "height")); float potWidth = Float.parseFloat(XMLHelper.getAttribute(pathObjectTypeNode, "width")); float potMaxClimbSlope = Float.parseFloat(XMLHelper.getAttribute(pathObjectTypeNode, "maxClimbSlope")); instance.getPathInfo().getTypeDictionary().put( potName, new PathObjectType(potName, potHeight, potWidth, potMaxClimbSlope)); if (Log.loggingDebug) Log.debug("Path object type name=" + potName); } } // get the ocean Node oceanNode = XMLHelper.getMatchingChild(worldNode, "Ocean"); if (oceanNode != null) { OceanData oceanData = new OceanData(); String displayOcean = XMLHelper.getAttribute(oceanNode, "DisplayOcean"); oceanData.displayOcean = displayOcean.equals("True") ? Boolean.TRUE : Boolean.FALSE; String useParams = XMLHelper.getAttribute(oceanNode, "UseParams"); if (useParams != null) { oceanData.useParams = useParams.equals("True") ? Boolean.TRUE : Boolean.FALSE; } String waveHeight = XMLHelper.getAttribute(oceanNode, "WaveHeight"); if (waveHeight != null) { oceanData.waveHeight = Float.parseFloat(waveHeight); } String seaLevel = XMLHelper.getAttribute(oceanNode, "SeaLevel"); if (seaLevel != null) { oceanData.seaLevel = Float.parseFloat(seaLevel); } String bumpScale = XMLHelper.getAttribute(oceanNode, "BumpScale"); if (bumpScale != null) { oceanData.bumpScale = Float.parseFloat(bumpScale); } String bumpSpeedX = XMLHelper.getAttribute(oceanNode, "BumpSpeedX"); if (bumpSpeedX != null) { oceanData.bumpSpeedX = Float.parseFloat(bumpSpeedX); } String bumpSpeedZ = XMLHelper.getAttribute(oceanNode, "BumpSpeedZ"); if (bumpSpeedZ != null) { oceanData.bumpSpeedZ = Float.parseFloat(bumpSpeedZ); } String textureScaleX = XMLHelper.getAttribute(oceanNode, "TextureScaleX"); if (textureScaleX != null) { oceanData.textureScaleX = Float.parseFloat(textureScaleX); } String textureScaleZ = XMLHelper.getAttribute(oceanNode, "TextureScaleZ"); if (textureScaleZ != null) { oceanData.textureScaleZ = Float.parseFloat(textureScaleZ); } Node deepColorNode = XMLHelper.getMatchingChild(oceanNode, "DeepColor"); if (deepColorNode != null) { oceanData.deepColor = getColor(deepColorNode); } Node shallowColorNode = XMLHelper.getMatchingChild(oceanNode, "ShallowColor"); if (shallowColorNode != null) { oceanData.shallowColor = getColor(shallowColorNode); } instance.setOceanData(oceanData); if (Log.loggingDebug) Log.debug("Ocean: " + oceanData); } // Terrain configuration. Only get from the world file if the // instance doesn't already have terrain config. Terrain config // can be set by instance template or property. TerrainConfig terrainConfig = instance.getTerrainConfig(); if (terrainConfig != null && Log.loggingDebug) Log.debug("Terrain: " + terrainConfig); if (terrainConfig == null) { Node terrainNode = XMLHelper.getMatchingChild(worldNode, "Terrain"); if (terrainNode != null) { String terrainXML = XMLHelper.toXML(terrainNode); if (Log.loggingDebug) Log.debug("Terrain: xmlsize=" + terrainXML.length()); // add in the terrain display Node terrainDisplay = XMLHelper.getMatchingChild(worldNode, "TerrainDisplay"); if (terrainDisplay != null) { String terrainDisplayXML = XMLHelper.toXML(terrainDisplay); if (Log.loggingDebug) Log.debug("TerrainDisplay: " + terrainDisplayXML); terrainXML += terrainDisplayXML; } terrainConfig = new TerrainConfig(); terrainConfig.setConfigType(TerrainConfig.configTypeXMLSTRING); terrainConfig.setConfigData(terrainXML); instance.setTerrainConfig(terrainConfig); if (Log.loggingDebug) Log.debug("terrain has been set:" + terrainConfig); } else { Log.debug("No terrain in file"); } } // read in filenames for world collections if (! processWorldCollections(worldNode)) return false; // send out global region, including the // new road region info Message msg = new WorldManagerClient.NewRegionMessage( instance.getOid(), instance.getGlobalRegion()); Engine.getAgent().sendBroadcast(msg); return true; } protected boolean processWorldCollections(Node node) { List<Node> worldCollections = XMLHelper.getMatchingChildren(node, "WorldCollection"); for (Node worldCollectionNode : worldCollections) { String colFilename = XMLHelper.getAttribute(worldCollectionNode, "Filename"); String fullFile = worldFileBasePath + File.separator + colFilename; if (Log.loggingDebug) Log.debug("Loading world collection " + fullFile); WorldCollectionLoader collectionLoader = new WorldCollectionLoader(instance, fullFile, worldLoaderOverride); if (! collectionLoader.load()) return false; } return true; } // Parses the CVPolygons or TerrainPolygons phrase, depending on kind protected static List<PathPolygon> processPathPolygons(String introducer, Node parentNode) { Node polyContainerNode = XMLHelper.getMatchingChild(parentNode, introducer); List<Node> polyNodes = XMLHelper.getMatchingChildren(polyContainerNode, "PathPolygon"); LinkedList<PathPolygon> polys = new LinkedList<PathPolygon>(); if (polyNodes == null) return polys; for (Node polyNode : polyNodes) { int index = (int)Float.parseFloat(XMLHelper.getAttribute(polyNode, "index")); String stringKind = XMLHelper.getAttribute(polyNode, "kind"); byte polygonKind = PathPolygon.parsePolygonKind(stringKind); List<Node> cornerNodes = XMLHelper.getMatchingChildren(polyNode, "Corner"); assert cornerNodes.size() >= 3; LinkedList<MVVector> corners = new LinkedList<MVVector>(); for (Node corner : cornerNodes) corners.add(new MVVector(getPoint(corner))); polys.add(new PathPolygon(index, polygonKind, corners)); } return polys; } // Parses the PathArcs phrase protected static List<PathArc> processPathArcs(String introducer, Node parentNode) { Node arcContainerNode = XMLHelper.getMatchingChild(parentNode, introducer); List<Node> arcNodes = XMLHelper.getMatchingChildren(arcContainerNode, "PathArc"); LinkedList<PathArc> arcs = new LinkedList<PathArc>(); if (arcNodes == null) return arcs; for (Node arcNode : arcNodes) { byte arcKind = PathArc.parseArcKind(XMLHelper.getAttribute(arcNode, "kind")); int poly1Index = (int)Float.parseFloat(XMLHelper.getAttribute(arcNode, "poly1Index")); int poly2Index = (int)Float.parseFloat(XMLHelper.getAttribute(arcNode, "poly2Index")); PathEdge edge = processPathEdge(arcNode); arcs.add(new PathArc(arcKind, poly1Index, poly2Index, edge)); } return arcs; } // Parses a PathEdge protected static PathEdge processPathEdge(Node parentNode) { Node edgeNode = XMLHelper.getMatchingChild(parentNode, "PathEdge"); return new PathEdge(new MVVector(getPoint(XMLHelper.getMatchingChild(edgeNode, "Start"))), new MVVector(getPoint(XMLHelper.getMatchingChild(edgeNode, "End")))); } public static Color getColor(Node colorNode) { String redS = XMLHelper.getAttribute(colorNode, "R"); String greenS = XMLHelper.getAttribute(colorNode, "G"); String blueS = XMLHelper.getAttribute(colorNode, "B"); Color color = new Color(); color.setRed((int) (Float.parseFloat(redS) * 255)); color.setGreen((int) (Float.parseFloat(greenS) * 255)); color.setBlue((int) (Float.parseFloat(blueS) * 255)); return color; } public static MVVector getVector(Node xyzNode) { String posX = XMLHelper.getAttribute(xyzNode, "x"); String posY = XMLHelper.getAttribute(xyzNode, "y"); String posZ = XMLHelper.getAttribute(xyzNode, "z"); float x = Float.parseFloat(posX); float y = Float.parseFloat(posY); float z = Float.parseFloat(posZ); return new MVVector(x, y, z); } // pass in a node that has x y z attributes, returns a point public static Point getPoint(Node xyzNode) { String posX = XMLHelper.getAttribute(xyzNode, "x"); String posY = XMLHelper.getAttribute(xyzNode, "y"); String posZ = XMLHelper.getAttribute(xyzNode, "z"); int x = (int) Math.round(Double.parseDouble(posX)); int y = (int) Math.round(Double.parseDouble(posY)); int z = (int) Math.round(Double.parseDouble(posZ)); return new Point(x, y, z); } public static Quaternion getQuaternion(Node quatNode) { String x = XMLHelper.getAttribute(quatNode, "x"); String y = XMLHelper.getAttribute(quatNode, "y"); String z = XMLHelper.getAttribute(quatNode, "z"); String w = XMLHelper.getAttribute(quatNode, "w"); return new Quaternion( Float.parseFloat(x), Float.parseFloat(y), Float.parseFloat(z), Float.parseFloat(w)); } protected Instance instance; protected String worldFileName; protected String worldFileBasePath; protected WorldLoaderOverride worldLoaderOverride; protected Document worldDoc; }
mit
ebemunk/blog
projects/lastwords/viz/legend.ts
4837
import { create, quantize, interpolate, interpolateRound, range, quantile, format, scaleLinear, scaleBand, axisBottom, } from 'd3' export function DOMcanvas(width, height) { var canvas = document.createElement('canvas') canvas.width = width canvas.height = height return canvas } export function ramp(color, n = 256) { const canvas = DOMcanvas(n, 1) const context = canvas.getContext('2d') for (let i = 0; i < n; ++i) { context.fillStyle = color(i / (n - 1)) context.fillRect(i, 0, 1, 1) } return canvas } export function legend({ color, title, tickSize = 6, width = 320, height = 44 + tickSize, marginTop = 18, marginRight = 0, marginBottom = 16 + tickSize, marginLeft = 0, ticks = width / 64, tickFormat, tickValues, returnG = false, } = {}) { const svg = returnG ? create('svg:g') : create('svg') .attr('width', width) .attr('height', height) .attr('viewBox', [0, 0, width, height]) .style('overflow', 'visible') let tickAdjust = g => g.selectAll('.tick line').attr('y1', marginTop + marginBottom - height) let x // Continuous if (color.interpolate) { const n = Math.min(color.domain().length, color.range().length) x = color .copy() .rangeRound(quantize(interpolate(marginLeft, width - marginRight), n)) svg .append('image') .attr('x', marginLeft) .attr('y', marginTop) .attr('width', width - marginLeft - marginRight) .attr('height', height - marginTop - marginBottom) .attr('preserveAspectRatio', 'none') .attr( 'xlink:href', ramp(color.copy().domain(quantize(interpolate(0, 1), n))).toDataURL() ) } // Sequential else if (color.interpolator) { x = Object.assign( color .copy() .interpolator(interpolateRound(marginLeft, width - marginRight)), { range() { return [marginLeft, width - marginRight] }, } ) svg .append('image') .attr('x', marginLeft) .attr('y', marginTop) .attr('width', width - marginLeft - marginRight) .attr('height', height - marginTop - marginBottom) .attr('preserveAspectRatio', 'none') .attr('xlink:href', ramp(color.interpolator()).toDataURL()) // scaleSequentialQuantile doesn’t implement ticks or tickFormat. if (!x.ticks) { if (tickValues === undefined) { const n = Math.round(ticks + 1) tickValues = range(n).map(i => quantile(color.domain(), i / (n - 1))) } if (typeof tickFormat !== 'function') { tickFormat = format(tickFormat === undefined ? ',f' : tickFormat) } } } // Threshold else if (color.invertExtent) { const thresholds = color.thresholds ? color.thresholds() // scaleQuantize : color.quantiles ? color.quantiles() // scaleQuantile : color.domain() // scaleThreshold const thresholdFormat = tickFormat === undefined ? d => d : typeof tickFormat === 'string' ? format(tickFormat) : tickFormat x = scaleLinear() .domain([-1, color.range().length - 1]) .rangeRound([marginLeft, width - marginRight]) svg .append('g') .selectAll('rect') .data(color.range()) .join('rect') .attr('x', (d, i) => x(i - 1)) .attr('y', marginTop) .attr('width', (d, i) => x(i) - x(i - 1)) .attr('height', height - marginTop - marginBottom) .attr('fill', d => d as string) tickValues = range(thresholds.length) tickFormat = i => thresholdFormat(thresholds[i], i) } // Ordinal else { x = scaleBand() .domain(color.domain()) .rangeRound([marginLeft, width - marginRight]) svg .append('g') .selectAll('rect') .data(color.domain()) .join('rect') .attr('x', x) .attr('y', marginTop) .attr('width', Math.max(0, x.bandwidth() - 1)) .attr('height', height - marginTop - marginBottom) .attr('fill', color) tickAdjust = () => {} } svg .append('g') .attr('transform', `translate(0,${height - marginBottom})`) .call( axisBottom(x) .ticks(ticks, typeof tickFormat === 'string' ? tickFormat : undefined) .tickFormat(typeof tickFormat === 'function' ? tickFormat : undefined) .tickSize(tickSize) .tickValues(tickValues) ) .call(tickAdjust) .call(g => g.select('.domain').remove()) .call(g => g .append('text') .attr('x', marginLeft) .attr('y', marginTop + marginBottom - height - 6) .attr('fill', 'currentColor') .attr('text-anchor', 'start') .attr('font-weight', 'bold') .attr('class', 'title') .text(title) ) return svg.node() }
mit
CGA1123/helpy
config/environments/development.rb
2397
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. #config.i18n.default_locale = :en # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = false config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.default_url_options = { host: Settings.site_url } config.action_mailer.delivery_method = :smtp # config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Disable database query caching # (this will highlight inefficient queries in development) config.middleware.delete 'ActiveRecord::QueryCache' # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Mute asset pipeline log messages config.assets.quiet = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations config.action_view.raise_on_missing_translations = true config.i18n.available_locales = [:en, :es, :de, :fr, :it, :et, :ca, :sv, :hu, :ru, :ja, :hi, 'zh-cn', 'zh-tw', 'pt', :nl, 'tr', 'pt-br', :fa, :fi, :id, :ar, :ko, :ms] config.i18n.default_locale = :en config.i18n.fallbacks = true config.after_initialize do # Bullet Configuration / https://github.com/flyerhzm/bullet Bullet.enable = true Bullet.bullet_logger = true Bullet.add_footer = true end end
mit
ToFuProject/tofu
tofu/spectro/_fit12d_funccostjac.py
25979
# Common import numpy as np import scipy.optimize as scpopt import scipy.sparse as scpsparse from scipy.interpolate import BSpline # Temporary for debugging import matplotlib.pyplot as plt _JAC = 'dense' ########################################################### ########################################################### # # Main function for fit1d # ########################################################### ########################################################### def multigausfit1d_from_dlines_funccostjac( lamb=None, indx=None, dinput=None, dind=None, jac=None, ): if jac is None: jac = _JAC ibckax = dind['bck_amp']['x'][0, :] ibckrx = dind['bck_rate']['x'][0, :] nbck = 1 # ibckax.size + ibckrx.size iax = dind['amp']['x'][0, :] iwx = dind['width']['x'][0, :] ishx = dind['shift']['x'][0, :] idratiox, idshx = None, None if dinput['double'] is not False: c0 = dinput['double'] is True if c0 or dinput['double'].get('dratio') is None: idratiox = dind['dratio']['x'][0, :] if c0 or dinput['double'].get('dshift') is None: idshx = dind['dshift']['x'][0, :] ial = dind['amp']['lines'][0, :] iwl = dind['width']['lines'][0, :] ishl = dind['shift']['lines'][0, :] iaj = dind['amp']['jac'] iwj = dind['width']['jac'] ishj = dind['shift']['jac'] coefsal = dinput['amp']['coefs'] coefswl = dinput['width']['coefs'] coefssl = dinput['shift']['coefs'] offsetal = dinput['amp']['offset'] offsetwl = dinput['width']['offset'] offsetsl = dinput['shift']['offset'] lambrel = lamb - dinput['lambmin_bck'] lambnorm = lamb[..., None]/dinput['lines'][None, ...] xscale = np.full((dind['sizex'],), np.nan) if indx is None: indx = np.ones((dind['sizex'],), dtype=bool) # func_details returns result in same shape as input def func_detail( x, xscale=xscale, indx=indx, lambrel=lambrel, lambnorm=lambnorm, ibckax=ibckax, ibckrx=ibckrx, ial=ial, iwl=iwl, ishl=ishl, idratiox=idratiox, idshx=idshx, nlines=dinput['nlines'], nbck=nbck, coefsal=coefsal[None, :], coefswl=coefswl[None, :], coefssl=coefssl[None, :], offsetal=offsetal[None, :], offsetwl=offsetwl[None, :], offsetsl=offsetsl[None, :], double=dinput['double'], scales=None, indok=None, const=None, ): if indok is None: indok = np.ones(lamb.shape, dtype=bool) shape = tuple(np.r_[indok.sum(), nbck+nlines]) y = np.full(shape, np.nan) xscale[indx] = x*scales[indx] xscale[~indx] = const # Prepare amp = xscale[ial]*coefsal + offsetal wi2 = xscale[iwl]*coefswl + offsetwl shift = xscale[ishl]*coefssl + offsetsl exp = np.exp(-(lambnorm[indok, :] - (1 + shift))**2 / (2*wi2)) if double is not False: # coefssl are line-specific, they do not affect dshift if double is True: dratio = xscale[idratiox] dshift = shift + xscale[idshx] # *coefssl else: dratio = double.get('dratio', xscale[idratiox]) dshift = shift + double.get('dshift', xscale[idshx]) expd = np.exp(-(lambnorm[indok, :] - (1 + dshift))**2 / (2*wi2)) # compute y y[:, :nbck] = ( xscale[ibckax] * np.exp(xscale[ibckrx]*lambrel[indok]) )[:, None] y[:, nbck:] = amp * exp if double is not False: y[:, nbck:] += amp * dratio * expd return y # cost and jacob return flattened results (for least_squares()) def cost( x, xscale=xscale, indx=indx, lambrel=lambrel, lambnorm=lambnorm, ibckax=ibckax, ibckrx=ibckrx, ial=ial, iwl=iwl, ishl=ishl, idratiox=idratiox, idshx=idshx, scales=None, coefsal=coefsal[None, :], coefswl=coefswl[None, :], coefssl=coefssl[None, :], offsetal=offsetal[None, :], offsetwl=offsetwl[None, :], offsetsl=offsetsl[None, :], double=dinput['double'], indok=None, const=None, data=0., ): if indok is None: indok = np.ones(lambrel.shape, dtype=bool) # xscale = x*scales !!! scales ??? !!! TBC xscale[indx] = x*scales[indx] xscale[~indx] = const # make sure iwl is 2D to get all lines at once amp = xscale[ial] * coefsal + offsetal inv_2wi2 = 1./(2.*(xscale[iwl] * coefswl + offsetwl)) shift = xscale[ishl] * coefssl + offsetsl y = ( np.nansum( amp * np.exp(-(lambnorm[indok, :]-(1 + shift))**2 * inv_2wi2), axis=1, ) + xscale[ibckax]*np.exp(xscale[ibckrx]*lambrel[indok]) ) if double is not False: if double is True: dratio = xscale[idratiox] # scales[ishl] or scales[idshx] ? coefssl ? +> no dshift = shift + xscale[idshx] else: dratio = double.get('dratio', xscale[idratiox]) dshift = shift + double.get('dshift', xscale[idshx]) y += np.nansum((amp * dratio * np.exp(-(lambnorm[indok, :] - (1 + dshift))**2 * inv_2wi2)), axis=1) if isinstance(data, np.ndarray): return y - data[indok] else: return y - data # Prepare jac if jac in ['dense', 'sparse']: # Define a callable jac returning (nlamb, sizex) matrix of partial # derivatives of np.sum(func_details(scaled), axis=0) # Pre-instanciate jacobian jac0 = np.zeros((lamb.size, dind['sizex']), dtype=float) # jac0 = np.zeros((lamb.size, indx.sum()), dtype=float) indxn = indx.nonzero()[0] def jacob( x, xscale=xscale, indx=indx, indxn=indxn, lambnorm=lambnorm, ibckax=ibckax, ibckrx=ibckrx, iax=iax, iaj=iaj, ial=ial, iwx=iwx, iwj=iwj, iwl=iwl, ishx=ishx, ishj=ishj, ishl=ishl, idratiox=idratiox, idshx=idshx, coefsal=coefsal[None, :], coefswl=coefswl[None, :], coefssl=coefssl[None, :], offsetal=offsetal[None, :], offsetwl=offsetwl[None, :], offsetsl=offsetsl[None, :], double=dinput['double'], scales=None, indok=None, data=None, jac0=jac0, const=None, ): """ Basic docstr """ if indok is None: indok = np.ones(lamb.shape, dtype=bool) xscale[indx] = x*scales[indx] xscale[~indx] = const # Intermediates amp = xscale[ial] * coefsal + offsetal wi2 = xscale[iwl] * coefswl + offsetwl inv_wi2 = 1./wi2 shift = xscale[ishl] * coefssl + offsetsl beta = (lambnorm[indok, :] - (1 + shift)) * inv_wi2 / 2. alpha = -beta**2 * (2*wi2) exp = np.exp(alpha) # Background jac0[indok, ibckax[0]] = ( scales[ibckax[0]] * np.exp(xscale[ibckrx]*lambrel[indok]) ) jac0[indok, ibckrx[0]] = ( xscale[ibckax[0]] * scales[ibckrx[0]] * lambrel[indok] * np.exp(xscale[ibckrx]*lambrel[indok]) ) # amp (shape: nphi/lamb, namp[jj]) # for jj in range(len(iaj)): for jj, aa in enumerate(iaj): jac0[indok, iax[jj]] = np.sum( exp[:, aa] * coefsal[:, aa], axis=1) * scales[iax[jj]] # width2 for jj in range(len(iwj)): jac0[indok, iwx[jj]] = np.sum( (-alpha[:, iwj[jj]] * amp[:, iwj[jj]] * exp[:, iwj[jj]] * coefswl[:, iwj[jj]] * inv_wi2[:, iwj[jj]]), axis=1) * scales[iwx[jj]] # shift for jj in range(len(ishj)): jac0[indok, ishx[jj]] = np.sum( (amp[:, ishj[jj]] * 2. * beta[:, ishj[jj]]) * exp[:, ishj[jj]] * coefssl[:, ishj[jj]], axis=1) * scales[ishx[jj]] # double if double is not False: if double is True: dratio = xscale[idratiox] # coefssl are line-specific, they do not affect dshift dshift = shift + xscale[idshx] else: dratio = double.get('dratio', xscale[idratiox]) dshift = shift + double.get('dshift', xscale[idshx]) # ampd not defined to save memory => *dratio instead # ampd = amp*dratio betad = (lambnorm[indok, :] - (1 + dshift)) * inv_wi2 / 2. alphad = -betad**2 * (2*wi2) expd = np.exp(alphad) # amp for jj in range(len(iaj)): jac0[indok, iax[jj]] += dratio*np.sum( expd[:, iaj[jj]] * coefsal[:, iaj[jj]], axis=1) * scales[iax[jj]] # width2 for jj in range(len(iwj)): jac0[indok, iwx[jj]] += np.sum( ( -alphad[:, iwj[jj]] * amp[:, iwj[jj]] * expd[:, iwj[jj]] * coefswl[:, iwj[jj]] * inv_wi2[:, iwj[jj]] ), axis=1, ) * scales[iwx[jj]] * dratio # shift for jj in range(len(ishj)): jac0[indok, ishx[jj]] += np.sum( (amp[:, ishj[jj]] * 2.*betad[:, ishj[jj]] * expd[:, ishj[jj]] * coefssl[:, ishj[jj]]), axis=1) * scales[ishx[jj]] * dratio # dratio if double is True or double.get('dratio') is None: jac0[indok, idratiox] = ( scales[idratiox] * np.sum(amp * expd, axis=1) ) # dshift if double is True or double.get('dshift') is None: jac0[indok, idshx] = dratio * np.sum( amp * 2.*betad*scales[idshx] * expd, axis=1) return jac0[indok, :][:, indx] elif jac == 'sparse': msg = "Sparse jacobian is pointless for 1d spectrum fitting" raise Exception(msg) if jac not in ['dense', 'sparse', 'LinearSparseOperator']: if jac not in ['2-point', '3-point']: msg = ("jac should be in " + "['dense', 'sparse', 'LinearsparseOp', " + "'2-point', '3-point']\n" + "\t- provided: {}".format(jac)) raise Exception(msg) jacob = jac return func_detail, cost, jacob ########################################################### ########################################################### # # Main function for fit2d # ########################################################### ########################################################### def multigausfit2d_from_dlines_funccostjac( phi_flat=None, dinput=None, dind=None, jac=None, ): return_costjac = phi_flat is not None ibckax = dind['bck_amp']['x'] ibckrx = dind['bck_rate']['x'] nbck = 1 # ibckax.size + ibckrx.size iax = dind['amp']['x'] iwx = dind['width']['x'] ishx = dind['shift']['x'] idratiox, idshx = None, None if dinput['double'] is not False: c0 = dinput['double'] is True if c0 or dinput['double'].get('dratio') is None: idratiox = dind['dratio']['x'] if c0 or dinput['double'].get('dshift') is None: idshx = dind['dshift']['x'] ial = dind['amp']['lines'] iwl = dind['width']['lines'] ishl = dind['shift']['lines'] iaj = dind['amp']['jac'] iwj = dind['width']['jac'] ishj = dind['shift']['jac'] coefsal = dinput['amp']['coefs'][None, :] coefswl = dinput['width']['coefs'][None, :] coefssl = dinput['shift']['coefs'][None, :] offsetal = dinput['amp']['offset'][None, :] offsetwl = dinput['width']['offset'][None, :] offsetsl = dinput['shift']['offset'][None, :] xscale = np.full((dind['sizex'],), np.nan) km = dinput['knots_mult'] kpb = dinput['nknotsperbs'] nbs = dinput['nbs'] BS = BSpline( km, np.ones(ial.shape, dtype=float), dinput['deg'], extrapolate=False, axis=0, ) nlines = dinput['nlines'] deg = dinput['deg'] double = dinput['double'] lambmin_bck = dinput['lambmin_bck'] # Pre-set kwdargs dkwdargs = dict( ibckax=ibckax, ibckrx=ibckrx, ial=ial, iwl=iwl, ishl=ishl, idratiox=idratiox, idshx=idshx, nlines=nlines, nbck=nbck, km=km, kpb=kpb, nbs=nbs, deg=deg, BS=BS, coefsal=coefsal[None, :], coefswl=coefswl[None, :], coefssl=coefssl[None, :], offsetal=offsetal[None, :], offsetwl=offsetwl[None, :], offsetsl=offsetsl[None, :], double=double, lambmin_bck=lambmin_bck, ) # ---------------------------- # details and sum for end-user # func_details returns result in same shape as input def func_detail( x, xscale=xscale, phi=None, lamb=None, scales=None, ind_bs=None, const=None, indx=None, **dkwdargs, ): # normalize lamb lambrel = lamb - lambmin_bck shape = tuple(np.r_[[1 for ii in range(lamb.ndim)], -1]) lambn = lamb[..., None] / dinput['lines'].reshape(shape) # shape = tuple(np.r_[indok.sum(), nbck+nlines, nbs]) shape = tuple(np.r_[phi.shape, nbck + nlines, nbs]) y = np.full(shape, np.nan) if indx is None: xscale = x*scales else: xscale[indx] = x*scales[indx] xscale[~indx] = const # bck rate BS.c = xscale[ibckrx] bckr = BS(phi) # make sure iwl is 2D to get all lines at once BS.c = xscale[iwl] * coefswl + offsetwl wi2 = BS(phi) BS.c = xscale[ishl] * coefssl + offsetsl shift = BS(phi) exp = np.exp(-(lambn - (1 + shift))**2 / (2*wi2)) if double is not False: # coefssl are line-specific, they do not affect dshift if double is True: dratio = xscale[idratiox[:, 0]] dshift = shift + xscale[idshx[:, 0]] # *coefssl else: dratio = double.get('dratio', xscale[idratiox[:, 0]]) dshift = shift + double.get('dshift', xscale[idshx[:, 0]]) expd = np.exp(-(lambn - (1 + dshift))**2 / (2*wi2)) # Loop on individual bsplines for amp for ii in range(nbs): if ind_bs is not None and ii not in ind_bs: continue bs = BSpline.basis_element( km[ii:ii + kpb], extrapolate=False, )(phi) indbs = np.isfinite(bs) if not np.any(indbs): continue bs = bs[indbs] # bck y[indbs, 0, ii] = ( xscale[ibckax[ii, 0]]*bs * np.exp(bckr[indbs, 0]*lambrel[indbs]) ) # lines for jj in range(nlines): amp = ( bs * xscale[ial[ii, jj]] * coefsal[:, jj] + offsetal[:, jj] ) y[indbs, nbck+jj, ii] = amp * exp[indbs, jj] if double is not False: y[indbs, nbck+jj, ii] += (amp * dratio * expd[indbs, jj]) return y # cost and jacob return flattened results (for least_squares()) def func_sum( x, xscale=xscale, phi=None, lamb=None, scales=None, ind_bs=None, const=None, indx=None, **dkwdargs, ): # normalize lamb lambrel = lamb - lambmin_bck shape = tuple(np.r_[[1 for ii in range(lamb.ndim)], -1]) lambn = lamb[..., None] / dinput['lines'].reshape(shape) # xscale = x*scales if indx is None: xscale = x*scales else: xscale[indx] = x*scales[indx] xscale[~indx] = const # Background BS.c = xscale[ibckax][:, 0] bcka = BS(phi) BS.c = xscale[ibckrx][:, 0] y = bcka * np.exp(BS(phi)*lambrel) # make sure iwl is 2D to get all lines at once BS.c = xscale[ial] * coefsal + offsetal amp = BS(phi) BS.c = xscale[iwl] * coefswl + offsetwl wi2 = BS(phi) BS.c = xscale[ishl] * coefssl + offsetsl csh = BS(phi) y += np.nansum( amp * np.exp(-(lambn - (1 + csh))**2 / (2*wi2)), axis=-1, ) if double is not False: if double is True: dratio = xscale[idratiox[:, 0]] # scales[ishl] or scales[idshx] ? coefssl ? +> no dcsh = csh + xscale[idshx[:, 0]] else: dratio = double.get('dratio', xscale[idratiox[:, 0]]) dcsh = csh + double.get('dshift', xscale[idshx[:, 0]]) expd = np.exp(-(lambn - (1 + dcsh))**2 / (2*wi2)) y += np.nansum(amp * dratio * expd, axis=-1) return y # ------------------------------- # cost and jacob for optimization func_cost, func_jacob = None, None if return_costjac: def func_cost( x, xscale=xscale, scales=None, indok_flat=None, ind_bs=None, const=None, indx=None, data_flat=None, phi_flat=None, lambrel_flat=None, lambn_flat=None, jac0=None, libs=None, **dkwdargs, ): assert data_flat.shape == lambrel_flat.shape assert indok_flat is not None if indx is None: xscale = x*scales else: xscale[indx] = x*scales[indx] xscale[~indx] = const # Background BS.c = xscale[ibckax][:, 0] bcka = BS(phi_flat) BS.c = xscale[ibckrx][:, 0] y = bcka * np.exp(BS(phi_flat)*lambrel_flat) # make sure iwl is 2D to get all lines at once BS.c = xscale[ial] * coefsal + offsetal amp = BS(phi_flat) BS.c = xscale[iwl] * coefswl + offsetwl wi2 = BS(phi_flat) BS.c = xscale[ishl] * coefssl + offsetsl csh = BS(phi_flat) y += np.nansum( amp * np.exp(-(lambn_flat - (1 + csh))**2 / (2*wi2)), axis=-1, ) if double is not False: if double is True: dratio = xscale[idratiox[:, 0]] # scales[ishl] or scales[idshx] ? coefssl ? +> no dcsh = csh + xscale[idshx[:, 0]] else: dratio = double.get('dratio', xscale[idratiox[:, 0]]) dcsh = csh + double.get('dshift', xscale[idshx[:, 0]]) expd = np.exp(-(lambn_flat - (1 + dcsh))**2 / (2*wi2)) y += np.nansum(amp * dratio * expd, axis=-1) return y - data_flat def func_jacob( x, xscale=xscale, scales=None, indok_flat=None, ind_bs=None, const=None, indx=None, data_flat=0., phi_flat=None, lambrel_flat=None, lambn_flat=None, jac0=None, libs=None, **dkwdargs, ): """ Basic docstr """ if indx is None: xscale = x*scales else: xscale[indx] = x*scales[indx] xscale[~indx] = const # Intermediates # Loop on bs for ii in range(nbs): # phi interval ibs = libs[ii] # bspline bs = BSpline.basis_element( km[ii:ii+kpb], extrapolate=False, )(phi_flat[ibs])[:, None] # check bspline if np.any(~np.isfinite(bs)): msg = "Non-finite values in bs (affecting jacobian)!" raise Exception(msg) # Intermediates - background BS.c = xscale[ibckax[:, 0]] bcka = BS(phi_flat[ibs]) BS.c[...] = xscale[ibckrx[:, 0]] bckr = BS(phi_flat[ibs]) expbck = np.exp(bckr*lambrel_flat[ibs]) # Intermediates - amp, wi2, shift BS.c = xscale[ial] * coefsal + offsetal amp = BS(phi_flat[ibs]) BS.c[...] = xscale[iwl] * coefswl + offsetwl wi2 = BS(phi_flat[ibs]) BS.c[...] = xscale[ishl] * coefssl + offsetsl shift = BS(phi_flat[ibs]) beta = (lambn_flat[ibs, :] - (1 + shift)) / (2*wi2) alpha = -beta**2 * (2*wi2) # exp = np.exp(alpha) bsexp = bs * np.exp(alpha) # Background amplitude jac0[ibs, ibckax[ii, 0]] = ( bs[:, 0] * scales[ibckax[ii, 0]] * expbck ) # Background rate jac0[ibs, ibckrx[ii, 0]] = ( bs[:, 0] * scales[ibckrx[ii, 0]] * lambrel_flat[ibs] * bcka * expbck ) # amp (shape: nphi/lamb, namp[jj]) for jj in range(len(iaj)): ix = iax[ii, jj] jac0[ibs, ix] = np.sum( bsexp[:, iaj[jj]] * coefsal[:, iaj[jj]], axis=1, ) * scales[ix] # width2 for jj in range(len(iwj)): ix = iwx[ii, jj] jac0[ibs, ix] = np.sum( ( -alpha[:, iwj[jj]] * amp[:, iwj[jj]] * bsexp[:, iwj[jj]] * coefswl[:, iwj[jj]] / wi2[:, iwj[jj]] ), axis=1, ) * scales[ix] # shift for jj in range(len(ishj)): ix = ishx[ii, jj] jac0[ibs, ix] = np.sum( ( amp[:, ishj[jj]] * 2. * beta[:, ishj[jj]] * bsexp[:, ishj[jj]] * coefssl[:, ishj[jj]] ), axis=1, ) * scales[ix] # double if double is False: continue if double is True: dratio = xscale[idratiox[:, 0]] # coefssl are line-specific, they do not affect dshift dshift = shift + xscale[idshx[:, 0]] else: dratio = double.get('dratio', xscale[idratiox[:, 0]]) dshift = shift + double.get('dshift', xscale[idshx[:, 0]]) # ampd = amp*dratio betad = (lambn_flat[ibs, :] - (1 + dshift)) / (2*wi2) alphad = -betad**2 * (2*wi2) expd = np.exp(alphad) bsexpd = bs * expd # amp for jj in range(len(iaj)): ix = iax[ii, jj] jac0[ibs, ix] += dratio*np.sum( bsexpd[:, iaj[jj]] * coefsal[:, iaj[jj]], axis=1, ) * scales[ix] # width2 for jj in range(len(iwj)): ix = iwx[ii, jj] jac0[ibs, ix] += np.sum( (-alphad[:, iwj[jj]] * amp[:, iwj[jj]] * bsexpd[:, iwj[jj]] * coefswl[:, iwj[jj]] / wi2[:, iwj[jj]]), axis=1, ) * scales[ix] * dratio # shift for jj in range(len(ishj)): ix = ishx[ii, jj] jac0[ibs, ix] += np.sum( (amp[:, ishj[jj]] * 2.*betad[:, ishj[jj]] * bsexpd[:, ishj[jj]] * coefssl[:, ishj[jj]]), axis=1, ) * scales[ix] * dratio # dratio if double is True or double.get('dratio') is None: jac0[ibs, idratiox[:, 0]] = ( scales[idratiox[:, 0]] * np.sum(amp * expd, axis=1) ) # dshift if double is True or double.get('dshift') is None: jac0[ibs, idshx[:, 0]] = dratio * np.sum( amp * 2.*betad*scales[idshx] * expd, axis=1, ) if indx is None: return jac0 else: return jac0[:, indx] return func_detail, func_sum, func_cost, func_jacob
mit
glenngillen/dotfiles
.vscode/extensions/tsandall.opa-0.8.0/out/opa.js
7278
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); const cp = require("child_process"); const commandExistsSync = require('command-exists').sync; const vscode = require("vscode"); const install_opa_1 = require("./install-opa"); const util_1 = require("./util"); const fs_1 = require("fs"); const path_1 = require("path"); var regoVarPattern = new RegExp('^[a-zA-Z_][a-zA-Z0-9_]*$'); function getDataDir(uri) { // NOTE(tsandall): we don't have a precise version for 3be55ed6 so // do our best and rely on the -dev tag. if (!installedOPASameOrNewerThan("0.14.0-dev")) { return uri.fsPath; } if (uri.scheme === "file") { return uri.toString(); } return decodeURIComponent(uri.toString()); } exports.getDataDir = getDataDir; function canUseBundleFlags() { let bundleMode = vscode.workspace.getConfiguration('opa').get('bundleMode', true); return installedOPASameOrNewerThan("0.14.0-dev") && bundleMode; } exports.canUseBundleFlags = canUseBundleFlags; function dataFlag() { if (canUseBundleFlags()) { return "--bundle"; } return "--data"; } // returns true if installed OPA is same or newer than OPA version x. function installedOPASameOrNewerThan(x) { const s = getOPAVersionString(); return opaVersionSameOrNewerThan(s, x); } // Returns a list of root data path URIs based on the plugin configuration. function getRoots() { const roots = vscode.workspace.getConfiguration('opa').get('roots', []); let formattedRoots = new Array(); roots.forEach(root => { root = root.replace('${workspaceFolder}', vscode.workspace.workspaceFolders[0].uri.toString()); root = root.replace('${fileDirname}', path_1.dirname(vscode.window.activeTextEditor.document.fileName)); formattedRoots.push(getDataDir(vscode.Uri.parse(root))); }); return formattedRoots; } exports.getRoots = getRoots; // Returns a list of root data parameters in an array // like ["--bundle=file:///a/b/x/", "--bundle=file:///a/b/y"] in bundle mode // or ["--data=file:///a/b/x", "--data=file://a/b/y"] otherwise. function getRootParams() { const flag = dataFlag(); const roots = getRoots(); let params = new Array(); roots.forEach(root => { params.push(`${flag}=${root}`); }); return params; } exports.getRootParams = getRootParams; // returns true if OPA version a is same or newer than OPA version b. If either // version is not in the expected format (i.e., // <major>.<minor>.<point>[-<patch>]) this function returns true. Major, minor, // and point versions are compared numerically. Patch versions are compared // lexigraphically however an empty patch version is considered newer than a // non-empty patch version. function opaVersionSameOrNewerThan(a, b) { const aVersion = parseOPAVersion(a); const bVersion = parseOPAVersion(b); if (aVersion.length !== 4 || bVersion.length !== 4) { return true; } for (let i = 0; i < 3; i++) { if (aVersion[i] > bVersion[i]) { return true; } else if (bVersion[i] > aVersion[i]) { return false; } } if (aVersion[3] === '' && bVersion[3] !== '') { return true; } else if (aVersion[3] !== '' && bVersion[3] === '') { return false; } return aVersion[3] >= bVersion[3]; } // returns array of numbers and strings representing an OPA semantic version. function parseOPAVersion(s) { const parts = s.split('.', 3); if (parts.length < 3) { return []; } const major = Number(parts[0]); const minor = Number(parts[1]); const pointParts = parts[2].split('-', 2); const point = Number(pointParts[0]); let patch = ''; if (pointParts.length >= 2) { patch = pointParts[1]; } return [major, minor, point, patch]; } // returns the installed OPA version as a string. function getOPAVersionString() { const result = cp.spawnSync('opa', ['version']); if (result.status !== 0) { return ''; } const lines = result.stdout.toString().split('\n'); for (let i = 0; i < lines.length; i++) { const parts = lines[i].trim().split(': ', 2); if (parts.length < 2) { continue; } if (parts[0] === 'Version') { return parts[1]; } } return ''; } // refToString formats a ref as a string. Strings are special-cased for // dot-style lookup. Note: this function is currently only used for populating // picklists based on dependencies. As such it doesn't handle all term types // properly. function refToString(ref) { let result = ref[0].value; for (let i = 1; i < ref.length; i++) { if (ref[i].type === "string") { if (regoVarPattern.test(ref[i].value)) { result += '.' + ref[i].value; continue; } } result += '[' + JSON.stringify(ref[i].value) + ']'; } return result; } exports.refToString = refToString; /** * Helpers for executing OPA as a subprocess. */ function parse(opaPath, path, cb, onerror) { run(opaPath, ['parse', path, '--format', 'json'], '', (error, result) => { if (error !== '') { onerror(error); } else { let pkg = util_1.getPackage(result); let imports = util_1.getImports(result); cb(pkg, imports); } }); } exports.parse = parse; // run executes the OPA binary at path with args and stdin. The callback is // invoked with an error message on failure or JSON object on success. function run(path, args, stdin, cb) { runWithStatus(path, args, stdin, (code, stderr, stdout) => { if (code !== 0) { if (stdout !== '') { cb(stdout, ''); } else { cb(stderr, ''); } } else { cb('', JSON.parse(stdout)); } }); } exports.run = run; // runWithStatus executes the OPA binary at path with args and stdin. The // callback is invoked with the exit status, stderr, and stdout buffers. function runWithStatus(path, args, stdin, cb) { const opaPath = vscode.workspace.getConfiguration('opa').get('path'); const existsOnPath = commandExistsSync(path); const existsInUserSettings = opaPath !== undefined && opaPath !== null && fs_1.existsSync(opaPath); if (!(existsOnPath || existsInUserSettings)) { install_opa_1.promptForInstall(); return; } if (existsInUserSettings && opaPath !== undefined) { // Prefer OPA in User Settings to the one installed on $PATH path = opaPath; } console.log("spawn:", path, "args:", args.toString()); let proc = cp.spawn(path, args); proc.stdin.write(stdin); proc.stdin.end(); let stdout = ""; let stderr = ""; proc.stdout.on('data', (data) => { stdout += data; }); proc.stderr.on('data', (data) => { stderr += data; }); proc.on('exit', (code, signal) => { console.log("code:", code); console.log("stdout:", stdout); console.log("stderr:", stderr); cb(code, stderr, stdout); }); } exports.runWithStatus = runWithStatus; //# sourceMappingURL=opa.js.map
mit
rickding/Hello
HelloHackerRank/src/test/java/com/hello/SubStrTest.java
1123
package com.hello; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class SubStrTest { @Test public void testSplitTokens() { Map<String, Integer> mapIO = new HashMap<String, Integer>() {{ put("He is a very very good boy, isn't he?", 10); put(" YES leading spaces are valid, problemsetters are evillllll", 8); put("", 0); put(null, 0); }}; for (Map.Entry<String, Integer> io : mapIO.entrySet()) { String[] ret = SubStr.splitTokens(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret == null ? 0 : ret.length); } } @Test public void testGetSmallestAndLargest() { Map<String, String> mapIO = new HashMap<String, String>() {{ put("welcometojava", "ava\nwel"); }}; for (Map.Entry<String, String> io : mapIO.entrySet()) { String ret = SubStr.getSmallestAndLargest(io.getKey(), 3); Assert.assertEquals(io.getValue(), ret); } } }
mit
astronote/astronote-docker
web/app/src/views/Settings/index.js
41
export { default } from './Settings.vue'
mit
tonimichel/djpl-schnippjs
setup.py
1062
#! /usr/bin/env python import os from setuptools import setup, find_packages def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return '' setup( name='djpl-schnippjs', version='0.1', description='a django-productline feature to include schnipp.js', long_description=read('README.rst'), license='The MIT License', keywords='django, django-productline, javascript, schnipp.js', author='Toni Michel', author_email='toni@schnapptack.de', url="https://github.com/tonimichel/djpl-schnippjs", packages=find_packages(), package_dir={'schnippjs': 'schnippjs'}, include_package_data=True, scripts=[], zip_safe=False, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent' ], install_requires=[ ] )
mit
DrunkyBard/CqrsMe
src/Cqrs.Persistance.Core/Properties/AssemblyInfo.cs
1418
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Cqrs.Persistance.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Cqrs.Persistance.Core")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e5c46f67-5d51-48c3-9107-28b769fae647")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
sstu-icsp/afisha
afisha/src/main/java/org/epl/dao/EventDao.java
235
package org.epl.dao; import java.util.List; import org.epl.model.Event; public interface EventDao { Event findById(int id); void saveEvent(Event event); void deleteEventById(int id); List <Event> findAllEvent(); }
mit
huangfeng19820712/hfast
core/js/tree/KendoTree.js
718
/** * @author: * @date: 15-1-9 */ define([ "kendo"], function(kendo,template) { var tree = { menuTree : function(el) { homogeneous = new kendo.data.HierarchicalDataSource({ type:"json", transport : { read : { dataType: "json", url:$route.getCorePath("Menu") } }, schema : { model : { id : "id", hasChildren : "hasChildren" } } }); $(el).kendoTreeView({ dataSource : homogeneous, dataTextField : "title", select : function(event) { var dataItem = this.dataItem(event.node); var url = dataItem.menuUrl; } }); } } return tree; });
mit
alexplatonov/angularity
src/core/test/controllers.test.js
768
describe('CoreController', function() { var $scope, $window; beforeEach(function() { $window = {}; angular.mock.module('angularity'); angular.mock.module(function($provide) { $provide.value('$window', $window); }); angular.mock.inject(function($injector, $controller) { $scope = $injector.get('$rootScope').$new(); $controller('CoreController', {$scope: $scope}); }); spyOn($scope.$root, '$broadcast').and.stub(); spyOn($scope.loading, 'start').and.stub(); spyOn($scope.loading, 'stop').and.stub(); }); describe('hello method', function() { beforeEach(function() { }); it('should say hello', function(){ expect($scope.hello).toBe('Hello Universe!'); }); }); });
mit
AlexPodobed/Angular2.0
src/app/features/courses/state/courses.reducer.ts
1850
import { Action } from '@ngrx/store'; import * as actions from './courses.actions'; import { CoursesState } from './courses-state.model'; const initialState: CoursesState = { loaded: false, loading: false, items: [], page: 0, size: 3, query: '', total: null }; function setState(state, data) { return Object.assign({}, state, data); } export const courses = (state: CoursesState = initialState, action: Action) => { switch (action.type) { case actions.LOAD_COURSES: case actions.REMOVE_COURSE: case actions.SAVE_COURSE: case actions.GET_COURSE: return setState(state, { loading: true }); case actions.LOAD_COURSES_SUCCESS: return setState(state, { loading: false, loaded: true, total: action.payload.total, items: action.payload.items, page: action.payload.page }); case actions.SELECT_PAGE: return setState(state, { page: action.payload.page }); case actions.SELECT_SIZE: return setState(state, { size: action.payload.size }); case actions.REMOVE_COURSE_SUCCESS: case actions.SAVE_COURSE_SUCCESS: case actions.GET_COURSE_SUCCESS: return setState(state, { loading: false }); case actions.REMOVE_COURSE_FAIL: case actions.LOAD_COURSES_FAIL: case actions.SAVE_COURSE_FAIL: case actions.GET_COURSE_FAIL: return setState(state, { error: action.payload.error, loading: false }); case actions.SEARCH_COURSE: return setState(state, { query: action.payload.query, page: 0 }); default: return state; } };
mit
alexlafroscia/ember-steps
tests/assertions/wait-for.js
100
import QUnit from 'qunit'; import { installWaitFor } from 'qunit-wait-for'; installWaitFor(QUnit);
mit
saumitrabhave/qr-zbar-ane
NativeAndroid/src/com/sbhave/nativeExtension/function/ScanBitmapFunction.java
3436
/* * Copyright (c) 2014 Saumitra R Bhave * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * File : /Users/saumib/projects/repos/qr-zbar-ane/NativeAndroid/src/com/sbhave/nativeExtension/function/ScanBitmapFunction.java */ package com.sbhave.nativeExtension.function; import android.graphics.Bitmap; import android.util.Log; import com.adobe.fre.*; import com.sbhave.nativeExtension.QRExtensionContext; import com.sbhave.nativeExtension.ui.CameraPreviewManager; import net.sourceforge.zbar.Image; import net.sourceforge.zbar.ImageScanner; import net.sourceforge.zbar.Symbol; import net.sourceforge.zbar.SymbolSet; import java.util.Arrays; //Implementation Inspired From: https://github.com/luarpro/BitmapDataQRCodeScanner public class ScanBitmapFunction implements FREFunction { @Override public FREObject call(FREContext freContext, FREObject[] args) { FREObject retVal = null; retVal = null; QRExtensionContext qrCtx =(QRExtensionContext)freContext; if(args.length != 1){ Log.e("saumitra","Error, Invalid number of arguments in scanBitmap"); } try { FREBitmapData inputValue = (FREBitmapData)args[0]; inputValue.acquire(); int width = inputValue.getWidth(); int height = inputValue.getHeight(); int[] pixels = new int[width * height]; Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bmp.copyPixelsFromBuffer(inputValue.getBits()); bmp.getPixels(pixels, 0, width, 0, 0, width, height); Image myImage = new Image(width, height, "RGB4"); myImage.setData(pixels); myImage = myImage.convert("Y800"); String[] results = qrCtx.getPreviewManager().scanImage(myImage,qrCtx.getScanner()); inputValue.release(); if (results != null && results.length > 0){ FREArray freArray = FREArray.newArray(results.length); for(int ctr=0; ctr < results.length; ctr++){ FREObject freString = FREObject.newObject(results[ctr]); freArray.setObjectAt(ctr, freString); } retVal = freArray; } } catch (Exception e) { Log.e("saumitra","Got Exception",e) ; return null; } return retVal; } }
mit
att/XACML
XACML-PAP-ADMIN/src/main/java/com/att/research/xacml/admin/view/events/AttributeChangedEventListener.java
329
/* * * Copyright (c) 2014,2019 AT&T Knowledge Ventures * SPDX-License-Identifier: MIT */ package com.att.research.xacml.admin.view.events; import com.att.research.xacml.admin.jpa.Attribute; public interface AttributeChangedEventListener { public void attributeChanged(Attribute attribute); }
mit
JoAutomation/todo-for-you
ext/comment/asset/js/Ext.js
4870
/**************************************************************************** * todoyu is published under the BSD License: * http://www.opensource.org/licenses/bsd-license.php * * Copyright (c) 2012, snowflake productions GmbH, Switzerland * All rights reserved. * * This script is part of the todoyu project. * The todoyu project is free software; you can redistribute it and/or modify * it under the terms of the BSD License. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD License * for more details. * * This copyright notice MUST APPEAR in all copies of the script. *****************************************************************************/ /** * @module Comment */ /** * Main comment object * * @class Comment * @namespace Todoyu.Ext */ Todoyu.Ext.comment = { /** * @property PanelWidget * @type Object */ PanelWidget: {}, /** * Initialize comment extension * Add a hook to observe form display to fix email receivers field display * * @method init */ init: function() { Todoyu.Hook.add('form.display', this.onFormDisplay.bind(this)); }, /** * Hook, when a form is displayed * * @method onFormDisplay * @param {String} idForm * @param {String} name * @param {String} recordID idTask-idComment */ onFormDisplay: function(idForm, name, recordID) { if( name === 'comment' ) { this.Edit.onFormDisplay(idForm, name, recordID) } }, /** * @method updateFeedbackTab * @param {Number} numFeedbacks * @todo Use core tab handling */ updateFeedbackTab: function(numFeedbacks) { // Count-down the feedback counter if( Todoyu.isInArea('portal') && Todoyu.exists('portal-tab-feedback') ) { var labelElement = $('portal-tab-feedback').down('span.labeltext'); labelElement.update(labelElement.innerHTML.replace(/\(\d\)/, '(' + numFeedbacks + ')')); } }, /** * Add new comment to given task: expand task details and open comments tab with new comment form * * @method addTaskComment * @param {Number} idTask */ addTaskComment: function(idTask) { Todoyu.Ext.project.Task.showDetails(idTask, 'comment', this.onTaskCommentTabLoaded.bind(this)); }, /** * Handler when task comment tab is loaded * * @method onTaskCommentTabLoaded * @param {Number} idTask * @param {String} tab */ onTaskCommentTabLoaded: function(idTask, tab) { if( !Todoyu.exists('task-' + idTask + '-commentform-0') ) { this.add(idTask); } else { if( !Todoyu.Ext.project.Task.isDetailsVisible(idTask) ) { $('task-' + idTask + '-details').toggle(); } } }, /** * Set Label (on adding or removing comment) * * @method setTabLabel * @param {Number} idTask * @param {String} label */ setTabLabel: function(idTask, label){ $('task-' + idTask + '-tab-comment-label').select('.labeltext').first().update(label); }, /** * Check whether sorting of comments of given task is desc (true) or asc (false) * * @method checkSortingIsDesc * @param {Number} idTask * @return {Boolean} */ checkSortingIsDesc: function( idTask ) { var elementID, isDesc; elementID = 'task-' + idTask + '-comments'; isDesc = false; if( elementID ) { isDesc = $(elementID).hasClassName('desc'); } return isDesc; }, /** * Add a new comment, open empty edit form * * @method add * @param {Number} idTask * @param {Number} [idCommentQuote] Use this comment as template * @param {Number} [idCommentMailReply] */ add: function(idTask, idCommentQuote, idCommentMailReply) { idCommentQuote = idCommentQuote || 0; idCommentMailReply = idCommentMailReply || 0; // Clean up UI this.removeForms(idTask); // Load new comment form var url, options, target; url = Todoyu.getUrl('comment', 'comment'); options = { parameters: { action: 'add', task: idTask, quote: idCommentQuote, mailReply: idCommentMailReply }, insertion: 'after', onComplete: this.onAdded.bind(this, idTask, idCommentQuote, idCommentMailReply) }; target = 'task-' + idTask + '-comment-commands-top'; Todoyu.Ui.update(target, url, options); }, /** * Handler when empty edit form to add comment loaded * * @method onAdded * @param {Number} idTask * @param {Number} idCommentQuote * @param {Number} idCommentMailReply * @param {Ajax.Response} response */ onAdded: function(idTask, idCommentQuote, idCommentMailReply, response) { $('task-' + idTask + '-comment-commands-top').scrollToElement(); }, /** * Remove all open edit forms for comment * * @method removeForms * @param {Number} idTask */ removeForms: function(idTask) { $('task-' + idTask + '-tabcontent-comment').select('.commentform').invoke('remove'); } };
mit
bhollis/DIM
src/app/loadout/loadout-apply.ts
14690
import { DimStore, StoreServiceType } from 'app/inventory/store-types'; import { Loadout } from './loadout-types'; import { queuedAction } from 'app/inventory/action-queue'; import { loadingTracker } from 'app/shell/loading-tracker'; import { showNotification, NotificationType } from 'app/notifications/notifications'; import { loadoutNotification } from 'app/inventory/MoveNotifications'; import { t } from 'app/i18next-t'; import { DimItem } from 'app/inventory/item-types'; import _ from 'lodash'; import { dimItemService, MoveReservations } from 'app/inventory/item-move-service'; import { default as reduxStore } from '../store/store'; import { savePreviousLoadout } from './actions'; import copy from 'fast-copy'; const outOfSpaceWarning = _.throttle((store) => { showNotification({ type: 'info', title: t('FarmingMode.OutOfRoomTitle'), body: t('FarmingMode.OutOfRoom', { character: store.name }) }); }, 60000); /** * Apply a loadout - a collection of items to be moved and possibly equipped all at once. * @param allowUndo whether to include this loadout in the "undo loadout" menu stack. * @return a promise for the completion of the whole loadout operation. */ export async function applyLoadout( store: DimStore, loadout: Loadout, allowUndo = false ): Promise<void> { if (!store) { throw new Error('You need a store!'); } if ($featureFlags.debugMoves) { console.log('LoadoutService: Apply loadout', loadout.name, 'to', store.name); } const applyLoadoutFn = queuedAction(doApplyLoadout); const loadoutPromise = applyLoadoutFn(store, loadout, allowUndo); loadingTracker.addPromise(loadoutPromise); if ($featureFlags.moveNotifications) { showNotification( loadoutNotification( loadout, store, // TODO: allow for an error view function to be passed in // TODO: cancel button! loadoutPromise.then((scope) => { if (scope.failed > 0) { if (scope.failed === scope.total) { throw new Error(t('Loadouts.AppliedError')); } else { throw new Error( t('Loadouts.AppliedWarn', { failed: scope.failed, total: scope.total }) ); } } }) ) ); } const scope = await loadoutPromise; if (!$featureFlags.moveNotifications) { let value: NotificationType = 'success'; let message = t('Loadouts.Applied', { // t('Loadouts.Applied_male') // t('Loadouts.Applied_female') // t('Loadouts.Applied_male_plural') // t('Loadouts.Applied_female_plural') count: scope.total, store: store.name, context: store.genderName }); if (scope.failed > 0) { if (scope.failed === scope.total) { value = 'error'; message = t('Loadouts.AppliedError'); } else { value = 'warning'; message = t('Loadouts.AppliedWarn', { failed: scope.failed, total: scope.total }); } } showNotification({ type: value, title: loadout.name, body: message }); } } async function doApplyLoadout(store: DimStore, loadout: Loadout, allowUndo = false) { const storeService = store.getStoresService(); if (allowUndo && !store.isVault) { reduxStore.dispatch( savePreviousLoadout({ storeId: store.id, loadoutId: loadout.id, previousLoadout: store.loadoutFromCurrentlyEquipped( t('Loadouts.Before', { name: loadout.name }) ) }) ); } let items: DimItem[] = copy(Object.values(loadout.items)).flat(); const loadoutItemIds = items.map((i) => ({ id: i.id, hash: i.hash })); // Only select stuff that needs to change state let totalItems = items.length; items = items.filter((pseudoItem) => { const item = getLoadoutItem(pseudoItem, store); // provide a more accurate count of total items if (!item) { totalItems--; return true; } const notAlreadyThere = item.owner !== store.id || item.location.inPostmaster || // Needs to be equipped. Stuff not marked "equip" doesn't // necessarily mean to de-equip it. (pseudoItem.equipped && !item.equipped) || pseudoItem.amount > 1; return notAlreadyThere; }); // only try to equip subclasses that are equippable, since we allow multiple in a loadout items = items.filter((item) => { const ok = item.type !== 'Class' || !item.equipped || item.canBeEquippedBy(store); if (!ok) { totalItems--; } return ok; }); // vault can't equip if (store.isVault) { items.forEach((i) => { i.equipped = false; }); } // We'll equip these all in one go! let itemsToEquip = items.filter((i) => i.equipped); if (itemsToEquip.length > 1) { // we'll use the equipItems function itemsToEquip.forEach((i) => { i.equipped = false; }); } // Stuff that's equipped on another character. We can bulk-dequip these const itemsToDequip = items.filter((pseudoItem) => { const item = storeService.getItemAcrossStores(pseudoItem); return item?.equipped && item.owner !== store.id; }); const scope = { failed: 0, total: totalItems, successfulItems: [] as DimItem[], errors: [] as { item: DimItem | null; message: string; level: string; }[] }; if (itemsToDequip.length > 1) { const realItemsToDequip = _.compact( itemsToDequip.map((i) => storeService.getItemAcrossStores(i)) ); const dequips = _.map( _.groupBy(realItemsToDequip, (i) => i.owner), (dequipItems, owner) => { const equipItems = _.compact( dequipItems.map((i) => dimItemService.getSimilarItem(i, loadoutItemIds)) ); return dimItemService.equipItems(storeService.getStore(owner)!, equipItems); } ); await Promise.all(dequips); } await applyLoadoutItems(store, items, loadoutItemIds, scope); let equippedItems: DimItem[]; if (itemsToEquip.length > 1) { // Use the bulk equipAll API to equip all at once. itemsToEquip = itemsToEquip.filter((i) => scope.successfulItems.find((si) => si.id === i.id)); const realItemsToEquip = _.compact(itemsToEquip.map((i) => getLoadoutItem(i, store))); equippedItems = await dimItemService.equipItems(store, realItemsToEquip); } else { equippedItems = itemsToEquip; } if (equippedItems.length < itemsToEquip.length) { const failedItems = itemsToEquip.filter((i) => !equippedItems.find((it) => it.id === i.id)); failedItems.forEach((item) => { scope.failed++; scope.errors.push({ level: 'error', item, message: t('Loadouts.CouldNotEquip', { itemname: item.name }) }); if (!$featureFlags.moveNotifications) { showNotification({ type: 'error', title: loadout.name, body: t('Loadouts.CouldNotEquip', { itemname: item.name }) }); } }); } // We need to do this until https://github.com/DestinyItemManager/DIM/issues/323 // is fixed on Bungie's end. When that happens, just remove this call. if (scope.successfulItems.length > 0) { await storeService.updateCharacters(); } if (loadout.clearSpace) { const allItems = _.compact( Object.values(loadout.items) .flat() .map((i) => getLoadoutItem(i, store)) ); await clearSpaceAfterLoadout(storeService.getStore(store.id)!, allItems, storeService); } return scope; } // Move one loadout item at a time. Called recursively to move items! async function applyLoadoutItems( store: DimStore, items: DimItem[], loadoutItemIds: { id: string; hash: number }[], scope: { failed: number; total: number; successfulItems: DimItem[]; errors: { item: DimItem | null; message: string; level: string; }[]; } ) { if (items.length === 0) { // We're done! return; } const pseudoItem = items.shift()!; const item = getLoadoutItem(pseudoItem, store); try { if (item) { if (item.maxStackSize > 1) { // handle consumables! const amountAlreadyHave = store.amountOfItem(pseudoItem); let amountNeeded = pseudoItem.amount - amountAlreadyHave; if (amountNeeded > 0) { const otherStores = store .getStoresService() .getStores() .filter((otherStore) => store.id !== otherStore.id); const storesByAmount = _.sortBy( otherStores.map((store) => ({ store, amount: store.amountOfItem(pseudoItem) })), 'amount' ).reverse(); let totalAmount = amountAlreadyHave; while (amountNeeded > 0) { const source = _.maxBy(storesByAmount, (s) => s.amount)!; const amountToMove = Math.min(source.amount, amountNeeded); const sourceItem = source.store.items.find((i) => i.hash === pseudoItem.hash); if (amountToMove === 0 || !sourceItem) { const error: Error & { level?: string } = new Error( t('Loadouts.TooManyRequested', { total: totalAmount, itemname: item.name, requested: pseudoItem.amount }) ); error.level = 'warn'; throw error; } source.amount -= amountToMove; amountNeeded -= amountToMove; totalAmount += amountToMove; await dimItemService.moveTo(sourceItem, store, false, amountToMove, loadoutItemIds); } } } else { // Pass in the list of items that shouldn't be moved away await dimItemService.moveTo(item, store, pseudoItem.equipped, item.amount, loadoutItemIds); } } if (item) { scope.successfulItems.push(item); } } catch (e) { const level = e.level || 'error'; if (level === 'error') { scope.failed++; } scope.errors.push({ item, level: e.level, message: e.message }); if (!$featureFlags.moveNotifications) { showNotification({ type: e.level || 'error', title: item ? item.name : 'Unknown', body: e.message }); } } // Keep going return applyLoadoutItems(store, items, loadoutItemIds, scope); } // A special getItem that takes into account the fact that // subclasses have unique IDs, and emblems/shaders/etc are interchangeable. function getLoadoutItem(pseudoItem: DimItem, store: DimStore): DimItem | null { let item = store.getStoresService().getItemAcrossStores(_.omit(pseudoItem, 'amount')); if (!item) { return null; } if (['Class', 'Shader', 'Emblem', 'Emote', 'Ship', 'Horn'].includes(item.type)) { // Same character first item = store.items.find((i) => i.hash === pseudoItem.hash) || // Then other characters store.getStoresService().getItemAcrossStores({ hash: item.hash }) || item; } return item; } function clearSpaceAfterLoadout( store: DimStore, items: DimItem[], storesService: StoreServiceType ) { const itemsByType = _.groupBy(items, (i) => i.bucket.id); const reservations: MoveReservations = {}; // reserve one space in the active character reservations[store.id] = {}; const itemsToRemove: DimItem[] = []; _.forIn(itemsByType, (loadoutItems, bucketId) => { // Blacklist a handful of buckets from being cleared out if (['Consumable', 'Consumables', 'Material'].includes(loadoutItems[0].bucket.type!)) { return; } let numUnequippedLoadoutItems = 0; for (const existingItem of store.buckets[bucketId]) { if (existingItem.equipped) { // ignore equipped items continue; } if ( existingItem.notransfer || loadoutItems.some( (i) => i.id === existingItem.id && i.hash === existingItem.hash && i.amount <= existingItem.amount ) ) { // This was one of our loadout items (or it can't be moved) numUnequippedLoadoutItems++; } else { // Otherwise ee should move it to the vault itemsToRemove.push(existingItem); } } // Reserve enough space to only leave the loadout items reservations[store.id] = loadoutItems[0].bucket.capacity - numUnequippedLoadoutItems; }); return clearItemsOffCharacter(store, itemsToRemove, reservations, storesService); } /** * Move a list of items off of a character to the vault (or to other characters if the vault is full). * * Shows a warning if there isn't any space. */ export async function clearItemsOffCharacter( store: DimStore, items: DimItem[], reservations: MoveReservations, storesService: StoreServiceType ) { for (const item of items) { try { // Move a single item. We reevaluate each time in case something changed. const vault = storesService.getVault()!; const vaultSpaceLeft = vault.spaceLeftForItem(item); if (vaultSpaceLeft <= 1) { // If we're down to one space, try putting it on other characters const otherStores = storesService .getStores() .filter((s) => !s.isVault && s.id !== store.id); const otherStoresWithSpace = otherStores.filter((store) => store.spaceLeftForItem(item)); if (otherStoresWithSpace.length) { if ($featureFlags.debugMoves) { console.log( 'clearItemsOffCharacter initiated move:', item.amount, item.name, item.type, 'to', otherStoresWithSpace[0].name, 'from', storesService.getStore(item.owner)!.name ); } await dimItemService.moveTo( item, otherStoresWithSpace[0], false, item.amount, items, reservations ); continue; } else if (vaultSpaceLeft === 0) { outOfSpaceWarning(store); continue; } } if ($featureFlags.debugMoves) { console.log( 'clearItemsOffCharacter initiated move:', item.amount, item.name, item.type, 'to', vault.name, 'from', storesService.getStore(item.owner)!.name ); } await dimItemService.moveTo(item, vault, false, item.amount, items, reservations); } catch (e) { if (e.code === 'no-space') { outOfSpaceWarning(store); } else { showNotification({ type: 'error', title: item.name, body: e.message }); } } } }
mit
mejackreed/rspec_say
lib/rspec_say/say_formatter.rb
752
require 'rspec' require 'rspec/core/formatters/base_text_formatter' class SayFormatter < RSpec::Core::Formatters::BaseTextFormatter RSpec::Core::Formatters.register self, :dump_summary def dump_summary(summary) output.puts summary.fully_formatted phrase = "Tests finished in #{format_time(summary.duration)}, " \ "#{summary.examples.count} examples, " \ "#{summary.failed_examples.count} failed, "\ "#{summary.pending_examples.count} pending" `say #{phrase}` end private ## # @param [Float] # @return [String] def format_time(duration) if duration > 60 return "#{(duration / 60.0).round(3)} minutes" else return "#{duration.round(3)} seconds" end end end
mit
janghe11/MobileProgramming
SimpleButton/app/src/androidTest/java/com/jang/simplebutton/ApplicationTest.java
352
package com.jang.simplebutton; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
ssherwood/symptom-mgmt-android
app/src/main/java/mobile/symptom/androidcapstone/coursera/org/symptommanagement/ListPatientsActivity.java
7003
package mobile.symptom.androidcapstone.coursera.org.symptommanagement; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import mobile.symptom.androidcapstone.coursera.org.symptommanagement.model.Patient; import mobile.symptom.androidcapstone.coursera.org.symptommanagement.model.PatientResponse; import mobile.symptom.androidcapstone.coursera.org.symptommanagement.model.SDRFindAllResponse; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class ListPatientsActivity extends Activity { private ListView mPatientListView; private PatientAdapter mPatientAdapter; private SearchView mSearchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_patients); ArrayList<Patient> arrayOfUsers = new ArrayList<>(); mPatientAdapter = new PatientAdapter(this, arrayOfUsers); mPatientListView = (ListView)findViewById(R.id.patientListView); mPatientListView.setAdapter(mPatientAdapter); RestAPI.getSymptomMgmtAPI().getPatientsByDoctorId(SymptomManagement.getCurrentEntityId(), new Callback<SDRFindAllResponse<PatientResponse>>() { @Override public void success(SDRFindAllResponse<PatientResponse> patientResponseSDRFindAllResponse, Response response) { mPatientAdapter.clear(); if (patientResponseSDRFindAllResponse != null && patientResponseSDRFindAllResponse.getEmbedded() != null) { mPatientAdapter.addAll(patientResponseSDRFindAllResponse.getEmbedded().getPatients()); } mPatientAdapter.notifyDataSetChanged(); } @Override public void failure(RetrofitError error) { Toast.makeText(ListPatientsActivity.this, "Error: " + error.getResponse().getReason(), Toast.LENGTH_LONG).show(); } }); mPatientListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Patient patient = mPatientAdapter.getItem(position); Intent patientSummaryIntent = new Intent(ListPatientsActivity.this, PatientSummaryActivity.class); patientSummaryIntent.putExtra("patient", patient); startActivity(patientSummaryIntent); } }); mSearchView = (SearchView) findViewById(R.id.searchView); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { RestAPI.getSymptomMgmtAPI().getPatientsByDoctorIdThatMatchTerm(SymptomManagement.getCurrentEntityId(), newText.toLowerCase(), new Callback<SDRFindAllResponse<PatientResponse>>() { @Override public void success(SDRFindAllResponse<PatientResponse> patientResponseSDRFindAllResponse, Response response) { mPatientAdapter.clear(); if (patientResponseSDRFindAllResponse != null && patientResponseSDRFindAllResponse.getEmbedded() != null) { mPatientAdapter.addAll(patientResponseSDRFindAllResponse.getEmbedded().getPatients()); } else { //mPatientListView.addFooterView(); } mPatientAdapter.notifyDataSetChanged(); } @Override public void failure(RetrofitError error) { Toast.makeText(ListPatientsActivity.this, "Error: " + error.getResponse().getReason(), Toast.LENGTH_LONG).show(); } }); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_list_patients, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } else if (id == R.id.action_logout) { Log.d(SymptomManagement.LOG_ID, "Logging out..."); Intent intent = new Intent(getApplicationContext(), LaunchActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("EXIT", true); startActivity(intent); finish(); } return super.onOptionsItemSelected(item); } public static class PatientAdapter extends ArrayAdapter<Patient> { private static class ViewHolder { TextView name; TextView email; } public PatientAdapter(Context context, ArrayList<Patient> patients) { super(context, R.layout.item_patients, patients); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(R.layout.item_patients, parent, false); viewHolder.name = (TextView) convertView.findViewById(R.id.nameTextView); viewHolder.email = (TextView) convertView.findViewById(R.id.emailTextView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } Patient patient = getItem(position); viewHolder.name.setText(patient.getFirstName() + " " + patient.getLastName()); viewHolder.email.setText(patient.getEmailAddress()); return convertView; } } }
mit
mikesaelim/arXivOAIHarvester
src/main/java/io/github/mikesaelim/arxivoaiharvester/model/request/ListRecordsRequest.java
3151
package io.github.mikesaelim.arxivoaiharvester.model.request; import io.github.mikesaelim.arxivoaiharvester.model.response.ListRecordsResponse; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.http.client.utils.URIBuilder; import java.net.URI; import java.net.URISyntaxException; import java.time.LocalDate; /** * A ListRecords request, used to retrieve a range of records between two datestamps. * * Note that ListRecords responses may be paginated. {@link ResumeListRecordsRequest} is a ListRecordsRequest that * continues the original request by sending back the resumption token received from the last response. */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class ListRecordsRequest extends ArxivRequest { /** * Optional lower bound of the datestamp range. If null, the range is unbounded from below. */ private final LocalDate fromDate; /** * Optional upper bound of the datestamp range. If null, the range is unbounded from above. */ private final LocalDate untilDate; /** * Optional set to restrict the retrieval to. If null, the retrieval is not restricted to any set. */ private final String setSpec; /** * The URI for the initial request to the repository, created from these settings. */ protected URI uri; /** * Constructs a ListRecordsRequest object. All parameters are optional. * @throws IllegalArgumentException if fromDate is after untilDate. * @throws URISyntaxException if the input did not create a valid URI */ public ListRecordsRequest(LocalDate fromDate, LocalDate untilDate, String setSpec) throws IllegalArgumentException, URISyntaxException { super(Verb.LIST_RECORDS); this.fromDate = fromDate; this.untilDate = untilDate; this.setSpec = setSpec; if (fromDate != null && untilDate != null && fromDate.isAfter(untilDate)) { throw new IllegalArgumentException("tried to create ListRecordsRequest with invalid datestamp range"); } uri = constructURI(); } private URI constructURI() throws URISyntaxException { URIBuilder uriBuilder = getUriBuilder() .setParameter("metadataPrefix", METADATA_PREFIX); if (fromDate != null) { uriBuilder.setParameter("from", fromDate.toString()); } if (untilDate != null) { uriBuilder.setParameter("until", untilDate.toString()); } if (setSpec != null) { uriBuilder.setParameter("set", setSpec); } return uriBuilder.build(); } /** * Static dummy value that gets returned when a {@link ListRecordsResponse} has no resumption. */ public static ListRecordsRequest NONE = createNone(); private static ListRecordsRequest createNone() { try { return new ListRecordsRequest(LocalDate.MAX, LocalDate.MAX, null); } catch (URISyntaxException e) { throw new Error("Error creating ListRecordsRequest.NONE"); } } }
mit
groupdocs-metadata/GroupDocs.Metadata-for-.NET
Examples/GroupDocs.Metadata.Examples.CSharp/AdvancedUsage/ManagingMetadataForSpecificFormats/Document/Diagram/DiagramReadBuiltInProperties.cs
1153
// <copyright company="Aspose Pty Ltd"> // Copyright (C) 2011-2021 GroupDocs. All Rights Reserved. // </copyright> namespace GroupDocs.Metadata.Examples.CSharp.AdvancedUsage.ManagingMetadataForSpecificFormats.Document.Diagram { using System; using Formats.Document; /// <summary> /// This code sample demonstrates how to extract built-in metadata properties from a diagram. /// </summary> public static class DiagramReadBuiltInProperties { public static void Run() { using (Metadata metadata = new Metadata(Constants.InputVsdx)) { var root = metadata.GetRootPackage<DiagramRootPackage>(); Console.WriteLine(root.DocumentProperties.Creator); Console.WriteLine(root.DocumentProperties.Company); Console.WriteLine(root.DocumentProperties.Keywords); Console.WriteLine(root.DocumentProperties.Language); Console.WriteLine(root.DocumentProperties.TimeCreated); Console.WriteLine(root.DocumentProperties.Category); // ... } } } }
mit
tohashi/wareki
src/index.ts
1215
type Options = { unit?: boolean } const eraDataList = [ { code: 'reiwa', firstDate: '2019-05-01', name: '令和' }, { code: 'heisei', firstDate: '1989-01-08', name: '平成' }, { code: 'showa', firstDate: '1926-12-25', name: '昭和' }, { code: 'taisho', firstDate: '1912-07-30', name: '大正' }, { code: 'meiji', firstDate: '1868-01-25', name: '明治' } ] export default function( value: string | number | undefined = Date.now(), opts: Options = {} ): string | number { const dateObj = new Date(value) const year = dateObj.getFullYear() if (isNaN(year)) { return year } let wareki = `${year}` for (const eraData of eraDataList) { const { firstDate } = eraData let { name } = eraData const eraFirstDateObj = new Date(firstDate) if (dateObj.getTime() - eraFirstDateObj.getTime() >= 0) { let eraYear = `${year - eraFirstDateObj.getFullYear() + 1}` if (eraYear === '1') { eraYear = '元' } wareki = `${name}${eraYear}` break } } if (opts.unit) { wareki += '年' } if (!isNaN(Number(wareki))) { return Number(wareki) } return wareki }
mit
outsmartin/ispconfig3
vendor/bundler/ruby/2.0.0/gems/librarian-0.0.26/spec/integration/chef/source/git_spec.rb
15567
require 'pathname' require 'securerandom' require 'librarian' require 'librarian/helpers' require 'librarian/error' require 'librarian/action/resolve' require 'librarian/action/install' require 'librarian/action/update' require 'librarian/chef' module Librarian module Chef module Source describe Git do let(:project_path) do project_path = Pathname.new(__FILE__).expand_path project_path = project_path.dirname until project_path.join("Rakefile").exist? project_path end let(:tmp_path) { project_path.join("tmp/spec/integration/chef/source/git") } after { tmp_path.rmtree if tmp_path && tmp_path.exist? } let(:cookbooks_path) { tmp_path.join("cookbooks") } # depends on repo_path being defined in each context let(:env) { Environment.new(:project_path => repo_path) } context "a single dependency with a git source" do let(:sample_path) { tmp_path.join("sample") } let(:sample_metadata) do Helpers.strip_heredoc(<<-METADATA) version "0.6.5" METADATA end let(:first_sample_path) { cookbooks_path.join("first-sample") } let(:first_sample_metadata) do Helpers.strip_heredoc(<<-METADATA) version "3.2.1" METADATA end let(:second_sample_path) { cookbooks_path.join("second-sample") } let(:second_sample_metadata) do Helpers.strip_heredoc(<<-METADATA) version "4.3.2" METADATA end before do sample_path.rmtree if sample_path.exist? sample_path.mkpath sample_path.join("metadata.rb").open("wb") { |f| f.write(sample_metadata) } Dir.chdir(sample_path) do `git init` `git add metadata.rb` `git commit -m "Initial commit."` end cookbooks_path.rmtree if cookbooks_path.exist? cookbooks_path.mkpath first_sample_path.mkpath first_sample_path.join("metadata.rb").open("wb") { |f| f.write(first_sample_metadata) } second_sample_path.mkpath second_sample_path.join("metadata.rb").open("wb") { |f| f.write(second_sample_metadata) } Dir.chdir(cookbooks_path) do `git init` `git add .` `git commit -m "Initial commit."` end end context "resolving" do let(:repo_path) { tmp_path.join("repo/resolve") } before do repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) #!/usr/bin/env ruby cookbook "sample", :git => #{sample_path.to_s.inspect} CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } end context "the resolve" do it "should not raise an exception" do expect { Action::Resolve.new(env).run }.to_not raise_error end end context "the results" do before { Action::Resolve.new(env).run } it "should create the lockfile" do repo_path.join("Cheffile.lock").should exist end it "should not attempt to install the sample cookbok" do repo_path.join("cookbooks/sample").should_not exist end end end context "installing" do let(:repo_path) { tmp_path.join("repo/install") } before do repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) #!/usr/bin/env ruby cookbook "sample", :git => #{sample_path.to_s.inspect} CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } Action::Resolve.new(env).run end context "the install" do it "should not raise an exception" do expect { Action::Install.new(env).run }.to_not raise_error end end context "the results" do before { Action::Install.new(env).run } it "should create the lockfile" do repo_path.join("Cheffile.lock").should exist end it "should create the directory for the cookbook" do repo_path.join("cookbooks/sample").should exist end it "should copy the cookbook files into the cookbook directory" do repo_path.join("cookbooks/sample/metadata.rb").should exist end end end context "resolving and and separately installing" do let(:repo_path) { tmp_path.join("repo/resolve-install") } before do repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) #!/usr/bin/env ruby cookbook "sample", :git => #{sample_path.to_s.inspect} CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } Action::Resolve.new(env).run repo_path.join("tmp").rmtree if repo_path.join("tmp").exist? end context "the install" do it "should not raise an exception" do expect { Action::Install.new(env).run }.to_not raise_error end end context "the results" do before { Action::Install.new(env).run } it "should create the directory for the cookbook" do repo_path.join("cookbooks/sample").should exist end it "should copy the cookbook files into the cookbook directory" do repo_path.join("cookbooks/sample/metadata.rb").should exist end end end context "resolving, changing, and resolving" do let(:repo_path) { tmp_path.join("repo/resolve-update") } before do repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) git #{cookbooks_path.to_s.inspect} cookbook "first-sample" CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } Action::Resolve.new(env).run cheffile = Helpers.strip_heredoc(<<-CHEFFILE) git #{cookbooks_path.to_s.inspect} cookbook "first-sample" cookbook "second-sample" CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } end context "the second resolve" do it "should not raise an exception" do expect { Action::Resolve.new(env).run }.to_not raise_error end end end end context "with a path" do let(:git_path) { tmp_path.join("big-git-repo") } let(:sample_path) { git_path.join("buttercup") } let(:sample_metadata) do Helpers.strip_heredoc(<<-METADATA) version "0.6.5" METADATA end before do git_path.rmtree if git_path.exist? git_path.mkpath sample_path.mkpath sample_path.join("metadata.rb").open("wb") { |f| f.write(sample_metadata) } Dir.chdir(git_path) do `git init` `git add .` `git commit -m "Initial commit."` end end context "if no path option is given" do let(:repo_path) { tmp_path.join("repo/resolve") } before do repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) #!/usr/bin/env ruby cookbook "sample", :git => #{git_path.to_s.inspect} CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } end it "should not resolve" do expect{ Action::Resolve.new(env).run }.to raise_error end end context "if the path option is wrong" do let(:repo_path) { tmp_path.join("repo/resolve") } before do repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) #!/usr/bin/env ruby cookbook "sample", :git => #{git_path.to_s.inspect}, :path => "jelly" CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } end it "should not resolve" do expect{ Action::Resolve.new(env).run }.to raise_error end end context "if the path option is right" do let(:repo_path) { tmp_path.join("repo/resolve") } before do repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) #!/usr/bin/env ruby cookbook "sample", :git => #{git_path.to_s.inspect}, :path => "buttercup" CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } end context "the resolve" do it "should not raise an exception" do expect { Action::Resolve.new(env).run }.to_not raise_error end end context "the results" do before { Action::Resolve.new(env).run } it "should create the lockfile" do repo_path.join("Cheffile.lock").should exist end end end end context "missing a metadata" do let(:git_path) { tmp_path.join("big-git-repo") } let(:repo_path) { tmp_path.join("repo/resolve") } before do git_path.rmtree if git_path.exist? git_path.mkpath Dir.chdir(git_path) do `git init` `touch not-a-metadata` `git add .` `git commit -m "Initial commit."` end repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) cookbook "sample", :git => #{git_path.to_s.inspect} CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } end context "the resolve" do it "should raise an exception" do expect { Action::Resolve.new(env).run }.to raise_error end it "should explain the problem" do expect { Action::Resolve.new(env).run }. to raise_error(Error, /no metadata file found/i) end end context "the results" do before { Action::Resolve.new(env).run rescue nil } it "should not create the lockfile" do repo_path.join("Cheffile.lock").should_not exist end it "should not create the directory for the cookbook" do repo_path.join("cookbooks/sample").should_not exist end end end context "when upstream updates" do let(:git_path) { tmp_path.join("upstream-updates-repo") } let(:repo_path) { tmp_path.join("repo/resolve-with-upstream-updates") } let(:sample_metadata) do Helpers.strip_heredoc(<<-METADATA) version "0.6.5" METADATA end before do # set up the git repo as normal, but let's also set up a release-stable branch # from which our Cheffile will only pull stable releases git_path.rmtree if git_path.exist? git_path.mkpath git_path.join("metadata.rb").open("w+b"){|f| f.write(sample_metadata)} Dir.chdir(git_path) do `git init` `git add metadata.rb` `git commit -m "Initial Commit."` `git checkout -b some-branch --quiet` `echo 'hi' > some-file` `git add some-file` `git commit -m 'Some File.'` `git checkout master --quiet` end # set up the chef repo as normal, except the Cheffile points to the release-stable # branch - we expect when the upstream copy of that branch is changed, then we can # fetch & merge those changes when we update repo_path.rmtree if repo_path.exist? repo_path.mkpath repo_path.join("cookbooks").mkpath cheffile = Helpers.strip_heredoc(<<-CHEFFILE) cookbook "sample", :git => #{git_path.to_s.inspect}, :ref => "some-branch" CHEFFILE repo_path.join("Cheffile").open("wb") { |f| f.write(cheffile) } Action::Resolve.new(env).run # change the upstream copy of that branch: we expect to be able to pull the latest # when we re-resolve Dir.chdir(git_path) do `git checkout some-branch --quiet` `echo 'ho' > some-other-file` `git add some-other-file` `git commit -m 'Some Other File.'` `git checkout master --quiet` end end let(:metadata_file) { repo_path.join("cookbooks/sample/metadata.rb") } let(:old_code_file) { repo_path.join("cookbooks/sample/some-file") } let(:new_code_file) { repo_path.join("cookbooks/sample/some-other-file") } context "when updating not a cookbook from that source" do before do Action::Update.new(env).run end it "should pull the tip from upstream" do Action::Install.new(env).run metadata_file.should exist #sanity old_code_file.should exist #sanity new_code_file.should_not exist # the assertion end end context "when updating a cookbook from that source" do before do Action::Update.new(env, :names => %w(sample)).run end it "should pull the tip from upstream" do Action::Install.new(env).run metadata_file.should exist #sanity old_code_file.should exist #sanity new_code_file.should exist # the assertion end end end end end end end
mit
Javier3131/ProyectoDAW
public/config.js
1307
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'angleApp'; var applicationModuleVendorDependencies = ['ngRoute', 'ngAnimate', 'ngStorage', 'ngTouch', 'ngCookies', 'pascalprecht.translate', 'ui.bootstrap', 'ui.router', 'oc.lazyLoad', 'cfp.loadingBar', 'ngSanitize', 'ngResource', 'ui.utils', 'tmh.dynamicLocale', //Javier - Agregando dependencia 'angularFileUpload' ]; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })();
mit
mahdihijazi/training
beginner/toolbar/ToolbarSample3/app/src/androidTest/java/com/training/toolbarsample3/ApplicationTest.java
358
package com.training.toolbarsample3; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
sapirgolan/MFIBlocking
MFIblocks/original/src/main/java/DataStructures/EntityProfile.java
798
package DataStructures; import java.io.Serializable; import java.util.HashSet; /** * * @author gap2 */ public class EntityProfile implements Serializable { private static final long serialVersionUID = 122354534453243447L; private HashSet<Attribute> attributes; private String entityUrl; public EntityProfile(String url) { entityUrl = url; attributes = new HashSet(); } public void addAttribute(String propertyName, String propertyValue) { attributes.add(new Attribute(propertyName, propertyValue)); } public String getEntityUrl() { return entityUrl; } public int getProfileSize() { return attributes.size(); } public HashSet<Attribute> getAttributes() { return attributes; } }
mit
jucimarjr/html5games
phaser/ohhman/js/screen/Splash.js
1102
Splash = function() { }; Splash.prototype = { preload : function() { //Preload das telas de Splash game.load.image('bgSplashTeam', fp_bgSplashTeam); game.load.image('bgSplashGame', fp_bgSplashGame); }, create : function() { var bg = game.add.sprite(0, 0, 'bgSplashTeam'); bg.alpha = 0; var fadein = game.add.tween(bg).to( { alpha: 1 }, 2000, Phaser.Easing.Linear.None, true, 0, 0, true); setTimeout(function() { var fadeout = game.add.tween(bg).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true, 0, 0, true); fadeout.onComplete.add(function() { bg.anchor.setTo(0.5,0.5); bg.x = game.width/2; bg.y = game.height/2; bg.loadTexture('bgSplashGame'); var fadein = game.add.tween(bg).to( { alpha: 1 }, 2000, Phaser.Easing.Linear.None, true, 0, 0, true); setTimeout(function() { var fadeout = game.add.tween(bg).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true, 0, 0, true); fadeout.onComplete.add(function(){ //Chamada do Menu game.state.start('sceneMenu'); }); }, 2500); }); }, 3000); } };
mit
mapbox/glsl-optimizer
src/glsl/opt_algebraic.cpp
17921
/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file opt_algebraic.cpp * * Takes advantage of association, commutivity, and other algebraic * properties to simplify expressions. */ #include "ir.h" #include "ir_visitor.h" #include "ir_rvalue_visitor.h" #include "ir_optimization.h" #include "ir_builder.h" #include "glsl_types.h" using namespace ir_builder; namespace { /** * Visitor class for replacing expressions with ir_constant values. */ class ir_algebraic_visitor : public ir_rvalue_visitor { public: ir_algebraic_visitor() { this->progress = false; this->mem_ctx = NULL; } virtual ~ir_algebraic_visitor() { } ir_rvalue *handle_expression(ir_expression *ir); void handle_rvalue(ir_rvalue **rvalue); bool reassociate_constant(ir_expression *ir1, int const_index, ir_constant *constant, ir_expression *ir2); void reassociate_operands(ir_expression *ir1, int op1, ir_expression *ir2, int op2); ir_rvalue *swizzle_if_required(ir_expression *expr, ir_rvalue *operand); void *mem_ctx; bool progress; }; } /* unnamed namespace */ static inline bool is_vec_zero(ir_constant *ir) { return (ir == NULL) ? false : ir->is_zero(); } static inline bool is_vec_one(ir_constant *ir) { return (ir == NULL) ? false : ir->is_one(); } static inline bool is_vec_two(ir_constant *ir) { return (ir == NULL) ? false : ir->is_value(2.0, 2); } static inline bool is_vec_negative_one(ir_constant *ir) { return (ir == NULL) ? false : ir->is_negative_one(); } static inline bool is_vec_basis(ir_constant *ir) { return (ir == NULL) ? false : ir->is_basis(); } static void update_type(ir_expression *ir) { if (ir->operands[0]->type->is_vector()) { ir->type = ir->operands[0]->type; ir->set_precision (ir->operands[0]->get_precision()); } else { ir->type = ir->operands[1]->type; ir->set_precision (ir->operands[1]->get_precision()); } } void ir_algebraic_visitor::reassociate_operands(ir_expression *ir1, int op1, ir_expression *ir2, int op2) { ir_rvalue *temp = ir2->operands[op2]; ir2->operands[op2] = ir1->operands[op1]; ir1->operands[op1] = temp; /* Update the type of ir2. The type of ir1 won't have changed -- * base types matched, and at least one of the operands of the 2 * binops is still a vector if any of them were. */ update_type(ir2); this->progress = true; } /** * Reassociates a constant down a tree of adds or multiplies. * * Consider (2 * (a * (b * 0.5))). We want to send up with a * b. */ bool ir_algebraic_visitor::reassociate_constant(ir_expression *ir1, int const_index, ir_constant *constant, ir_expression *ir2) { if (!ir2 || ir1->operation != ir2->operation) return false; /* Don't want to even think about matrices. */ if (ir1->operands[0]->type->is_matrix() || ir1->operands[1]->type->is_matrix() || ir2->operands[0]->type->is_matrix() || ir2->operands[1]->type->is_matrix()) return false; ir_constant *ir2_const[2]; ir2_const[0] = ir2->operands[0]->constant_expression_value(); ir2_const[1] = ir2->operands[1]->constant_expression_value(); if (ir2_const[0] && ir2_const[1]) return false; if (ir2_const[0]) { reassociate_operands(ir1, const_index, ir2, 1); return true; } else if (ir2_const[1]) { reassociate_operands(ir1, const_index, ir2, 0); return true; } if (reassociate_constant(ir1, const_index, constant, ir2->operands[0]->as_expression())) { update_type(ir2); return true; } if (reassociate_constant(ir1, const_index, constant, ir2->operands[1]->as_expression())) { update_type(ir2); return true; } return false; } /* When eliminating an expression and just returning one of its operands, * we may need to swizzle that operand out to a vector if the expression was * vector type. */ ir_rvalue * ir_algebraic_visitor::swizzle_if_required(ir_expression *expr, ir_rvalue *operand) { if (expr->type->is_vector() && operand->type->is_scalar()) { return new(mem_ctx) ir_swizzle(operand, 0, 0, 0, 0, expr->type->vector_elements); } else return operand; } ir_rvalue * ir_algebraic_visitor::handle_expression(ir_expression *ir) { ir_constant *op_const[4] = {NULL, NULL, NULL, NULL}; ir_expression *op_expr[4] = {NULL, NULL, NULL, NULL}; unsigned int i; assert(ir->get_num_operands() <= 4); for (i = 0; i < ir->get_num_operands(); i++) { if (ir->operands[i]->type->is_matrix()) return ir; op_const[i] = ir->operands[i]->constant_expression_value(); op_expr[i] = ir->operands[i]->as_expression(); } if (this->mem_ctx == NULL) this->mem_ctx = ralloc_parent(ir); switch (ir->operation) { case ir_unop_bit_not: if (op_expr[0] && op_expr[0]->operation == ir_unop_bit_not) return op_expr[0]->operands[0]; break; case ir_unop_abs: if (op_expr[0] == NULL) break; switch (op_expr[0]->operation) { case ir_unop_abs: case ir_unop_neg: return abs(op_expr[0]->operands[0]); default: break; } break; case ir_unop_neg: if (op_expr[0] == NULL) break; if (op_expr[0]->operation == ir_unop_neg) { return op_expr[0]->operands[0]; } if (op_expr[0] && op_expr[0]->operation == ir_binop_sub) { // -(A-B) => (B-A) this->progress = true; return new(mem_ctx) ir_expression(ir_binop_sub, ir->type, op_expr[0]->operands[1], op_expr[0]->operands[0]); } break; case ir_unop_exp: if (op_expr[0] == NULL) break; if (op_expr[0]->operation == ir_unop_log) { return op_expr[0]->operands[0]; } break; case ir_unop_log: if (op_expr[0] == NULL) break; if (op_expr[0]->operation == ir_unop_exp) { return op_expr[0]->operands[0]; } break; case ir_unop_exp2: if (op_expr[0] == NULL) break; if (op_expr[0]->operation == ir_unop_log2) { return op_expr[0]->operands[0]; } break; case ir_unop_log2: if (op_expr[0] == NULL) break; if (op_expr[0]->operation == ir_unop_exp2) { return op_expr[0]->operands[0]; } break; case ir_unop_logic_not: { enum ir_expression_operation new_op = ir_unop_logic_not; if (op_expr[0] == NULL) break; switch (op_expr[0]->operation) { case ir_binop_less: new_op = ir_binop_gequal; break; case ir_binop_greater: new_op = ir_binop_lequal; break; case ir_binop_lequal: new_op = ir_binop_greater; break; case ir_binop_gequal: new_op = ir_binop_less; break; case ir_binop_equal: new_op = ir_binop_nequal; break; case ir_binop_nequal: new_op = ir_binop_equal; break; case ir_binop_all_equal: new_op = ir_binop_any_nequal; break; case ir_binop_any_nequal: new_op = ir_binop_all_equal; break; default: /* The default case handler is here to silence a warning from GCC. */ break; } if (new_op != ir_unop_logic_not) { return new(mem_ctx) ir_expression(new_op, ir->type, op_expr[0]->operands[0], op_expr[0]->operands[1]); } break; } case ir_binop_add: if (is_vec_zero(op_const[0])) return ir->operands[1]; if (is_vec_zero(op_const[1])) return ir->operands[0]; /* Reassociate addition of constants so that we can do constant * folding. */ if (op_const[0] && !op_const[1]) reassociate_constant(ir, 0, op_const[0], op_expr[1]); if (op_const[1] && !op_const[0]) reassociate_constant(ir, 1, op_const[1], op_expr[0]); // A + (-B) => A-B if (op_expr[1] && op_expr[1]->operation == ir_unop_neg) { this->progress = true; return sub(ir->operands[0], op_expr[1]->operands[0]); } /* Replace (-x + y) * a + x and commutative variations with lrp(x, y, a). * * (-x + y) * a + x * (x * -a) + (y * a) + x * x + (x * -a) + (y * a) * x * (1 - a) + y * a * lrp(x, y, a) */ for (int mul_pos = 0; mul_pos < 2; mul_pos++) { ir_expression *mul = op_expr[mul_pos]; if (!mul || mul->operation != ir_binop_mul) continue; /* Multiply found on one of the operands. Now check for an * inner addition operation. */ for (int inner_add_pos = 0; inner_add_pos < 2; inner_add_pos++) { ir_expression *inner_add = mul->operands[inner_add_pos]->as_expression(); if (!inner_add || inner_add->operation != ir_binop_add) continue; /* Inner addition found on one of the operands. Now check for * one of the operands of the inner addition to be the negative * of x_operand. */ for (int neg_pos = 0; neg_pos < 2; neg_pos++) { ir_expression *neg = inner_add->operands[neg_pos]->as_expression(); if (!neg || neg->operation != ir_unop_neg) continue; ir_rvalue *x_operand = ir->operands[1 - mul_pos]; if (!neg->operands[0]->equals(x_operand)) continue; ir_rvalue *y_operand = inner_add->operands[1 - neg_pos]; ir_rvalue *a_operand = mul->operands[1 - inner_add_pos]; if (x_operand->type != y_operand->type || x_operand->type != a_operand->type) continue; return lrp(x_operand, y_operand, a_operand); } } } break; case ir_binop_sub: if (is_vec_zero(op_const[0])) return neg(ir->operands[1]); if (is_vec_zero(op_const[1])) return ir->operands[0]; break; case ir_binop_mul: if (is_vec_one(op_const[0])) return ir->operands[1]; if (is_vec_one(op_const[1])) return ir->operands[0]; if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) return ir_constant::zero(ir, ir->type); if (is_vec_negative_one(op_const[0])) return neg(ir->operands[1]); if (is_vec_negative_one(op_const[1])) return neg(ir->operands[0]); /* Reassociate multiplication of constants so that we can do * constant folding. */ if (op_const[0] && !op_const[1]) reassociate_constant(ir, 0, op_const[0], op_expr[1]); if (op_const[1] && !op_const[0]) reassociate_constant(ir, 1, op_const[1], op_expr[0]); break; case ir_binop_div: if (is_vec_one(op_const[0]) && ir->type->base_type == GLSL_TYPE_FLOAT) { return new(mem_ctx) ir_expression(ir_unop_rcp, ir->operands[1]->type, ir->operands[1], NULL); } if (is_vec_one(op_const[1])) return ir->operands[0]; break; case ir_binop_dot: if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) return ir_constant::zero(mem_ctx, ir->type); if (is_vec_basis(op_const[0])) { unsigned component = 0; for (unsigned c = 0; c < op_const[0]->type->vector_elements; c++) { if (op_const[0]->value.f[c] == 1.0) component = c; } return new(mem_ctx) ir_swizzle(ir->operands[1], component, 0, 0, 0, 1); } if (is_vec_basis(op_const[1])) { unsigned component = 0; for (unsigned c = 0; c < op_const[1]->type->vector_elements; c++) { if (op_const[1]->value.f[c] == 1.0) component = c; } return new(mem_ctx) ir_swizzle(ir->operands[0], component, 0, 0, 0, 1); } break; case ir_binop_rshift: case ir_binop_lshift: /* 0 >> x == 0 */ if (is_vec_zero(op_const[0])) return ir->operands[0]; /* x >> 0 == x */ if (is_vec_zero(op_const[1])) return ir->operands[0]; break; case ir_binop_logic_and: if (is_vec_one(op_const[0])) { return ir->operands[1]; } else if (is_vec_one(op_const[1])) { return ir->operands[0]; } else if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) { return ir_constant::zero(mem_ctx, ir->type); } else if (op_expr[0] && op_expr[0]->operation == ir_unop_logic_not && op_expr[1] && op_expr[1]->operation == ir_unop_logic_not) { /* De Morgan's Law: * (not A) and (not B) === not (A or B) */ return logic_not(logic_or(op_expr[0]->operands[0], op_expr[1]->operands[0])); } else if (ir->operands[0]->equals(ir->operands[1])) { /* (a && a) == a */ return ir->operands[0]; } break; case ir_binop_logic_xor: if (is_vec_zero(op_const[0])) { return ir->operands[1]; } else if (is_vec_zero(op_const[1])) { return ir->operands[0]; } else if (is_vec_one(op_const[0])) { return logic_not(ir->operands[1]); } else if (is_vec_one(op_const[1])) { return logic_not(ir->operands[0]); } else if (ir->operands[0]->equals(ir->operands[1])) { /* (a ^^ a) == false */ return ir_constant::zero(mem_ctx, ir->type); } break; case ir_binop_logic_or: if (is_vec_zero(op_const[0])) { return ir->operands[1]; } else if (is_vec_zero(op_const[1])) { return ir->operands[0]; } else if (is_vec_one(op_const[0]) || is_vec_one(op_const[1])) { ir_constant_data data; for (unsigned i = 0; i < 16; i++) data.b[i] = true; return new(mem_ctx) ir_constant(ir->type, &data); } else if (op_expr[0] && op_expr[0]->operation == ir_unop_logic_not && op_expr[1] && op_expr[1]->operation == ir_unop_logic_not) { /* De Morgan's Law: * (not A) or (not B) === not (A and B) */ return logic_not(logic_and(op_expr[0]->operands[0], op_expr[1]->operands[0])); } else if (ir->operands[0]->equals(ir->operands[1])) { /* (a || a) == a */ return ir->operands[0]; } break; case ir_binop_pow: /* 1^x == 1 */ if (is_vec_one(op_const[0])) return op_const[0]; /* x^1 == x */ if (is_vec_one(op_const[1])) return ir->operands[0]; /* pow(2,x) == exp2(x) */ if (is_vec_two(op_const[0])) return expr(ir_unop_exp2, ir->operands[1]); break; case ir_unop_rcp: if (op_expr[0] && op_expr[0]->operation == ir_unop_rcp) return op_expr[0]->operands[0]; /* While ir_to_mesa.cpp will lower sqrt(x) to rcp(rsq(x)), it does so at * its IR level, so we can always apply this transformation. */ if (op_expr[0] && op_expr[0]->operation == ir_unop_rsq) return sqrt(op_expr[0]->operands[0]); /* As far as we know, all backends are OK with rsq. */ if (op_expr[0] && op_expr[0]->operation == ir_unop_sqrt) { return rsq(op_expr[0]->operands[0]); } break; case ir_triop_fma: /* Operands are op0 * op1 + op2. */ if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) { return ir->operands[2]; } else if (is_vec_zero(op_const[2])) { return mul(ir->operands[0], ir->operands[1]); } else if (is_vec_one(op_const[0])) { return add(ir->operands[1], ir->operands[2]); } else if (is_vec_one(op_const[1])) { return add(ir->operands[0], ir->operands[2]); } break; case ir_triop_lrp: /* Operands are (x, y, a). */ if (is_vec_zero(op_const[2])) { return ir->operands[0]; } else if (is_vec_one(op_const[2])) { return ir->operands[1]; } else if (ir->operands[0]->equals(ir->operands[1])) { return ir->operands[0]; } break; case ir_triop_csel: if (is_vec_one(op_const[0])) return ir->operands[1]; if (is_vec_zero(op_const[0])) return ir->operands[2]; break; default: break; } return ir; } void ir_algebraic_visitor::handle_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_expression *expr = (*rvalue)->as_expression(); if (!expr || expr->operation == ir_quadop_vector) return; ir_rvalue *new_rvalue = handle_expression(expr); if (new_rvalue == *rvalue) return; /* If the expr used to be some vec OP scalar returning a vector, and the * optimization gave us back a scalar, we still need to turn it into a * vector. */ *rvalue = swizzle_if_required(expr, new_rvalue); this->progress = true; } bool do_algebraic(exec_list *instructions) { ir_algebraic_visitor v; visit_list_elements(&v, instructions); return v.progress; }
mit
TekMonks/monkshu
backend/server/lib/Timer.js
430
/* * Timer.js - Resetable timer * * (C) 2018 TekMonks. All rights reserved. */ class Timer { constructor(t, fn) { this.fn = fn; this.timeout = t; this.timer = setTimeout(this.fn, this.timeout); } reset() { clearTimeout(this.timer); this.timer = setTimeout(this.fn, this.timeout); } } exports.createTimer = (time, onTimeout) => {return new Timer(time, onTimeout);}
mit
nagoring/jp-address
src/Nago/JpAddress/StreetData/45/45383.php
88
<?php return ['453830001' => '入野','453830002' => '北俣','453830003' => '南俣',];
mit
dhcode/angular-bingo-game
src/app/bingo/game-board/game-board.component.ts
680
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { BingoGame } from '../bingo-game'; @Component({ selector: 'app-game-board', templateUrl: './game-board.component.html', styleUrls: ['./game-board.component.scss'] }) export class GameBoardComponent implements OnInit { @Input() game: BingoGame; @Output() onFound = new EventEmitter<string>(); constructor() { } ngOnInit() { } getBoardRows() { if (!this.game) { return []; } return this.game.getRows(); } isFound(word: string) { return this.game.foundWords.includes(word); } setFound(word: string) { this.onFound.next(word); } }
mit
sixohsix/simplecoremidi
simplecoremidi/examples/emitter.py
1403
from itertools import chain from heapq import heappush, heappop from time import time, sleep from random import random, randint from simplecoremidi import MIDISource, MIDIDestination LOOP_WAIT = 1.0 / 200 # 200 Hz def gen_all_off(now): return ((now, tuple(chain(*((0x90, n, 0) for n in range(127))))),) def gen_random_notes(now): pitch = randint(24, 72) velocity = randint(80, 127) duration = random() * 0.75 return ((now, (0x90, pitch, velocity)), (now + duration, (0x90, pitch, 0))) def maybe_gen_notes(now): probability = 0.006 if random() < probability: return gen_random_notes(now) else: return () def heappush_all(heap, seq): for item in seq: heappush(heap, item) def emitter(): source = MIDISource("random note emitter") sleep(4) frames = [] frame_time = time() heappush_all(frames, gen_all_off(frame_time)) while True: heappush_all(frames, maybe_gen_notes(frame_time)) while frames and (frames[0][0] < frame_time): midi_out = heappop(frames) print "emit {}".format(midi_out[1]) source.send(midi_out[1]) now = time() wait_time = -1 while wait_time <= 0: frame_time = frame_time + LOOP_WAIT wait_time = frame_time - now sleep(wait_time) if __name__=='__main__': emitter()
mit
tobiaghiraldini/DjangoBBB
profiles/serializers.py
248
# -*- coding: utf-8 -*- from rest_framework import serializers from profiles.models import Profile class ProfileSerializer(serializers.ModelSerializer): user = serializers.Field(source='user.username') class Meta: model = Profile
mit
martijn00/XamarinMediaManager
MediaManager.Forms/Platforms/Android/VideoViewRenderer.cs
2435
using Android.Content; using MediaManager.Forms; using MediaManager.Forms.Platforms.Android; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(VideoView), typeof(VideoViewRenderer))] namespace MediaManager.Forms.Platforms.Android { [global::Android.Runtime.Preserve(AllMembers = true)] public class VideoViewRenderer : Xamarin.Forms.Platform.Android.AppCompat.ViewRenderer<VideoView, MediaManager.Platforms.Android.Video.VideoView> { private MediaManager.Platforms.Android.Video.VideoView _videoView; public VideoViewRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<VideoView> args) { if (args.OldElement != null) { args.OldElement.Dispose(); } if (args.NewElement != null) { if (Control == null) { _videoView = new MediaManager.Platforms.Android.Video.VideoView(Context); SetNativeControl(_videoView); UpdateBackgroundColor(); UpdateLayout(); } } base.OnElementChanged(args); } protected override void UpdateBackgroundColor() { base.UpdateBackgroundColor(); Control?.SetShutterBackgroundColor(Element.BackgroundColor.ToAndroid()); } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (_videoView != null && widthMeasureSpec > -1 && heightMeasureSpec > -1) { var p = _videoView.LayoutParameters; if (p == null) p = new LayoutParams(widthMeasureSpec, heightMeasureSpec); else { p.Height = heightMeasureSpec; p.Width = widthMeasureSpec; } _videoView.LayoutParameters = p; } base.OnMeasure(widthMeasureSpec, heightMeasureSpec); } protected override void Dispose(bool disposing) { //On Android we need to call this manually it seems, since args.OldElement is never filled Element?.Dispose(); _videoView = null; base.Dispose(disposing); } } }
mit
peterdanis/my-js-learning
free-code-camp/where-do-i-belong.js
333
function getIndexToIns(arr, num) { const index = arr.sort((a, b) => a - b).findIndex(x => x >= num); if (index === -1) { return arr.length; } return index; } console.log(getIndexToIns([1, 3], 0.8)); console.log(getIndexToIns([1, 3], 1.8)); console.log(getIndexToIns([1, 3], 3)); console.log(getIndexToIns([1, 3], 3.8));
mit
jonnorstrom/CardShuffler
runner.rb
186
## run this to see how many times you must shuffle a deck ## until it returns back to it's original state require_relative 'cards' p continuous_shuffle(make_deck, shuffle(make_deck), 1)
mit
andrewelkins/Laravel-5-Bootstrap-Starter-Site
app/Http/Controllers/Admin/DashboardController.php
374
<?php namespace Starter\Http\Controllers\Admin; class DashboardController extends Controller { /** * Create a new controller instance. */ public function __construct() { parent::__construct(); } /** * Show the application dashboard to the user. * * @return Response */ public function index() { return view('admin/dashboard'); } }
mit
DanielYKPan/movies-finder
src/app/app.routes.ts
538
import { Routes } from '@angular/router'; import { NoContentComponent } from './no-content'; import { HomeComponent, HomeDataResolver } from "./home"; export const ROUTES: Routes = [ { path: '', component: HomeComponent, resolve: { res: HomeDataResolver } }, {path: 'movies', loadChildren: './+movie#MovieModule'}, {path: 'series', loadChildren: './+tv#TVModule'}, {path: 'actors', loadChildren: './+actor#ActorModule'}, {path: '**', component: NoContentComponent}, ];
mit
sensiolabs-de/deprecation-detector
tests/TypeGuessing/SymbolTable/Resolver/PropertyAssignResolverTest.php
3412
<?php namespace SensioLabs\DeprecationDetector\Tests\TypeGuessing\SymbolTable\Resolver; use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\PropertyFetch; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; use PhpParser\Node\Expr\New_; use SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\Resolver\PropertyAssignResolver; use SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\Symbol; class PropertyAssignResolverTest extends \PHPUnit_Framework_TestCase { public function testClassIsInitializable() { $table = $this->prophesize('SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\SymbolTable'); $resolver = new PropertyAssignResolver($table->reveal()); $this->assertInstanceOf( 'SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\Resolver\PropertyAssignResolver', $resolver ); } public function testAssignPropertyWithClass() { $table = $this->prophesize('SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\SymbolTable'); $resolver = new PropertyAssignResolver($table->reveal()); $left = new PropertyFetch(new Variable('this'), 'prop'); $right = new New_(new Name('SomeClass')); $node = new Assign($left, $right); $resolver->resolveVariableType($node); $this->assertSame('SomeClass', $node->var->getAttribute('guessedType')); } public function testAssignPropertyWithVariable() { $table = $this->prophesize('SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\SymbolTable'); $table->lookUp('someVar')->willReturn(new Symbol('someVar', 'SomeClass')); $table->setClassProperty('prop', 'SomeClass')->shouldBeCalled(); $resolver = new PropertyAssignResolver($table->reveal()); $left = new PropertyFetch(new Variable('this'), 'prop'); $right = new Variable('someVar'); $node = new Assign($left, $right); $resolver->resolveVariableType($node); $this->assertSame('SomeClass', $node->var->getAttribute('guessedType')); } public function testAssignPropertyVariableWithVariable() { $table = $this->prophesize('SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\SymbolTable'); $table->setClassProperty('prop', 'SomeClass')->shouldNotBeCalled(); $resolver = new PropertyAssignResolver($table->reveal()); $left = new PropertyFetch(new Variable('this'), new Variable('prop')); $right = new Variable('someVar'); $node = new Assign($left, $right); $resolver->resolveVariableType($node); $this->assertNull($node->var->getAttribute('guessedType')); } public function testAssignPropertyWithProperty() { $table = $this->prophesize('SensioLabs\DeprecationDetector\TypeGuessing\SymbolTable\SymbolTable'); $table->lookUpClassProperty('someProp')->willReturn(new Symbol('someProp', 'SomeClass')); $table->setClassProperty('prop', 'SomeClass')->shouldBeCalled(); $resolver = new PropertyAssignResolver($table->reveal()); $left = new PropertyFetch(new Variable('this'), 'prop'); $right = new PropertyFetch(new Variable('this'), 'someProp'); $node = new Assign($left, $right); $resolver->resolveVariableType($node); $this->assertSame('SomeClass', $node->var->getAttribute('guessedType')); } }
mit
feskne/POS_Projekt
app/src/main/java/com/example/ratzf/pos_projekt/MainActivity.java
349
package com.example.ratzf.pos_projekt; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { //seas @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
mit
codeminery/gfw
app/assets/javascripts/abstract/timeline/TimelineBtnClass.js
7462
/** * The Timeline view module. * * Timeline for all layers configured by setting layer-specific options. * * @return Timeline view (extends Backbone.View). */ define([ 'underscore', 'backbone', 'moment', 'handlebars', 'd3', 'text!templates/timelineBtn-mobile.handlebars' ], function(_, Backbone, moment, Handlebars, d3, tplMobile) { 'use strict'; var TimelineBtnClass = Backbone.View.extend({ className: 'timeline-btn', templateMobile: Handlebars.compile(tplMobile), defaults: { dateRange: [moment([2001]), moment()], width: 1000, height: 50, tickWidth: 120, tipsy: true }, events: { 'change .select-date' : 'setSelects' }, initialize: function(layer, currentDate) { _.bindAll(this, '_onClickTick', '_selectDate'); this.layer = layer; this.name = layer.slug; ga('send', 'event', 'Map', 'Settings', 'Timeline: ' + layer.slug); this.options = _.extend({}, this.defaults, this.options || {}); this.data = this._getData(); if (currentDate && currentDate[0]) { this.currentDate = currentDate; } else { this._updateCurrentDate([this.data[this.data.length - 1].start, this.data[this.data.length - 1].end]); } // d3 slider objets this.svg = {}; this.xscale = {}; enquire.register("screen and (min-width:"+window.gfw.config.GFW_MOBILE+"px)", { match: _.bind(function(){ this.render(_.bind(function() { this._selectDate({ start: this.currentDate[0], end: this.currentDate[1] }); }, this)); },this) }); enquire.register("screen and (max-width:"+window.gfw.config.GFW_MOBILE+"px)", { match: _.bind(function(){ this.renderMobile(); },this) }); }, renderMobile: function(){ this.$timeline = $('.timeline-container'); this.$el.html(this.templateMobile({name:this.layer.title})); this.$timeline.html('').append(this.el); this.$selects = $('.select-date'); this.$from = $('#from-timeline'); this.fillSelects(); }, fillSelects: function(){ var options = ''; var currentIndex = this.data.length - 1; var currentDate = this.currentDate; var dformat = 'DD-MM-YYYY'; _.each(this.data, function(label, i){ options += '<option value="'+i+'">'+label.label+'</option>'; if (label.start.format(dformat) == currentDate[0].format(dformat) && label.end.format(dformat) == currentDate[1].format(dformat)) { currentIndex = i; } }); this.$from.html(options).val(currentIndex); this.setSelects(); }, setSelects: function(){ var index = this.$from[0].selectedIndex; var $dateButton = $('#'+this.$from.attr('id')+'-button'); $dateButton.text(this.data[index].label); this._updateCurrentDate([this.data[index].start,this.data[index].end]); }, /** * Render d3 timeline slider. */ render: function(callback) { var self = this; this.$timeline = $('.timeline-container'); this.$timeline.html('').append(this.el); // SVG options var margin = {top: 0, right: 15, bottom: 0, left: 15}; var width = this.options.width - margin.left - margin.right; var height = this.options.height - margin.bottom - margin.top; // Set xscale this.xscale = d3.scale.linear() .domain([moment(this.options.dateRange[0]).month(), moment(this.options.dateRange[1]).month()]) .range([0, width]) .clamp(true); // Set SVG this.svg = d3.select(this.el) .append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .attr('style','width:'+ (width + margin.left + margin.right) +'px;') .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // Set tipsy if (this.options.tipsy) { this.tipsy = this.svg.append('g') .attr('class', 'tipsy') .style('visibility', 'hidden'); this.tooltip = d3.select(this.el).append('div') .attr('class', 'tooltip') .style('left', width + 'px') .style('visibility', 'hidden'); } // Set ticks this.tickG = this.svg.append('g') .attr('class', 'ticks') .selectAll('g') .data(this.data) .enter() .append('g') .attr('class', 'tick') .attr('transform', _.bind(function(d, i) { i++; var slotWidth = (width / this.data.length); var x = (i * slotWidth) + ((slotWidth - this.options.tickWidth) / 2) - slotWidth; return 'translate(' + x + ', 13)'; }, this)); this.tickG.append('rect') .attr('width', this.options.tickWidth) .attr('height', 24) .attr('ry', 12); this.tickG.append('text') .attr('y', 16) .attr('x', this.options.tickWidth/2) .attr('text-anchor', 'middle') .text(function(d) { return d.label; }); this.tickG .on('click', function(date, i) { self._onClickTick(this, date, i); }); callback(); }, _onClickTick: function(el, date) { this._selectDate(date, el); this._updateCurrentDate([date.start, date.end]); ga('send', 'event', 'Map', 'Settings', 'Timeline: '+ el); }, /** * Add selected class to the tick and moves * the tipsy to that position. * * @param {object} el Tipsy element * @param {date} date {start:{}, end:{}} */ _selectDate: function(date, el) { if (!el) { el = this.tickG.filter(function(d) { var dformat = 'DD-MM-YYYY'; return (d.start.format(dformat) === date.start.format(dformat) && d.end.format(dformat) === date.end.format(dformat)); }).node(); } el = d3.select(el); var x = d3.transform(el.attr('transform')).translate[0]; this.svg.selectAll('.tick').filter(function() { d3.select(this).classed('selected', false); }); el.classed('selected', true); // Move tipsy if (this.options.tipsy) { var duration = (this.tipsy.style('visibility') === 'visible') ? 100 : 0; this.tipsy .style('visibility', 'visible'); this.tooltip .transition() .duration(duration) .ease('line') .text(this._getTooltipText(date)) .style('left', x + 'px') .style('visibility', 'visible'); } ga('send', 'event', 'Map', 'Settings', 'Timeline: ' + el); }, _getTooltipText: function(date) { return '{0}-{1} {2}'.format(date.start.format('MMM'), date.end.format('MMM'), date.end.year()); }, /** * Handles a timeline date change UI event by dispaching * to TimelinePresenter. * * @param {Array} timelineDate 2D array of moment dates [begin, end] */ _updateCurrentDate: function(date) { this.currentDate = date; this.presenter.updateTimelineDate(date); }, getName: function() { return this.name; }, getCurrentDate: function() { return this.currentDate; } }); return TimelineBtnClass; });
mit
nambawan/g-old
src/components/TableRow/TableRow.js
820
import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/withStyles'; import classnames from 'classnames'; import s from './TableRow.css'; class TableRow extends React.Component { static propTypes = { children: PropTypes.element, className: PropTypes.string, onClick: PropTypes.func, }; static defaultProps = { children: null, className: null, onClick: null, }; render() { const { children, className, onClick, ...otherProps } = this.props; const classes = classnames( { [s.selectable]: onClick, }, s.row, className, ); return ( <tr {...otherProps} className={classes} onClick={onClick}> {children} </tr> ); } } export default withStyles(s)(TableRow);
mit
mgax/mptracker
alembic/versions/38579825699_person_minority_colu.py
268
revision = '38579825699' down_revision = '4bc50a6cca9' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('person', sa.Column('minority', sa.Boolean(), nullable=True)) def downgrade(): op.drop_column('person', 'minority')
mit
ychaker/sunspot_admin
spec/sunspot_helper.rb
734
require "net/http" class CukeSunspot def initialize @server = Sunspot::Rails::Server.new end def start @started = Time.now @server.start up end def self.stop puts "Sunspot server is stoping..." Sunspot::Rails::Server.new.stop end private def port @server.port end def uri "http://0.0.0.0:#{port}/solr/" end def up while starting puts "Sunspot server is starting..." end puts "Sunspot server took #{'%.2f' % (Time.now - @started)} sec. to get up and running. Let's cuke!" end def starting begin sleep(1) request = Net::HTTP.get_response(URI.parse(uri)) false rescue Errno::ECONNREFUSED true end end end
mit
vegvari/AliusInjector
src/Injector.php
6476
<?php namespace Alius\Injector; use Closure; use ReflectionClass; use ReflectionFunction; use ReflectionParameter; use Alius\Injector\Exceptions\AlreadyShared; use Alius\Injector\Exceptions\ImplementationNotFound; use Alius\Injector\Exceptions\SharedInstanceArguments; use Alius\Injector\Exceptions\ImplementationAlreadySet; class Injector { /** * @var array */ protected $shared = []; /** * @var array */ protected $shared_interfaces = []; /** * @var array */ protected $interfaces = []; /** * @param array $shared * @param array $implementations */ public function __construct(array $shared = [], array $implementations = []) { foreach ($shared as $key => $value) { $this->shared($value); } foreach ($implementations as $key => $value) { $this->setImplementation($key, $value); } } /** * Define a shared class * * @param string $class_name * @param array $class_args */ public function shared($class_name, array $class_args = []) { if ($this->isShared($class_name)) { throw new AlreadyShared($class_name); } $this->shared[$class_name]['instance'] = null; $this->shared[$class_name]['args'] = $class_args; foreach (class_implements($class_name) as $value) { if (! isset($this->shared_interfaces[$value])) { $this->shared_interfaces[$value] = $class_name; } } } /** * Is this class shared? * * @param string $class_name * * @return bool */ public function isShared($class_name) { return array_key_exists($class_name, $this->shared); } /** * Set an interface implementation * * @param string $interface_name * @param string $class_name */ public function setImplementation($interface_name, $class_name) { if (isset($this->interfaces[$interface_name])) { throw new ImplementationAlreadySet($interface_name, $this->interfaces[$interface_name]); } $this->interfaces[$interface_name] = $class_name; } /** * Get the class name of the registered implementation * * @param string $interface_name * * @return string */ public function getImplementation($interface_name) { if (isset($this->interfaces[$interface_name])) { return $this->interfaces[$interface_name]; } elseif (isset($this->shared_interfaces[$interface_name])) { return $this->shared_interfaces[$interface_name]; } throw new ImplementationNotFound($interface_name); } /** * Get a shared or new instance * * @param string $class_name The name of the class * @param array $class_args * * @return object */ public function get($class_name, array $class_args = []) { if ($this->isShared($class_name)) { if (! empty($class_args)) { throw new SharedInstanceArguments($class_name); } if ($this->shared[$class_name]['instance'] === null) { $this->shared[$class_name]['instance'] = $this->make($class_name, $this->shared[$class_name]['args']); } return $this->shared[$class_name]['instance']; } return $this->make($class_name, $class_args); } /** * Create a new instance or invoke a Closure * * @param string|Closure $class_name * @param array $custom_args * * @return object */ public function make($class_name, array $custom_args = []) { // Closure if ($class_name instanceof Closure) { $reflection = new ReflectionFunction($class_name); $params = $reflection->getParameters(); return call_user_func_array([$class_name, '__invoke'], $this->createArguments($params, $custom_args)); } // Interface $reflection = new ReflectionClass($class_name); if ($reflection->isInterface()) { return $this->get($this->getImplementation($class_name), $custom_args); } // Class $constructor = $reflection->getConstructor(); if ($constructor !== null) { $params = $constructor->getParameters(); return $reflection->newInstanceArgs($this->createArguments($params, $custom_args)); } return $reflection->newInstanceArgs([]); } /** * Create an argument array * * @param array $params * @param array $custom_args * * @return array */ protected function createArguments(array $params, array $custom_args = []) { $arguments = []; foreach ($params as $param_key => $param) { $arguments[$param_key] = $this->getDefaultValue($param); $name = $param->getName(); $hint = $this->getTypeHint($param); // Get the custom argument based on the argument's name or position if (array_key_exists($name, $custom_args)) { $arguments[$param_key] = $custom_args[$name]; } elseif (array_key_exists($param_key, $custom_args)) { $arguments[$param_key] = $custom_args[$param_key]; } // Invoke the closure or get the hinted instance if ($hint !== Closure::class && $arguments[$param_key] instanceof Closure) { $arguments[$param_key] = $this->make($arguments[$param_key]); } elseif (empty($custom_args) && $hint !== null && ! $param->isOptional()) { $arguments[$param_key] = $this->get($hint); } } return $arguments; } /** * Get the default value of the parameter * * @param ReflectionParameter $param * * @return mixed */ protected function getDefaultValue(ReflectionParameter $param) { if ($param->isDefaultValueAvailable()) { return $param->getDefaultValue(); } } /** * Get the type hint of the parameter * * @param ReflectionParameter $param * * @return string|null */ protected function getTypeHint(ReflectionParameter $param) { if ($param->getClass() !== null) { return $param->getClass()->name; } } }
mit
mgomes/lamer
spec/lamer_spec.rb
3430
require File.dirname(__FILE__) + '/spec_helper' describe "A new Lamer" do before(:each) do @la = Lamer.new end it "should have a blank argument list" do @la.argument_list.empty?.should == true end it "should record valid bitrates" do @la.bitrate 128 @la.options[:bitrate].should == "-b 128" end it "should record valid sample rates" do @la.sample_rate 44.1 @la.options[:sample_rate].should == "--resample 44.1" end it "should record valid VBR quality" do @la.vbr_quality 5 @la.options[:vbr_quality].should == "-V 5" @la.options[:vbr].should == "-v" end it "should record valid quality" do @la.encode_quality 1 @la.options[:encode_quality].should == "-q 1" end it "should record valid quality" do @la.encode_quality 5 @la.options[:encode_quality].should == "-q 5" end it "should record valid quality shortcut" do @la.encode_quality :high @la.options[:encode_quality].should == "-q 2" @la.encode_quality :fast @la.options[:encode_quality].should == "-q 7" end it "should balk at invalid bitrates" do lambda {@la.bitrate 113}.should raise_error(ArgumentError) end it "should balk at invalid sample rates" do lambda {@la.sample_rate 113}.should raise_error(ArgumentError) end it "should balk at invalid VBR qualities" do lambda {@la.vbr_quality 113}.should raise_error(ArgumentError) end it "should balk at invalid encode qualities" do lambda {@la.encode_quality 113}.should raise_error(ArgumentError) end it "should set mode to stereo or mono" do {:stereo => '-m s', :mono => '-m m', :joint => '-m j'}.each do |option, setting| @la.mode option @la.options[:mode].should == setting end end it "should set mode to nil on bad option" do @la.mode :bugz @la.options[:mode].should == nil end it "should accept flag that input is mp3" do @la.input_mp3! @la.options[:input_mp3].should == "--mp3input" end it "should accept an input filename" do @la.input_file "/Path/to/my/audio_file.wav" @la.command_line.should == "lame /Path/to/my/audio_file.wav" end it "should accept replygain options" do {:accurate => "--replaygain-accurate", :fast => "--replaygain-fast", :none => "--noreplaygain", :clip_detect => "--clipdetect", :default => nil }.each do |option, setting| @la.replay_gain option @la.options[:replay_gain].should == setting end end it "should accept raw PCM files" do @la.input_raw 44.1 @la.options[:input_raw].should == "-r -s 44.1" @la.input_raw 32, true @la.options[:input_raw].should == "-r -s 32 -x" end it "should mark as copy when requested" do @la.mark_as_copy! @la.options[:copy].should == "-o" end it "should mark as copy when starting from a file ending in .mp3" do @la.input_file "/Path/to/my/audio_file.mp3" @la.options[:copy].should == "-o" end it "should mark as copy when starting from an mp3 file" do @la.input_mp3! @la.options[:copy].should == "-o" end it "should not mark as copy when starting from a file not ending in .mp3" do @la.input_file "/Path/to/my/audio_file.aif" @la.options[:copy].should == nil end it "should output ogg files when requested" do @la.output_ogg! @la.options[:output_ogg].should == "--ogg" end end
mit
vulcansteel/autorest
AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs
32701
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Dictionary operations. /// </summary> public partial class Dictionary : IServiceOperations<AutoRestComplexTestService>, IDictionary { /// <summary> /// Initializes a new instance of the Dictionary class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Dictionary(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types with dictionary property /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with dictionary property /// </summary> /// <param name='defaultProgram'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { DictionaryWrapper complexBody = null; if (defaultProgram != null) { complexBody = new DictionaryWrapper(); complexBody.DefaultProgram = defaultProgram; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with dictionary property which is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with dictionary property which is empty /// </summary> /// <param name='defaultProgram'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { DictionaryWrapper complexBody = null; if (defaultProgram != null) { complexBody = new DictionaryWrapper(); complexBody.DefaultProgram = defaultProgram; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with dictionary property which is null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/null").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with dictionary property while server doesn't provide a /// response payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/notprovided").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DictionaryWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
mit
yksz/netlib
src/netlib/error.cpp
13291
#include "netlib/error.h" #include <map> #if defined(_WIN32) || defined(_WIN64) #include <winsock2.h> #else #include <cerrno> #include <netdb.h> #endif // defined(_WIN32) || defined(_WIN64) #ifdef NETLIB_USE_OPENSSL #include <openssl/err.h> #endif // NETLIB_USE_OPENSSL namespace net { const error error::nil = { etype::base, 0 }; const error error::unknown = { etype::base, 1 }; const error error::eof = { etype::base, 2 }; const error error::illegal_argument = { etype::base, 3 }; const error error::illegal_state = { etype::base, 4 }; const error error::not_found = { etype::base, 5 }; #if defined(_WIN32) || defined(_WIN64) const error error::perm = { etype::os, ERROR_ACCESS_DENIED }; const error error::noent = { etype::os, ENOENT }; const error error::intr = { etype::os, WSAEINTR }; const error error::io = { etype::os, EIO }; const error error::badf = { etype::os, WSAEBADF }; const error error::nomem = { etype::os, ERROR_OUTOFMEMORY }; const error error::acces = { etype::os, WSAEACCES }; const error error::fault = { etype::os, WSAEFAULT }; const error error::notdir = { etype::os, ENOTDIR }; const error error::isdir = { etype::os, EISDIR }; const error error::inval = { etype::os, WSAEINVAL }; const error error::nfile = { etype::os, ENFILE }; const error error::mfile = { etype::os, WSAEMFILE }; const error error::notty = { etype::os, ENOTTY }; const error error::fbig = { etype::os, EFBIG }; const error error::nospc = { etype::os, ENOSPC }; const error error::rofs = { etype::os, EROFS }; const error error::pipe = { etype::os, ERROR_BROKEN_PIPE }; const error error::again = { etype::os, ERROR_RETRY }; const error error::wouldblock = { etype::os, WSAEWOULDBLOCK }; const error error::inprogress = { etype::os, WSAEINPROGRESS }; const error error::already = { etype::os, WSAEALREADY }; const error error::notsock = { etype::os, WSAENOTSOCK }; const error error::destaddrreq = { etype::os, WSAEDESTADDRREQ }; const error error::msgsize = { etype::os, WSAEMSGSIZE }; const error error::prototype = { etype::os, WSAEPROTOTYPE }; const error error::noprotoopt = { etype::os, WSAENOPROTOOPT }; const error error::protonosupport = { etype::os, WSAEPROTONOSUPPORT }; const error error::opnotsupp = { etype::os, WSAEOPNOTSUPP }; const error error::afnosupport = { etype::os, WSAEAFNOSUPPORT }; const error error::addrinuse = { etype::os, WSAEADDRINUSE }; const error error::addrnotavail = { etype::os, WSAEADDRNOTAVAIL }; const error error::netdown = { etype::os, WSAENETDOWN }; const error error::netunreach = { etype::os, WSAENETUNREACH }; const error error::netreset = { etype::os, WSAENETRESET }; const error error::connaborted = { etype::os, WSAECONNABORTED }; const error error::connreset = { etype::os, WSAECONNRESET }; const error error::nobufs = { etype::os, WSAENOBUFS }; const error error::isconn = { etype::os, WSAEISCONN }; const error error::notconn = { etype::os, WSAENOTCONN }; const error error::timedout = { etype::os, WSAETIMEDOUT }; const error error::connrefused = { etype::os, WSAECONNREFUSED }; const error error::loop = { etype::os, WSAELOOP }; const error error::nametoolong = { etype::os, WSAENAMETOOLONG }; const error error::hostunreach = { etype::os, WSAEHOSTUNREACH }; const error error::proto = { etype::os, EPROTO }; const error error::host_not_found = { etype::netdb, WSAHOST_NOT_FOUND }; const error error::no_data = { etype::netdb, WSANO_DATA }; const error error::no_recovery = { etype::netdb, WSANO_RECOVERY }; const error error::try_again = { etype::netdb, WSATRY_AGAIN }; #else const error error::perm = { etype::os, EPERM }; const error error::noent = { etype::os, ENOENT }; const error error::intr = { etype::os, EINTR }; const error error::io = { etype::os, EIO }; const error error::badf = { etype::os, EBADF }; const error error::nomem = { etype::os, ENOMEM }; const error error::acces = { etype::os, EACCES }; const error error::fault = { etype::os, EFAULT }; const error error::notdir = { etype::os, ENOTDIR }; const error error::isdir = { etype::os, EISDIR }; const error error::inval = { etype::os, EINVAL }; const error error::nfile = { etype::os, ENFILE }; const error error::mfile = { etype::os, EMFILE }; const error error::notty = { etype::os, ENOTTY }; const error error::fbig = { etype::os, EFBIG }; const error error::nospc = { etype::os, ENOSPC }; const error error::rofs = { etype::os, EROFS }; const error error::pipe = { etype::os, EPIPE }; const error error::again = { etype::os, EAGAIN }; const error error::wouldblock = { etype::os, EWOULDBLOCK }; const error error::inprogress = { etype::os, EINPROGRESS }; const error error::already = { etype::os, EALREADY }; const error error::notsock = { etype::os, ENOTSOCK }; const error error::destaddrreq = { etype::os, EDESTADDRREQ }; const error error::msgsize = { etype::os, EMSGSIZE }; const error error::prototype = { etype::os, EPROTOTYPE }; const error error::noprotoopt = { etype::os, ENOPROTOOPT }; const error error::protonosupport = { etype::os, EPROTONOSUPPORT }; const error error::opnotsupp = { etype::os, EOPNOTSUPP }; const error error::afnosupport = { etype::os, EAFNOSUPPORT }; const error error::addrinuse = { etype::os, EADDRINUSE }; const error error::addrnotavail = { etype::os, EADDRNOTAVAIL }; const error error::netdown = { etype::os, ENETDOWN }; const error error::netunreach = { etype::os, ENETUNREACH }; const error error::netreset = { etype::os, ENETRESET }; const error error::connaborted = { etype::os, ECONNABORTED }; const error error::connreset = { etype::os, ECONNRESET }; const error error::nobufs = { etype::os, ENOBUFS }; const error error::isconn = { etype::os, EISCONN }; const error error::notconn = { etype::os, ENOTCONN }; const error error::timedout = { etype::os, ETIMEDOUT }; const error error::connrefused = { etype::os, ECONNREFUSED }; const error error::loop = { etype::os, ELOOP }; const error error::nametoolong = { etype::os, ENAMETOOLONG }; const error error::hostunreach = { etype::os, EHOSTUNREACH }; const error error::proto = { etype::os, EPROTO }; const error error::host_not_found = { etype::netdb, EAI_NONAME }; const error error::no_data = { etype::netdb, EAI_NODATA }; const error error::no_recovery = { etype::netdb, EAI_FAIL }; const error error::try_again = { etype::netdb, EAI_AGAIN }; #endif // defined(_WIN32) || defined(_WIN64) const error error::ssl_cert = { etype::ssl, -1 }; static const std::map<const error, const char*> emessages { { error::unknown, "Unknown error" }, { error::nil, "No error" }, { error::eof, "End of file" }, { error::illegal_argument, "Illegal argument" }, { error::illegal_state, "Illegal state" }, { error::not_found, "Element not found" }, { error::perm, "Operation not permitted" }, { error::noent, "No such file or directory" }, { error::intr, "Interrupted system call" }, { error::io, "Input/output error" }, { error::badf, "Bad file descriptor" }, { error::nomem, "Cannot allocate memory" }, { error::acces, "Permission denied" }, { error::fault, "Bad address" }, { error::notdir, "Not a directory" }, { error::isdir, "Is a directory" }, { error::inval, "Invalid argument" }, { error::nfile, "Too many open files in system" }, { error::mfile, "Too many open files" }, { error::notty, "Inappropriate ioctl for device" }, { error::fbig, "File too large" }, { error::nospc, "No space left on device" }, { error::rofs, "Read-only file system" }, { error::pipe, "Broken pipe" }, { error::again, "Resource temporarily unavailable" }, { error::wouldblock, "Operation would block" }, { error::inprogress, "Operation now in progress" }, { error::already, "Operation already in progress" }, { error::notsock, "Socket operation on non-socket" }, { error::destaddrreq, "Destination address required" }, { error::msgsize, "Message too long" }, { error::prototype, "Protocol wrong type for socket" }, { error::noprotoopt, "Protocol not available" }, { error::protonosupport, "Protocol not supported" }, { error::opnotsupp, "Operation not supported" }, { error::afnosupport, "Address family not supported by protocol family" }, { error::addrinuse, "Address already in use" }, { error::addrnotavail, "Can't assign requested address" }, { error::netdown, "Network is down" }, { error::netunreach, "Network is unreachable" }, { error::netreset, "Network dropped connection on reset" }, { error::connaborted, "Software caused connection abort" }, { error::connreset, "Connection reset by peer" }, { error::nobufs, "No buffer space available" }, { error::isconn, "Socket is already connected" }, { error::notconn, "Socket is not connected" }, { error::timedout, "Operation timed out" }, { error::connrefused, "Connection refused" }, { error::loop, "Too many levels of symbolic links" }, { error::nametoolong, "File name too long" }, { error::hostunreach, "No route to host" }, { error::proto, "Protocol error" }, { error::host_not_found, "No such host is known" }, { error::no_data, "The requested name is valid but does not have an IP address" }, { error::no_recovery, "A nonrecoverable name server error occurred" }, { error::try_again, "A temporary error occurred on an authoritative name server" }, { error::ssl_cert, "Certificate error" }, }; const char* error::Message(const error& err) { #ifdef NETLIB_USE_OPENSSL if (err.type == etype::ssl) { const char* s = ERR_reason_error_string(err.code); if (s != nullptr) { return s; } } #endif // NETLIB_USE_OPENSSL auto it = emessages.find(err); if (it != emessages.end()) { return it->second; } switch (err.type) { case etype::base: return "base error"; case etype::os: return "os error"; case etype::netdb: return "netdb error"; case etype::ssl: return "ssl error"; default: return ""; } } error error::wrap(const etype& type, const int& err) { if (err == 0) { return error::nil; } return { type, err }; } } // namespace net
mit