code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
using System.Linq;
using EspaceClient.FrontOffice.Business.Depots;
using EspaceClient.FrontOffice.Domaine;
namespace EspaceClient.FrontOffice.Data.Depots
{
public partial class DepotTypeRenduBloc : Depot<TypeRenduBloc>, IDepotTypeRenduBloc
{
public TypeRenduBloc GetByCode(string code, string codeTypeBloc)
{
var query = from trb in DbContext.TypeRenduBlocs
where trb.Code == code
where trb.TypeBloc.Code == codeTypeBloc
select trb;
return query.FirstOrDefault();
}
}
}
| apo-j/Projects_Working | EC/espace-client-dot-net/EspaceClient.FrontOffice.Data/Depots/DepotTypeRenduBloc.BackOffice.cs | C# | mit | 604 |
'use strict'
const { EventEmitter } = require('events')
const { Multiaddr } = require('multiaddr')
/**
* @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener
*/
/**
* @param {import('../')} libp2p
* @returns {Listener} a transport listener
*/
module.exports = (libp2p) => {
const listeningAddrs = new Map()
/**
* Add swarm handler and listen for incoming connections
*
* @param {Multiaddr} addr
* @returns {Promise<void>}
*/
async function listen (addr) {
const addrString = String(addr).split('/p2p-circuit').find(a => a !== '')
const relayConn = await libp2p.dial(new Multiaddr(addrString))
const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')
listeningAddrs.set(relayConn.remotePeer.toB58String(), relayedAddr)
listener.emit('listening')
}
/**
* Get fixed up multiaddrs
*
* NOTE: This method will grab the peers multiaddrs and expand them such that:
*
* a) If it's an existing /p2p-circuit address for a specific relay i.e.
* `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the
* address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where
* `QmPeer` is this peers id
* b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit
* addr, such when dialing over a relay with this address, it will create the circuit using
* the encapsulated transport address. This is useful when for example, a peer should only
* be dialed over TCP rather than any other transport
*
* @returns {Multiaddr[]}
*/
function getAddrs () {
const addrs = []
for (const addr of listeningAddrs.values()) {
addrs.push(addr)
}
return addrs
}
/** @type Listener */
const listener = Object.assign(new EventEmitter(), {
close: () => Promise.resolve(),
listen,
getAddrs
})
// Remove listeningAddrs when a peer disconnects
libp2p.connectionManager.on('peer:disconnect', (connection) => {
const deleted = listeningAddrs.delete(connection.remotePeer.toB58String())
if (deleted) {
// Announce listen addresses change
listener.emit('close')
}
})
return listener
}
| libp2p/js-libp2p | src/circuit/listener.js | JavaScript | mit | 2,218 |
using System.Collections.Generic;
namespace BlobTransfer
{
public class TransferResult
{
public List<string> Succeeded { get; set; } = new List<string>();
public List<string> Skipped { get; set; } = new List<string>();
public List<string> Failed { get; set; } = new List<string>();
}
}
| jhkimnew/iistest | temp/BlobTransfer/src/TransferResult.cs | C# | mit | 324 |
using System.Reflection;
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("Twainsoft.FHDO.Compiler.App")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Twainsoft.FHDO.Compiler.App")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("c67323cd-9d0c-4fbd-9ff4-3c0cad27d20c")]
// 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")]
| fdeitelhoff/Twainsoft.FHDO.Compiler | src/Twainsoft.FHDO.Compiler.App/Properties/AssemblyInfo.cs | C# | mit | 1,391 |
using Owin;
using SimpleInjector;
using SimpleInjector.Extensions.ExecutionContextScoping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Reporter.WebAPI.Infrastructure.Owin
{
public static class OwinContextExecutionScopeMiddleware
{
public static void UseOwinContextExecutionScope(this IAppBuilder app, Container container)
{
// Create an OWIN middleware to create an execution context scope
app.Use(async (context, next) =>
{
using (var scope = container.BeginExecutionContextScope())
{
await next.Invoke();
}
});
}
}
} | darjanbogdan/reporter | src/Reporter.WebAPI/Infrastructure/Owin/OwinContextExecutionScopeMiddleware.cs | C# | mit | 725 |
#------------------------------------------------------------------------------
# Copyright (c) 2013 The University of Manchester, UK.
#
# BSD Licenced. See LICENCE.rdoc for details.
#
# Taverna Player was developed in the BioVeL project, funded by the European
# Commission 7th Framework Programme (FP7), through grant agreement
# number 283359.
#
# Author: Robert Haines
#------------------------------------------------------------------------------
class TavernaPlayer::RunsController < ApplicationController
# Do not remove the next line.
include TavernaPlayer::Concerns::Controllers::RunsController
# Extend the RunsController here.
private
alias_method :old_find_run, :find_run
def update_params
params.require(:run).permit(:name, :policy_attributes => [:id, :public_permissions => []])
end
def run_params
params.require(:run).permit(
:create_time, :delayed_job, :embedded, :finish_time, :inputs_attributes,
:log, :name, :parent_id, :results, :run_id, :start_time,
:status_message_key, :user_id, :workflow_id,
:inputs_attributes => [:depth, :file, :metadata, :name, :value],
:policy_attributes => [:id, :public_permissions => []]
)
end
def find_runs
select = { :embedded => false }
select[:workflow_id] = params[:workflow_id] if params[:workflow_id]
@runs = TavernaPlayer::Run.where(select).order("created_at DESC").with_permissions(current_user, :view).page(params[:page])
end
def find_run
old_find_run
authorize(@run.can?(current_user, action_name))
end
end
| Samhane/taverna-player-portal | app/controllers/taverna_player/runs_controller.rb | Ruby | mit | 1,563 |
var common = require('../common');
var connection = common.createConnection({port: common.fakeServerPort});
var assert = require('assert');
var server = common.createFakeServer();
var connectErr;
server.listen(common.fakeServerPort, function(err) {
if (err) throw err;
connection.connect(function(err) {
connectErr = err;
server.destroy();
});
});
server.on('connection', function(incomingConnection) {
var errno = 1130; // ER_HOST_NOT_PRIVILEGED
incomingConnection.deny('You suck.', errno);
});
process.on('exit', function() {
assert.equal(connectErr.code, 'ER_HOST_NOT_PRIVILEGED');
assert.equal(connectErr.fatal, true);
});
| cheekujodhpur/ipho2015 | node_modules/mysql/test/integration/test-host-denied-error.js | JavaScript | mit | 662 |
/*!
* @license MIT
* Copyright (c) 2017 Bernhard Grünewaldt - codeclou.io
* https://github.com/cloukit/legal
*/
import { Component, Input } from '@angular/core';
import * as _ from 'lodash';
@Component({
selector: 'app-component-info-header',
template: `
<div class="info-header">
<div class="info-header-buttons">
<span
class="vendor-logo-link"
[ngStyle]="getButtonStyle(getStatusSwitchNameForComponentStatus(componentStatus))"
(mouseover)="hoverStatus(componentStatus)"
(mouseleave)="resetSwitchState()"
><img [src]="getComponentStatusUri()" class="vendor-logo"></span>
<a
href="https://www.npmjs.com/package/@cloukit/{{componentName}}"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('npm')"
(mouseover)="switchState.npm=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('npm')" class="vendor-logo"></a>
<a
href="https://github.com/cloukit/{{componentName}}/tree/{{componentVersion}}"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('github')"
(mouseover)="switchState.github=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('github')" class="vendor-logo"></a>
<a
href="https://unpkg.com/@cloukit/{{componentName}}@{{componentVersion}}/"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('unpkg')"
(mouseover)="switchState.unpkg=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('unpkg')" class="vendor-logo"></a>
<a
href="https://cloukit.github.io/{{componentName}}/{{componentVersion}}/documentation/"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('compodoc')"
(mouseover)="switchState.compodoc=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('compodoc')" class="vendor-logo"></a>
</div>
<div class="info-header-bar" [ngStyle]="getInfoHeaderStyle()">
<div class="info-header-bar-content">
<div *ngIf="isSwitchStateOn()">
{{switchState.statusExperimental ? 'API might change unexpectedly. Use at own risk. It is alive!' : ''}}
{{switchState.statusStable ? 'API should be stable.' : ''}}
{{switchState.npm ? 'Show package page on npmjs.com' : ''}}
{{switchState.github ? 'Show example project on github.com' : ''}}
{{switchState.unpkg ? 'Show dist contents on unpkg.com' : ''}}
{{switchState.compodoc ? 'Show detailed Component Documentation' : ''}}
</div>
</div>
</div>
</div>`,
styles: [
'.vendor-logo { width:120px; }',
'.info-header-bar { height:40px; width:100%; }',
'.info-header-bar-content { width:100%; padding: 10px; text-align:center; }',
'.info-header-buttons { display: flex; justify-content: space-between; }',
'.vendor-logo-link { display:flex; width: 120px; min-width:120px; max-width: 120px; padding:0; height:65px; }',
],
})
export class ComponentInfoHeaderComponent {
@Input()
componentName: string;
@Input()
componentVersion: string;
@Input()
componentStatus: string;
private initialSwitchState = {
npm: false,
unpkg: false,
github: false,
compodoc: false,
statusStable: false,
statusExperimental: false,
};
private colors = {
npm: {
bg: '#cb3837',
fg: '#fff',
},
unpkg: {
bg: '#000',
fg: '#fff',
},
github: {
bg: '#0366d6',
fg: '#fff',
},
compodoc: {
bg: '#2582d5',
fg: '#fff',
},
statusStable: {
bg: '#4ad57d',
fg: '#fff',
},
statusExperimental: {
bg: '#d55900',
fg: '#fff',
},
};
switchState = Object.assign({}, this.initialSwitchState);
getSwitchState(name: string) {
return this.switchState[name] ? 'on' : 'off';
}
isSwitchStateOn() {
for (let pair of _.toPairs(this.switchState)) {
if (pair[1]) {
return true;
}
}
return false;
}
getOnSwitchName() {
for (let pair of _.toPairs(this.switchState)) {
if (pair[1]) {
return pair[0];
}
}
return null;
}
getVendorLogo(name: string) {
return `/assets/images/vendor-logos/${name}-${this.getSwitchState(name)}.svg`;
}
resetSwitchState() {
this.switchState = Object.assign({}, this.initialSwitchState);
}
getButtonStyle(name: string) {
return this.switchState[name] ? {
border: `3px solid ${this.colors[name]['bg']}`,
transition: 'border-color 200ms linear'
} : {
border: `3px solid transparent`,
transition: 'border-color 200ms linear'
};
}
getInfoHeaderStyle() {
return this.isSwitchStateOn() ? {
backgroundColor: this.colors[this.getOnSwitchName()]['bg'],
color: this.colors[this.getOnSwitchName()]['fg'],
transition: 'background-color 200ms linear'
} : {
backgroundColor: 'transparent',
transition: 'background-color 200ms linear'
};
}
//
// STATUS
//
getStatusSwitchNameForComponentStatus(status: string) {
if (status === 'STABLE') {
return 'statusStable';
}
if (status === 'EXPERIMENTAL') {
return 'statusExperimental';
}
return null;
}
hoverStatus(status: string) {
if (status === 'STABLE') {
this.switchState.statusStable = true;
}
if (status === 'EXPERIMENTAL') {
this.switchState.statusExperimental = true;
}
}
getComponentStatusUri() {
if (this.componentStatus === 'STABLE') {
if (this.switchState.statusStable) {
return '/assets/images/status-icons/status-stable-on.svg';
}
return '/assets/images/status-icons/status-stable-off.svg';
}
if (this.componentStatus === 'EXPERIMENTAL') {
if (this.switchState.statusExperimental) {
return '/assets/images/status-icons/status-experimental-on.svg';
}
return '/assets/images/status-icons/status-experimental-off.svg';
}
}
}
| cloukit/cloukit.github.io | src/app/components/component-info-header.component.ts | TypeScript | mit | 6,127 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace DynamicSerializer.Test
{
public class IX
{
public int IP { get; set; }
}
[Serializable]
public class A
{
public A()
{
}
public A(string _name, C _c)
{
name = _name;
cref = _c;
}
public string name { get; set; }
public C cref { get; set; }
public override bool Equals(object obj)
{
return ((obj is A) && ((A) obj).name == this.name);
}
public override int GetHashCode()
{
return 1;
}
public static bool operator ==(A a, A b)
{
return a.Equals(b);
}
public static bool operator !=(A a, A b)
{
return !(a == b);
}
}
public class B : A
{
public B()
{
}
public int number { get { return Number; } set { Number = value; } }
[NonSerialized]
private int Number;
public B(string name, int num, C c)
: base(name, c)
{
number = num;
}
}
[Serializable]
public class C
{
public C()
{
}
public int adat { get; set; }
public C(int _b)
{
adat = _b;
}
}
public class CircularA
{
public List<CircularB> BArray { get; set; }
public List<CircularB> CArray { get; set; }
public CircularB BField { get; set; }
}
public class CircularB
{
public CircularA A { get; set; }
public int Id { get; set; }
public CircularB(int id)
{
Id = id;
}
}
public class NoCtor
{
public int i;
//public string s { get; set; }
public string s;
public NoCtor(int i, string s)
{
this.i = i;
this.s = s;
}
}
public class Basic
{
public int num;
}
}
| conwid/IL-boss | DynamicSerializer.Test/TestClasses.cs | C# | mit | 2,153 |
#ifndef _HC_EXCEPTION_HPP_
#define _HC_EXCEPTION_HPP_
//////////////
// Includes //
#include <exception>
#include <string>
//////////
// Code //
// To distinguish between different HCExceptions.
enum HCType {
// When the game cannot open the SDL window.
HC_WINDOW_EXCEPTION,
// When the game cannot load an asset, or it has been destroyed.
HC_ASSET_EXCEPTION
};
// A custom exception for this project.
class HCException : public std::exception {
private:
std::string msg;
HCType type;
public:
// Creating an HCException with a message and a type.
HCException(std::string, HCType);
// The message of this HCException.
const char* what() throw();
};
#endif
| crockeo/hc | src/hcexception.hpp | C++ | mit | 707 |
<?php
namespace Proxies\__CG__\Cabinet\PatientBundle\Entity;
/**
* THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
*/
class Patient extends \Cabinet\PatientBundle\Entity\Patient implements \Doctrine\ORM\Proxy\Proxy
{
private $_entityPersister;
private $_identifier;
public $__isInitialized__ = false;
public function __construct($entityPersister, $identifier)
{
$this->_entityPersister = $entityPersister;
$this->_identifier = $identifier;
}
/** @private */
public function __load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if (method_exists($this, "__wakeup")) {
// call this after __isInitialized__to avoid infinite recursion
// but before loading to emulate what ClassMetadata::newInstance()
// provides.
$this->__wakeup();
}
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
/** @private */
public function __isInitialized()
{
return $this->__isInitialized__;
}
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) $this->_identifier["id"];
}
$this->__load();
return parent::getId();
}
public function setNom($nom)
{
$this->__load();
return parent::setNom($nom);
}
public function getNom()
{
$this->__load();
return parent::getNom();
}
public function setPrenom($prenom)
{
$this->__load();
return parent::setPrenom($prenom);
}
public function getPrenom()
{
$this->__load();
return parent::getPrenom();
}
public function setDateNaissance($dateNaissance)
{
$this->__load();
return parent::setDateNaissance($dateNaissance);
}
public function getDateNaissance()
{
$this->__load();
return parent::getDateNaissance();
}
public function setAdresse($adresse)
{
$this->__load();
return parent::setAdresse($adresse);
}
public function getAdresse()
{
$this->__load();
return parent::getAdresse();
}
public function setTel($tel)
{
$this->__load();
return parent::setTel($tel);
}
public function getTel()
{
$this->__load();
return parent::getTel();
}
public function setCin($cin)
{
$this->__load();
return parent::setCin($cin);
}
public function getCin()
{
$this->__load();
return parent::getCin();
}
public function setMedecin(\Cabinet\UserBundle\Entity\Medecin $medecin = NULL)
{
$this->__load();
return parent::setMedecin($medecin);
}
public function getMedecin()
{
$this->__load();
return parent::getMedecin();
}
public function setFiche(\Cabinet\PatientBundle\Entity\Fiche $fiche = NULL)
{
$this->__load();
return parent::setFiche($fiche);
}
public function getFiche()
{
$this->__load();
return parent::getFiche();
}
public function __toString()
{
$this->__load();
return parent::__toString();
}
public function __sleep()
{
return array('__isInitialized__', 'id', 'nom', 'prenom', 'dateNaissance', 'adresse', 'tel', 'cin', 'medecin', 'fiche');
}
public function __clone()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
$class = $this->_entityPersister->getClassMetadata();
$original = $this->_entityPersister->load($this->_identifier);
if ($original === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
foreach ($class->reflFields as $field => $reflProperty) {
$reflProperty->setValue($this, $reflProperty->getValue($original));
}
unset($this->_entityPersister, $this->_identifier);
}
}
} | houcine88/Cabinet | app/cache/prod/doctrine/orm/Proxies/__CG__CabinetPatientBundleEntityPatient.php | PHP | mit | 4,377 |
export default {
// 购物车的商品数量
cartCommodityCount: state => {
const totalCount = state.cartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
},
removeCommodityCount: state => {
const totalCount = state.removeCartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
}
}
| luoshi0429/vue2-yanxuan | src/store/getters.js | JavaScript | mit | 424 |
require "uri"
require "net/http"
module JingdongFu
module Rest
class << self
def get(url, hashed_vars)
res = request(url, 'GET', hashed_vars)
process_result(res, url)
end
def post(url, hashed_vars)
res = request(url, 'POST', hashed_vars)
process_result(res, url)
end
def put(url, hashed_vars)
res = request(url, 'PUT', hashed_vars)
process_result(res, url)
end
def delete(url, hashed_vars)
res = request(url, 'DELETE', hashed_vars)
process_result(res, url)
end
protected
def request(url, method=nil, params = {})
if !url || url.length < 1
raise ArgumentError, 'Invalid url parameter'
end
if method && !['GET', 'POST', 'DELETE', 'PUT'].include?(method)
raise NotImplementedError, 'HTTP %s not implemented' % method
end
if method && method == 'GET'
url = build_get_uri(url, params)
end
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
if method && method == 'GET'
req = Net::HTTP::Get.new(uri.request_uri)
elsif method && method == 'DELETE'
req = Net::HTTP::Delete.new(uri.request_uri)
elsif method && method == 'PUT'
req = Net::HTTP::Put.new(uri.request_uri)
req.set_form_data(params)
else
req = Net::HTTP::Post.new(uri.request_uri)
req.set_form_data(params)
end
http.request(req)
end
def build_get_uri(uri, params)
if params && params.length > 0
uri += '?' unless uri.include?('?')
uri += urlencode(params)
end
URI.escape(uri)
end
def urlencode(params)
params.to_a.collect! { |k, v| "#{k.to_s}=#{v.to_s}" }.join("&")
end
def process_result(res, raw_url)
if res.code =~ /\A2\d{2}\z/
res.body
elsif %w(301 302 303).include? res.code
url = res.header['Location']
if url !~ /^http/
uri = URI.parse(raw_url)
uri.path = "/#{url}".squeeze('/')
url = uri.to_s
end
raise RuntimeError, "Redirect #{url}"
elsif res.code == "304"
raise RuntimeError, "NotModified #{res}"
elsif res.code == "401"
raise RuntimeError, "Unauthorized #{res}"
elsif res.code == "404"
raise RuntimeError, "Resource not found #{res}"
else
raise RuntimeError, "Maybe request timed out #{res}. HTTP status code #{res.code}"
end
end
end
end
end
| nioteam/jingdong_fu | lib/rest.rb | Ruby | mit | 2,853 |
package source
import (
log "github.com/Sirupsen/logrus"
"github.com/howardplus/lirest/describe"
"github.com/howardplus/lirest/util"
"os"
"strconv"
"strings"
"time"
)
// Extractor returns a generic data based
// on the converter.
// An object that implements the Extractor interface needs
// to know where to get the data, which then feeds to the
// converter.
type Extractor interface {
Extract() (*ExtractOutput, error)
}
// ExtractOutput is the output of the extracted data
// with json tags
type ExtractOutput struct {
Name string `json:"name"`
Time time.Time `json:"time"`
Data interface{} `json:"data"`
}
// NewExtractor create a new extractor based on the description
func NewExtractor(s describe.DescriptionSource, rd describe.DescriptionReadFormat, c Converter, vars map[string]string) (Extractor, error) {
var extractor Extractor
refresh := time.Duration(0)
switch s.Refresh {
case "never":
// never say never, 10 day is long enough
refresh = 240 * time.Hour
default:
// something s/m/h
v, err := strconv.Atoi(s.Refresh[:len(s.Refresh)-1])
if err == nil {
if strings.HasSuffix(s.Refresh, "s") {
refresh = time.Duration(v) * time.Second
} else if strings.HasSuffix(s.Refresh, "m") {
refresh = time.Duration(v) * time.Minute
} else if strings.HasSuffix(s.Refresh, "h") {
refresh = time.Duration(v) * time.Hour
}
}
case "":
// Did not specify, which implies always refresh
}
switch s.Type {
case "procfs", "sysfs", "sysctl":
extractor = NewGenericExtractor(rd.Path, refresh, c, vars)
case "command":
extractor = NewCommandExtractor(rd.Command, c, vars)
}
// found an extractor, use it
if extractor != nil {
return extractor, nil
}
// return error on default
return nil, util.NewError("Internal error: unknown input type")
}
// GenericExtractor extract data from reading from a file
// use this until it's not enough
type GenericExtractor struct {
path string
conv Converter
refresh time.Duration
vars map[string]string
}
// NewGenericExtractor creates a GenericExtractor
func NewGenericExtractor(path string, refresh time.Duration, conv Converter, vars map[string]string) *GenericExtractor {
return &GenericExtractor{path: path, refresh: refresh, conv: conv, vars: vars}
}
func (e *GenericExtractor) Extract() (*ExtractOutput, error) {
log.WithFields(log.Fields{
"path": e.path,
"vars": e.vars,
}).Debug("Extract from file system")
// create path from variables
path, err := util.FillVars(e.path, e.vars)
if err != nil {
return nil, util.NewError("Failed to generate path")
}
// ask data from cache
var hash string
if e.refresh != time.Duration(0) {
hash = CacheHash("command" + path)
if data, time, err := Cache(hash); err == nil {
log.WithFields(log.Fields{
"hash": hash,
"path": e.path,
}).Debug("Serve from cache")
return &ExtractOutput{
Name: e.conv.Name(),
Time: time,
Data: data,
}, nil
}
}
// open file from path
f, err := os.Open(path)
if err != nil {
return nil, util.NewError("Failed to open system path")
}
defer f.Close()
// TODO: verify the rw format on this path
// give it to the converter
data, err := e.conv.ConvertStream(f)
if err != nil {
return nil, err
}
// send to cache
if e.refresh != time.Duration(0) {
if err := SendCache(hash, data, e.refresh); err != nil {
// cache error, non-fatal
log.WithFields(log.Fields{
"path": e.path,
}).Debug("Failed to send cache")
}
}
log.WithFields(log.Fields{
"path": e.path,
}).Debug("Convert successful")
return &ExtractOutput{
Name: e.conv.Name(),
Time: time.Now(),
Data: data,
}, nil
}
| howardplus/lirest | source/extract.go | GO | mit | 3,669 |
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Cognifide.PowerShell.Core.Extensions;
using Sitecore.Data.Items;
using Sitecore.Layouts;
namespace Cognifide.PowerShell.Commandlets.Presentation
{
[Cmdlet(VerbsCommon.Get, "Rendering")]
[OutputType(typeof (RenderingDefinition))]
public class GetRenderingCommand : BaseRenderingCommand
{
protected override void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
IEnumerable<RenderingDefinition> renderings)
{
renderings.ToList().ForEach(r => WriteObject(ItemShellExtensions.WrapInItemOwner(SessionState, item, r)));
}
}
} | ostat/Console | Cognifide.PowerShell/Commandlets/Presentation/GetRenderingCommand.cs | C# | mit | 716 |
/**
* Copyright 2017, 2018, 2019, 2020 Stephen Powis https://github.com/Crim/pardot-java-client
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.darksci.pardot.api.parser.user;
import com.darksci.pardot.api.parser.JacksonFactory;
import com.darksci.pardot.api.parser.ResponseParser;
import com.darksci.pardot.api.response.user.UserAbilitiesResponse;
import java.io.IOException;
/**
* Handles parsing UserAbilities API responses into POJOs.
*/
public class UserAbilitiesParser implements ResponseParser<UserAbilitiesResponse.Result> {
@Override
public UserAbilitiesResponse.Result parseResponse(final String responseStr) throws IOException {
return JacksonFactory.newInstance().readValue(responseStr, UserAbilitiesResponse.class).getResult();
}
}
| Crim/pardot-java-client | src/main/java/com/darksci/pardot/api/parser/user/UserAbilitiesParser.java | Java | mit | 1,801 |
<?php
namespace App\Controller;
use Core\http;
use Core\view;
use Core\db;
class main
{
protected $http;
protected $view;
protected $db;
public function __construct()
{
$this->http = new http();
$this->view = new view();
$this->db = new db();
}
} | jersobh/edge-framework | src/controller/main.php | PHP | mit | 300 |
//this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it
angular.module('umbraco')
.controller("Umbraco.PropertyEditors.ImageCropperController",
function ($rootScope, $routeParams, $scope, $log, mediaHelper, cropperHelper, $timeout, editorState, umbRequestHelper, fileManager) {
var config = angular.copy($scope.model.config);
//move previously saved value to the editor
if ($scope.model.value) {
//backwards compat with the old file upload (incase some-one swaps them..)
if (angular.isString($scope.model.value)) {
config.src = $scope.model.value;
$scope.model.value = config;
} else if ($scope.model.value.crops) {
//sync any config changes with the editor and drop outdated crops
_.each($scope.model.value.crops, function (saved) {
var configured = _.find(config.crops, function (item) { return item.alias === saved.alias });
if (configured && configured.height === saved.height && configured.width === saved.width) {
configured.coordinates = saved.coordinates;
}
});
$scope.model.value.crops = config.crops;
//restore focalpoint if missing
if (!$scope.model.value.focalPoint) {
$scope.model.value.focalPoint = { left: 0.5, top: 0.5 };
}
}
$scope.imageSrc = $scope.model.value.src;
}
//crop a specific crop
$scope.crop = function (crop) {
$scope.currentCrop = crop;
$scope.currentPoint = undefined;
};
//done cropping
$scope.done = function () {
$scope.currentCrop = undefined;
$scope.currentPoint = undefined;
};
//crop a specific crop
$scope.clear = function (crop) {
//clear current uploaded files
fileManager.setFiles($scope.model.alias, []);
//clear the ui
$scope.imageSrc = undefined;
if ($scope.model.value) {
delete $scope.model.value;
}
};
//show previews
$scope.togglePreviews = function () {
if ($scope.showPreviews) {
$scope.showPreviews = false;
$scope.tempShowPreviews = false;
} else {
$scope.showPreviews = true;
}
};
//on image selected, update the cropper
$scope.$on("filesSelected", function (ev, args) {
$scope.model.value = config;
if (args.files && args.files[0]) {
fileManager.setFiles($scope.model.alias, args.files);
var reader = new FileReader();
reader.onload = function (e) {
$scope.$apply(function () {
$scope.imageSrc = e.target.result;
});
};
reader.readAsDataURL(args.files[0]);
}
});
})
.run(function (mediaHelper, umbRequestHelper) {
if (mediaHelper && mediaHelper.registerFileResolver) {
mediaHelper.registerFileResolver("Umbraco.ImageCropper", function (property, entity, thumbnail) {
if (property.value.src) {
if (thumbnail === true) {
return property.value.src + "?width=600&mode=max";
}
else {
return property.value.src;
}
//this is a fallback in case the cropper has been asssigned a upload field
}
else if (angular.isString(property.value)) {
if (thumbnail) {
if (mediaHelper.detectIfImageByExtension(property.value)) {
var thumbnailUrl = umbRequestHelper.getApiUrl(
"imagesApiBaseUrl",
"GetBigThumbnail",
[{ originalImagePath: property.value }]);
return thumbnailUrl;
}
else {
return null;
}
}
else {
return property.value;
}
}
return null;
});
}
}); | zidad/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js | JavaScript | mit | 4,659 |
package data_struct.in_class.d10_02;
/**
* A class to test basic 'Object' methods
*
* @author Eddie Gurnee
* @version 10/02/13
* @see TestingSam
*
*/
public class Sam {
public int mikesplan = 8;
/**
* No argument constructor for the Sam class
*
*/
public Sam() {
}
/**
* Indicates if some other "Sam" object is equal to this one.
*
*/
public boolean equals(Sam otherObject) {
if (otherObject == null) {
System.out.println("check1");
return false;
}
else if (this.getClass() != otherObject.getClass()) {
System.out.println("check2");
return false;
}
else {
System.out.println("if this shows then fuck the police");
Sam otherSam = (Sam)otherObject;
return this.mikesplan == otherSam.mikesplan;
}
}
public int getMikesPlan() {
return mikesplan;
}
} | pegurnee/2013-03-211 | complete/src/data_struct/in_class/d10_02/Sam.java | Java | mit | 817 |
__author__ = 'brianoneill'
from log_calls import log_calls
global_settings = dict(
log_call_numbers=True,
log_exit=False,
log_retval=True,
)
log_calls.set_defaults(global_settings, args_sep=' $ ')
| Twangist/log_calls | tests/set_reset_defaults/global_defaults.py | Python | mit | 211 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PineTree.Language.Syntax
{
public abstract class ExpressionTerminal : Expression
{
}
} | seaboy1234/PineTreeLanguage | PineTree.Language/Syntax/ExpressionTerminal.cs | C# | mit | 228 |
#include "Common.h"
#include "Script.h"
#include <atlimage.h>
#include <hidsdi.h>
#include <SetupAPI.h>
#define HID_SFIP 'SFIP'
#define HID_X52P 'X52P'
#define HID_UNKN 'UNKN'
// CHECKME : Do we still need all this code since we now have a GetSerialNumber() in the DO API?
DeviceManager *DevMan = DeviceManager::GetInstance();
SaitekDevice HID[HID_COUNT];
int HIDCount = HID_EMPTY;
int ToDeviceShortName(const char *type) {
if (strcmp(type, "SFIP") == 0)
return HID_SFIP;
if (strcmp(type, "X52P") == 0)
return HID_X52P;
return HID_UNKN;
}
int GetDeviceShortName(GUID type) {
if (type == DeviceType_Fip)
return HID_SFIP;
if (type == DeviceType_X52Pro)
return HID_X52P;
return HID_UNKN;
}
const char *GetDeviceStringName(GUID type) {
if (type == DeviceType_Fip)
return "SFIP";
if (type == DeviceType_X52Pro)
return "X52P";
return "UNKN";
}
int HIDLookupByType(const char *type, int index) {
int count = 1; // Index starts at 1 in Lua
int dev = ToDeviceShortName(type);
for (int i = 0; i < HIDCount; i++) {
if (GetDeviceShortName(HID[i].type) == dev/* && HID[i].isActive*/) {
if (count++ == index)
return i;
}
}
return HID_NOTFOUND;
}
int HIDLookupByIndex(int index) {
int count = 1; // Index starts at 1 in Lua
int dev = GetDeviceShortName(HID[index].type);
for (int i = 0; i < HIDCount; i++) {
if (GetDeviceShortName(HID[i].type) == dev/* && HID[i].isActive*/) {
if (index == i)
return count;
count++;
}
}
return HID_NOTFOUND;
}
static void CALLBACK DO_Enumerate(void* hDevice, void* pCtxt) {
DevMan->HandleDeviceChange(hDevice, true);
}
static void CALLBACK DO_DeviceChange(void* hDevice, bool bAdded, void* pCtxt) {
int index = DevMan->HandleDeviceChange(hDevice, bAdded);
LuaMan->CallDeviceChangeCallbacks(index, bAdded);
}
void DeviceManager::Initialize() {
_lockInit.Acquire();
if (_initializedCounter > 0) {
_initializedCounter++;
_lockInit.Release();
return;
}
// Initialize...
memset(HID, 0, sizeof(SaitekDevice) * HID_COUNT);
HIDCount = HID_EMPTY;
//Initialize DirectInput
HRESULT hdi = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID *)&this->_di, NULL);
if (!SUCCEEDED(hdi)) {
_lockInit.Release();
return;
}
//Initialize Saitek DirectOutput
_do = new CDirectOutput();
HRESULT hdo = _do->Initialize(L"" LUALIB_IDENT);
if (!SUCCEEDED(hdo)) {
_di->Release();
_lockInit.Release();
return;
}
// Register callbacks
HRESULT h1 = _do->Enumerate((Pfn_DirectOutput_EnumerateCallback)DO_Enumerate, NULL);
HRESULT h2 = _do->RegisterDeviceCallback((Pfn_DirectOutput_DeviceChange)DO_DeviceChange, NULL);
// Everything OK
_initializedCounter = 1;
_lockInit.Release();
}
void DeviceManager::Release() {
_lockInit.Acquire();
if (_initializedCounter-- > 1) {
_lockInit.Release();
return;
}
_do->Deinitialize();
_di->Release();
_initializedCounter = 0;
_lockInit.Release();
}
void DeviceManager::GetDeviceInfo(void *hDevice, DeviceData &dd) {
GUID gi;
HRESULT hr = DO()->GetDeviceInstance(hDevice, &gi);
GetDeviceInfo(gi, dd);
}
void DeviceManager::GetDeviceInfo(const GUID &iid, DeviceData &dd) {
SP_DEVINFO_DATA DeviceInfoData;
SP_DEVICE_INTERFACE_DATA did;
struct { DWORD cbSize; TCHAR DevicePath[256]; } ciddd;
TCHAR s[64];
GUID HidGuid;
//Empty
dd.instanceID[0] = 0;
dd.name[0] = 0;
dd.serialNumber[0] = 0;
// Try to create a device
LPDIRECTINPUTDEVICE8 pDevice;
HRESULT hd = DevMan->DI()->CreateDevice(iid, &pDevice, NULL);
if (FAILED(hd)) {
return;
}
// Get the GUID and Path
DIPROPGUIDANDPATH h;
h.diph.dwSize = sizeof(DIPROPGUIDANDPATH);
h.diph.dwHeaderSize = sizeof(DIPROPHEADER);
h.diph.dwObj = 0;
h.diph.dwHow = DIPH_DEVICE;
HRESULT hp = pDevice->GetProperty(DIPROP_GUIDANDPATH, (LPDIPROPHEADER)&h);
if (FAILED(hd))
return;
// Change # to \ to match structure of instance ID
for (size_t i = 0; i < wcslen(h.wszPath); i++) {
if (h.wszPath[i] == L'#') {
h.wszPath[i] = L'\\';
}
}
// Prepare enumeration
HidD_GetHidGuid(&HidGuid);
HDEVINFO hdi = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
did.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
ciddd.cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
for (int i = 0; SetupDiEnumDeviceInterfaces(hdi, 0, &HidGuid, i, &did); i++) {
if (!SetupDiGetDeviceInterfaceDetail(hdi, &did, PSP_INTERFACE_DEVICE_DETAIL_DATA(&ciddd), sizeof(ciddd.DevicePath), 0, &DeviceInfoData))
continue;
if (!SetupDiGetDeviceInstanceId(hdi, &DeviceInfoData, s, sizeof(s), 0))
continue;
_wcslwr_s(s);
if(!wcsstr(h.wszPath, s))
continue;
strncpy_s(dd.instanceID, CT2A(s), sizeof(dd.instanceID) - 1);
HANDLE h = CreateFile(ciddd.DevicePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (HidD_GetProductString(h, s, sizeof(s)))
strncpy_s(dd.name, CT2A(s), sizeof(dd.name) - 1);
if (HidD_GetSerialNumberString(h, s, sizeof(s)))
strncpy_s(dd.serialNumber, CT2A(s), sizeof(dd.serialNumber) - 1);
CloseHandle(h);
}
SetupDiDestroyDeviceInfoList(hdi);
}
int DeviceManager::Prepare(void *hDevice) {
if (HIDCount == HID_COUNT)
return HID_NOTFOUND;
int index = HIDCount++;
HID[index].hDevice = hDevice;
return index;
}
void DeviceManager::Set(int index) {
void *hDevice = HID[index].hDevice;
GUID gt, gi;
DeviceData dd;
GetDeviceInfo(hDevice, dd);
DO()->GetDeviceType(hDevice, >);
DO()->GetDeviceInstance(hDevice, &gi);
HID[index].type = gt;
HID[index].instance = gi;
strcpy_s(HID[index].instanceID, dd.instanceID);
strcpy_s(HID[index].name, dd.name);
strcpy_s(HID[index].serialNumber, dd.serialNumber);
}
int DeviceManager::HandleDeviceChange(void *hDevice, bool bAdded) {
int index = LookupByHandle(hDevice);
_lockHID.Acquire();
if (bAdded) {
if (index == HID_NOTFOUND)
index = LookupByDeviceInfo(hDevice, false);
if (index == HID_NOTFOUND)
index = Prepare(hDevice);
}
if (index != HID_NOTFOUND) {
HID[index].isActive = bAdded;
if (bAdded) {
HID[index].hDevice = hDevice;
Set(index);
}
}
_lockHID.Release();
return index;
}
int DeviceManager::LookupByHandle(void* hDevice) {
_lockHID.Acquire();
for (int i = 0; i < HIDCount; i++) {
if (hDevice == HID[i].hDevice) {
_lockHID.Release();
return i;
}
}
_lockHID.Release();
return HID_NOTFOUND;
}
int DeviceManager::LookupByDeviceInfo(void *hDevice, bool isActive) {
GUID gt;
DeviceData dd;
DO()->GetDeviceType(hDevice, >);
GetDeviceInfo(hDevice, dd);
return LookupByDeviceInfo(gt, dd, isActive);
}
int DeviceManager::LookupByDeviceInfo(GUID &type, DeviceData &dd, bool isActive) {
for (int i = 0; i < HIDCount; i++) {
if (HID[i].isActive == isActive && HID[i].type == type &&
strcmp(dd.instanceID, HID[i].instanceID) == 0 &&
strcmp(dd.serialNumber, HID[i].serialNumber) == 0) {
return i;
}
}
return HID_NOTFOUND;
}
| chrilith/Passerelle | Lua Module/Device.cpp | C++ | mit | 6,949 |
game.TitleScreen = me.ScreenObject.extend({
init: function(){
this.font = null;
},
onResetEvent: function() {
me.audio.stop("theme");
game.data.newHiScore = false;
me.game.world.addChild(new BackgroundLayer('bg', 1));
me.input.bindKey(me.input.KEY.ENTER, "enter", true);
me.input.bindKey(me.input.KEY.SPACE, "enter", true);
me.input.bindMouse(me.input.mouse.LEFT, me.input.KEY.ENTER);
this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) {
if (action === "enter") {
me.state.change(me.state.PLAY);
}
});
//logo
var logoImg = me.loader.getImage('logo');
var logo = new me.SpriteObject (
me.game.viewport.width/2 - 170,
-logoImg,
logoImg
);
me.game.world.addChild(logo, 10);
var logoTween = new me.Tween(logo.pos).to({y: me.game.viewport.height/2 - 100},
1000).easing(me.Tween.Easing.Exponential.InOut).start();
this.ground = new TheGround();
me.game.world.addChild(this.ground, 11);
me.game.world.addChild(new (me.Renderable.extend ({
// constructor
init: function() {
// size does not matter, it's just to avoid having a zero size
// renderable
this.parent(new me.Vector2d(), 100, 100);
//this.font = new me.Font('Arial Black', 20, 'black', 'left');
this.text = me.device.touch ? 'Tap to start' : 'PRESS SPACE OR CLICK LEFT MOUSE BUTTON TO START';
this.font = new me.Font('gamefont', 20, '#000');
},
update: function () {
return true;
},
draw: function (context) {
var measure = this.font.measureText(context, this.text);
this.font.draw(context, this.text, me.game.viewport.width/2 - measure.width/2, me.game.viewport.height/2 + 50);
}
})), 12);
},
onDestroyEvent: function() {
// unregister the event
me.event.unsubscribe(this.handler);
me.input.unbindKey(me.input.KEY.ENTER);
me.input.unbindKey(me.input.KEY.SPACE);
me.input.unbindMouse(me.input.mouse.LEFT);
me.game.world.removeChild(this.ground);
}
});
| jeshuamaxey/flappy-tom | js/screens/title.js | JavaScript | mit | 2,176 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First Steps Into PHP</title>
</head>
<body>
<form>
X: <input type="text" name="num1" />
Y: <input type="text" name="num2" />
Z: <input type="text" name="num3" />
<input type="submit" />
</form>
<?php
if (!isset($_GET['num1']) || !isset($_GET['num2']) || !isset($_GET['num3'])){
exit(1);
}
$numbers = [$_GET['num1'], $_GET['num2'], $_GET['num3']];
$numbers = array_map('intval',$numbers);
if (in_array(0, $numbers)){
echo "Positive";
exit(0);
}
$numbers = array_filter($numbers,function ($num){
return $num<0;
});
$negativeNumbersCount = count($numbers);
$isPositive = $negativeNumbersCount%2==0;
if ($isPositive){
echo "Positive";
}
else{
echo "Negative";
}
?>
</body>
</html> | leonnybg/SoftUni-SoftwareTechnologies-july2017 | L8-PHP-Syntax- Basic-Web-Ex/04. Product of 3 Numbers.php | PHP | mit | 895 |
<?php
/* SRVDVServerBundle:ChangePassword:changePassword.html.twig */
class __TwigTemplate_e5da0f0553fed635f2774271a2ef3982b389e99e651b1a8527dd0c0b6ca90bd7 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'fos_user_content' => array($this, 'block_fos_user_content'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749->enter($__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "SRVDVServerBundle:ChangePassword:changePassword.html.twig"));
// line 1
echo "
";
// line 3
$this->displayBlock('fos_user_content', $context, $blocks);
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749->leave($__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749_prof);
}
public function block_fos_user_content($context, array $blocks = array())
{
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db->enter($__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "fos_user_content"));
// line 4
echo " ";
$this->loadTemplate("SRVDVServerBundle:ChangePassword:changePassword_content.html.twig", "SRVDVServerBundle:ChangePassword:changePassword.html.twig", 4)->display($context);
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db->leave($__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db_prof);
}
public function getTemplateName()
{
return "SRVDVServerBundle:ChangePassword:changePassword.html.twig";
}
public function getDebugInfo()
{
return array ( 39 => 4, 27 => 3, 23 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("
{% block fos_user_content %}
{% include \"SRVDVServerBundle:ChangePassword:changePassword_content.html.twig\" %}
{% endblock fos_user_content %}
", "SRVDVServerBundle:ChangePassword:changePassword.html.twig", "C:\\wamp64\\www\\serveurDeVoeux\\src\\SRVDV\\ServerBundle/Resources/views/ChangePassword/changePassword.html.twig");
}
}
| youcefboukersi/serveurdevoeux | app/cache/dev/twig/1b/1bf602c2860b97f0808215b5052e0f5850091179d1670e489003312b329f5b04.php | PHP | mit | 3,227 |
<?php
declare(strict_types=1);
/*
* This file is part of eelly package.
*
* (c) eelly.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eelly\SDK\Order\Api;
use Eelly\SDK\Order\Service\OfflineInterface;
/**
* @author shadonTools<localhost.shell@gmail.com>
*/
class Offline implements OfflineInterface
{
/**
* @return self
*/
public static function getInstance(): self
{
static $instance;
if (null === $instance) {
$instance = new self();
}
return $instance;
}
}
| junming4/eelly-sdk-php | src/SDK/Order/Api/Offline.php | PHP | mit | 641 |
import_module('Athena.Math');
m1 = new Athena.Math.Matrix3(1, 2, 3,
4, 5, 6,
7, 8, 9);
for (var row = 0; row < 3; ++row)
{
for (var col = 0; col < 3; ++col)
CHECK_CLOSE(row * 3 + col + 1, m1.get(row, col));
}
| Kanma/Athena-Math | unittests/scripting/js/Matrix3/CreationWithValues.js | JavaScript | mit | 282 |
version https://git-lfs.github.com/spec/v1
oid sha256:27606576bf3cd46c15755bdec387cc97145a4a0c0a5b3933c11d30ab8c6c5ec7
size 1825
| yogeshsaroya/new-cdnjs | ajax/libs/timelinejs/2.35.6/js/locale/el.js | JavaScript | mit | 129 |
<?php
/**
* The default template for displaying content
*
* Used for both single and index/archive/search.
*
* @package FoundationPress
* @since FoundationPress 1.0.0
*/
?>
<div id="post-<?php the_ID(); ?>" <?php post_class('blogpost-entry'); ?>>
<header>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php foundationpress_entry_meta(); ?>
</header>
<div class="entry-content">
<?php the_content( __( 'Continue reading...', 'foundationpress' ) ); ?>
</div>
<footer>
<?php $tag = get_the_tags(); if ( $tag ) { ?><p><?php the_tags(); ?></p><?php } ?>
</footer>
<hr />
</div>
| fredlincoln/sprcorp | template-parts/content.php | PHP | mit | 624 |
class EnsureNoLimitOnUserDataField < ActiveRecord::Migration
def up
change_column :users, :user_data, :text, :limit => nil
end
def down
end
end
| dtulibrary/toshokan | db/migrate/20130827081527_ensure_no_limit_on_user_data_field.rb | Ruby | mit | 157 |
<?php
/*
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2004 Bharat Mediratta
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id: User.php,v 1.7 2004/03/23 17:53:16 cryptographite Exp $
*/
?>
<?php
class PostNuke_User extends Abstract_User {
function loadByUid($uid) {
global $name; /* Gallery PN module name */
/*
* Consider the case where we're trying to load a $uid
* that stemmed from a user created by a standalone
* Gallery. That $uid won't be valid for PostNuke.
* We don't want this to cause problems, so in that
* case we'll just pretend that it was Nobody.
*
* But how do we detect those users? Well, let's take
* the quick and dirty approach of making sure that
* the uid is numeric.
*/
if (ereg("[^0-9]", $uid)) {
$newuser = new NobodyUser();
foreach ($newuser as $k => $v) {
$this->$k = $v;
}
return;
}
$this->username = pnUserGetVar('uname', $uid);
$this->fullname = pnUserGetVar('name', $uid);
$this->email = pnUserGetVar('email', $uid);
$this->canCreateAlbums = 0;
$this->uid = $uid;
/*
* XXX: this sets the admin-ness according to the user who's
* currently logged in -- NOT the $uid in question! This would
* be an issue, except that it just so happens that it doesn't
* affect anything we're doing in the app level code.
*/
$this->isAdmin = (pnSecAuthAction(0, "$name::", '::', ACCESS_ADMIN));
}
function loadByUserName($uname) {
list($dbconn) = pnDBGetConn();
$pntable = pnDBGetTables();
$userscolumn = &$pntable['users_column'];
$userstable = $pntable['users'];
/* Figure out the uid for this uname */
$query = "SELECT $userscolumn[uid] " .
"FROM $userstable " .
"WHERE $userscolumn[uname] = '" . pnVarPrepForStore($uname) ."'";
$result = $dbconn->Execute($query);
list($uid) = $result->fields;
$result->Close();
$this->loadByUid($uid);
}
}
?>
| TelemarkAlpint/telemark-2004 | bilder/gallery/classes/postnuke0.7.1/User.php | PHP | mit | 2,614 |
module MuhrTable
VERSION = "1.0.22"
end
| dsandber/muhr_table | lib/muhr_table/version.rb | Ruby | mit | 42 |
import Objective from '../objective';
export default class KillShipsObjective extends Objective {
constructor (game, ships) {
super(game);
if (!Array.isArray(ships)) {
ships = [ships];
}
this.bots = _.filter(ships, ship => { return ship.alive; });
this.ships = ships;
}
isComplete () {
var all_dead = true;
for (var i = 0; i < this.ships.length; i++) {
if (this.ships[i].alive) {
all_dead = false;
break;
}
}
return all_dead;
}
};
| gaudeon/interstice | src/stage/objectives/kill_ships.js | JavaScript | mit | 622 |
module Storegine
class Category
include Mongoid::Document
field :title, type: String
has_many :products
end
end
| liligga/storegine | app/models/storegine/category.rb | Ruby | mit | 133 |
export * from './privacy.component';
| asadsahi/AspNetCoreSpa | src/Presentation/Web/ClientApp/src/app/components/privacy/index.ts | TypeScript | mit | 37 |
// Calendar SK language
// Author: Peter Valach (pvalach@gmx.net)
// Encoding: utf-8
// Last update: 2003/10/29
// full day names
Calendar._DN = new Array
("NedeÄľa",
"Pondelok",
"Utorok",
"Streda",
"Ĺ tvrtok",
"Piatok",
"Sobota",
"NedeÄľa");
// short day names
Calendar._SDN = new Array
("Ned",
"Pon",
"Uto",
"Str",
"Ĺ tv",
"Pia",
"Sob",
"Ned");
// full month names
Calendar._MN = new Array
("Január",
"Február",
"Marec",
"AprĂl",
"Máj",
"JĂşn",
"JĂşl",
"August",
"September",
"OktĂłber",
"November",
"December");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"Máj",
"JĂşn",
"JĂşl",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendári";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"Poslednú verziu nájdete na: http://www.dynarch.com/projects/calendar/\n" +
"Distribuované pod GNU LGPL. Viď http://gnu.org/licenses/lgpl.html pre detaily." +
"\n\n" +
"Výber dátumu:\n" +
"- Použite tlačidlá \xab, \xbb pre výber roku\n" +
"- Použite tlačidlá " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " pre výber mesiaca\n" +
"- Ak ktorĂ©koÄľvek z tĂ˝chto tlaÄŤidiel podrĹľĂte dlhšie, zobrazĂ sa rĂ˝chly vĂ˝ber.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Výber času:\n" +
"- Kliknutie na niektorú položku času ju zvýši\n" +
"- Shift-klik ju znĂĹľi\n" +
"- Ak podrĹľĂte tlaÄŤĂtko stlaÄŤenĂ©, posĂşvanĂm menĂte hodnotu.";
Calendar._TT["PREV_YEAR"] = "Predošlý rok (podržte pre menu)";
Calendar._TT["PREV_MONTH"] = "Predošlý mesiac (podržte pre menu)";
Calendar._TT["GO_TODAY"] = "Prejsť na dnešok";
Calendar._TT["NEXT_MONTH"] = "Nasl. mesiac (podrĹľte pre menu)";
Calendar._TT["NEXT_YEAR"] = "Nasl. rok (podrĹľte pre menu)";
Calendar._TT["SEL_DATE"] = "Zvoľte dátum";
Calendar._TT["DRAG_TO_MOVE"] = "PodrĹľanĂm tlaÄŤĂtka zmenĂte polohu";
Calendar._TT["PART_TODAY"] = " (dnes)";
Calendar._TT["MON_FIRST"] = "ZobraziĹĄ pondelok ako prvĂ˝";
Calendar._TT["SUN_FIRST"] = "ZobraziĹĄ nedeÄľu ako prvĂş";
Calendar._TT["CLOSE"] = "ZavrieĹĄ";
Calendar._TT["TODAY"] = "Dnes";
Calendar._TT["TIME_PART"] = "(Shift-)klik/ĹĄahanie zmenĂ hodnotu";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "$d. %m. %Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e. %b";
Calendar._TT["WK"] = "týž";
| JoAutomation/todo-for-you | lib/js/jscalendar/lang/calendar-sk-utf8.js | JavaScript | mit | 2,589 |
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("03. Rage Quit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03. Rage Quit")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("102e97e8-a5dc-4989-9bff-d9818c2cabbf")]
// 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")]
| viktor4o4o/Homework | Exam Preparation III - Taking a Sample Exam/03. Rage Quit/Properties/AssemblyInfo.cs | C# | mit | 1,402 |
module Jdt
class GeneratorCLI < Thor
desc "library NAME", "generate library with NAME"
def library(name)
LibraryGenerator.new.generate(name)
end
end
end | Fekide/joomlatools | lib/jdt/cli/new/library.rb | Ruby | mit | 179 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.test.annotations.cascade;
import java.util.HashSet;
import org.junit.Test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.fail;
/**
* @author Jeff Schnitzer
* @author Gail Badner
*/
@SuppressWarnings("unchecked")
public class NonNullableCircularDependencyCascadeTest extends BaseCoreFunctionalTestCase {
@Test
public void testIdClassInSuperclass() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Parent p = new Parent();
p.setChildren( new HashSet<Child>() );
Child ch = new Child(p);
p.getChildren().add(ch);
p.setDefaultChild(ch);
try {
s.persist(p);
s.flush();
fail( "should have failed because of transient entities have non-nullable, circular dependency." );
}
catch ( HibernateException ex) {
// expected
}
tx.rollback();
s.close();
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[]{
Child.class,
Parent.class
};
}
}
| HerrB92/obp | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/annotations/cascade/NonNullableCircularDependencyCascadeTest.java | Java | mit | 2,167 |
System.config({
baseURL: ".",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
bundles: {
"build.js": [
"lib/main.js",
"lib/filelayer/ajaxUtil.js",
"lib/filelayer/corslite.js",
"github:shramov/leaflet-plugins@1.4.2",
"npm:leaflet@0.7.7",
"npm:togeojson@0.13.0",
"lib/filelayer/leaflet.filelayer.js",
"github:mholt/PapaParse@4.1.2",
"npm:font-awesome@4.5.0/css/font-awesome.min.css!github:systemjs/plugin-css@0.1.20",
"github:shramov/leaflet-plugins@1.4.2/control/Distance",
"npm:leaflet@0.7.7/dist/leaflet-src",
"npm:togeojson@0.13.0/togeojson",
"github:mholt/PapaParse@4.1.2/papaparse",
"github:jspm/nodelibs-process@0.1.2",
"github:jspm/nodelibs-process@0.1.2/index",
"npm:process@0.11.2",
"npm:process@0.11.2/browser"
]
},
map: {
"adm-zip": "npm:adm-zip@0.4.7",
"babel": "npm:babel-core@5.8.34",
"babel-runtime": "npm:babel-runtime@5.8.34",
"clean-css": "npm:clean-css@3.4.9",
"core-js": "npm:core-js@1.2.6",
"css": "github:systemjs/plugin-css@0.1.20",
"font-awesome": "npm:font-awesome@4.5.0",
"gildas-lormeau/zip.js": "github:gildas-lormeau/zip.js@master",
"leaflet": "npm:leaflet@0.7.7",
"mapbox/togeojson": "github:mapbox/togeojson@0.13.0",
"mholt/PapaParse": "github:mholt/PapaParse@4.1.2",
"shramov/leaflet-plugins": "github:shramov/leaflet-plugins@1.4.2",
"togeojson": "npm:togeojson@0.13.0",
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.3.0"
},
"github:jspm/nodelibs-buffer@0.1.0": {
"buffer": "npm:buffer@3.6.0"
},
"github:jspm/nodelibs-constants@0.1.0": {
"constants-browserify": "npm:constants-browserify@0.0.1"
},
"github:jspm/nodelibs-crypto@0.1.0": {
"crypto-browserify": "npm:crypto-browserify@3.11.0"
},
"github:jspm/nodelibs-events@0.1.1": {
"events": "npm:events@1.0.2"
},
"github:jspm/nodelibs-http@1.7.1": {
"Base64": "npm:Base64@0.2.1",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"github:jspm/nodelibs-https@0.1.0": {
"https-browserify": "npm:https-browserify@0.0.0"
},
"github:jspm/nodelibs-os@0.1.0": {
"os-browserify": "npm:os-browserify@0.1.2"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.2"
},
"github:jspm/nodelibs-stream@0.1.0": {
"stream-browserify": "npm:stream-browserify@1.0.0"
},
"github:jspm/nodelibs-string_decoder@0.1.0": {
"string_decoder": "npm:string_decoder@0.10.31"
},
"github:jspm/nodelibs-url@0.1.0": {
"url": "npm:url@0.10.3"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:jspm/nodelibs-vm@0.1.0": {
"vm-browserify": "npm:vm-browserify@0.0.4"
},
"github:jspm/nodelibs-zlib@0.1.0": {
"browserify-zlib": "npm:browserify-zlib@0.1.4"
},
"npm:adm-zip@0.4.7": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"zlib": "github:jspm/nodelibs-zlib@0.1.0"
},
"npm:amdefine@1.0.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"module": "github:jspm/nodelibs-module@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:asn1.js@4.3.0": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:assert@1.3.0": {
"util": "npm:util@0.10.3"
},
"npm:babel-runtime@5.8.34": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:browserify-aes@1.0.5": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"buffer-xor": "npm:buffer-xor@1.0.3",
"cipher-base": "npm:cipher-base@1.0.2",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:browserify-cipher@1.0.0": {
"browserify-aes": "npm:browserify-aes@1.0.5",
"browserify-des": "npm:browserify-des@1.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0"
},
"npm:browserify-des@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"des.js": "npm:des.js@1.0.0",
"inherits": "npm:inherits@2.0.1"
},
"npm:browserify-rsa@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"constants": "github:jspm/nodelibs-constants@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:browserify-sign@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.0.2",
"inherits": "npm:inherits@2.0.1",
"parse-asn1": "npm:parse-asn1@5.0.0",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:browserify-zlib@0.1.4": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"pako": "npm:pako@0.2.8",
"process": "github:jspm/nodelibs-process@0.1.2",
"readable-stream": "npm:readable-stream@2.0.5",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:buffer-xor@1.0.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:buffer@3.6.0": {
"base64-js": "npm:base64-js@0.0.8",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"ieee754": "npm:ieee754@1.1.6",
"isarray": "npm:isarray@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:cipher-base@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"string_decoder": "github:jspm/nodelibs-string_decoder@0.1.0"
},
"npm:clean-css@3.4.9": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"commander": "npm:commander@2.8.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"http": "github:jspm/nodelibs-http@1.7.1",
"https": "github:jspm/nodelibs-https@0.1.0",
"os": "github:jspm/nodelibs-os@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"source-map": "npm:source-map@0.4.4",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:commander@2.8.1": {
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"graceful-readlink": "npm:graceful-readlink@1.0.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:concat-stream@1.4.10": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.13",
"typedarray": "npm:typedarray@0.0.6"
},
"npm:constants-browserify@0.0.1": {
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-js@1.2.6": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-util-is@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:create-ecdh@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.0.2"
},
"npm:create-hash@1.1.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"ripemd160": "npm:ripemd160@1.0.1",
"sha.js": "npm:sha.js@2.4.4"
},
"npm:create-hmac@1.1.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:crypto-browserify@3.11.0": {
"browserify-cipher": "npm:browserify-cipher@1.0.0",
"browserify-sign": "npm:browserify-sign@4.0.0",
"create-ecdh": "npm:create-ecdh@4.0.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"diffie-hellman": "npm:diffie-hellman@5.0.1",
"inherits": "npm:inherits@2.0.1",
"pbkdf2": "npm:pbkdf2@3.0.4",
"public-encrypt": "npm:public-encrypt@4.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:des.js@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0"
},
"npm:diffie-hellman@5.0.1": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"miller-rabin": "npm:miller-rabin@4.0.0",
"randombytes": "npm:randombytes@2.0.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:elliptic@6.0.2": {
"bn.js": "npm:bn.js@4.6.2",
"brorand": "npm:brorand@1.0.5",
"hash.js": "npm:hash.js@1.0.3",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:evp_bytestokey@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0"
},
"npm:font-awesome@4.5.0": {
"css": "github:systemjs/plugin-css@0.1.20"
},
"npm:graceful-readlink@1.0.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:hash.js@1.0.3": {
"inherits": "npm:inherits@2.0.1"
},
"npm:https-browserify@0.0.0": {
"http": "github:jspm/nodelibs-http@1.7.1"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:leaflet@0.7.7": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"util": "github:jspm/nodelibs-util@0.1.0",
"zlib": "github:jspm/nodelibs-zlib@0.1.0"
},
"npm:miller-rabin@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"brorand": "npm:brorand@1.0.5"
},
"npm:os-browserify@0.1.2": {
"os": "github:jspm/nodelibs-os@0.1.0"
},
"npm:pako@0.2.8": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:parse-asn1@5.0.0": {
"asn1.js": "npm:asn1.js@4.3.0",
"browserify-aes": "npm:browserify-aes@1.0.5",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"pbkdf2": "npm:pbkdf2@3.0.4",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:pbkdf2@3.0.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:process-nextick-args@1.0.6": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:process@0.11.2": {
"assert": "github:jspm/nodelibs-assert@0.1.0"
},
"npm:public-encrypt@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"parse-asn1": "npm:parse-asn1@5.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:punycode@1.3.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:randombytes@2.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:readable-stream@1.1.13": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
},
"npm:readable-stream@2.0.5": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"process-nextick-args": "npm:process-nextick-args@1.0.6",
"string_decoder": "npm:string_decoder@0.10.31",
"util-deprecate": "npm:util-deprecate@1.0.2"
},
"npm:ripemd160@1.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:sha.js@2.4.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:source-map@0.4.4": {
"amdefine": "npm:amdefine@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:stream-browserify@1.0.0": {
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.13"
},
"npm:string_decoder@0.10.31": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:togeojson@0.13.0": {
"concat-stream": "npm:concat-stream@1.4.10",
"minimist": "npm:minimist@0.0.8",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:url@0.10.3": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"punycode": "npm:punycode@1.3.2",
"querystring": "npm:querystring@0.2.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util-deprecate@1.0.2": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:vm-browserify@0.0.4": {
"indexof": "npm:indexof@0.0.1"
}
}
});
| p4535992/Leaflet.FileLayer-1 | config.js | JavaScript | mit | 16,544 |
// languages index
var localeIndex = {
"en" : 0,
"ja" : 1,
"es" : 2,
"hu" : 3,
"lt" : 4,
"ru" : 5,
"it" : 6,
"pt" : 7,
"sp_ch" : 8,
"fr" : 9,
"ge" : 10,
"ua" : 11,
"lv" : 12,
"no" : 13,
"pt_br" : 14
};
| miya2000/Twippera-OAuth | js/lng.js | JavaScript | mit | 251 |
<?php
/**
* This file is part of gh-dashboard.
*
* (c) Daniel Londero <daniel.londero@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
function includeIfExists($file)
{
return file_exists($file) ? include $file : false;
}
if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
echo "Cannot find an autoload.php file, have you executed composer install command?" . PHP_EOL;
exit(1);
}
return $loader;
| dlondero/gh-dashboard | src/bootstrap.php | PHP | mit | 597 |
import React, { PropTypes, Component } from 'react';
import { Breadcrumb, Table, Button, Col } from 'react-bootstrap';
import cx from 'classnames';
import _ from 'lodash';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ProductList.css';
import Link from '../Link';
class ProductList extends Component {
static propTypes = {
isFetching: PropTypes.bool,
rs: PropTypes.array,
popAddApp: PropTypes.func,
};
static defaultProps = {
isFetching: true,
rs: [],
popAddApp: () => {},
};
constructor() {
super();
this.renderRow = this.renderRow.bind(this);
}
renderRow(rowData, index) {
const appName = _.get(rowData, 'name');
return (
<tr key={_.get(rowData, 'name')}>
<td>
<Link to={`/apps/${appName}`}>{appName}</Link>
</td>
<td style={{ textAlign: 'left' }}>
<ul>
{
_.map(_.get(rowData, 'collaborators'), (item, email) => (
<li key={email}>
{email}
<span className={s.permission}>
(<em>{_.get(item, 'permission')}</em>)
</span>
{
_.get(item, 'isCurrentAccount') ?
<span className={cx(s.label, s.labelSuccess)}>
it's you
</span>
: null
}
</li>
))
}
</ul>
</td>
<td>
<ul>
{
_.map(_.get(rowData, 'deployments'), (item, email) => (
<li key={email} style={item === 'Production' ? { color: 'green' } : null} >
<Link to={`/apps/${appName}/${item}`}>{item}</Link>
</li>
))
}
</ul>
</td>
<td />
</tr>
);
}
render() {
const self = this;
const tipText = '暂无数据';
return (
<div className={s.root}>
<div className={s.container}>
<Breadcrumb>
<Breadcrumb.Item active>
应用列表
</Breadcrumb.Item>
</Breadcrumb>
<Col style={{ marginBottom: '20px' }}>
<Button
onClick={this.props.popAddApp}
bsStyle="primary"
>
添加应用
</Button>
</Col>
<Table striped bordered condensed hover responsive>
<thead>
<tr>
<th style={{ textAlign: 'center' }} >产品名</th>
<th style={{ textAlign: 'center' }} >成员</th>
<th style={{ textAlign: 'center' }} >Deployments</th>
<th style={{ textAlign: 'center' }} >操作</th>
</tr>
</thead>
<tbody>
{
this.props.rs.length > 0 ?
_.map(this.props.rs, (item, index) => self.renderRow(item, index))
:
<tr>
<td colSpan="4" >{tipText}</td>
</tr>
}
</tbody>
</Table>
</div>
</div>
);
}
}
export default withStyles(s)(ProductList);
| lisong/code-push-web | src/components/ProductList/ProductList.js | JavaScript | mit | 3,199 |
define(['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var globalExtraOptions = exports.globalExtraOptions = {
mappingDataStructure: {
class: 'class',
content: 'content',
disabled: 'disabled',
divider: 'divider',
groupLabel: 'group',
groupDisabled: 'disabled',
icon: 'icon',
maxOptions: 'maxOptions',
option: 'option',
subtext: 'subtext',
style: 'style',
title: 'title',
tokens: 'tokens'
}
};
var globalPickerOptions = exports.globalPickerOptions = {
dropupAuto: true,
showTick: true,
width: 'auto'
};
}); | ghiscoding/Aurelia-Bootstrap-Plugins | aurelia-bootstrap-select/dist/amd/picker-global-options.js | JavaScript | mit | 686 |
"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
| algorhythms/LeetCode | 282 Expression Add Operators.py | Python | mit | 1,769 |
package softuni.io;
import org.springframework.stereotype.Component;
import java.io.*;
@Component
public class FileParser {
public String readFile(String path) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream is = this.getClass().getResourceAsStream(path);
BufferedReader bfr = new BufferedReader(new InputStreamReader(is))) {
String line = bfr.readLine();
while (line != null) {
stringBuilder.append(line);
line = bfr.readLine();
}
}
return stringBuilder.toString();
}
public void writeFile(String path, String content) throws IOException {
File file = new File(System.getProperty("user.dir") + File.separator + path);
if (!file.exists()) {
file.createNewFile();
}
try (OutputStream os = new FileOutputStream(System.getProperty("user.dir")+ File.separator + path);
BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(os))) {
bfw.write(content);
}
}
}
| yangra/SoftUni | Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/EXAMS/exam/src/main/java/softuni/io/FileParser.java | Java | mit | 1,123 |
using System;
namespace EasyNetQ
{
public class EasyNetQException : Exception
{
public EasyNetQException() {}
public EasyNetQException(string message) : base(message) {}
public EasyNetQException(string format, params string[] args) : base(string.Format(format, args)) {}
public EasyNetQException(string message, Exception inner) : base(message, inner) {}
}
public class EasyNetQResponderException : EasyNetQException
{
public EasyNetQResponderException() { }
public EasyNetQResponderException(string message) : base(message) { }
public EasyNetQResponderException(string format, params string[] args) : base(format, args) { }
public EasyNetQResponderException(string message, Exception inner) : base(message, inner) { }
}
} | ar7z1/EasyNetQ | Source/EasyNetQ/EasyNetQException.cs | C# | mit | 815 |
# frozen_string_literal: true
module ReviewBot
class Notification
def initialize(pull_request:, suggested_reviewers:)
@pull_request = pull_request
@suggested_reviewers = suggested_reviewers
end
attr_reader :pull_request, :suggested_reviewers
def message
[
%(• ##{pull_request.number} <#{pull_request.html_url}|#{pull_request.title}> needs a *#{needed_review_type}* from),
suggested_reviewers.map(&:slack_emoji).join(' ')
].join(' ')
end
private
def needed_review_type
pull_request.needs_first_review? ? 'first review' : 'second review'
end
end
end
| danielma/reviewbot | lib/review_bot/notification.rb | Ruby | mit | 636 |
function closeObject(id) {
document.getElementById(id).style.display = 'none';
}
function openObject(id) {
document.getElementById(id).style.display = 'block';
}
function openClose(id){
if (document.getElementById(id).style.display == 'block'){
console.log('intenta cerrar');
closeObject(id);
}else{
console.log('intenta abrir');
openObject(id);
}
}
$(document).ready(function () {
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
$(".botonRectificarEvento").on("click", function () {
$.ajax({
type: 'POST',
data: { id: $(this).attr("data-id") },
url: Routing.generate('eventos_rectificacion_nueva',null,true),
context: document.body
})
.done(function (datos) {
if(datos.estado) {
$('#tituloPopUp').html('Rectificar Evento');
$("#contenidoPopUp").html(datos.vista);
$('.modal-dialog').removeClass('modal-lg');
$('#piePopUp').addClass('show');
$('#ventanaPopUp').modal('show');
}
});
});
$("#botonGuardarPopUp").on("click", function () {
var datosFormulario = $("#formularioRectificarEvento").serializeArray();
var urlFormulario = Routing.generate('eventos_rectificacion_crear',null,true);
$.ajax(
{
url : urlFormulario,
type: "POST",
data : datosFormulario,
success: function(datos)
{
if(datos.estado){
if(datos.rectificado){
$('#ventanaPopUp').modal('hide');
$( location ).attr("href", Routing.generate('eventos',null,true));
} else {
$("#contenidoPopUp").html(datos.html);
}
}
},
error: function() {
alert('error');
}
});
return false;
});
// Visualizar detalles
$('.botonMostrarDetallesEvento').on('click',function(){
$.ajax({
type: 'GET',
url: Routing.generate('eventos_detalle',{ id: $(this).attr('data-id') },true),
context: document.body
})
.done(function (html) {
$('#tituloPopUp').html('Detalle eventos');
$("#contenidoPopUp").html(html);
$('.modal-dialog').addClass('modal-lg');
$('#piePopUp').addClass('hide');
$('#piePopUp').removeClass('show');
$('#ventanaPopUp').modal('show');
});
});
//Agregar nuevo detalle
$('#ventanaPopUp').on("click",'#botonAgregarDetalle',function(){
var datosFormulario = $("#formularioAgregarDetalle").serializeArray();
var urlFormulario = Routing.generate('eventos_detalle_crear',null,true);
$.ajax(
{
url : urlFormulario,
type: "POST",
data : datosFormulario,
success: function(datos)
{
$("#contenidoPopUp").html(datos.html);
}
});
return false;
});
$('#ventanaPopUp').on('mouseover','#dp-detalle',function(){
$('#dp-detalle').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
$('#ventanaPopUp').on('mouseover','#dp-rectificar',function(){
$('#dp-rectificar').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
$(".estado-switch").bootstrapSwitch();
$('#botonFormularioRegistro').on('click',function(){
if(! $('#botonFormularioRegistro').hasClass('active')) {
$(':input','#formularioBusqueda')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
$('#formularioBusqueda').append('<input type="hidden" name="seccion" value="registro" />');
$('#formularioBusqueda').submit();
}
// $('#botonFormularioBusqueda').removeClass('active');
// $(this).addClass('active');
// $('#divFormularioRegistro').removeClass('hide');
// $('#divFormularioRegistro').addClass('show');
// $('#divFormularioBusqueda').removeClass('show');
// $('#divFormularioBusqueda').addClass('hide');
});
$('#botonFormularioBusqueda').on('click',function(){
$('#botonFormularioRegistro').removeClass('active');
$(this).addClass('active');
$('#divFormularioBusqueda').removeClass('hide');
$('#divFormularioBusqueda').addClass('show');
$('#divFormularioRegistro').removeClass('show');
$('#divFormularioRegistro').addClass('hide');
});
$('#dtp-fecha-desde').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
$('#dtp-fecha-hasta').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
| jogianotti/RegistroEventosIntendencia | src/RegistroEventos/CoreBundle/Resources/public/js/eventos.js | JavaScript | mit | 5,274 |
import {Component, OnInit, ElementRef,} from '@angular/core';
import {FileSelect} from './file.select';
import {NgIf} from '@angular/common';
import {NgForm} from '@angular/common';
import {CostImport, CostImportService} from '../../../services/cost-import-service';
import {FourcastService} from '../../../services/fourcast-service';
import {FileUploader} from './file-uploader';
import {FileItem} from './file-uploader';
const TEMPLATE: string = require('./simple.import.setup.html');
const URL = 'http://127.0.0.1:8081/rest/$upload';
@Component({
selector: 'simple-demo',
template: TEMPLATE,
directives: [FileSelect],
styles: [`
.active {
background-color: red;
}
.disabled {
color: gray;
border: medium solid gray;
}
`],
providers: [FileUploader, CostImportService, FourcastService]
})
export class SimpleCostImportSetup implements OnInit {
isOn = true;
isDisabled = false;
importId: string;
private _file: File;
public isUploaded: boolean = false;
constructor( uploader: FileUploader, public importService: CostImportService){}
public isFileSelected: boolean = false;
typeNames = CostImport.typeNames;
model: CostImport = new CostImport();
ngOnInit(){
this.model.division = ''
}
onFileSelected(event){
console.log('File selected', event);
this._file = event['file'];
this.isFileSelected = true
this.model.importFileName = this._file.name;
//console.log('File selected 2: ', this.model.importFileName)
}
updateCostImport(fileId:string){
console.log('FileId (update): ', fileId)
this.importService.updateCostImportHdr(this.model, fileId)
.subscribe((res) =>{
var temp = JSON.stringify(res);
console.log("Update cost import header result: ",res);
this.importId = res['id'];
this.isUploaded = true;
//console.log('File content: ', text);
});
}
processCostImport(importId:string){
}
onImportFileClicked(){
console.log("Button clicked");
let uploader = new FileUploader();
uploader.uploadFile(this._file);
uploader.emitter.subscribe((data) => {
console.log("Upload event: ", data);
let response = JSON.parse(data['response']);
let fileId = response['ID'];
console.log('FileId (clicked): ', fileId)
this.updateCostImport(fileId);
});
//this.uploadFile(this._file);
}
onImportTypeChange(event){
this.model.isSupplierInvoices = false;
this.model.isPayrollWeekly = false;
this.model.isPayrollMonthly = false;
switch (true){
case event.target[0].selected:
this.model.isSupplierInvoices = true;
break;
case event.target[1].selected:
this.model.isPayrollWeekly = true;
break;
case event.target[2].selected:
this.model.isPayrollMonthly = true;
break;
}
}
testUpdate(){
let url:string = "http://127.0.0.1:8081/processImport";
let xhr=new XMLHttpRequest();
let formdata=new FormData();
formdata.append('ID',this.importId);
xhr.addEventListener("load", function (evt) {
let responseStr = evt.currentTarget['response'];
let res = JSON.parse(responseStr);
let id = res['ID'];
console.log("Response: ", res['ID']);
nextStep(id);
})
xhr.open('POST', url, true);
xhr.send(formdata);
function nextStep(id: string){
let url:string = "http://127.0.0.1:8081/processData";
let xhr=new XMLHttpRequest();
let formdata=new FormData();
formdata.append('ID',id);
xhr.addEventListener("load", function (evt) {
console.log(evt);
})
xhr.open('POST', url, true);
xhr.send(formdata);
}
}
}
| chriscurnow/angular2-webpack-starter | src/app/components/costImports/simple.cost.import.setup.ts | TypeScript | mit | 3,556 |
#include <iostream>
#include <string>
#include<iomanip>
using namespace std;
int main()
{
string a;
double h,m,x;
while(cin>>a)
{
if(a=="0:00")break;
if(a[1]==':')
{
h=a[0]-'0';
m=(a[2]-'0')*10+(a[3]-'0');
}
else if(a[2]==':')
{
h=(a[0]-'0')*10+(a[1]-'0');
m=(a[3]-'0')*10+(a[4]-'0');
}
x=30*h+m/2-6*m;
if(x<0)
{
x=-x;
}
if(x>180)
{
x=360-x;
}
cout<<fixed<<setprecision(3)<<x<<endl;
}
}
| w181496/OJ | Zerojudge/d095.cpp | C++ | mit | 718 |
<?php
namespace HealthCareAbroad\LogBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* ErrorLogRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ErrorLogRepository extends EntityRepository
{
} | richtermarkbaay/MEDTrip | src/HealthCareAbroad/LogBundle/Repository/ErrorLogRepository.php | PHP | mit | 277 |
<?php
/*
* This file is part of the MopaBootstrapBundle.
*
* (c) Philipp A. Mohrenweiser <phiamo@googlemail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mopa\Bundle\BootstrapBundle\Menu\Factory;
use Knp\Menu\Factory\ExtensionInterface;
use Knp\Menu\ItemInterface;
/**
* Extension for integrating Bootstrap Menus into KnpMenu.
*/
class MenuExtension implements ExtensionInterface
{
/**
* Builds a menu item based.
*
* @param ItemInterface $item
* @param array $options
*/
public function buildItem(ItemInterface $item, array $options)
{
if ($options['navbar']) {
$item->setChildrenAttribute('class', 'nav navbar-nav');
}
if ($options['pills']) {
$item->setChildrenAttribute('class', 'nav nav-pills');
}
if ($options['stacked']) {
$class = $item->getChildrenAttribute('class');
$item->setChildrenAttribute('class', $class . ' nav-stacked');
}
if ($options['dropdown-header']) {
$item
->setAttribute('role', 'presentation')
->setAttribute('class', 'dropdown-header')
->setUri(null);
}
if ($options['list-group']) {
$item->setChildrenAttribute('class', 'list-group');
$item->setAttribute('class', 'list-group-item');
}
if ($options['list-group-item']) {
$item->setAttribute('class', 'list-group-item');
}
if ($options['dropdown']) {
$item
->setUri('#')
->setAttribute('class', 'dropdown')
->setLinkAttribute('class', 'dropdown-toggle')
->setLinkAttribute('data-toggle', 'dropdown')
->setChildrenAttribute('class', 'dropdown-menu')
->setChildrenAttribute('role', 'menu');
if ($options['caret']) {
$item->setExtra('caret', 'true');
}
}
if ($options['divider']) {
$item
->setLabel('')
->setUri(null)
->setAttribute('role', 'presentation')
->setAttribute('class', 'divider');
}
if ($options['pull-right']) {
$className = $options['navbar'] ? 'navbar-right' : 'pull-right';
$class = $item->getChildrenAttribute('class', '');
$item->setChildrenAttribute('class', $class . ' ' . $className);
}
if ($options['icon']) {
$item->setExtra('icon', $options['icon']);
}
}
/**
* Builds the options for extension.
*
* @param array $options
*
* @return array $options
*/
public function buildOptions(array $options)
{
return array_merge(array(
'navbar' => false,
'pills' => false,
'stacked' => false,
'dropdown-header' => false,
'dropdown' => false,
'list-group' => false,
'list-group-item' => false,
'caret' => false,
'pull-right' => false,
'icon' => false,
'divider' => false,
), $options);
}
}
| naitsirch/mopa-bootstrap-bundle | Menu/Factory/MenuExtension.php | PHP | mit | 3,307 |
<?php
require_once "class_db.php";
class qly_pages extends db{
public function LayTieuDeKD($idPa){
$sql="SELECT TieuDeKD FROM mk_pages WHERE idPa = '$idPa'";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['TieuDeKD'];
}
public function LayTieuDe($idPa){
$sql="SELECT TieuDe FROM mk_pages WHERE idPa = '$idPa'";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['TieuDe'];
}
public function LayID($TieuDeKD){
$sql="SELECT idPa FROM mk_pages WHERE TieuDeKD = '$TieuDeKD'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['idPa'];
}
public function LayIDGroup($idPa){
$sql="SELECT idGroup FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['idGroup'];
}
public function LayParent($idPa){
$sql="SELECT Parent FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Parent'];
}
public function LayNoiDung($idPa){
$sql="SELECT NoiDung FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['NoiDung'];
}
public function Pages($idPa){
$sql="SELECT *
FROM mk_pages
WHERE idPa = $idPa";
$kq = mysql_query($sql,$this->conn);
return $kq;
}
public function ListCauHoi(){
$sql="SELECT TomTat, NoiDung
FROM mk_pages
WHERE AnHien = 1 and idGroup = 2
ORDER BY idPa
";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
return $kq;
}
public function DanhChoKhachHang($parent){
$sql="SELECT *
FROM mk_pages
WHERE Parent = $parent and AnHien = 1
Order By ThuTu ASC, idLoai DESC
";
$kq = mysql_query($sql,$this->conn);
return $sql;
}
public function ListPagesParent($idGroup, &$totalRows, $pageNum=1, $pageSize = 10, $Parent){
$startRow = ($pageNum-1)*$pageSize;
$sql="SELECT TieuDe, TieuDeKD, TomTat, NoiDung, UrlHinh
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup and Parent = '$Parent'
ORDER BY idPa desc
LIMIT $startRow , $pageSize
";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
$sql="SELECT count(*) FROM mk_pages WHERE AnHien = 1 and idGroup = $idGroup and Parent = '$Parent'
";
$rs= mysql_query($sql) or die(mysql_error());;
$row_rs = mysql_fetch_row($rs);
$totalRows = $row_rs[0];
return $kq;
}
public function ListPages($idGroup, &$totalRows, $pageNum=1, $pageSize = 10, $lang = 'vi'){
$startRow = ($pageNum-1)*$pageSize;
$sql="SELECT TieuDe, TomTat, TieuDeKD, UrlHinh, NgayDang, NoiDung
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup and Lang = '$lang'
ORDER BY idPa desc
LIMIT $startRow , $pageSize
";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
$sql="SELECT count(*) FROM mk_pages WHERE AnHien = 1 and idGroup = $idGroup and Lang = '$lang'
";
$rs= mysql_query($sql) or die(mysql_error());;
$row_rs = mysql_fetch_row($rs);
$totalRows = $row_rs[0];
return $kq;
}
public function ListTinTuc($sotin, $idGroup){
if($idGroup == -1){
$sql="SELECT TieuDe, TomTat, TieuDeKD, UrlHinh, NgayDang
FROM mk_pages
WHERE AnHien = 1 and idGroup in (1, 2)
ORDER BY idPa desc
LIMIT 0 , $sotin
";
}else{
$sql="SELECT TieuDe, TomTat, TieuDeKD, UrlHinh, NgayDang
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup
ORDER BY idPa desc
LIMIT 0 , $sotin
";
}
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
return $kq;
}
public function ListMenu($idGroup){
$sql="SELECT TieuDe, TieuDeKD, idPa
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup and idPa <> 2 and idPa <> 109
ORDER BY ThuTu ASC";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
return $kq;
}
public function LayTitle($idPa){
$sql="SELECT Title FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Title'];
}
public function LayDes($idPa){
$sql="SELECT Des FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Des'];
}
public function LayKeyword($idPa){
$sql="SELECT Keyword FROM mk_pages WHERE idPa = '$idPa'";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Keyword'];
}
}
?> | pkapollo/phongkhamapollo.com | san-phu-khoa/m/lib/class_pages.php | PHP | mit | 4,795 |
/* eslint-env node*/
var gutil = require('gulp-util')
var paths = {
layouts: {
componentsDir: './app/components/**/*.jade',
src: './app/views/**/*.jade',
dest: './app/public/assets/html/'
},
styles: {
componentsDir: './app/lib/stylesheets/**/*.styl',
src: './app/lib/stylesheets/styles.styl',
dest: './app/public/assets/css/'
},
scripts: {
entry: './app/lib/scripts/entry.jsx',
src: ['./app/lib/scripts/**/*.jsx', './app/lib/scripts/**/*.js'],
dest: './app/public/assets/js/'
}
}
var onError = function (error) {
gutil.log(gutil.colors.red(error))
this.emit('end')
}
module.exports = {
paths: paths,
onError: onError
}
| datyayu/cemetery | [JS-ES6][React] Raji - first version/gulp/config.js | JavaScript | mit | 716 |
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
| BeardedPlatypus/capita-selecta-ctf | ctf/players/admin.py | Python | mit | 126 |
/**
*
* app.js
*
* This is the entry file for the application
*
*/
import FilmLocationSearchComponent from '../MovieSearchApp/Containers/FilmSearchContainer/FilmSearchComponent';
import AppComponent from '../CommonComponent/app.js';
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
console.log("current href",window.location.href);
const getAppRouter = () => {
return (
<Route component={AppComponent}>
<Route component={FilmLocationSearchComponent} path='/searchmovies' />
</Route>
);
}
export {
getAppRouter
}
| anil26/MovieSearchGoogleMaps | js/Routes/AppRouter.js | JavaScript | mit | 597 |
/* Accordion directive */
app.directive('vmfAccordionContainer', ['$compile', function($compile) {
return {
restrict: 'EA',
scope: {
type: '@',
headers: '=',
accData: '=',
selAcc: '=',
customClass:'='
},
link: function(scope, elem, attrs) {
var template;
if(scope.type === '1') {
template = '<table class="vmf-accordion-table1"><thead class="vmf-accordion-table-header"><tr><td class="col1"></td>';
var count = 1;
angular.forEach(scope.headers, function(item) {
// if(count === 1) {
// template += '<td colspan="2">' + item + '</td>';
// }
// else {
template += '<td class="col' + (count + 1) +'">' + item + '</td>';
// }
count += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td ><span class="vmf-arrow"></span></td><td colspan="3">' + item.header + '</td></tr>';
angular.forEach(item.contents, function(content) {
template += '<tr class="vmf-accordion-row" ng-show="activeIndex =='+ scope.accordionIndex + '"><td colspan="1"></td>';
angular.forEach(content, function(cellData) {
template += '<td colspan="1">' + cellData + '</td>';
});
template += '</tr>';
});
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row').hide();
}
else if(scope.type === '2') {
template = '<table class="vmf-accordion-table2"><thead class="vmf-accordion-table2-header" style="background-color: lightgray;"><tr><td class="col1"></td>';
var headerCount = 0;
angular.forEach(scope.headers, function(item) {
if(headerCount !== scope.headers.length - 1) {
template += '<td class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
else {
template += '<td colspan="2" class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
headerCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table2-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header2" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td><span class="vmf-arrow"></span></td>';
var accHeadersCount = 1;
angular.forEach(item.headers, function(header) {
if(accHeadersCount !== item.headers.length) {
template += '<td>' + header + '</td>';
}
else {
template += '<td class="vmf-acc-header-last-child">' + header + '</td>';
}
accHeadersCount += 1;
});
template += '</tr><tr class="vmf-accordion-row2"><td></td><td class="vmf-acc-header-last-child" colspan="' + item.headers.length + '"><table class="vmf-accordion-sub-table" ng-show="activeIndex =='+ scope.accordionIndex + '">';
var count = 0;
angular.forEach(item.contents, function(content) {
if(count !== 0) {
template += '<tr class="vmf-accordion-sub-table-row">';
angular.forEach(content, function(cellData) {
template += '<td>' + cellData + '</td>';
});
template += '</tr>';
}
else {
template += '<thead class="vmf-accordion-sub-table-header"><tr>';
var subHeaderCount = 1;
angular.forEach(content, function(cellData) {
template += '<td class="col' + subHeaderCount + '">' + cellData + '</td>';
subHeaderCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-sub-table-body">';
}
count += 1;
});
template += '</tbody></table></td></tr>';
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
if(scope.customClass){
angular.forEach(scope.customClass, function(item) {
elem.find(item.selector).addClass(item.cusclass);
});
}
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row2').hide();
// elem.find('.vmf-accordion-row2').hide();
}
scope.toggleAccordion = function(index) {
scope.activeIndex = scope.activeIndex === index ? -1 : index;
var accordions, accordionRows;
if(scope.type === '1') {
elem.find('.vmf-accordion-row').hide();
accordions = elem.find('.vmf-accordion-header');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
// accordions = elem.find('.vmf-accordion-header');
// console.log(accordions[index]);
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header');
$(accordionRows).show();
}
}
else if(scope.type === '2') {
elem.find('.vmf-accordion-row2').hide();
accordions = elem.find('.vmf-accordion-header2');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header2');
$(accordionRows).show();
}
}
};
scope.buttonClick = function($event, index) {
$event.stopPropagation();
scope.selAcc = index;
};
}
};
}]); | anandharshan/Web-components-DD | dev/modules/Accordion/accordionDirectives.js | JavaScript | mit | 8,055 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.comci.bigbib;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bson.types.ObjectId;
import org.codehaus.jackson.annotate.JsonProperty;
import org.jbibtex.BibTeXEntry;
import org.jbibtex.Key;
import org.jbibtex.StringValue;
import org.jbibtex.Value;
/**
*
* @author Sebastian
*/
@XmlRootElement()
@XmlAccessorType(XmlAccessType.NONE)
public class PeristentBibTexEntry extends BibTeXEntry {
private ObjectId id;
public PeristentBibTexEntry(Key type, Key key) {
super(type, key);
}
static Map<String, Key> keyMapping = new HashMap<String, Key>();
static {
keyMapping.put("address", BibTeXEntry.KEY_ADDRESS);
keyMapping.put("annote", BibTeXEntry.KEY_ANNOTE);
keyMapping.put("author", BibTeXEntry.KEY_AUTHOR);
keyMapping.put("booktitle", BibTeXEntry.KEY_BOOKTITLE);
keyMapping.put("chapter", BibTeXEntry.KEY_CHAPTER);
keyMapping.put("crossref", BibTeXEntry.KEY_CROSSREF);
keyMapping.put("doi", BibTeXEntry.KEY_DOI);
keyMapping.put("edition", BibTeXEntry.KEY_EDITION);
keyMapping.put("editor", BibTeXEntry.KEY_EDITOR);
keyMapping.put("eprint", BibTeXEntry.KEY_EPRINT);
keyMapping.put("howpublished", BibTeXEntry.KEY_HOWPUBLISHED);
keyMapping.put("institution", BibTeXEntry.KEY_INSTITUTION);
keyMapping.put("journal", BibTeXEntry.KEY_JOURNAL);
keyMapping.put("key", BibTeXEntry.KEY_KEY);
keyMapping.put("month", BibTeXEntry.KEY_MONTH);
keyMapping.put("note", BibTeXEntry.KEY_NOTE);
keyMapping.put("number", BibTeXEntry.KEY_NUMBER);
keyMapping.put("organization", BibTeXEntry.KEY_ORGANIZATION);
keyMapping.put("pages", BibTeXEntry.KEY_PAGES);
keyMapping.put("publisher", BibTeXEntry.KEY_PUBLISHER);
keyMapping.put("school", BibTeXEntry.KEY_SCHOOL);
keyMapping.put("series", BibTeXEntry.KEY_SERIES);
keyMapping.put("title", BibTeXEntry.KEY_TITLE);
keyMapping.put("type", BibTeXEntry.KEY_TYPE);
keyMapping.put("url", BibTeXEntry.KEY_URL);
keyMapping.put("volume", BibTeXEntry.KEY_VOLUME);
keyMapping.put("year", BibTeXEntry.KEY_YEAR);
}
public PeristentBibTexEntry(DBObject persistentObject) {
super(
new Key((String) persistentObject.get("type")),
new Key((String) persistentObject.get("key"))
);
BasicDBObject fields = (BasicDBObject) persistentObject.get("fields");
id = (ObjectId) persistentObject.get("_id");
for (String key : fields.keySet()) {
if (keyMapping.containsKey(key)) {
this.addField(keyMapping.get(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
} else {
this.addField(new Key(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
}
}
}
@JsonProperty("id")
@XmlElement(name="id")
public String getStringId() {
return id.toString();
}
@JsonProperty("key")
@XmlElement(name="key")
public String getStringKey() {
return super.getKey().getValue();
}
@JsonProperty("type")
@XmlElement(name="type")
public String getStringType() {
return super.getType().getValue();
}
@JsonProperty("fields")
@XmlElement(name="fields")
public Map<String, String> getStringFields() {
Map<String, String> fields = new HashMap<String, String>();
for (Entry<Key,Value> e : getFields().entrySet()) {
if (e.getKey() != null && e.getValue() != null) {
fields.put(e.getKey().getValue(), e.getValue().toUserString());
}
}
return fields;
}
@Override
public String toString() {
return String.format("[%s:%s] %s: %s (%s)",
this.getType(),
this.getKey(),
this.getField(KEY_AUTHOR).toUserString(),
this.getField(KEY_TITLE).toUserString(),
this.getField(KEY_YEAR).toUserString());
}
}
| maiers/bigbib | src/main/java/de/comci/bigbib/PeristentBibTexEntry.java | Java | mit | 4,524 |
module Admin::BaseHelper
include ActionView::Helpers::DateHelper
def subtabs_for(current_module)
output = []
AccessControl.project_module(current_user.profile.label, current_module).submenus.each_with_index do |m,i|
current = (m.url[:controller] == params[:controller] && m.url[:action] == params[:action]) ? "current" : ""
output << subtab(_(m.name), current, m.url)
end
content_for(:tasks) { output.join("\n") }
end
def subtab(label, style, options = {})
content_tag :li, link_to(label, options, { "class"=> style })
end
def show_page_heading
content_tag(:h2, @page_heading, :class => 'mb20') unless @page_heading.blank?
end
def cancel(url = {:action => 'index'})
link_to _("Cancel"), url
end
def save(val = _("Store"))
'<input type="submit" value="' + val + '" class="save" />'
end
def confirm_delete(val = _("Delete"))
'<input type="submit" value="' + val + '" />'
end
def link_to_show(record, controller = @controller.controller_name)
if record.published?
link_to image_tag('admin/show.png', :alt => _("show"), :title => _("Show content")),
{:controller => controller, :action => 'show', :id => record.id},
{:class => "lbOn"}
end
end
def link_to_edit(label, record, controller = @controller.controller_name)
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
def link_to_edit_with_profiles(label, record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
end
def link_to_destroy(record, controller = @controller.controller_name)
link_to image_tag('admin/delete.png', :alt => _("delete"), :title => _("Delete content")),
:controller => controller, :action => 'destroy', :id => record.id
end
def link_to_destroy_with_profiles(record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to(_("delete"),
{ :controller => controller, :action => 'destroy', :id => record.id }, :confirm => _("Are you sure?"), :method => :post, :title => _("Delete content"))
end
end
def text_filter_options
TextFilter.find(:all).collect do |filter|
[ filter.description, filter ]
end
end
def text_filter_options_with_id
TextFilter.find(:all).collect do |filter|
[ filter.description, filter.id ]
end
end
def alternate_class
@class = @class != '' ? '' : 'class="shade"'
end
def reset_alternation
@class = nil
end
def task_quickpost(title)
link_to_function(title, toggle_effect('quick-post', 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_overview
content_tag :li, link_to(_('Back to overview'), :action => 'index')
end
def task_add_resource_metadata(title,id)
link_to_function(title, toggle_effect('add-resource-metadata-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_edit_resource_metadata(title,id)
link_to_function(title, toggle_effect('edit-resource-metadata-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_edit_resource_mime(title,id)
link_to_function(title, toggle_effect('edit-resource-mime-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def class_write
if controller.controller_name == "content" or controller.controller_name == "pages"
"current" if controller.action_name == "new"
end
end
def class_content
if controller.controller_name =~ /content|pages|categories|resources|feedback/
"current" if controller.action_name =~ /list|index|show/
end
end
def class_themes
"current" if controller.controller_name =~ /themes|sidebar/
end
def class_users
controller.controller_name =~ /users/ ? "current right" : "right"
end
def class_dashboard
controller.controller_name =~ /dashboard/ ? "current right" : "right"
end
def class_settings
controller.controller_name =~ /settings|textfilter/ ? "current right" : "right"
end
def class_profile
controller.controller_name =~ /profiles/ ? "current right" : "right"
end
def alternate_editor
return 'visual' if current_user.editor == 'simple'
return 'simple'
end
def collection_select_with_current(object, method, collection, value_method, text_method, current_value, prompt=false)
result = "<select name='#{object}[#{method}]'>\n"
if prompt == true
result << "<option value=''>" << _("Please select") << "</option>"
end
for element in collection
if current_value and current_value == element.send(value_method)
result << "<option value='#{element.send(value_method)}' selected='selected'>#{element.send(text_method)}</option>\n"
else
result << "<option value='#{element.send(value_method)}'>#{element.send(text_method)}</option>\n"
end
end
result << "</select>\n"
return result
end
def render_void_table(size, cols)
if size == 0
"<tr>\n<td colspan=#{cols}>" + _("There are no %s yet. Why don't you start and create one?", _(controller.controller_name)) + "</td>\n</tr>\n"
end
end
def cancel_or_save
result = '<p class="right">'
result << cancel
result << " "
result << _("or")
result << " "
result << save( _("Save") + " »")
result << '</p>'
return result
end
def link_to_published(item)
item.published? ? link_to_permalink(item, _("published"), '', 'published') : "<span class='unpublished'>#{_("unpublished")}</span>"
end
def macro_help_popup(macro, text)
unless current_user.editor == 'visual'
"<a rel='lightbox' href=\"#{url_for :controller => 'textfilters', :action => 'macro_help', :id => macro.short_name}\" onclick=\"return popup(this, 'Typo Macro Help')\">#{text}</a>"
end
end
def render_macros(macros)
result = link_to_function _("Show help on Typo macros") + " (+/-)",update_page { |page| page.visual_effect(:toggle_blind, "macros", :duration => 0.2) }
result << "<table id='macros' style='display: none;'>"
result << "<tr>"
result << "<th>#{_('Name')}</th>"
result << "<th>#{_('Description')}</th>"
result << "<th>#{_('Tag')}</th>"
result << "</tr>"
for macro in macros.sort_by { |f| f.short_name }
result << "<tr #{alternate_class}>"
result << "<td>#{macro_help_popup macro, macro.display_name}</td>"
result << "<td>#{h macro.description}</td>"
result << "<td><code><typo:#{h macro.short_name}></code></td>"
result << "</tr>"
end
result << "</table>"
end
def build_editor_link(label, action, id, update, editor)
link = link_to_remote(label,
:url => { :action => action, 'editor' => editor},
:loading => "new Element.show('update_spinner_#{id}')",
:success => "new Element.toggle('update_spinner_#{id}')",
:update => "#{update}")
link << image_tag("spinner-blue.gif", :id => "update_spinner_#{id}", :style => 'display:none;')
end
def display_pagination(collection, cols)
if WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1
return "<tr><td colspan=#{cols} class='paginate'>#{will_paginate(collection)}</td></tr>"
end
end
def show_thumbnail_for_editor(image)
thumb = "#{RAILS_ROOT}/public/files/thumb_#{image.filename}"
picture = "#{this_blog.base_url}/files/#{image.filename}"
image.create_thumbnail unless File.exists? thumb
# If something went wrong with thumbnail generation, we just display a place holder
thumbnail = (File.exists? thumb) ? "#{this_blog.base_url}/files/thumb_#{image.filename}" : "#{this_blog.base_url}/images/thumb_blank.jpg"
picture = "<img class='tumb' src='#{thumbnail}' "
picture << "alt='#{this_blog.base_url}/files/#{image.filename}' "
picture << " onclick=\"edInsertImageFromCarousel('article_body_and_extended', '#{this_blog.base_url}/files/#{image.filename}');\" />"
return picture
end
end
| jasondew/cola.rb | app/helpers/admin/base_helper.rb | Ruby | mit | 8,319 |
<?php
namespace Editionista\WebsiteBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as Controller;
use Editionista\WebsiteBundle\Entity\Tag;
/**
* Edition controller.
*
* @Route("/tags")
*/
class TagController extends Controller
{
/**
* @Route("/", name="tags")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$tags = $em->getRepository('EditionistaWebsiteBundle:Tag')->findAll();
return array('tags' => $tags);
}
/**
* @Route("/{tag}", name="show_tag")
* @Template()
*/
public function showAction($tag)
{
$em = $this->getDoctrine()->getManager();
$tag = $em->getRepository('EditionistaWebsiteBundle:Tag')->findOneByName($tag);
$editions = $tag->getEditions();
return array('tag' => $tag, 'editions' => $editions);
}
/**
* @Route("/push", name="push_tags")
* @Method({"POST"})
*/
public function pushAction(Request $request)
{
$pushedTag = $request->request->get('tag');
$em = $this->getDoctrine()->getManager();
$storedTag = $em->getRepository('EditionistaWebsiteBundle:Tag')->findOneByName($pushedTag);
if($storedTag == null) {
$tag = new Tag();
$tag->setName($pushedTag);
$em = $this->getDoctrine()->getManager();
$em->persist($tag);
$em->flush();
}
$response = new Response(json_encode(array('tag' => $pushedTag)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/pull", name="pull_tags")
*/
public function pullAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EditionistaWebsiteBundle:Tag')->findAll();
$tags = array();
foreach($entities as $entity) {
$tags['tags'][] = array('tag' => $entity->getName());
}
$response = new Response(json_encode($tags));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
| fabstei/editionista | src/Editionista/WebsiteBundle/Controller/TagController.php | PHP | mit | 2,557 |
using System;
using System.Reflection;
namespace Light.DataCore
{
abstract class DynamicFieldMapping : FieldMapping
{
public static DynamicFieldMapping CreateDynmaicFieldMapping (PropertyInfo property, DynamicCustomMapping mapping)
{
DynamicFieldMapping fieldMapping;
Type type = property.PropertyType;
TypeInfo typeInfo = type.GetTypeInfo();
string fieldName = property.Name;
if (typeInfo.IsGenericType) {
Type frameType = type.GetGenericTypeDefinition ();
if (frameType.FullName == "System.Nullable`1") {
Type [] arguments = type.GetGenericArguments ();
type = arguments [0];
typeInfo = type.GetTypeInfo();
}
}
if (type.IsArray) {
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
}
else if (type.IsGenericParameter || typeInfo.IsGenericTypeDefinition) {
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
}
else if (typeInfo.IsEnum) {
DynamicEnumFieldMapping enumFieldMapping = new DynamicEnumFieldMapping (type, fieldName, mapping);
fieldMapping = enumFieldMapping;
}
else {
TypeCode code = Type.GetTypeCode (type);
switch (code) {
case TypeCode.Empty:
case TypeCode.Object:
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
default:
DynamicPrimitiveFieldMapping primitiveFieldMapping = new DynamicPrimitiveFieldMapping (type, fieldName, mapping);
fieldMapping = primitiveFieldMapping;
break;
}
}
return fieldMapping;
}
protected DynamicFieldMapping (Type type, string fieldName, DynamicCustomMapping mapping, bool isNullable)
: base (type, fieldName, fieldName, mapping, isNullable, null)
{
}
}
}
| aquilahkj/Light.DataCore | Light.DataCore/Mappings/DynamicFieldMapping.cs | C# | mit | 1,881 |
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
auto radius = 0;
auto idx = 0;
for (auto house : houses) {
auto current = abs(house - heaters[idx]);
if (current <= radius) continue;
for (auto n = idx + 1; n < heaters.size(); ++n) {
if (abs(house - heaters[n]) <= current) {
current = abs(house - heaters[n]);
idx = n;
} else {
break;
}
}
radius = max(radius, current);
}
return radius;
}
}; | wait4pumpkin/leetcode | 475.cc | C++ | mit | 561 |
from django.conf.urls import patterns, include, url
import views
urlpatterns = patterns('',
url(r'^logout', views.logout, name='logout'),
url(r'^newUser', views.newUser, name='newUser'),
url(r'^appHandler', views.appHandler, name='appHandler'),
url(r'^passToLogin', views.loginByPassword, name='passToLogin'),
url(r'^signToLogin', views.loginBySignature, name='signToLogin'),
url(r'^authUserHandler', views.authUserHandler, name='authUserHandler'),
)
| odeke-em/restAssured | auth/urls.py | Python | mit | 477 |
module Dragoman
module Mapper
def localize
locales = I18n.available_locales
unscoped_locales = [I18n.default_locale]
scoped_locales = locales - unscoped_locales
scope ':locale', shallow_path: ':locale', defaults: {dragoman_options: {locales: scoped_locales}} do
yield
end
defaults dragoman_options: {locales: unscoped_locales} do
yield
end
@locales = nil
end
end
end | pietervisser/dragoman | lib/dragoman/mapper.rb | Ruby | mit | 442 |
<?php
if(!defined('BASEPATH'))
die;
class MY_Controller extends CI_Controller
{
public $session;
public $user;
function __construct(){
parent::__construct();
$this->output->set_header('X-Powered-By: ' . config_item('system_vendor'));
$this->output->set_header('X-Deadpool: ' . config_item('header_message'));
$this->load->library('SiteEnum', '', 'enum');
$this->load->library('SiteParams', '', 'setting');
$this->load->library('SiteTheme', '', 'theme');
$this->load->library('SiteMenu', '', 'menu');
$this->load->library('SiteForm', '', 'form');
$this->load->library('SiteMeta', '', 'meta');
$this->load->library('ObjectMeta', '', 'ometa');
$this->load->library('ActionEvent', '', 'event');
$cookie_name = config_item('sess_cookie_name');
$hash = $this->input->cookie($cookie_name);
if($hash){
$this->load->model('Usersession_model', 'USession');
$session = $this->USession->getBy('hash', $hash);
$this->session = $session;
if($session){
$this->load->model('User_model', 'User');
$user = $this->User->get($session->user);
// TODO
// Increase session expiration if it's almost expired
if($user && $user->status > 1){
$this->user = $user;
$this->user->perms = [];
if($user){
if($user->id == 1){
$this->load->model('Perms_model', 'Perms');
$user_perms = $this->Perms->getByCond([], true, false);
$this->user->perms = prop_values($user_perms, 'name');
}else{
$this->load->model('Userperms_model', 'UPerms');
$user_perms = $this->UPerms->getBy('user', $user->id, true);
if($user_perms)
$this->user->perms = prop_values($user_perms, 'perms');
}
$this->user->perms[] = 'logged_in';
}
}
}
}
if($this->theme->current() == 'admin/')
$this->lang->load('admin', config_item('language'));
}
/**
* Return to client as ajax respond.
* @param mixed data The data to return.
* @param mixed error The error data.
* @param mixed append Additional data to append to result.
*/
public function ajax($data, $error=false, $append=null){
$result = array(
'data' => $data,
'error'=> $error
);
if($append)
$result = array_merge($result, $append);
$cb = $this->input->get('cb');
if(!$cb)
$cb = $this->input->get('callback');
$json = json_encode($result);
$cset = config_item('charset');
if($cb){
$json = "$cb($json);";
$this->output
->set_status_header(200)
->set_content_type('application/javascript', $cset)
->set_output($json)
->_display();
exit;
}else{
$this->output
->set_status_header(200)
->set_content_type('application/json', $cset)
->set_output($json)
->_display();
exit;
}
}
/**
* Check if current admin user can do something
* @param string perms The perms to check.
* @return boolean true on allowed, false otherwise.
*/
public function can_i($perms){
if(!$this->user)
return false;
return in_array($perms, $this->user->perms);
}
/**
* Redirect to some URL.
* @param string next Target URL.
* @param integer status Redirect status.
*/
public function redirect($next='/', $status=NULL){
if(substr($next, 0, 4) != 'http')
$next = base_url($next);
redirect($next, 'auto', $status);
}
/**
* Print page.
* @param string view The view to load.
* @param array params The parameters to send to view.
*/
public function respond($view, $params=array()){
$page_title = '';
if(array_key_exists('title', $params))
$page_title = $params['title'] . ' - ';
$page_title.= $this->setting->item('site_name');
$params['page_title'] = $page_title;
if(!$this->theme->exists($view) && !is_dev())
return $this->show_404();
$this->theme->load($view, $params);
}
/**
* Print 404 page
*/
public function show_404(){
$this->load->model('Urlredirection_model', 'Redirection');
$next = $this->Redirection->getBy('source', uri_string());
if($next)
return $this->redirect($next->target, 301);
$this->output->set_status_header('404');
$params = array(
'title' => _l('Page not found')
);
$this->respond('404', $params);
}
} | iqbalfn/admin | application/core/MY_Controller.php | PHP | mit | 5,404 |
/* ================================================================
* startserver by xdf(xudafeng[at]126.com)
*
* first created at : Mon Jun 02 2014 20:15:51 GMT+0800 (CST)
*
* ================================================================
* Copyright 2013 xdf
*
* Licensed under the MIT License
* You may not use this file except in compliance with the License.
*
* ================================================================ */
'use strict';
var logx = require('logx');
function *logger() {
var log = 'Method: '.gray + this.req.method.red;
log += ' Url: '.gray + this.req.url.red;
logx.info(log);
yield this.next();
}
module.exports = logger;
| xudafeng/startserver | lib/middleware/logger/index.js | JavaScript | mit | 675 |
using UnityEngine;
using System.Collections;
public class GravitySwitch : MonoBehaviour
{
public float GravityStrength;
float momentum;
float click;
public bool GameState;
bool GravityState;
public GameObject Explosion;
public GameObject[] Jets;
public GameObject[] CharacterPieces;
public Vector3 hitposition;
public GameObject EndScreen;
public UILabel BestScore;
void Start()
{
GravityStrength = 0;
BestScore.text = "Best:" + PlayerPrefs.GetFloat("BestScore").ToString();
GameState = true;
}
void Update ()
{
Gravity();
Controls();
if (GameState == false)
{
transform.position = hitposition;
EndScreen.SetActive(true);
}
}
void Gravity()
{
//transform.Translate(new Vector3(3,0) * Time.deltaTime);
switch (GravityState)
{
case true: Physics2D.gravity = new Vector2(momentum,GravityStrength); /*transform.localEulerAngles = new Vector2(-180, 0);*/ break;
case false: Physics2D.gravity = new Vector2(momentum,-GravityStrength); /*transform.localEulerAngles = new Vector2(0, 0);*/ break;
}
if (GravityStrength == 0)
{
transform.position = new Vector3(0,-5.5f,0);
}
}
void Controls()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GravityState = !GravityState;
}
if (Input.GetMouseButtonDown(0))
{
GravityState = !GravityState;
if (click == 0)
{
momentum = 2;
GravityStrength = 27;
foreach(GameObject jet in Jets)
{
jet.SetActive(true);
}
}
click+=1;
}
}
void OnCollisionEnter2D(Collision2D other)
{
//Application.LoadLevel(Application.loadedLevel);
if (GameState == true)
{
foreach (ContactPoint2D contact in other.contacts)
{
GameObject Hit = Instantiate (Explosion, contact.point, Quaternion.identity) as GameObject;
hitposition = Hit.transform.position;
GameState = false;
}
foreach (GameObject self in CharacterPieces)
{
self.SetActive(false);
}
}
}
}
| parodyband/Polarity | Assets/Code/GravitySwitch.cs | C# | mit | 1,927 |
// Write a boolean expression that returns if the bit at position p (counting from 0)
// in a given integer number v has value of 1. Example: v=5; p=1 -> false.
using System;
class BitInIntegerCheck
{
static void Main()
{
// декларираме променливи за числото (v) и позицията (p), за която ще проверяваме
int v = 8;
int p = 3;
// израза е прекалено лесен и не мисля, че си заслужава декларацията на 2 допълнителни променливи...
// умножаваме "v" с 1 предварително отместено "p" пъти наляво, след което резултатът бива отместен "p" пъти надясно
// със същият успех може и да се премести единицата от дясната страна на израза "p" пъти наляво,
// като по този начин си спестяваме връщането "p" пъти надясно от другата страна на равенството и е по-лесно за разбиране/четене
// => if( v & ( 1 << p ) == 1 << p )
if( ( v & ( 1 << p ) ) >> p == 1 )
{
Console.WriteLine("The value {0} has a 1 at bit number {1}", v, p);
}
else
{
Console.WriteLine("The value {0} has a 0 at bit number {1}", v, p);
}
}
} | Steffkn/TelerikAcademy | Programming/01. CSharp Part 1/03.OperatorsAndExpressions/10.BinInIntegerCheck/BitInIntegerCheck.cs | C# | mit | 1,546 |
/*
* Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.example.lit.habit;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Base64;
import android.util.Log;
import com.example.lit.exception.BitmapTooLargeException;
import com.example.lit.exception.HabitFormatException;
import com.example.lit.saving.Saveable;
import com.example.lit.exception.HabitFormatException;
import io.searchbox.annotations.JestId;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* This class is an abstract habit class
* @author Steven Weikai Lu
*/
public abstract class Habit implements Habitable , Parcelable, Saveable {
private String title;
private SimpleDateFormat format;
private Date date;
public abstract String habitType();
private String user;
private String reason;
private int titleLength = 20;
private int reasonLength = 30;
private List<Calendar> calendars;
private List<Date> dates;
private String encodedImage;
@JestId
private String id;
private Bitmap image;
public String getID(){ return id ;}
public void setID(String id){ this.id = id ;}
public Habit(String title) throws HabitFormatException {
this.setTitle(title);
this.setDate(new Date());
}
public Habit(String title, Date date) throws HabitFormatException{
this.setTitle(title);
this.setDate(date);
}
public Habit(String title, Date date, String reason) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
}
/**
* This is the main constructor we are using in AddHabitActivity
*
* @see com.example.lit.activity.AddHabitActivity
* @param title Habit name, should be at most 20 char long.
* @param reason Habit Comment, should be at most 30 char long.
* @param date Set by GPS when creating the habit
* @param calendarList Set by user when creating the habit
* @throws HabitFormatException thrown when title longer than 20 char or reason longer than 30 char
* */
public Habit(String title, Date date, String reason, List<Calendar> calendarList) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendarList);
}
public Habit(String title, Date date, String reason, List<Calendar> calendars, Bitmap image)throws HabitFormatException, BitmapTooLargeException{
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendars);
this.setImage(image);
}
// TODO: Constructor with JestID
public String getTitle() {
return title;
}
public void setTitle(String title) throws HabitFormatException {
if (title.length() > this.titleLength){
throw new HabitFormatException();
}
this.title = title;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Date getDate() {
return date;
}
/**
* Function takes in a Date object and formats it to dd-MM-yyyy
* @param date
*/
public void setDate(Date date) {
// Format the current time.
SimpleDateFormat format = new SimpleDateFormat ("dd-MM-yyyy");
String dateString = format.format(date);
// Parse the previous string back into a Date.
ParsePosition pos = new ParsePosition(0);
this.date = format.parse(dateString, pos);
}
public String getReason() {
return reason;
}
public void setReason(String reason) throws HabitFormatException {
if (reason.length() < this.reasonLength) {
this.reason = reason;
}
else {
throw new HabitFormatException();
}
}
public List<Calendar> getCalendars() {
return calendars;
}
public void setCalendars(List<Calendar> calendars) {
this.calendars = calendars;
}
public Bitmap getImage() {
if(encodedImage != null) {
byte[] decodedString = Base64.decode(this.encodedImage, Base64.DEFAULT);
this.image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
return this.image;
}
/**
* Function takes in a Bitmap object and decodes it to a 64Base string
* @param image
* @throws BitmapTooLargeException
*/
public void setImage(Bitmap image) throws BitmapTooLargeException {
if (image == null){
this.image = null;
}
else if (image.getByteCount() > 65536){
throw new BitmapTooLargeException();
}
else {
this.image = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
this.encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
//Log.i("encoded",this.encodedImage);
}
}
@Override
public String toString() {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
return "Habit Name: " + this.getTitle() + '\n' +
"Started From: " + format.format(this.getDate());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeSerializable(this.format);
dest.writeLong(this.date != null ? this.date.getTime() : -1);
dest.writeString(this.user);
dest.writeString(this.reason);
dest.writeInt(this.titleLength);
dest.writeInt(this.reasonLength);
dest.writeList(this.calendars);
dest.writeList(this.dates);
dest.writeString(this.encodedImage);
dest.writeString(this.id);
dest.writeParcelable(this.image, flags);
}
protected Habit(Parcel in) {
this.title = in.readString();
this.format = (SimpleDateFormat) in.readSerializable();
long tmpDate = in.readLong();
this.date = tmpDate == -1 ? null : new Date(tmpDate);
this.user = in.readString();
this.reason = in.readString();
this.titleLength = in.readInt();
this.reasonLength = in.readInt();
this.calendars = new ArrayList<Calendar>();
in.readList(this.calendars, Calendar.class.getClassLoader());
this.dates = new ArrayList<Date>();
in.readList(this.dates, Date.class.getClassLoader());
this.encodedImage = in.readString();
this.id = in.readString();
this.image = in.readParcelable(Bitmap.class.getClassLoader());
}
}
| CMPUT301F17T06/Lit | app/src/main/java/com/example/lit/habit/Habit.java | Java | mit | 8,243 |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M2 21.5c0 .28.22.5.49.5h13.02c.27 0 .49-.22.49-.5V20H2v1.5zM15.5 16H11v-2H7v2H2.5c-.28 0-.5.22-.5.5V18h14v-1.5c0-.28-.22-.5-.5-.5zm4.97-.55c.99-1.07 1.53-2.48 1.53-3.94V2h-6v9.47c0 1.48.58 2.92 1.6 4l.4.42V22h4v-2h-2v-4.03l.47-.52zM18 4h2v4h-2V4zm1.03 10.07c-.65-.71-1.03-1.65-1.03-2.6V10h2v1.51c0 .95-.34 1.85-.97 2.56z" />
, 'BrunchDiningOutlined');
| callemall/material-ui | packages/material-ui-icons/src/BrunchDiningOutlined.js | JavaScript | mit | 477 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataMigration::Mgmt::V2018_07_15_preview
module Models
#
# Results for query analysis comparison between the source and target
#
class QueryAnalysisValidationResult
include MsRestAzure
# @return [QueryExecutionResult] List of queries executed and it's
# execution results in source and target
attr_accessor :query_results
# @return [ValidationError] Errors that are part of the execution
attr_accessor :validation_errors
#
# Mapper for QueryAnalysisValidationResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'QueryAnalysisValidationResult',
type: {
name: 'Composite',
class_name: 'QueryAnalysisValidationResult',
model_properties: {
query_results: {
client_side_validation: true,
required: false,
serialized_name: 'queryResults',
type: {
name: 'Composite',
class_name: 'QueryExecutionResult'
}
},
validation_errors: {
client_side_validation: true,
required: false,
serialized_name: 'validationErrors',
type: {
name: 'Composite',
class_name: 'ValidationError'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_data_migration/lib/2018-07-15-preview/generated/azure_mgmt_data_migration/models/query_analysis_validation_result.rb | Ruby | mit | 1,785 |
import {MdSnackBar} from '@angular/material';
export abstract class CommonCrudService {
constructor(private snackBar: MdSnackBar) {
}
// todo refactor crud operations to here (use metadata?)
onOperationPerformedNotify(opName: string): (res: boolean) => void {
return (res) => {
let text;
if (res) {
text = `Successful ${opName}!`;
} else {
text = `Failed to ${opName}!`;
}
this.snackBar.open(text, null, {
duration: 1000
});
};
}
}
| Ivanbmstu/angular | src/app/modules/shared/editor/common-crud.service.ts | TypeScript | mit | 514 |
package org.vitrivr.cineast.core.util.audio.pitch.tracking;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.vitrivr.cineast.core.util.audio.pitch.Pitch;
/**
* This is a helper class for pitch tracking. It represents a pitch contour, that is, a candidate for a melody fragment. The contour has a fixed length and each slot in the sequence represents a specific timeframe (e.g. belonging to a FFT bin in the underlying STFT).
* <p>
* The intention behind this class is the simplification of comparison between different pitch contours, either on a frame-by-frame basis but also as an entity. In addition to the actual pitch information, the pitch contour class also provides access to pitch contour statistics related to salience and pitch frequency.
*
* @see PitchTracker
*/
public class PitchContour {
/**
* The minimum frequency in Hz on the (artifical) cent-scale.
*/
private static final float CENT_SCALE_MINIMUM = 55.0f;
/**
* Entity that keeps track of salience related contour statistics.
*/
private SummaryStatistics salienceStatistics = new SummaryStatistics();
/**
* Entity that keeps track of frequency related contour statistics.
*/
private SummaryStatistics frequencyStatistics = new SummaryStatistics();
/**
* Sequence of pitches that form the PitchContour.
*/
private final List<Pitch> contour = new LinkedList<>();
/**
* Indicates that the PitchContour statistics require recalculation.
*/
private boolean dirty = true;
/**
* The start frame-index of the pitch-contour. Marks beginning in time.
*/
private int start;
/**
* The end frame-index of the pitch-contour. Marks ending in time.
*/
private int end;
/**
* Constructor for PitchContour.
*
* @param start Start-index of the contour.
* @param pitch Pitch that belongs to the start-index.
*/
public PitchContour(int start, Pitch pitch) {
this.start = start;
this.end = start;
this.contour.add(pitch);
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void append(Pitch p) {
this.contour.add(p);
this.end += 1;
this.dirty = true;
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void prepend(Pitch p) {
this.contour.add(0, p);
this.start -= 1;
this.dirty = true;
}
/**
* Returns the pitch at the given index or null, if the index is out of bounds. Note that even if the index is within bounds, the Pitch can still be null.
*
* @param i Index for which to return a pitch.
*/
public Pitch getPitch(int i) {
if (i >= this.start && i <= this.end) {
return this.contour.get(i - this.start);
} else {
return null;
}
}
/**
* Getter for start.
*
* @return Start frame-index.
*/
public final int getStart() {
return start;
}
/**
* Getter for end.
*
* @return End frame-index.
*/
public final int getEnd() {
return end;
}
/**
* Size of the pitch-contour. This number also includes empty slots.
*
* @return Size of the contour.
*/
public final int size() {
return this.contour.size();
}
/**
* Returns the mean of all pitches in the melody.
*
* @return Pitch mean
*/
public final double pitchMean() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getMean();
}
/**
* Returns the standard-deviation of all pitches in the melody.
*
* @return Pitch standard deviation
*/
public final double pitchDeviation() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getStandardDeviation();
}
/**
* Returns the mean-salience of all pitches in the contour.
*
* @return Salience mean
*/
public final double salienceMean() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getMean();
}
/**
* Returns the salience standard deviation of all pitches in the contour.
*
* @return Salience standard deviation.
*/
public final double salienceDeviation() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getStandardDeviation();
}
/**
* Returns the sum of all salience values in the pitch contour.
*/
public final double salienceSum() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getSum();
}
/**
* Calculates the overlap between the given pitch-contours.
*
* @return Size of the overlap between two pitch-contours.
*/
public final int overlap(PitchContour contour) {
return Math.max(0, Math.min(this.end, contour.end) - Math.max(this.start, contour.start));
}
/**
* Determines if two PitchContours overlap and returns true of false.
*
* @return true, if two PitchContours overlap and falseotherwise.
*/
public final boolean overlaps(PitchContour contour) {
return this.overlap(contour) > 0;
}
/**
* Re-calculates the PitchContour statistics.
*/
private void calculate() {
this.salienceStatistics.clear();
this.frequencyStatistics.clear();
for (Pitch pitch : this.contour) {
if (pitch != null) {
this.salienceStatistics.addValue(pitch.getSalience());
this.frequencyStatistics.addValue(pitch.distanceCents(CENT_SCALE_MINIMUM));
}
}
this.dirty = false;
}
}
| vitrivr/cineast | cineast-core/src/main/java/org/vitrivr/cineast/core/util/audio/pitch/tracking/PitchContour.java | Java | mit | 5,638 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
// 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("RapidPliant.App.EarleyDebugger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RapidPliant.App.EarleyDebugger")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "RapidPliant.App.EarleyDebugger.Views")]
| bilsaboob/RapidPliant | src/app/RapidPliant.App.EarleyDebugger/Properties/AssemblyInfo.cs | C# | mit | 2,546 |
package com.company;
import java.util.Scanner;
public class EvenPowersOf2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int num = 1;
for (int i = 0; i <= n ; i+=2) {
System.out.println(num);
num *= 4;
}
}
}
| ivelin1936/Studing-SoftUni- | Programing Basic/Programming Basics - Exercises/Advanced Loops/src/com/company/EvenPowersOf2.java | Java | mit | 368 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Participant'
db.delete_table(u'pa_participant')
# Removing M2M table for field user on 'Participant'
db.delete_table('pa_participant_user')
# Adding M2M table for field user on 'ReportingPeriod'
db.create_table(u'pa_reportingperiod_user', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('reportingperiod', models.ForeignKey(orm[u'pa.reportingperiod'], null=False)),
('user', models.ForeignKey(orm[u'pa.user'], null=False))
))
db.create_unique(u'pa_reportingperiod_user', ['reportingperiod_id', 'user_id'])
def backwards(self, orm):
# Adding model 'Participant'
db.create_table(u'pa_participant', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('reporting_period', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['pa.ReportingPeriod'])),
))
db.send_create_signal(u'pa', ['Participant'])
# Adding M2M table for field user on 'Participant'
db.create_table(u'pa_participant_user', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('participant', models.ForeignKey(orm[u'pa.participant'], null=False)),
('user', models.ForeignKey(orm[u'pa.user'], null=False))
))
db.create_unique(u'pa_participant_user', ['participant_id', 'user_id'])
# Removing M2M table for field user on 'ReportingPeriod'
db.delete_table('pa_reportingperiod_user')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'pa.activity': {
'Meta': {'object_name': 'Activity'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Category']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'pa.activityentry': {
'Meta': {'object_name': 'ActivityEntry'},
'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Activity']"}),
'day': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'hour': ('django.db.models.fields.IntegerField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.User']"})
},
u'pa.category': {
'Meta': {'object_name': 'Category'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'grouping': ('django.db.models.fields.CharField', [], {'default': "'d'", 'max_length': '15'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'reporting_period': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.ReportingPeriod']"})
},
u'pa.profession': {
'Meta': {'object_name': 'Profession'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '60'})
},
u'pa.reportingperiod': {
'Meta': {'object_name': 'ReportingPeriod'},
'end_date': ('django.db.models.fields.DateTimeField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '120'}),
'slots_per_hour': ('django.db.models.fields.IntegerField', [], {}),
'start_date': ('django.db.models.fields.DateTimeField', [], {}),
'user': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['pa.User']", 'symmetrical': 'False'})
},
u'pa.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'profession': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Profession']", 'null': 'True', 'blank': 'True'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
}
}
complete_apps = ['pa'] | Mathew/psychoanalysis | psychoanalysis/apps/pa/migrations/0002_auto__del_participant.py | Python | mit | 7,476 |
# Jrails-ui
module ActionView
module Helpers
module JavaScriptHelper
def hash_to_jquery(hash)
'{'+hash.map { |k,v|
[k,
case v.class.name
when 'String'
"'#{v}'"
when 'Hash'
hash_to_jquery(v)
else
v.to_s
end
].join(':')
}.join(',')+'}'
end
def flash_messages
content_tag(:div, :class => "ui-widget flash") do
flash.map { |type,message|
state = case type
when :notice; 'highlight'
when :error; 'error'
end
icon = case type
when :notice; 'info'
when :error; 'alert'
end
content_tag(:div, content_tag(:span, "", :class => "ui-icon ui-icon-#{icon}", :style => "float: left; margin-right: 0.3em;")+message, :class => "ui-state-#{state} ui-corner-all #{type}", :style => "margin-top: 5px; padding: 0.7em;")
}.join
end
end
def link_to_dialog(*args, &block)
div_id = "dialog#{args[1].gsub(/\//,'_')}"
dialog = {
:modal => true,
:draggable => false,
:resizable => false,
:width => 600
}.merge(args[2][:dialog] || {})
args[2].merge!(
:onclick => "$('##{div_id}').dialog(#{hash_to_jquery(dialog)});return false;"
)
args[2].delete(:dialog)
if block_given?
dialog_html = capture(&block)
else
render_options = args[2][:render] || {}
dialog_html = render(render_options)
end
link_html = link_to(*args)+content_tag(:div, dialog_html, :style => 'display:none;', :id => div_id, :title => args.first)
return block_given? ? concat(link_html) : link_html
end
end
end
end
| jadencarver/jquery_ui | lib/jrails_ui.rb | Ruby | mit | 1,890 |
/*
* Copyright (c) 2020 by Stefan Schubert under the MIT License (MIT).
* See project LICENSE file for the detailed terms and conditions.
*/
package de.bluewhale.sabi.webclient.rest.exceptions;
import de.bluewhale.sabi.exception.ExceptionCode;
import de.bluewhale.sabi.exception.MessageCode;
import de.bluewhale.sabi.exception.TankExceptionCodes;
/**
* MessageCodes that may arise by using the Tank Restservice
*
* @author schubert
*/
public enum TankMessageCodes implements MessageCode {
NO_SUCH_TANK(TankExceptionCodes.TANK_NOT_FOUND_OR_DOES_NOT_BELONG_TO_USER);
// ------------------------------ FIELDS ------------------------------
private TankExceptionCodes exceptionCode;
// --------------------------- CONSTRUCTORS ---------------------------
TankMessageCodes() {
exceptionCode = null;
}
TankMessageCodes(TankExceptionCodes pExceptionCode) {
exceptionCode = pExceptionCode;
}
// --------------------- GETTER / SETTER METHODS ---------------------
@Override
public ExceptionCode getExceptionCode() {
return exceptionCode;
}
}
| StefanSchubert/sabi | sabi-webclient/src/main/java/de/bluewhale/sabi/webclient/rest/exceptions/TankMessageCodes.java | Java | mit | 1,112 |
package okeanos.data.services.entities;
import javax.measure.quantity.Power;
import org.jscience.physics.amount.Amount;
public interface Price {
double getCostAtConsumption(Amount<Power> consumption);
}
| wolfgang-lausenhammer/Okeanos | okeanos.data/src/main/java/okeanos/data/services/entities/Price.java | Java | mit | 207 |
<?php
namespace Shop\MainBundle\Data;
use Doctrine\Common\Persistence\ObjectRepository;
use Shop\MainBundle\Entity\Settings;
/**
* Class ShopSettingsResource
* @package Shop\MainBundle\Data
*/
class ShopSettingsResource {
/**
* @var ObjectRepository
*/
protected $settingsRepository;
/**
* @var Settings|null
*/
protected $settings;
function __construct(ObjectRepository $settingsRepository)
{
$this->settingsRepository = $settingsRepository;
}
/**
* @return null|Settings
*/
public function getSettings()
{
if($this->settings === null){
$this->settings = $this->settingsRepository->findOneBy(array());
if (!$this->settings) {
$this->settings = new Settings();
}
}
return $this->settings;
}
/**
* @param $key
* @return mixed
*/
public function get($key){
return $this->getSettings()->offsetGet($key);
}
} | ja1cap/shop | src/Shop/MainBundle/Data/ShopSettingsResource.php | PHP | mit | 1,014 |
var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
const notUtils = require('./notifications-utils.js');
module.exports = [
function (session) {
session.beginDialog('notifications-common-symbol');
},
function (session, results) {
var pair = results.response;
session.dialogData.symbol = pair;
builder.Prompts.number(session, 'How big should the interval be?');
},
function (session, results) {
session.dialogData.interval = results.response;
builder.Prompts.text(session, "What name would you like to give to this notification?");
},
function (session, results) {
var sub = notUtils.getBaseNotification('interval', session.message.address);
sub.symbol = session.dialogData.symbol;
sub.interval = session.dialogData.interval;
sub.previousprice = 0;
sub.isfirstun = true;
sub.name = results.response;
notUtils.createNotification(sub).then((r) => {
session.endDialog('Notification created!');
}).catch((e) => {
session.endDialog('Couldn\'t create notification: ' + e);
});
}
]; | jantielens/CryptoBuddy | messages/dialogs/notifications-add-interval.js | JavaScript | mit | 1,193 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Terra.WebUI.Models.AccountViewModels
{
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
}
| Arukim/terra | Terra.WebUI/Models/AccountViewModels/LoginViewModel.cs | C# | mit | 512 |
version https://git-lfs.github.com/spec/v1
oid sha256:a396601eca15b0c281513d01941cfd37300b927b32a1bb9bb6e708a9910f1b49
size 2712
| yogeshsaroya/new-cdnjs | ajax/libs/ckeditor/4.2/plugins/a11yhelp/dialogs/lang/sr-latn.min.js | JavaScript | mit | 129 |
package com.ruenzuo.weatherapp.adapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ruenzuo.weatherapp.R;
import com.ruenzuo.weatherapp.models.City;
/**
* Created by ruenzuo on 08/05/14.
*/
public class CitiesAdapter extends ArrayAdapter<City> {
private int resourceId;
public CitiesAdapter(Context context, int resource) {
super(context, resource);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity)getContext()).getLayoutInflater();
convertView = inflater.inflate(resourceId, null);
}
City country = getItem(position);
TextView txtViewCityName = (TextView) convertView.findViewById(R.id.txtViewCityName);
txtViewCityName.setText(country.getName());
return convertView;
}
} | Ruenzuo/android-facade-example | WeatherApp/src/main/java/com/ruenzuo/weatherapp/adapters/CitiesAdapter.java | Java | mit | 1,106 |
module SelecaoAdmin
class Engine < ::Rails::Engine
isolate_namespace SelecaoAdmin
end
end
| swayzepatryck/selecao_admin | lib/selecao_admin/engine.rb | Ruby | mit | 98 |
<?php
include __DIR__.'/../lib/SALT.php';
/** An example of using the SALT Secure Storage API to store then use a stored Credit Card */
use \SALT\Merchant;
use \SALT\HttpsCreditCardService;
use \SALT\CreditCard;
use \SALT\PaymentProfile;
// connection parameters to the gateway
$url = 'https://test.salt.com/gateway/creditcard/processor.do';
//$merchant = new Merchant ('Your Merchant ID', 'Your API Token');
$merchant = new Merchant ( VALID_MERCHANT_ID, VALID_API_TOKEN );
$service = new HttpsCreditCardService( $merchant, $url );
// credit card info from customer - to be stored
$creditCard = new CreditCard( '4242424242424242', '1010', null, '123 Street', 'A1B23C' );
// payment profile to be stored (just using the card component in this example)
$paymentProfile = new PaymentProfile( $creditCard, null );
// store data under the token 'my-token-001'
//$storageToken = 'my-token-'.date('Ymd');
$storageToken = uniqid();
$storageReceipt = $service->addToStorage( $storageToken, $paymentProfile );
if ( $storageReceipt->approved ) {
echo "Credit card storage approved.\n";
$purchaseOrderId = uniqid();
echo "Creating Single purchase with Order ID $purchaseOrderId\n";
$singlePurchaseReceipt = $service->singlePurchase( $purchaseOrderId, $storageToken, '100', null );
// optional array dump of response params
// print_r($receipt->params);
if ( $singlePurchaseReceipt->approved ) {
//Store the transaction id.
echo "Single Purchase Receipt approved\n";
} else {
echo "Single purchase receipt not approved\n";
}
} else {
echo "Credit card storage not approved.\n";
}
//Update the credit card stored
$updatedCreditCard = new CreditCard ( '4012888888881881', '1010', null, '1 Market St.', '94105' );
$paymentProfile->creditCard = $updatedCreditCard;
$updatedStorageReceipt = $service->updateStorage($storageToken, $paymentProfile);
if ( $updatedStorageReceipt->approved ) {
echo "Updated credit card storage approved.\n";
} else {
echo "Updated credit card storage not approved.\n";
}
//Query the credit card stored
$queryStorageReceipt = $service->queryStorage($storageToken);
if ( $queryStorageReceipt->approved ) {
echo "Secure storage query successful.\n";
echo "Response: \n";
print_r($queryStorageReceipt->params);
} else {
echo "Secure storage query failed.\n";
}
| SaltTechnology/salt-payment-client-php | examples/CreditCardStorage.php | PHP | mit | 2,376 |
package tehnut.resourceful.crops.compat;
import mcp.mobius.waila.api.*;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.ItemHandlerHelper;
import tehnut.resourceful.crops.block.tile.TileSeedContainer;
import tehnut.resourceful.crops.core.RegistrarResourcefulCrops;
import tehnut.resourceful.crops.core.data.Seed;
import javax.annotation.Nonnull;
import java.util.List;
@WailaPlugin
public class CompatibilityWaila implements IWailaPlugin {
@Override
public void register(IWailaRegistrar registrar) {
final CropProvider cropProvider = new CropProvider();
registrar.registerStackProvider(cropProvider, TileSeedContainer.class);
registrar.registerNBTProvider(cropProvider, TileSeedContainer.class);
}
public static class CropProvider implements IWailaDataProvider {
@Nonnull
@Override
public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) {
Seed seed = RegistrarResourcefulCrops.SEEDS.getValue(new ResourceLocation(accessor.getNBTData().getString("seed")));
if (seed == null)
return accessor.getStack();
if (seed.isNull())
return accessor.getStack();
if (seed.getOutputs().length == 0)
return accessor.getStack();
return ItemHandlerHelper.copyStackWithSize(seed.getOutputs()[0].getItem(), 1);
}
@Nonnull
@Override
public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaTail(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) {
tag.setString("seed", ((TileSeedContainer) te).getSeedKey().toString());
return tag;
}
}
}
| TehNut/ResourcefulCrops | src/main/java/tehnut/resourceful/crops/compat/CompatibilityWaila.java | Java | mit | 2,650 |
import _ from 'lodash';
/**
* Represents a channel with which commands can be invoked.
*
* Channels are one-per-origin (protocol/domain/port).
*/
class Channel {
constructor(config, $rootScope, $timeout, contentWindow) {
this.config = config;
this.$rootScope = $rootScope;
this.$timeout = $timeout;
this._contentWindow = contentWindow;
this.messageCounter = 0;
}
ab2str(buffer) {
let result = "";
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
result += String.fromCharCode(bytes[i]);
}
return result;
};
/**
* Fire and forget pattern that sends the command to the target without waiting for a response.
*/
invokeDirect(command, data, targetOrigin, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
}
/**
* Invokes the specified command on the channel with the specified data, constrained to the specified domain awaiting for max ms specified in timeout
*/
async invoke(command, data, targetOrigin, timeout, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
if (!timeout) {
timeout = 0;
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let resolve, reject;
let promise = new Promise((innerResolve, innerReject) => {
resolve = innerResolve;
reject = innerReject;
});
let timeoutPromise;
if (timeout > 0) {
timeoutPromise = this.$timeout(() => {
reject(new Error(`invoke() timed out while waiting for a response while executing ${data.command}`));
}, timeout);
}
let removeMonitor = this.$rootScope.$on(this.config.crossDomainMessageSink.incomingMessageName, (event, response) => {
if (response.postMessageId !== data.postMessageId)
return;
if (response.result === "error") {
reject(response);
}
else {
if (response.data) {
let contentType = response.headers["content-type"] || response.headers["Content-Type"];
if (contentType.startsWith("application/json")) {
let str = this.ab2str(response.data);
if (str.length > 0) {
try
{
response.data = JSON.parse(str);
}
catch(ex) {
}
}
} else if (contentType.startsWith("text")) {
response.data = this.ab2str(response.data);
}
}
resolve(response);
}
removeMonitor();
if (timeoutPromise)
this.$timeout.cancel(timeoutPromise);
});
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
return promise;
}
}
module.exports = Channel; | beyond-sharepoint/sp-angular-webpack | src/ng-sharepoint/Channel.js | JavaScript | mit | 4,352 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include __DIR__.'/../../../application/config/config.php';
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = $config['gi_base_url'].'/api/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'AUTO' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
if( defined('__CLI_MODE') && __CLI_MODE === TRUE ) {
$config['uri_protocol'] = 'AUTO';
}
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'GI_';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify with a regular expression which characters are permitted
| within your URLs. When someone tries to submit a URL with disallowed
| characters they will get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ folder. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/cache/ folder. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = 'dfsa09302qdflaskf0-2iq';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_cookie_name' = the name you want for the cookie
| 'sess_expiration' = the number of SECONDS you want the session to last.
| by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
| 'sess_expire_on_close' = Whether to cause the session to expire automatically
| when the browser window is closed
| 'sess_encrypt_cookie' = Whether to encrypt the cookie
| 'sess_use_database' = Whether to save the session data to a database
| 'sess_table_name' = The name of the session database table
| 'sess_match_ip' = Whether to match the user's IP address when reading the session data
| 'sess_match_useragent' = Whether to match the User Agent when reading the session data
| 'sess_time_to_update' = how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name'] = 'gi_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or 'gmt'. This pref tells the system whether to use
| your server's local time as the master 'now' reference, or convert it to
| GMT. See the 'date helper' page of the user guide for information
| regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
/* End of file config.php */
/* Location: ./application/config/config.php */
| Minds-On-Design-Lab/giving-impact | gi-api/application/config/config.php | PHP | mit | 13,001 |
export function getName(value) {
if (value == 0) {
return "上班";
}
if (value == 1) {
return "下班";
}
throw "invalid route direction";
}
export function getValue(name) {
if (name == "上班") {
return 0;
}
if (name == "下班") {
return 1;
}
throw "invalid route direction";
} | plantain-00/demo-set | js-demo/restful-api-demo/services/routeDirection.ts | TypeScript | mit | 354 |
import {
LOAD_SEARCH_RESULT_SUCCESS,
CLEAR_SEARCH_RESULTS,
} from 'actions/search';
import { createActionHandlers } from 'utils/reducer/actions-handlers';
const actionHandlers = {};
export function loadSearchResultSuccess(state, searchResultsList) {
return searchResultsList.reduce((acc, result) => {
return {
...acc,
[result.id]: result,
};
}, {});
}
export function clearSearchResult() {
return {};
}
actionHandlers[LOAD_SEARCH_RESULT_SUCCESS] = loadSearchResultSuccess;
actionHandlers[CLEAR_SEARCH_RESULTS] = clearSearchResult;
export default createActionHandlers(actionHandlers);
| InseeFr/Pogues | src/reducers/search-result-by-id.js | JavaScript | mit | 619 |
import { autoinject } from 'aurelia-framework';
import { Customers } from './customers';
import { Router } from 'aurelia-router';
@autoinject()
export class List {
heading = 'Customer management';
customerList = [];
customers: Customers;
router: Router;
constructor(customers: Customers, router: Router) {
this.customers = customers;
this.router = router;
}
gotoCustomer(customer: any) {
this.router.navigateToRoute('edit', {id: customer.id});
}
new() {
this.router.navigateToRoute('create');
}
activate() {
return this.customers.getAll()
.then(customerList => this.customerList = customerList);
}
}
| doktordirk/aurelia-authentication-loopback-sample | client-ts/src/modules/customer/list.ts | TypeScript | mit | 657 |
/**
* Created by huangxinghui on 2016/1/20.
*/
var $ = require('jquery')
var Widget = require('../../widget')
var plugin = require('../../plugin')
var TreeNode = require('./treenode')
var Tree = Widget.extend({
options: {
'labelField': null,
'labelFunction': null,
'childrenField': 'children',
'autoOpen': true
},
events: {
'click li': '_onSelect',
'click i': '_onExpand'
},
_create: function() {
this.$element.addClass('tree')
var that = this
var $ul = $('<ul></ul>')
this._loadFromDataSource()
this.nodes.forEach(function(node) {
that._createNode(node)
$ul.append(node.element)
})
this.$element.append($ul)
},
_onSelect: function(e) {
var $li = $(e.currentTarget),
node = $li.data('node')
e.preventDefault()
if (!$li.hasClass('active')) {
this._setSelectedNode(node)
this._trigger('itemClick', node.data)
}
},
_onExpand: function(e) {
var $li = $(e.currentTarget).closest('li'),
node = $li.data('node')
e.preventDefault()
if (node.isOpen) {
this.collapseNode(node)
}
else {
this.expandNode(node)
}
},
_setSelectedNode: function(node) {
var $active = this.$element.find('.active')
$active.removeClass('active')
var $li = node.element
$li.addClass('active')
this._trigger('change', node.data)
},
_createNode: function(node) {
if (node.isBranch()) {
this._createFolder(node)
}
else {
this._createLeaf(node)
}
},
_createLeaf: function(node) {
var html = ['<li><a href="#"><span>']
html.push(this._createIndentationHtml(node.getLevel()))
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
$li.data('node', node)
node.element = $li
return $li
},
_createFolder: function(node) {
var that = this
var html = []
if (node.isOpen) {
html.push('<li class="open"><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-minus-sign js-folder"></i>')
}
else {
html.push('<li><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-plus-sign js-folder"></i>')
}
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
var $ul = $('<ul class="children-list"></ul>')
node.children.forEach(function(childNode) {
that._createNode(childNode)
$ul.append(childNode.element)
})
$li.append($ul)
$li.data('node', node)
node.element = $li
return $li
},
_createLabel: function(node) {
var html = ['<span>']
var level = node.getLevel()
if (node.isBranch()) {
html.push(this._createIndentationHtml(level - 1))
html.push('<i class="glyphicon ',
node.isOpen ? 'glyphicon-minus-sign' : 'glyphicon-plus-sign',
' js-folder"></i>')
}
else {
html.push(this._createIndentationHtml(level))
}
html.push(this.itemToLabel(node.data))
html.push('</span>')
return html.join('')
},
_createIndentationHtml: function(count) {
var html = []
for (var i = 0; i < count; i++) {
html.push('<i class="glyphicon tree-indentation"></i>')
}
return html.join('')
},
_loadFromDataSource: function() {
var node, children, nodes = [], that = this
if (this.options.dataSource) {
this.options.dataSource.forEach(function(item) {
node = new TreeNode(item)
children = item[that.options.childrenField]
if (children) {
node.isOpen = that.options.autoOpen
that._loadFromArray(children, node)
}
nodes.push(node)
})
}
this.nodes = nodes
},
_loadFromArray: function(array, parentNode) {
var node, children, that = this
array.forEach(function(item) {
node = new TreeNode(item)
parentNode.addChild(node)
children = item[that.childrenField]
if (children) {
node.isOpen = that.autoOpen
that._loadFromArray(children, node)
}
})
},
expandNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (!node.isOpen) {
node.isOpen = true
$li.addClass('open')
$disclosureIcon.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign')
this._trigger('itemOpen')
}
},
collapseNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (node.isOpen) {
node.isOpen = false
$li.removeClass('open')
$disclosureIcon.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign')
this._trigger('itemClose')
}
},
expandAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.expandNode(node)
})
},
collapseAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.collapseNode(node)
})
},
append: function(item, parentNode) {
var $ul, $li, $prev, node = new TreeNode(item)
if (parentNode.isBranch()) {
parentNode.addChild(node)
$ul = parentNode.element.children('ul')
this._createNode(node)
$li = node.element
$ul.append($li)
}
else {
parentNode.addChild(node)
$li = parentNode.element
$prev = $li.prev()
$ul = $li.parent()
parentNode.element = null
$li.remove()
$li = this._createFolder(parentNode)
if ($prev.length) {
$prev.after($li)
}
else {
$ul.append($li)
}
}
this.expandNode(parentNode)
this._setSelectedNode(node)
},
remove: function(node) {
var parentNode = node.parent
node.element.remove()
node.destroy()
this._setSelectedNode(parentNode)
},
update: function(node) {
var $li = node.element
$li.children('a').html(this._createLabel(node))
},
getSelectedNode: function() {
var $li = this.$element.find('.active')
return $li.data('node')
},
getSelectedItem: function() {
var node = this.getSelectedNode()
return node.data
},
itemToLabel: function(data) {
if (!data) {
return ''
}
if (this.options.labelFunction != null) {
return this.options.labelFunction(data)
}
else if (this.options.labelField != null) {
return data[this.options.labelField]
}
else {
return data
}
}
})
plugin('tree', Tree)
| huang-x-h/Bean.js | src/components/tree/index.js | JavaScript | mit | 6,725 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2015 from http://adventofcode.com/2015/day/5
Author: James Walker
Copyrighted 2017 under the MIT license:
http://www.opensource.org/licenses/mit-license.php
Execution:
python advent_of_code_2015_day_05.py
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Santa needs help figuring out which strings in his text file are naughty or
nice.
A nice string is one with all of the following properties:
It contains at least three vowels (aeiou only), like aei, xazegov, or
aeiouaeiouaeiou.
It contains at least one letter that appears twice in a row, like xx,
abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
It does not contain the strings ab, cd, pq, or xy, even if they are part of
one of the other requirements.
For example:
ugknbfddgicrmopn is nice because it has at least three vowels
(u...i...o...), a double letter (...dd...), and none of the disallowed
substrings.
aaa is nice because it has at least three vowels and a double letter, even
though the letters used by different rules overlap.
jchzalrnumimnmhp is naughty because it has no double letter.
haegwjzuvuyypxyu is naughty because it contains the string xy.
dvszwmarrgswjxmb is naughty because it contains only one vowel.
How many strings are nice?
Answer: 258
--- Day 5: Part Two ---
Realizing the error of his ways, Santa has switched to a better model of
determining whether a string is naughty or nice. None of the old rules apply,
as they are all clearly ridiculous. Now, a nice string is one with all of the
following properties:
It contains a pair of any two letters that appears at least twice in the
string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not
like aaa (aa, but it overlaps).
It contains at least one letter which repeats with exactly one letter
between them, like xyx, abcdefeghi (efe), or even aaa.
For example:
qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and
a letter that repeats with exactly one letter between them (zxz).
xxyxx is nice because it has a pair that appears twice and a letter that
repeats with one between, even though the letters used by each rule
overlap.
uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a
single letter between them.
ieodomkazucvgmuy is naughty because it has a repeating letter with one
between (odo), but no pair that appears twice.
How many strings are nice under these new rules?
Answer: 53
"""
import collections
import os
import re
import sys
TestCase = collections.namedtuple('TestCase', 'input expected1 expected2')
class Advent_Of_Code_2015_Solver_Day05(object):
"""Advent of Code 2015 Day 5: Doesn't He Have Intern-Elves For This?"""
def __init__(self, file_name=None):
self._file_name = file_name
self._puzzle_input = None
self._solved_output = (
"The text file had {0} nice strings using the original rules\n"
"and it had {1} nice strings using the new rules."
)
self.__regex_vowels = re.compile('[aeiou]')
self.__regex_double_char = re.compile('(\w)\\1+')
self.__regex_naughty = re.compile('ab|cd|pq|xy')
self.__regex_double_pair = re.compile('(\w{2})\w*\\1')
self.__regex_triplet = re.compile('(\w)\w\\1')
def _load_puzzle_file(self):
filePath = "{dir}/{f}".format(dir=os.getcwd(), f=self._file_name)
try:
with open(filePath, mode='r') as puzzle_file:
self._puzzle_input = puzzle_file.readlines()
except IOError as err:
errorMsg = (
"ERROR: Failed to read the puzzle input from file '{file}'\n"
"{error}"
)
print(errorMsg.format(file=self._file_name, error=err))
exit(1)
def __is_nice_string_using_old_rules(self, string):
return (self.__regex_naughty.search(string) is None
and len(self.__regex_vowels.findall(string)) > 2
and self.__regex_double_char.search(string))
def __is_nice_string_using_new_rules(self, string):
return (self.__regex_double_pair.search(string)
and self.__regex_triplet.search(string))
def _solve_puzzle_parts(self):
old_nice_count = 0
new_nice_count = 0
for string in self._puzzle_input:
if not string:
continue
if self.__is_nice_string_using_old_rules(string):
old_nice_count += 1
if self.__is_nice_string_using_new_rules(string):
new_nice_count += 1
return (old_nice_count, new_nice_count)
def get_puzzle_solution(self, alt_input=None):
if alt_input is None:
self._load_puzzle_file()
else:
self._puzzle_input = alt_input
old_nice_count, new_nice_count = self._solve_puzzle_parts()
return self._solved_output.format(old_nice_count, new_nice_count)
def _run_test_case(self, test_case):
correct_output = self._solved_output.format(
test_case.expected1,
test_case.expected2
)
test_output = self.get_puzzle_solution(test_case.input)
if correct_output == test_output:
print("Test passed for input '{0}'".format(test_case.input))
else:
print("Test failed for input '{0}'".format(test_case.input))
print(test_output)
def run_test_cases(self):
print("No Puzzle Input for {puzzle}".format(puzzle=self.__doc__))
print("Running Test Cases...")
self._run_test_case(TestCase(['ugknbfddgicrmopn'], 1, 0))
self._run_test_case(TestCase(['aaa'], 1, 0))
self._run_test_case(TestCase(['jchzalrnumimnmhp'], 0, 0))
self._run_test_case(TestCase(['haegwjzuvuyypxyu'], 0, 0))
self._run_test_case(TestCase(['dvszwmarrgswjxmb'], 0, 0))
self._run_test_case(TestCase(['xyxy'], 0, 1))
self._run_test_case(TestCase(['aabcdefgaa'], 0, 0))
self._run_test_case(TestCase(['qjhvhtzxzqqjkmpb'], 0, 1))
self._run_test_case(TestCase(['xxyxx'], 0, 1))
self._run_test_case(TestCase(['uurcxstgmygtbstg'], 0, 0))
self._run_test_case(TestCase(['ieodomkazucvgmuy'], 0, 0))
self._run_test_case(TestCase(['aaccacc'], 1, 1))
if __name__ == '__main__':
try:
day05_solver = Advent_Of_Code_2015_Solver_Day05(sys.argv[1])
print(day05_solver.__doc__)
print(day05_solver.get_puzzle_solution())
except IndexError:
Advent_Of_Code_2015_Solver_Day05().run_test_cases()
| JDSWalker/AdventOfCode | 2015/Day05/advent_of_code_2015_day_05.py | Python | mit | 6,750 |
function solve(args) {
function biSearch(array, searchedNumber, start, end) {
for (var i = start; i <= end; i += 1) {
if (+array[i] === searchedNumber) {
return i;
}
}
return -1;
}
var data = args[0].split('\n'),
numberN = +data.shift(),
numberX = +data.pop();
var firstIndex = 0;
var lastIndex = data.length - 1;
var resultIndex = 0;
var middle = 0;
for (var j = firstIndex; j < lastIndex; j += 1) {
middle = (lastIndex / 2) | 0;
if (+data[middle] === numberX) {
resultIndex = middle;
break;
}
if (+data[middle] < numberX) {
firstIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
if (+data[middle] > numberX) {
lastIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
}
if (resultIndex >= 0 && resultIndex < data.length) {
console.log(resultIndex);
} else {
console.log('-1');
}
} | jorosoft/Telerik-Academy | Homeworks/JS Fundamentals/07. Arrays/07. Binary search/binary-search.js | JavaScript | mit | 1,110 |
#!/usr/bin/env node
var pluginlist = [
];
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
console.log(stdout);
}
pluginlist.forEach(function(plug) {
exec("cordova plugin add " + plug, puts);
});
| ozsay/ionic-brackets | templates/plugins_hook.js | JavaScript | mit | 240 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.text;
import java.util.Map;
public abstract class StrLookup<V> {
public static StrLookup<?> noneLookup() {
return null;
}
public static StrLookup<String> systemPropertiesLookup() {
return null;
}
public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
return null;
}
public abstract String lookup(String key);
}
| github/codeql | java/ql/test/stubs/apache-commons-lang3-3.7/org/apache/commons/lang3/text/StrLookup.java | Java | mit | 1,213 |
#!/bin/env/python
# coding: utf-8
import logging
import os
import time
import uuid
from logging import Formatter
from logging.handlers import RotatingFileHandler
from multiprocessing import Queue
from time import strftime
import dill
from .commands import *
from .processing import MultiprocessingLogger
class TaskProgress(object):
"""
Holds both data and graphics-related information for a task's progress bar.
The logger will iterate over TaskProgress objects to draw progress bars on screen.
"""
def __init__(self,
total,
prefix='',
suffix='',
decimals=0,
bar_length=60,
keep_alive=False,
display_time=False):
"""
Creates a new progress bar using the given information.
:param total: The total number of iteration for this progress bar.
:param prefix: [Optional] The text that should be displayed at the left side of the
progress bar. Note that progress bars will always stay left-aligned at the
shortest possible.
:param suffix: [Optional] The text that should be displayed at the very right side of the
progress bar.
:param decimals: [Optional] The number of decimals to display for the percentage.
:param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character.
:param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever
once completed or if it should vanish.
:param display_time: [Optional] Specify whether the duration since the progress has begun should
be displayed. Running time will be displayed between parenthesis, whereas it
will be displayed between brackets when the progress has completed.
"""
super(TaskProgress, self).__init__()
self.progress = 0
# Minimum number of seconds at maximum completion before a progress bar is removed from display
# The progress bar may vanish at a further time as the redraw rate depends upon chrono AND method calls
self.timeout_chrono = None
self.begin_time = None
self.end_time = None
self.elapsed_time_at_end = None
# Graphics related information
self.keep_alive = keep_alive
self.display_time = display_time
self.total = total
self.prefix = prefix
self.suffix = suffix
self.decimals = decimals
self.bar_length = bar_length
def set_progress(self, progress):
"""
Defines the current progress for this progress bar in iteration units (not percent).
:param progress: Current progress in iteration units regarding its total (not percent).
:return: True if the progress has changed. If the given progress is higher than the total or lower
than 0 then it will be ignored.
"""
_progress = progress
if _progress > self.total:
_progress = self.total
elif _progress < 0:
_progress = 0
# Stop task chrono if needed
if _progress == self.total and self.display_time:
self.end_time = time.time() * 1000
# If the task has completed instantly then define its begin_time too
if not self.begin_time:
self.begin_time = self.end_time
has_changed = self.progress != _progress
if has_changed:
self.progress = _progress
return has_changed
class FancyLogger(object):
"""
Defines a multiprocess logger object. Logger uses a redraw rate because of console flickering. That means it will
not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the
right time. Logger will redraw at a given time period AND when new messages or progress are logged.
If you still want to force redraw immediately (may produce flickering) then call 'flush' method.
Logger uses one file handler and then uses standard output (stdout) to draw on screen.
"""
queue = None
"Handles all messages and progress to be sent to the logger process."
default_message_number = 20
"Default value for the logger configuration."
default_exception_number = 5
"Default value for the logger configuration."
default_permanent_progressbar_slots = 0
"Default value for the logger configuration."
default_redraw_frequency_millis = 500
"Default value for the logger configuration."
default_level = logging.INFO
"Default value for the logger configuration."
default_task_millis_to_removal = 500
"Default value for the logger configuration."
default_console_format_strftime = '%d %B %Y %H:%M:%S'
"Default value for the logger configuration."
default_console_format = '{T} [{L}]'
"Default value for the logger configuration."
default_file_handlers = []
"Default value for the logger configuration. Filled in constructor."
def __init__(self,
message_number=default_message_number,
exception_number=default_exception_number,
permanent_progressbar_slots=default_permanent_progressbar_slots,
redraw_frequency_millis=default_redraw_frequency_millis,
console_level=default_level,
task_millis_to_removal=default_task_millis_to_removal,
console_format_strftime=default_console_format_strftime,
console_format=default_console_format,
file_handlers=None,
application_name=None):
"""
Initializes a new logger and starts its process immediately using given configuration.
:param message_number: [Optional] Number of simultaneously displayed messages below progress bars.
:param exception_number: [Optional] Number of simultaneously displayed exceptions below messages.
:param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times,
so the message logger will not move anymore if the bar number is equal or
lower than this parameter.
:param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be
more because the redraw rate depends upon time AND method calls.
:param console_level: [Optional] The logging level (from standard logging module).
:param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before
a progress bar is removed from display. The progress bar may vanish at a
further time as the redraw rate depends upon time AND method calls.
:param console_format_strftime: [Optional] Specify the time format for console log lines using python
strftime format. Defaults to format: '29 november 2016 21:52:12'.
:param console_format: [Optional] Specify the format of the console log lines. There are two
variables available: {T} for timestamp, {L} for level. Will then add some
tabulations in order to align text beginning for all levels.
Defaults to format: '{T} [{L}]'
Which will produce: '29 november 2016 21:52:12 [INFO] my log text'
'29 november 2016 21:52:13 [WARNING] my log text'
'29 november 2016 21:52:14 [DEBUG] my log text'
:param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its
own regular formatter and level. Console logging is distinct from file
logging. Console logging uses custom stdout formatting, while file logging
uses regular python logging rules. All handlers are permitted except
StreamHandler if used with stdout or stderr which are reserved by this
library for custom console output.
:param application_name: [Optional] Used only if 'file_handlers' parameter is ignored. Specifies the
application name to use to format the default file logger using format:
application_%Y-%m-%d_%H-%M-%S.log
"""
super(FancyLogger, self).__init__()
# Define default file handlers
if not file_handlers:
if not application_name:
app_name = 'application'
else:
app_name = application_name
handler = RotatingFileHandler(filename=os.path.join(os.getcwd(), '{}_{}.log'
.format(app_name, strftime('%Y-%m-%d_%H-%M-%S'))),
encoding='utf8',
maxBytes=5242880, # 5 MB
backupCount=10,
delay=True)
handler.setLevel(logging.INFO)
handler.setFormatter(fmt=Formatter(fmt='%(asctime)s [%(levelname)s]\t%(message)s',
datefmt=self.default_console_format_strftime))
self.default_file_handlers.append(handler)
file_handlers = self.default_file_handlers
if not self.queue:
self.queue = Queue()
self.process = MultiprocessingLogger(queue=self.queue,
console_level=console_level,
message_number=message_number,
exception_number=exception_number,
permanent_progressbar_slots=permanent_progressbar_slots,
redraw_frequency_millis=redraw_frequency_millis,
task_millis_to_removal=task_millis_to_removal,
console_format_strftime=console_format_strftime,
console_format=console_format,
file_handlers=file_handlers)
self.process.start()
def flush(self):
"""
Flushes the remaining messages and progress bars state by forcing redraw. Can be useful if you want to be sure
that a message or progress has been updated in display at a given moment in code, like when you are exiting an
application or doing some kind of synchronized operations.
"""
self.queue.put(dill.dumps(FlushCommand()))
def terminate(self):
"""
Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some
messages of progresses that have not been displayed yet. This method blocks until logger process has stopped.
"""
self.queue.put(dill.dumps(ExitCommand()))
if self.process:
self.process.join()
def set_configuration(self,
message_number=default_message_number,
exception_number=default_exception_number,
permanent_progressbar_slots=default_permanent_progressbar_slots,
redraw_frequency_millis=default_redraw_frequency_millis,
console_level=default_level,
task_millis_to_removal=default_task_millis_to_removal,
console_format_strftime=default_console_format_strftime,
console_format=default_console_format,
file_handlers=default_file_handlers):
"""
Defines the current configuration of the logger. Can be used at any moment during runtime to modify the logger
behavior.
:param message_number: [Optional] Number of simultaneously displayed messages below progress bars.
:param exception_number: [Optional] Number of simultaneously displayed exceptions below messages.
:param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times,
so the message logger will not move anymore if the bar number is equal or
lower than this parameter.
:param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be
more because the redraw rate depends upon time AND method calls.
:param console_level: [Optional] The logging level (from standard logging module).
:param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before
a progress bar is removed from display. The progress bar may vanish at a
further time as the redraw rate depends upon time AND method calls.
:param console_format_strftime: [Optional] Specify the time format for console log lines using python
strftime format. Defaults to format: '29 november 2016 21:52:12'.
:param console_format: [Optional] Specify the format of the console log lines. There are two
variables available: {T} for timestamp, {L} for level. Will then add some
tabulations in order to align text beginning for all levels.
Defaults to format: '{T} [{L}]'
Which will produce: '29 november 2016 21:52:12 [INFO] my log text'
'29 november 2016 21:52:13 [WARNING] my log text'
'29 november 2016 21:52:14 [DEBUG] my log text'
:param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its
own regular formatter and level. Console logging is distinct from file
logging. Console logging uses custom stdout formatting, while file logging
uses regular python logging rules. All handlers are permitted except
StreamHandler if used with stdout or stderr which are reserved by this
library for custom console output.
"""
self.queue.put(dill.dumps(SetConfigurationCommand(task_millis_to_removal=task_millis_to_removal,
console_level=console_level,
permanent_progressbar_slots=permanent_progressbar_slots,
message_number=message_number,
exception_number=exception_number,
redraw_frequency_millis=redraw_frequency_millis,
console_format_strftime=console_format_strftime,
console_format=console_format,
file_handlers=file_handlers)))
def set_level(self,
level,
console_only=False):
"""
Defines the logging level (from standard logging module) for log messages.
:param level: Level of logging for the file logger.
:param console_only: [Optional] If True then the file logger will not be affected.
"""
self.queue.put(dill.dumps(SetLevelCommand(level=level,
console_only=console_only)))
def set_task_object(self,
task_id,
task_progress_object):
"""
Defines a new progress bar with the given information using a TaskProgress object.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param task_progress_object: TaskProgress object holding the progress bar information.
"""
self.set_task(task_id=task_id,
total=task_progress_object.total,
prefix=task_progress_object.prefix,
suffix=task_progress_object.suffix,
decimals=task_progress_object.decimals,
bar_length=task_progress_object.bar_length,
keep_alive=task_progress_object.keep_alive,
display_time=task_progress_object.display_time)
def set_task(self,
task_id,
total,
prefix,
suffix='',
decimals=0,
bar_length=60,
keep_alive=False,
display_time=False):
"""
Defines a new progress bar with the given information.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param total: The total number of iteration for this progress bar.
:param prefix: The text that should be displayed at the left side of the progress bar. Note that
progress bars will always stay left-aligned at the shortest possible.
:param suffix: [Optional] The text that should be displayed at the very right side of the progress bar.
:param decimals: [Optional] The number of decimals to display for the percentage.
:param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character.
:param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever once completed
or if it should vanish.
:param display_time: [Optional] Specify whether the duration since the progress has begun should be
displayed. Running time will be displayed between parenthesis, whereas it will be
displayed between brackets when the progress has completed.
"""
self.queue.put(dill.dumps(NewTaskCommand(task_id=task_id,
task=TaskProgress(total,
prefix,
suffix,
decimals,
bar_length,
keep_alive,
display_time))))
def update(self,
task_id,
progress):
"""
Defines the current progress for this progress bar id in iteration units (not percent).
If the given id does not exist or the given progress is identical to the current, then does nothing.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param progress: Current progress in iteration units regarding its total (not percent).
"""
self.queue.put(dill.dumps(UpdateProgressCommand(task_id=task_id,
progress=progress)))
def debug(self, text):
"""
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.DEBUG)))
def info(self, text):
"""
Posts an info message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.INFO)))
def warning(self, text):
"""
Posts a warning message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.WARNING)))
def error(self, text):
"""
Posts an error message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.ERROR)))
def critical(self, text):
"""
Posts a critical message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.CRITICAL)))
def throw(self, stacktrace, process_title=None):
"""
Sends an exception to the logger so it can display it as a special message. Prevents console refresh cycles from
hiding exceptions that could be thrown by processes.
:param stacktrace: Stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
:param process_title: [Optional] Define the current process title to display into the logger for this
exception.
"""
self.queue.put(dill.dumps(StacktraceCommand(pid=os.getpid(),
stacktrace=stacktrace,
process_title=process_title)))
# --------------------------------------------------------------------
# Iterator implementation
def progress(self,
enumerable,
task_progress_object=None):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:param enumerable: Collection to iterate over.
:param task_progress_object: [Optional] TaskProgress object holding the progress bar information.
:return: The logger instance.
"""
self.list = enumerable
self.list_length = len(enumerable)
self.task_id = uuid.uuid4()
self.index = 0
if task_progress_object:
# Force total attribute
task_progress_object.total = self.list_length
else:
task_progress_object = TaskProgress(total=self.list_length,
display_time=True,
prefix='Progress')
# Create a task progress
self.set_task_object(task_id=self.task_id,
task_progress_object=task_progress_object)
return self
def __iter__(self):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:return: The logger instance.
"""
return self
def __next__(self):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:return: The current object of the iterator.
"""
if self.index >= self.list_length:
raise StopIteration
else:
self.index += 1
self.update(task_id=self.task_id,
progress=self.index)
return self.list[self.index - 1]
# ---------------------------------------------------------------------
| peepall/FancyLogger | FancyLogger/__init__.py | Python | mit | 27,844 |
package com.rebuy.consul;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.catalog.model.CatalogService;
import com.rebuy.consul.exceptions.NoServiceFoundException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConsulServiceTest
{
private ConsulClient clientMock;
private ConsulService service;
private NewService serviceMock;
@Before
public void before()
{
clientMock = mock(ConsulClient.class);
serviceMock = mock(NewService.class);
when(serviceMock.getId()).thenReturn("42");
service = new ConsulService(clientMock, serviceMock);
}
@Test
public void register_should_invoke_client()
{
when(clientMock.agentServiceRegister(Mockito.any())).thenReturn(null);
service.register();
Mockito.verify(clientMock).agentServiceRegister(serviceMock);
}
@Test
public void unregister_should_invoke_client()
{
service.unregister();
Mockito.verify(clientMock).agentServiceSetMaintenance("42", true);
}
@Test(expected = NoServiceFoundException.class)
public void findService_should_throw_exception_if_no_services_are_found()
{
Response<List<CatalogService>> response = new Response<>(new ArrayList<>(), 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService("service", Mockito.any(QueryParams.class));
}
@Test
public void findService_should_invoke_client()
{
List<CatalogService> services = new ArrayList<>();
services.add(mock(CatalogService.class));
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service_with_tag()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service", "my-tag");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.eq("my-tag"), Mockito.any(QueryParams.class));
}
}
| rebuy-de/consul-java-client | src/test/java/com/rebuy/consul/ConsulServiceTest.java | Java | mit | 5,239 |