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
<?php /* @var $this DemoController */ /* @var $model Demo */ $this->breadcrumbs=array( 'Demos'=>array('index'), $model->title=>array('view','id'=>$model->id), 'Update', ); $this->menu=array( array('label'=>'List Demo', 'url'=>array('index')), array('label'=>'Create Demo', 'url'=>array('create')), array('label'=>'View Demo', 'url'=>array('view', 'id'=>$model->id)), array('label'=>'Manage Demo', 'url'=>array('admin')), ); ?> <h1>Update Demo <?php echo $model->id; ?></h1> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?>
perminder-klair/cms-core
protected/views/demo/update.php
PHP
mit
553
<?php namespace Philsquare\LaraManager\Http\Controllers; use Illuminate\Http\Request; use Philsquare\LaraManager\Http\Requests\CreateRedirectRequest; use Philsquare\LaraManager\Http\Requests\UpdateRedirectRequest; use Philsquare\LaraManager\Models\Redirect; class RedirectsController extends Controller { protected $redirect; public function __construct(Redirect $redirect) { $this->redirect = $redirect; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $redirects = $this->redirect->all(); return view('laramanager::redirects.index', compact('redirects')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('laramanager::redirects.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CreateRedirectRequest $request) { $this->redirect->create($request->all()); return redirect('admin/redirects'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($type) { } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $redirect = $this->redirect->findOrFail($id); return view('laramanager::redirects.edit', compact('redirect')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateRedirectRequest $request, $id) { $redirect = $this->redirect->findOrFail($id); $redirect->update($request->all()); return redirect('admin/redirects'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $redirect = $this->redirect->findOrFail($id); if($redirect->delete()) return response()->json(['status' => 'ok']); return response()->json(['status' => 'failed']); } public function redirect(Request $request, Redirect $redirect) { $redirect = $redirect->where('from', $request->path())->first(); if(is_null($redirect)) abort(404); return redirect($redirect->to, $redirect->type); } }
frodex/LaraManager
src/Philsquare/LaraManager/Http/Controllers/RedirectsController.php
PHP
mit
2,779
When(/^I fill in the email details$/) do fill_in "Subject", :with => "Petition email subject" fill_in "Body", :with => "Petition email body" end Then(/^the petition should not have any emails$/) do @petition.reload expect(@petition.emails).to be_empty end Then(/^the petition should have the email details I provided$/) do @petition.reload @email = @petition.emails.last expect(@email.subject).to eq("Petition email subject") expect(@email.body).to match(%r[Petition email body]) expect(@email.sent_by).to eq("Admin User") end Then(/^the petition creator should have been emailed with the update$/) do @petition.reload steps %Q( Then "#{@petition.creator_signature.email}" should receive an email When they open the email Then they should see "Petition email body" in the email body When they follow "#{petition_url(@petition)}" in the email Then I should be on the petition page for "#{@petition.action}" ) end Then(/^all the signatories of the petition should have been emailed with the update$/) do @petition.reload @petition.signatures.notify_by_email.validated.where.not(id: @petition.creator_signature.id).each do |signatory| steps %Q( Then "#{signatory.email}" should receive an email When they open the email Then they should see "Petition email body" in the email body When they follow "#{petition_url(@petition)}" in the email Then I should be on the petition page for "#{@petition.action}" ) end end Then(/^the feedback email address should have been emailed a copy$/) do signatory = FeedbackSignature.new(@petition) steps %Q( Then "#{signatory.email}" should receive an email When they open the email Then they should see "Petition email body" in the email body When they follow "#{petition_url(@petition)}" in the email Then I should be on the petition page for "#{@petition.action}" ) end
telekomatrix/e-petitions
features/step_definitions/petition_email_steps.rb
Ruby
mit
1,922
module PageObjectModel require 'calabash-android/abase' require_relative '../../../features/pages/actions/common_actions' class Page < Calabash::ABase include PageOperations include UtilityObjects include PageObjectModel::PageActions def initialize(world, transition_duration = 0.5) logger.debug "Initializing page => #{self.class}" super(world, transition_duration) end def self.trait(selector) class_eval %Q{ def trait "#{selector}" end } end def self.element(identity, selector) class_eval %Q{ def #{identity} @_#{identity} ||= Element.new("#{selector}") end } end def self.section(identity, classname) class_eval %Q{ def #{identity} @_#{identity} ||= page(#{classname}) end } end def timeout_short 5 end def timeout_medium timeout_page_transition end def timeout_page_transition 10 end def timeout_long Calabash::Android::WaitHelpers.const_get(:DEFAULT_OPTS)[:timeout] end alias_method :displayed?, :current_page? #TODO: embed screenshots into our formatters def embed(file, _mime_type, _label = 'Screenshot') logger.info "Screenshot at #{file}" end #override default delegation to the World methods as defined in Calabash::ABase, to avoid explosion of methods #in the page models def method_missing(method_name, *_args, &_block) raise NoMethodError, "undefined method '#{method_name}' for \##{self.class.inspect}" end end end
blinkboxbooks/android-test
features/pages/model/page.rb
Ruby
mit
1,617
/* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.source.util; import com.sun.source.tree.CompilationUnitTree; import javax.lang.model.element.TypeElement; import javax.tools.JavaFileObject; /** * Provides details about work that has been done by the Sun Java Compiler, javac. * * @author Jonathan Gibbons * @since 1.6 */ public final class TaskEvent { /** * Kind of task event. * @since 1.6 */ public enum Kind { /** * For events related to the parsing of a file. */ PARSE, /** * For events relating to elements being entered. **/ ENTER, /** * For events relating to elements being analyzed for errors. **/ ANALYZE, /** * For events relating to class files being generated. **/ GENERATE, /** * For events relating to overall annotaion processing. **/ ANNOTATION_PROCESSING, /** * For events relating to an individual annotation processing round. **/ ANNOTATION_PROCESSING_ROUND }; public TaskEvent(Kind kind) { this(kind, null, null, null); } public TaskEvent(Kind kind, JavaFileObject sourceFile) { this(kind, sourceFile, null, null); } public TaskEvent(Kind kind, CompilationUnitTree unit) { this(kind, unit.getSourceFile(), unit, null); } public TaskEvent(Kind kind, CompilationUnitTree unit, TypeElement clazz) { this(kind, unit.getSourceFile(), unit, clazz); } private TaskEvent(Kind kind, JavaFileObject file, CompilationUnitTree unit, TypeElement clazz) { this.kind = kind; this.file = file; this.unit = unit; this.clazz = clazz; } public Kind getKind() { return kind; } public JavaFileObject getSourceFile() { return file; } public CompilationUnitTree getCompilationUnit() { return unit; } public TypeElement getTypeElement() { return clazz; } public String toString() { return "TaskEvent[" + kind + "," + file + "," // the compilation unit is identified by the file + clazz + "]"; } private Kind kind; private JavaFileObject file; private CompilationUnitTree unit; private TypeElement clazz; }
daniel-beck/sorcerer
javac/src/main/java/com/sun/source/util/TaskEvent.java
Java
mit
3,433
//****************************************************************************************************** // PQMarkAggregate.cs - Gbtc // // Copyright © 2017, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/29/2017 - Billy Ernest // Generated original version of source code. // //****************************************************************************************************** using GSF.Data.Model; namespace openXDA.Model { public class PQMarkAggregate { [PrimaryKey(true)] public int ID { get; set; } public int MeterID { get; set;} public int Year { get; set;} public int Month { get; set;} public int ITIC { get; set;} public int SEMI { get; set;} public int SARFI90 { get; set;} public int SARFI70 { get; set;} public int SARFI50 { get; set;} public int SARFI10 { get; set;} public string THDJson { get; set; } } }
GridProtectionAlliance/openXDA
Source/Libraries/openXDA.Model/PQMarkAggregate.cs
C#
mit
1,815
document.getElementById('input_search').onfocus = function () { document.getElementById('search').classList.add('activeSearch'); }; document.getElementById('input_search').onblur = function () { document.getElementById('search').classList.remove('activeSearch'); }; try { window.$ = window.jQuery = require('jquery'); require('./navbar'); require('./horizontalScroll'); } catch (e) {}
reed-jones/DiscoverMovies
resources/assets/js/app.js
JavaScript
mit
404
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("DisagLib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DisagLib")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6ba4c402-4a4f-41cb-adf6-519d4acd0832")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
chschenk/SVP
DisagLib/Properties/AssemblyInfo.cs
C#
mit
1,392
//------------------------------------------------------------------------------ // resourceBase.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "resourceBase.h" namespace Oryol { namespace _priv { //------------------------------------------------------------------------------ void shaderBase::Clear() { this->Setup = ShaderSetup(); } //------------------------------------------------------------------------------ void textureBase::Clear() { this->Setup = TextureSetup(); this->textureAttrs = TextureAttrs(); } //------------------------------------------------------------------------------ void meshBase::Clear() { this->Setup = MeshSetup(); this->vertexBufferAttrs = VertexBufferAttrs(); this->indexBufferAttrs = IndexBufferAttrs(); this->primGroups.Fill(PrimitiveGroup()); this->numPrimGroups = 0; } //------------------------------------------------------------------------------ void pipelineBase::Clear() { this->Setup = PipelineSetup(); this->shd = nullptr; } //------------------------------------------------------------------------------ void renderPassBase::Clear() { this->Setup = PassSetup(); this->colorTextures.Fill(nullptr); this->depthStencilTexture = nullptr; } } // namespace _priv } // namespace Oryol
floooh/oryol
code/Modules/Gfx/private/resourceBase.cc
C++
mit
1,349
/* * Jot v1.1 * License: The MIT License (MIT) * Code: https://github.com/jdemeuse1204/Jot * Email: james.demeuse@gmail.com * Copyright (c) 2016 James Demeuse */ namespace Jot { public enum TokenValidationResult { NotBeforeFailed, TokenExpired, TokenNotCorrectlyFormed, SignatureNotValid, OnTokenValidateFailed, OnJtiValidateFailed, CustomCheckFailed, CreatedTimeCheckFailed, Passed } }
jdemeuse1204/Jot
Jot/TokenValidationResult.cs
C#
mit
481
package main import ( "flag" "fmt" "net/http" . "gopkg.in/go-on/lib.v2/types" . "gopkg.in/go-on/lib.v2/html" "gopkg.in/go-on/lib.v2/internal/bootstrap/bs3" "gopkg.in/go-on/cdncache.v1" ) var ( port = flag.Int("port", 8083, "port of the http server") mountPoint = flag.String("mountpoint", "", "mount point for the cached files (leave empty to prevent caching)") ) func main() { flag.Parse() cdn := cdncache.CDN(*mountPoint) http.Handle("/", HTML5( Lang_("en"), HEAD( CharsetUtf8(), HttpEquiv("X-UA-Compatible", "IE=edge"), Viewport("width=device-width, initial-scale=1"), TITLE("Starter Template for Bootstrap"), CssHref(cdn(bs3.CDN_3_1_1_min)), CssHref(cdn(bs3.CDN_3_1_1_theme_min)), CssHref(cdn("http://getbootstrap.com/examples/starter-template/starter-template.css")), HTMLString(fmt.Sprintf(` <!--[if lt IE 9]> <script src="%s"></script> <script src="%s"></script> <![endif]--> `, cdn("https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"), cdn("https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"), ), ), ), BODY( DIV(bs3.Navbar, bs3.Navbar_inverse, bs3.Navbar_fixed_top, Attrs_("role", "navigation"), DIV(bs3.Container, DIV(bs3.Navbar_header, BUTTON(bs3.Navbar_toggle, Type_("button"), Attrs_("data-toggle", "collapse", "data-target", ".navbar-collapse"), SPAN(bs3.Sr_only, "Toogle navigation"), SPAN(bs3.Icon_bar), SPAN(bs3.Icon_bar), SPAN(bs3.Icon_bar), ), AHref("#", bs3.Navbar_brand, "Project name"), ), DIV(bs3.Collapse, bs3.Navbar_collapse, UL(bs3.Nav, bs3.Navbar_nav, LI(bs3.Active, AHref("#", "Home")), LI(AHref("#about", "About")), LI(AHref("#contact", "Contact")), ), ), ), ), DIV(bs3.Container, DIV(Class("starter-template"), H1("Bootstrap starter template"), P(bs3.Lead, "Use this document as a way to quickly start any new project.", BR(), "All you get is this text and a mostly barebones HTML document.", ), ), ), JsSrc(cdn("//code.jquery.com/jquery-1.11.0.min.js")), JsSrc(cdn(bs3.CDN_3_1_1_js_min)), ), ), ) fmt.Printf("listening on localhost: %d\n", *port) http.ListenAndServe(fmt.Sprintf(":%d", *port), nil) }
go-on/cdncache
example/main.go
GO
mit
2,369
/// <reference path="lib/jquery-2.0.3.js" /> define(["httpRequester"], function (httpRequester) { function getStudents() { var url = this.url + "api/students/"; return httpRequester.getJSON(url); } function getMarksByStudentId(studentId) { var url = this.url + "api/students/" + studentId + "/marks/"; return httpRequester.getJSON(url); } return { students: getStudents, marks: getMarksByStudentId, url: this.url } });
niki-funky/Telerik_Academy
Web Development/JS_frameworks/04. Reqiure/StudentsDB.WebClient/scripts/app/data-persister.js
JavaScript
mit
505
package apns import ( "errors" "github.com/cosminrentea/gobbler/server/connector" "github.com/jpillora/backoff" "github.com/sideshow/apns2" "net" "time" ) const ( // deviceIDKey is the key name set on the route params to identify the application deviceIDKey = "device_token" userIDKey = "user_id" ) var ( errPusherInvalidParams = errors.New("Invalid parameters of APNS Pusher") ErrRetryFailed = errors.New("Retry failed") ) type sender struct { client Pusher appTopic string } func NewSender(config Config) (connector.Sender, error) { pusher, err := newPusher(config) if err != nil { logger.WithField("error", err.Error()).Error("APNS Pusher creation error") return nil, err } return NewSenderUsingPusher(pusher, *config.AppTopic) } func NewSenderUsingPusher(pusher Pusher, appTopic string) (connector.Sender, error) { if pusher == nil || appTopic == "" { return nil, errPusherInvalidParams } return &sender{ client: pusher, appTopic: appTopic, }, nil } func (s sender) Send(request connector.Request) (interface{}, error) { l := logger.WithField("correlation_id", request.Message().CorrelationID()) deviceToken := request.Subscriber().Route().Get(deviceIDKey) l.WithField("deviceToken", deviceToken).Info("Trying to push a message to APNS") push := func() (interface{}, error) { return s.client.Push(&apns2.Notification{ Priority: apns2.PriorityHigh, Topic: s.appTopic, DeviceToken: deviceToken, Payload: request.Message().Body, }) } withRetry := &retryable{ Backoff: backoff.Backoff{ Min: 1 * time.Second, Max: 10 * time.Second, Factor: 2, Jitter: true, }, maxTries: 3, } result, err := withRetry.execute(push) if err != nil && err == ErrRetryFailed { if closable, ok := s.client.(closable); ok { l.Warn("Close TLS and retry again") mTotalSendRetryCloseTLS.Add(1) pSendRetryCloseTLS.Inc() closable.CloseTLS() return push() } else { mTotalSendRetryUnrecoverable.Add(1) pSendRetryUnrecoverable.Inc() l.Error("Cannot Close TLS. Unrecoverable state") } } return result, err } type retryable struct { backoff.Backoff maxTries int } func (r *retryable) execute(op func() (interface{}, error)) (interface{}, error) { tryCounter := 0 for { tryCounter++ result, opError := op() // retry on network errors if _, ok := opError.(net.Error); ok { mTotalSendNetworkErrors.Add(1) pSendNetworkErrors.Inc() if tryCounter >= r.maxTries { return "", ErrRetryFailed } d := r.Duration() logger.WithField("error", opError.Error()).Warn("Retry in ", d) time.Sleep(d) continue } else { return result, opError } } }
cosminrentea/gobbler
server/apns/apns_sender.go
GO
mit
2,689
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication21 { class Program { static void Main(string[] args) { int hour = int.Parse(Console.ReadLine()); int min = int.Parse(Console.ReadLine()); if (min + 15 >= 60 && hour <= 23) { hour += 1; min -= 45; if (hour == 24) hour -= 24; } else if (hour > 24) { hour %= 24; min += 15; } else min += 15; Console.WriteLine("{0}:{1:00}", hour, min); } } }
VaskoViktorov/SoftUni-Homework
01. Programming Basics - 20.08.2016/Other unsorted/time +15 min.cs
C#
mit
763
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "CommonDataStructuresPch.h" #include "DataStructures/BigInt.h" #include "Common/NumberUtilitiesBase.h" #include "Common/NumberUtilities.h" namespace Js { BigInt & BigInt::operator= (BigInt &bi) { AssertMsg(false, "can't assign BigInts"); return *this; } #if DBG void BigInt::AssertValid(bool fCheckVal) { Assert(m_cluMax >= kcluMaxInit); Assert(m_prglu != 0); Assert(m_clu >= 0 && m_clu <= m_cluMax); Assert(!fCheckVal || 0 == m_clu || 0 != m_prglu[m_clu - 1]); Assert((m_prglu == m_rgluInit) == (m_cluMax == kcluMaxInit)); } #endif BigInt::BigInt(void) { m_cluMax = kcluMaxInit; m_clu = 0; m_prglu = m_rgluInit; AssertBi(this); } BigInt::~BigInt(void) { if (m_prglu != m_rgluInit) free(m_prglu); } int32 BigInt::Clu(void) { return m_clu; } uint32 BigInt::Lu(int32 ilu) { AssertBi(this); Assert(ilu < m_clu); return m_prglu[ilu]; } bool BigInt::FResize(int32 clu) { AssertBiNoVal(this); uint32 *prglu; if (clu <= m_cluMax) return true; clu += clu; if (m_prglu == m_rgluInit) { if ((INT_MAX / sizeof(uint32) < clu) || (NULL == (prglu = (uint32 *)malloc(clu * sizeof(uint32))))) return false; if (0 < m_clu) js_memcpy_s(prglu, clu * sizeof(uint32), m_prglu, m_clu * sizeof(uint32)); } else if (NULL == (prglu = (uint32 *)realloc(m_prglu, clu * sizeof(uint32)))) return false; m_prglu = prglu; m_cluMax = clu; AssertBiNoVal(this); return true; } bool BigInt::FInitFromRglu(uint32 *prglu, int32 clu) { AssertBi(this); Assert(clu >= 0); Assert(prglu != 0); if (clu > m_cluMax && !FResize(clu)) return false; m_clu = clu; if (clu > 0) js_memcpy_s(m_prglu, m_clu * sizeof(uint32), prglu, clu * sizeof(uint32)); AssertBi(this); return true; } bool BigInt::FInitFromBigint(BigInt *pbiSrc) { AssertBi(this); AssertBi(pbiSrc); Assert(this != pbiSrc); return FInitFromRglu(pbiSrc->m_prglu, pbiSrc->m_clu); } template <typename EncodedChar> bool BigInt::FInitFromDigits(const EncodedChar *prgch, int32 cch, int32 *pcchDig) { AssertBi(this); Assert(cch >= 0); Assert(prgch != 0); Assert(pcchDig != 0); uint32 luAdd; uint32 luMul; int32 clu = (cch + 8) / 9; const EncodedChar *pchLim = prgch + cch; if (clu > m_cluMax && !FResize(clu)) return false; m_clu = 0; luAdd = 0; luMul = 1; for (*pcchDig = cch; prgch < pchLim; prgch++) { if (*prgch == '.') { (*pcchDig)--; continue; } Assert(NumberUtilities::IsDigit(*prgch)); if (luMul == 1000000000) { AssertVerify(FMulAdd(luMul, luAdd)); luMul = 1; luAdd = 0; } luMul *= 10; luAdd = luAdd * 10 + *prgch - '0'; } Assert(1 < luMul); AssertVerify(FMulAdd(luMul, luAdd)); AssertBi(this); return true; } bool BigInt::FMulAdd(uint32 luMul, uint32 luAdd) { AssertBi(this); Assert(luMul != 0); uint32 luT; uint32 *plu = m_prglu; uint32 *pluLim = plu + m_clu; for (; plu < pluLim; plu++) { *plu = NumberUtilities::MulLu(*plu, luMul, &luT); if (luAdd) luT += NumberUtilities::AddLu(plu, luAdd); luAdd = luT; } if (0 == luAdd) goto LDone; if (m_clu >= m_cluMax && !FResize(m_clu + 1)) return false; m_prglu[m_clu++] = luAdd; LDone: AssertBi(this); return true; } bool BigInt::FMulPow5(int32 c5) { AssertBi(this); Assert(c5 >= 0); const uint32 k5to13 = 1220703125; int32 clu = (c5 + 12) / 13; uint32 luT; if (0 == m_clu || 0 == c5) return true; if (m_clu + clu > m_cluMax && !FResize(m_clu + clu)) return false; for (; c5 >= 13; c5 -= 13) AssertVerify(FMulAdd(k5to13, 0)); if (c5 > 0) { for (luT = 5; --c5 > 0; ) luT *= 5; AssertVerify(FMulAdd(luT, 0)); } AssertBi(this); return true; } bool BigInt::FShiftLeft(int32 cbit) { AssertBi(this); Assert(cbit >= 0); int32 ilu; int32 clu; uint32 luExtra; if (0 == cbit || 0 == m_clu) return true; clu = cbit >> 5; cbit &= 0x001F; if (cbit > 0) { ilu = m_clu - 1; luExtra = m_prglu[ilu] >> (32 - cbit); for (; ; ilu--) { m_prglu[ilu] <<= cbit; if (0 == ilu) break; m_prglu[ilu] |= m_prglu[ilu - 1] >> (32 - cbit); } } else luExtra = 0; if (clu > 0 || 0 != luExtra) { // Make sure there's enough room. ilu = m_clu + (0 != luExtra) + clu; if (ilu > m_cluMax && !FResize(ilu)) return false; if (clu > 0) { // Shift the uint32s. memmove(m_prglu + clu, m_prglu, m_clu * sizeof(uint32)); memset(m_prglu, 0, clu * sizeof(uint32)); m_clu += clu; } // Throw on the extra one. if (0 != luExtra) m_prglu[m_clu++] = luExtra; } AssertBi(this); return true; } void BigInt::ShiftLusRight(int32 clu) { AssertBi(this); Assert(clu >= 0); if (clu >= m_clu) { m_clu = 0; AssertBi(this); return; } if (clu > 0) { memmove(m_prglu, m_prglu + clu, (m_clu - clu) * sizeof(uint32)); m_clu -= clu; } AssertBi(this); } void BigInt::ShiftRight(int32 cbit) { AssertBi(this); Assert(cbit >= 0); int32 ilu; int32 clu = cbit >> 5; cbit &= 0x001F; if (clu > 0) ShiftLusRight(clu); if (cbit == 0 || m_clu == 0) { AssertBi(this); return; } for (ilu = 0; ; ) { m_prglu[ilu] >>= cbit; if (++ilu >= m_clu) { // Last one. if (0 == m_prglu[ilu - 1]) m_clu--; break; } m_prglu[ilu - 1] |= m_prglu[ilu] << (32 - cbit); } AssertBi(this); } int BigInt::Compare(BigInt *pbi) { AssertBi(this); AssertBi(pbi); int32 ilu; if (m_clu > pbi->m_clu) return 1; if (m_clu < pbi->m_clu) return -1; if (0 == m_clu) return 0; #pragma prefast(suppress:__WARNING_LOOP_ONLY_EXECUTED_ONCE,"noise") for (ilu = m_clu - 1; m_prglu[ilu] == pbi->m_prglu[ilu]; ilu--) { if (0 == ilu) return 0; } Assert(ilu >= 0 && ilu < m_clu); Assert(m_prglu[ilu] != pbi->m_prglu[ilu]); return (m_prglu[ilu] > pbi->m_prglu[ilu]) ? 1 : -1; } bool BigInt::FAdd(BigInt *pbi) { AssertBi(this); AssertBi(pbi); Assert(this != pbi); int32 cluMax, cluMin; int32 ilu; int wCarry; if ((cluMax = m_clu) < (cluMin = pbi->m_clu)) { cluMax = pbi->m_clu; cluMin = m_clu; if (cluMax > m_cluMax && !FResize(cluMax + 1)) return false; } wCarry = 0; for (ilu = 0; ilu < cluMin; ilu++) { if (0 != wCarry) wCarry = NumberUtilities::AddLu(&m_prglu[ilu], wCarry); wCarry += NumberUtilities::AddLu(&m_prglu[ilu], pbi->m_prglu[ilu]); } if (m_clu < pbi->m_clu) { for (; ilu < cluMax; ilu++) { m_prglu[ilu] = pbi->m_prglu[ilu]; if (0 != wCarry) wCarry = NumberUtilities::AddLu(&m_prglu[ilu], wCarry); } m_clu = cluMax; } else { for (; 0 != wCarry && ilu < cluMax; ilu++) wCarry = NumberUtilities::AddLu(&m_prglu[ilu], wCarry); } if (0 != wCarry) { if (m_clu >= m_cluMax && !FResize(m_clu + 1)) return false; m_prglu[m_clu++] = wCarry; } AssertBi(this); return true; } void BigInt::Subtract(BigInt *pbi) { AssertBi(this); AssertBi(pbi); Assert(this != pbi); int32 ilu; int wCarry; uint32 luT; if (m_clu < pbi->m_clu) goto LNegative; wCarry = 1; for (ilu = 0; (ilu < pbi->m_clu) && (ilu < pbi->m_cluMax); ilu++) { Assert(wCarry == 0 || wCarry == 1); luT = pbi->m_prglu[ilu]; // NOTE: We should really do: // wCarry = AddLu(&m_prglu[ilu], wCarry); // wCarry += AddLu(&m_prglu[ilu], ~luT); // The only case where this is different than // wCarry = AddLu(&m_prglu[ilu], ~luT + wCarry); // is when luT == 0 and 1 == wCarry, in which case we don't // need to add anything and wCarry should still be 1, so we can // just skip the operations. if (0 != luT || 0 == wCarry) wCarry = NumberUtilities::AddLu(&m_prglu[ilu], ~luT + wCarry); } while ((0 == wCarry) && (ilu < m_clu) && (ilu < m_cluMax)) wCarry = NumberUtilities::AddLu(&m_prglu[ilu], 0xFFFFFFFF); if (0 == wCarry) { LNegative: // pbi was bigger than this. AssertMsg(false, "Who's subtracting to negative?"); m_clu = 0; } else if (ilu == m_clu) { // Trim off zeros. while (--ilu >= 0 && 0 == m_prglu[ilu]) ; m_clu = ilu + 1; } AssertBi(this); } int BigInt::DivRem(BigInt *pbi) { AssertBi(this); AssertBi(pbi); Assert(this != pbi); int32 ilu, clu; int wCarry; int wQuo; int wT; uint32 luT, luHi, luLo; clu = pbi->m_clu; Assert(m_clu <= clu); if ((m_clu < clu) || (clu <= 0)) return 0; // Get a lower bound on the quotient. wQuo = (int)(m_prglu[clu - 1] / (pbi->m_prglu[clu - 1] + 1)); Assert(wQuo >= 0 && wQuo <= 9); // Handle 0 and 1 as special cases. switch (wQuo) { case 0: break; case 1: Subtract(pbi); break; default: luHi = 0; wCarry = 1; for (ilu = 0; ilu < clu; ilu++) { Assert(wCarry == 0 || wCarry == 1); // Compute the product. luLo = NumberUtilities::MulLu(wQuo, pbi->m_prglu[ilu], &luT); luHi = luT + NumberUtilities::AddLu(&luLo, luHi); // Subtract the product. See note in BigInt::Subtract. if (0 != luLo || 0 == wCarry) wCarry = NumberUtilities::AddLu(&m_prglu[ilu], ~luLo + wCarry); } Assert(1 == wCarry); Assert(ilu == clu); // Trim off zeros. while (--ilu >= 0 && 0 == m_prglu[ilu]) ; m_clu = ilu + 1; } if (wQuo < 9 && (wT = Compare(pbi)) >= 0) { // Quotient was off too small (by one). wQuo++; if (wT == 0) m_clu = 0; else Subtract(pbi); } Assert(Compare(pbi) < 0); return wQuo; } double BigInt::GetDbl(void) { double dbl; uint32 luHi, luLo; uint32 lu1, lu2, lu3; int32 ilu; int cbit; switch (m_clu) { case 0: return 0; case 1: return m_prglu[0]; case 2: dbl = m_prglu[1]; NumberUtilities::LuHiDbl(dbl) += 0x02000000; return dbl + m_prglu[0]; } Assert(3 <= m_clu); if (m_clu > 32) { // Result is infinite. NumberUtilities::LuHiDbl(dbl) = 0x7FF00000; NumberUtilities::LuLoDbl(dbl) = 0; return dbl; } lu1 = m_prglu[m_clu - 1]; lu2 = m_prglu[m_clu - 2]; lu3 = m_prglu[m_clu - 3]; Assert(0 != lu1); cbit = 31 - NumberUtilities::CbitZeroLeft(lu1); if (cbit == 0) { luHi = lu2; luLo = lu3; } else { luHi = (lu1 << (32 - cbit)) | (lu2 >> cbit); // Or 1 if there are any remaining nonzero bits in lu3, so we take // them into account when rounding. luLo = (lu2 << (32 - cbit)) | (lu3 >> cbit) | (0 != (lu3 << (32 - cbit))); } // Set the mantissa bits. NumberUtilities::LuHiDbl(dbl) = luHi >> 12; NumberUtilities::LuLoDbl(dbl) = (luHi << 20) | (luLo >> 12); // Set the exponent field. NumberUtilities::LuHiDbl(dbl) |= (0x03FF + cbit + (m_clu - 1) * 0x0020) << 20; // Do IEEE rounding. if (luLo & 0x0800) { if ((luLo & 0x07FF) || (NumberUtilities::LuLoDbl(dbl) & 1)) { if (0 == ++NumberUtilities::LuLoDbl(dbl)) ++NumberUtilities::LuHiDbl(dbl); } else { // If there are any non-zero bits in m_prglu from 0 to m_clu - 4, round up. for (ilu = m_clu - 4; ilu >= 0; ilu--) { if (0 != m_prglu[ilu]) { if (0 == ++NumberUtilities::LuLoDbl(dbl)) ++NumberUtilities::LuHiDbl(dbl); break; } } } } return dbl; } template bool BigInt::FInitFromDigits<char16>(const char16 *prgch, int32 cch, int32 *pcchDig); template bool BigInt::FInitFromDigits<utf8char_t>(const utf8char_t *prgch, int32 cch, int32 *pcchDig); }
mrkmarron/ChakraCore
lib/Common/DataStructures/BigInt.cpp
C++
mit
15,350
package com.raoulvdberge.refinedstorage.block.enums; import net.minecraft.util.IStringSerializable; public enum ControllerType implements IStringSerializable { NORMAL(0, "normal"), CREATIVE(1, "creative"); private int id; private String name; ControllerType(int id, String name) { this.id = id; this.name = name; } @Override public String getName() { return name; } public int getId() { return id; } @Override public String toString() { return name; } }
way2muchnoise/refinedstorage
src/main/java/com/raoulvdberge/refinedstorage/block/enums/ControllerType.java
Java
mit
557
require 'spec_helper' describe Fulcrum::Client do let(:client) { Fulcrum::Client.new } it 'has a default url' do expect(client.url).to eq(Fulcrum::Client::DEFAULT_URL) end it 'can query' do url = "#{client.url}/query" response = 'audio,system,,,,,' stub_request(:post, url) .with(body: '{"q":"select name from tables limit 1;","format":"csv"}') .to_return(status: 200, body: response, headers: {"Content-Type" => "text/plain"}) sql = 'select name from tables limit 1;' csv = client.query(sql, 'csv') expect(csv).to eq(response) end it 'can get_user' do url = 'https://fred%40flinstones.com:secret@api.fulcrumapp.com/api/v2/users.json' response = '{"user":{"first_name":"Jason","last_name":"Sanford","email":"jason@fulcrumapp.com","image_small":"https://fulcrumapp-dev.s3.amazonaws.com/user-images/small_abc.jpg","image_large":"https://fulcrumapp-dev.s3.amazonaws.com/user-images/large_abc.jpg","id":"49d06ce5-1457-476c-9cb4-fd9d41ea43ef","contexts":[{"name":"Team Jason","id":"e09c1a03-819d-47d6-aebc-f8712d292b57","api_token":"abc123","image_small":"https://fulcrumapp-dev.s3.amazonaws.com/organization-images/small_abc.jpg","image_large":"https://fulcrumapp-dev.s3.amazonaws.com/organization-images/large_abc.jpg","type":"organization","role":{},"domain":null,"plan":{}}],"access":{"allowed":true}}}' stub_request(:get, url) .to_return(status: 200, body: response, headers: {"Content-Type" => "application/json"}) sql = 'select name from tables limit 1;' user = Fulcrum::Client.get_user('fred@flinstones.com', 'secret') expect(user['contexts'].length).to eq(1) expect(user['contexts'][0]['id']).to eq('e09c1a03-819d-47d6-aebc-f8712d292b57') end it 'can create_authorization' do url = 'https://fred%40flinstones.com:secret@api.fulcrumapp.com/api/v2/authorizations.json' body = '{"authorization":{"organization_id":"abc-123","note":"Tess Ting","timeout":null,"user_id":null}}' response = '{"authorization":{"note":"Tess Ting","expires_at":null,"timeout":null,"token_last_8":"46c5cb33","last_ip_address":null,"last_user_agent":null,"token":"ac493349cd4de0c376185c1d347d24ce5a3867bd3e04397bb875ed6b9b0546b768caa3bf46c5cb33","created_at":"2019-04-12T13:25:28Z","updated_at":"2019-04-12T13:25:28Z","id":"f1d84caa-da28-4fc5-a341-44bb9efa6266","last_used_at":null,"user_id":"4f1cfa091441405373000443"}}' stub_request(:post, url) .with(body: body) .to_return(status: 200, body: response, headers: {"Content-Type" => "application/json"}) authorization = Fulcrum::Client.create_authorization('fred@flinstones.com', 'secret', 'abc-123', 'Tess Ting') expect(authorization['note']).to eq('Tess Ting') expect(authorization['token_last_8']).to eq('46c5cb33') end end
fulcrumapp/fulcrum-ruby
spec/lib/client_spec.rb
Ruby
mit
2,850
/** * WhatsApp service provider */ module.exports = { popupUrl: 'whatsapp://send?text={title}%0A{url}', popupWidth: 600, popupHeight: 450 };
valerypatorius/Likely
source/services/whatsapp.js
JavaScript
mit
155
/*************************************************************************** * Copyright (C) 2006 by Arnaud Desaedeleer * * arnaud@desaedeleer.com * * * * This file is part of OpenOMR * * * * 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. * ***************************************************************************/ package openomr.omr_engine; import java.awt.image.BufferedImage; /** * The <code> XProjection </code> class will calculate the X-Projection of an image. The constructor * is given a <code> BufferedImage </code> and then the <code> calcXProjection </method> is invoked * to calculate the X-Projection of the <code> BufferedImage </code>. * <p> * The <code> XProjection </code> class is used as follows: * <p> * <code> * XProjection xProj = new XProjection(BufferedImage); <br> * xProj.calcXProjection(startH, endH, startW, endW); <br> * </code> * <p> * Calling the <code> calcXProjection </code> method will place the X-Projection of the <code> BufferedImage </code> * in a int[] array which can be obtained by calling the <code> getYProjection </code> method. * <p> * * @author Arnaud Desaedeleer * @version 1.0 */ public class XProjection { private int xProjection[]; private int size; private BufferedImage buffImage; public XProjection(BufferedImage buffImage) { this.buffImage = buffImage; } /** * Cacluate the X-Projection of the BufferedImage * @param startH Desired start Y-Coordinate of the BufferedImage * @param endH Desired end Y-Coordinate of the BufferedImage * @param startW Desired start X-Coordinate of the BufferedImage * @param endW Desired end X-Coordinate of the BufferedImage */ public void calcXProjection(int startH, int endH, int startW, int endW) { int size = Math.abs(endW - startW) + 1; //System.out.println("Size: " + size); this.size = size; xProjection = new int[size]; for (int i = startW; i < endW; i += 1) { for (int j = startH; j < endH; j += 1) { int color = 0; try { color = buffImage.getRGB(i, j); } catch (ArrayIndexOutOfBoundsException e) { } if (color != -1) //if black pixel { xProjection[i-startW] += 1; } } } } /** * Returns the resulting X-Projection of the BufferedImage * @return xProjection */ public int[] getXProjection() { return xProjection; } /** * Prints the X-Projection of the BufferedImage * */ public void printXProjection() { System.out.println("X Projection"); for (int i=0; i<size; i+=1) { System.out.println(xProjection[i]); } System.out.println("END X Projection"); } }
nayan92/ic-hack
OpenOMR/openomr/omr_engine/XProjection.java
Java
mit
4,106
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.eventgrid.v2020_04_01_preview; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * NumberGreaterThanOrEquals Advanced Filter. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "operatorType", defaultImpl = NumberGreaterThanOrEqualsAdvancedFilter.class) @JsonTypeName("NumberGreaterThanOrEquals") public class NumberGreaterThanOrEqualsAdvancedFilter extends AdvancedFilter { /** * The filter value. */ @JsonProperty(value = "value") private Double value; /** * Get the filter value. * * @return the value value */ public Double value() { return this.value; } /** * Set the filter value. * * @param value the value value to set * @return the NumberGreaterThanOrEqualsAdvancedFilter object itself. */ public NumberGreaterThanOrEqualsAdvancedFilter withValue(Double value) { this.value = value; return this; } }
selvasingh/azure-sdk-for-java
sdk/eventgrid/mgmt-v2020_04_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2020_04_01_preview/NumberGreaterThanOrEqualsAdvancedFilter.java
Java
mit
1,359
package derpstream; import java.io.FileOutputStream; import java.io.IOException; import java.util.PriorityQueue; import java.util.TimerTask; import java.util.concurrent.LinkedBlockingDeque; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Mads */ public final class ChunkInfo extends TimerTask { private static final Logger LOGGER = Logger.getLogger("derpstream"); private static final int BUFFER_PIECES = 3; private final StreamInfo streamInfo; private final DerpStream derpStream; // Template for generating chunk links private final String chunkPath; private final LinkedBlockingDeque<Piece> pieceQueue = new LinkedBlockingDeque<>(); private final PriorityQueue<Piece> bufferedPieces = new PriorityQueue<>(); private long nextPieceTime; // when next piece becomes available private int maxValidPiece; // maximum valid piece that can be requested private int writePiece; // next piece to be written to disk. private final Object waitObj = new Object(); ChunkInfo(DerpStream derpStream, StreamInfo streamInfo) throws IOException { this.streamInfo = streamInfo; this.derpStream = derpStream; // Download chunklist LOGGER.info("Getting latest chunklist..."); String chunkList = DerpStream.downloadString(streamInfo.getChunkInfoPath()); if(!DerpStream.isM3U(chunkList)) throw new IllegalStateException("Invalid chunklist: " + chunkList); // Parse current chunk index String search = "#EXT-X-MEDIA-SEQUENCE:"; int start = chunkList.indexOf(search) + search.length(); int end = chunkList.indexOf("\n", start); maxValidPiece = Integer.parseInt(chunkList.substring(start, end)); writePiece = maxValidPiece - BUFFER_PIECES; LOGGER.info("Ok. Stream is at piece " + maxValidPiece + "\n"); // Figure out chunkPath template String[] lines = chunkList.split("\n"); String chunkPath = null; for (String line : lines) { if(!line.startsWith("#")) { if(line.contains(""+maxValidPiece)) { chunkPath = line.replace("" + maxValidPiece, "%d"); LOGGER.info("Setting chunkpath: " + chunkPath); break; } } } if(chunkPath == null) throw new IllegalStateException("Couldn't find chunkPath"); this.chunkPath = chunkPath; // Enqueue valid pieces for (int i = 0; i < BUFFER_PIECES; i++) { pieceQueue.add(makePiece(writePiece+i)); } // 10 seconds to next piece becomes available nextPieceTime = System.currentTimeMillis() + 10000; } // Increments the piece counter for every 10 seconds since start. public void updatePiece() { long time = System.currentTimeMillis(); while(time >= nextPieceTime) { nextPieceTime += 10000; pieceQueue.add(makePiece(maxValidPiece)); DerpStreamCallbacks callbacks = derpStream.getCallbacks(); if(callbacks != null) { callbacks.pieceAvailable(maxValidPiece); } maxValidPiece++; } } public String getChunkPath() { return String.format(chunkPath, writePiece); } private Piece makePiece(int index) { return new Piece(index, String.format(chunkPath, index)); } @Override public void run() { // Update pieces updatePiece(); } void lostPiece(Piece p) { synchronized(bufferedPieces) { bufferedPieces.add(p); } synchronized(waitObj) { waitObj.notify(); } } public void registerPiece(Piece p) { synchronized(bufferedPieces) { bufferedPieces.add(p); } synchronized(waitObj) { waitObj.notify(); } } public Piece grabWork() throws InterruptedException { return pieceQueue.takeFirst(); } void startWriting(FileOutputStream fos) throws IOException { DerpStreamCallbacks callbacks = derpStream.getCallbacks(); while(derpStream.isRunning()) { // Write data to the file as it becomes available. synchronized(bufferedPieces) { while(bufferedPieces.size() > 0) { Piece topPiece = bufferedPieces.peek(); // Not what we're looking for? if(topPiece.pieceIndex != writePiece) break; // Grab it! Piece removedPiece = bufferedPieces.poll(); // Check it! if(removedPiece != topPiece) throw new RuntimeException("Huh?"); if(topPiece.data != null) { LOGGER.fine("Writing " + topPiece); // Write it! fos.getChannel().write(topPiece.data); if(callbacks != null) { callbacks.finishedWriting(topPiece.pieceIndex); } } else { LOGGER.warning("Skipping " + topPiece); if(callbacks != null) { callbacks.skippedWriting(topPiece.pieceIndex); } } writePiece++; } } synchronized(waitObj) { try { waitObj.wait(5000); } catch (InterruptedException ex) { } } } } }
maesse/DerpStream
src/derpstream/ChunkInfo.java
Java
mit
5,842
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.ComponentModel.DataAnnotations; namespace Piranha.Models { /// <summary> /// String parameter. /// </summary> [Serializable] public class Param { /// <summary> /// Gets/sets the unique id. /// </summary> public Guid Id { get; set; } /// <summary> /// Gets/sets the unique key. /// </summary> [Required] [StringLength(64)] public string Key { get; set; } /// <summary> /// Gets/sets the value. /// </summary> public string Value { get; set; } /// <summary> /// Gets/sets the optional description. /// </summary> [StringLength(255)] public string Description { get; set; } /// <summary> /// Gets/sets the created date. /// </summary> public DateTime Created { get; set; } /// <summary> /// Gets/sets the last modification date. /// </summary> public DateTime LastModified { get; set; } } }
PiranhaCMS/piranha.core
core/Piranha/Models/Param.cs
C#
mit
1,301
var path = require('path'), HtmlReporter = require('protractor-html-screenshot-reporter'); exports.config = { chromeDriver: 'node_modules/chromedriver/bin/chromedriver', // seleniumAddress: 'http://localhost:4444/wd/hub', // Boolean. If true, Protractor will connect directly to the browser Drivers // at the locations specified by chromeDriver and firefoxPath. Only Chrome // and Firefox are supported for direct connect. directConnect: true, // Use existing selenium local/remote // seleniumAddress: http://localhost:4444/wd/hub // When run without a command line parameter, all suites will run. If run // with --suite=login only the patterns matched by the specified suites will // run. // @todo specs: ['specs/aui-login.js'], // The timeout in milliseconds for each script run on the browser. This should // be longer than the maximum time your application needs to stabilize between // tasks. allScriptsTimeout: 20000, baseUrl: 'http://localhost:9010', multiCapabilities: [{ 'browserName': 'chrome' }, { 'browserName': 'firefox' }], onPrepare: function() { // Add a screenshot reporter and store screenshots to `result/screnshots`: jasmine.getEnv().addReporter(new HtmlReporter({ baseDirectory: './result/screenshots', takeScreenShotsOnlyForFailedSpecs: true, preserveDirectory: true, docTitle: 'E2E Result', docName: 'index.html', pathBuilder: function pathBuilder(spec, descriptions, results, capabilities) { var currentDate = new Date(), dateString = currentDate.getFullYear() + '-' + currentDate.getMonth() + '-' + currentDate.getDate(); return path.join(dateString, capabilities.caps_.browserName, descriptions.join('-')); } })); } };
rajanmayekar/e2e-protractor-setup
protractor.conf.js
JavaScript
mit
1,883
import express = require("express"); import passport = require('passport'); import jwt = require('express-jwt'); import AuthController = require("../../controllers/AuthController"); import IUser = require('../../app/model/interfaces/IUser'); import User = require('../../app/model/User'); var router = express.Router(); var auth = jwt({ secret: 'SECRET', userProperty: 'payload' }); class AuthRoutes { private _authController: AuthController; constructor() { this._authController = new AuthController(); } get routes() { var controller = this._authController; router.get("/", auth, controller.getAuthenticatedUser); router.post("/", controller.authenticate); router.get("/check", auth, controller.checkAuth); return router; } } Object.seal(AuthRoutes); export = AuthRoutes;
teengoz/inventory-management
server/src/config/routes/AuthRoutes.ts
TypeScript
mit
850
from bioscrape.inference import DeterministicLikelihood as DLL from bioscrape.inference import StochasticTrajectoriesLikelihood as STLL from bioscrape.inference import StochasticTrajectories from bioscrape.inference import BulkData import warnings import numpy as np class PIDInterface(): ''' PID Interface : Parameter identification interface. Super class to create parameter identification (PID) interfaces. Two PID interfaces currently implemented: Deterministic and Stochastic inference using time-series data. To add a new PIDInterface - simply add a new subclass of this parent class with your desired log-likelihood functions. You can even have your own check_prior function in that class if you do not prefer to use the built in priors with this package. ''' def __init__(self, params_to_estimate, M, prior): ''' Parent class for all PID interfaces. Arguments: * `params_to_estimate` : List of parameter names to be estimated * `M` : The bioscrape Model object to use for inference * `prior` : A dictionary specifying prior distribution. Two built-in prior functions are `uniform_prior` and `gaussian_prior`. Each prior has its own syntax for accepting the distribution parameters in the dictionary. New priors may be added. The suggested format for prior dictionaries: prior_dict = {'parameter_name': ['prior_name', prior_distribution_parameters]} For built-in uniform prior, use {'parameter_name':['uniform', lower_bound, upper_bound]} For built-in gaussian prior, use {'parameter_name':['gaussian', mean, standard_deviation, probability threshold]} New PID interfaces can be added by creating child classes of PIDInterface class as shown for Built-in PID interfaces : `StochasticInference` and `DeterministicInference` ''' self.params_to_estimate = params_to_estimate self.M = M self.prior = prior return def check_prior(self, params_dict): ''' To add new prior functions: simply add a new function similar to ones that exist and then call it here. ''' lp = 0.0 for key,value in params_dict.items(): if 'positive' in self.prior[key] and value < 0: return np.inf prior_type = self.prior[key][0] if prior_type == 'uniform': lp += self.uniform_prior(key, value) elif prior_type == 'gaussian': lp += self.gaussian_prior(key, value) elif prior_type == 'exponential': lp += self.exponential_prior(key, value) elif prior_type == 'gamma': lp += self.gamma_prior(key, value) elif prior_type == 'log-uniform': lp += self.log_uniform_prior(key, value) elif prior_type == 'log-gaussian': lp += self.log_gaussian_prior(key, value) elif prior_type == 'beta': lp += self.beta_prior(key, value) elif prior_type == 'custom': # The last element in the prior dictionary must be a callable function # The callable function shoud have the following signature : # Arguments: param_name (str), param_value(float) # Returns: log prior probability (float or numpy inf) custom_fuction = self.prior[key][-1] lp += custom_fuction(key, value) else: raise ValueError('Prior type undefined.') return lp def uniform_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns np.Inf if the param_value is outside the prior range and 0.0 if it is inside. param_name is used to look for the parameter in the prior dictionary. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') lower_bound = prior_dict[param_name][1] upper_bound = prior_dict[param_name][2] if param_value > upper_bound or param_value < lower_bound: return np.inf else: return np.log( 1/(upper_bound - lower_bound) ) def gaussian_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.Inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') mu = prior_dict[param_name][1] sigma = prior_dict[param_name][2] if sigma < 0: raise ValueError('The standard deviation must be positive.') # Using probability density function for normal distribution # Using scipy.stats.norm has overhead that affects speed up to 2x prob = 1/(np.sqrt(2*np.pi) * sigma) * np.exp(-0.5*(param_value - mu)**2/sigma**2) if prob < 0: warnings.warn('Probability less than 0 while checking Gaussian prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def exponential_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') lambda_p = prior_dict[param_name][1] prob = lambda_p * np.exp(-lambda_p * param_value) if prob < 0: warnings.warn('Probability less than 0 while checking Exponential prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def gamma_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') alpha = prior_dict[param_name][1] beta = prior_dict[param_name][2] from scipy.special import gamma prob = (beta**alpha)/gamma(alpha) * param_value**(alpha - 1) * np.exp(-1 * beta*param_value) if prob < 0: warnings.warn('Probability less than 0 while checking Exponential prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def beta_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') alpha = prior_dict[param_name][1] beta = prior_dict[param_name][2] import scipy.special.beta as beta_func prob = (param_value**(alpha-1) * (1 - param_value)**(beta - 1) )/beta_func(alpha, beta) if prob < 0: warnings.warn('Probability less than 0 while checking Exponential prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def log_uniform_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') lower_bound = prior_dict[param_name][1] upper_bound = prior_dict[param_name][2] if lower_bound < 0 or upper_bound < 0: raise ValueError('Upper and lower bounds for log-uniform prior must be positive.') if param_value > upper_bound or param_value < lower_bound: return np.inf prob = 1/(param_value* (np.log(upper_bound) - np.log(lower_bound))) if prob < 0: warnings.warn('Probability less than 0 while checking Log-Uniform prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def log_gaussian_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') mu = prior_dict[param_name][1] sigma = prior_dict[param_name][2] if sigma < 0: raise ValueError('The standard deviation must be positive.') # Using probability density function for log-normal distribution prob = 1/(param_value * np.sqrt(2*np.pi) * sigma) * np.exp((-0.5 * (np.log(param_value) - mu)**2)/sigma**2) if prob < 0: warnings.warn('Probability less than 0 while checking log-normal prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) # Add a new class similar to this to create new interfaces. class StochasticInference(PIDInterface): def __init__(self, params_to_estimate, M, prior): self.LL_stoch = None self.dataStoch = None super().__init__(params_to_estimate, M, prior) return def setup_likelihood_function(self, data, timepoints, measurements, initial_conditions, norm_order = 2, N_simulations = 3, debug = False, **kwargs): N = np.shape(data)[0] if debug: print('Stochastic inference attributes:') print('The timepoints shape is {0}'.format(np.shape(timepoints))) print('The data shape is {0}'.format(np.shape(data))) print('The measurmenets is {0}'.format(measurements)) print('The N is {0}'.format(N)) print('Using the initial conditions: {0}'.format(initial_conditions)) self.dataStoch = StochasticTrajectories(np.array(timepoints), data, measurements, N) #If there are multiple initial conditions in a data-set, should correspond to multiple initial conditions for inference. #Note len(initial_conditions) must be equal to the number of trajectories N self.LL_stoch = STLL(model = self.M, init_state = initial_conditions, data = self.dataStoch, N_simulations = N_simulations, norm_order = norm_order) def get_likelihood_function(self, params): # Set params here and return the likelihood object. if self.LL_stoch is None: raise RuntimeError("Must call StochasticInference.setup_likelihood_function before using StochasticInference.get_likelihood_function.") #Set params params_dict = {} for key, p in zip(self.params_to_estimate, params): params_dict[key] = p self.LL_stoch.set_init_params(params_dict) #Prior lp = self.check_prior(params_dict) if not np.isfinite(lp): return -np.inf LL_stoch_cost = self.LL_stoch.py_log_likelihood() ln_prob = lp + LL_stoch_cost return ln_prob # Add a new class similar to this to create new interfaces. class DeterministicInference(PIDInterface): def __init__(self, params_to_estimate, M, prior): self.LL_det = None self.dataDet = None super().__init__(params_to_estimate, M, prior) return def setup_likelihood_function(self, data, timepoints, measurements, initial_conditions, norm_order = 2, debug = False, **kwargs): N = np.shape(data)[0] #Create a data Objects # In this case the timepoints should be a list of timepoints vectors for each iteration self.dataDet = BulkData(np.array(timepoints), data, measurements, N) #If there are multiple initial conditions in a data-set, should correspond to multiple initial conditions for inference. #Note len(initial_conditions) must be equal to the number of trajectories N if debug: print('The deterministic inference attributes:') print('The timepoints shape is {0}'.format(np.shape(timepoints))) print('The data shape is {0}'.format(np.shape(data))) print('The measurmenets is {0}'.format(measurements)) print('The N is {0}'.format(N)) print('Using the initial conditions: {0}'.format(initial_conditions)) #Create Likelihood object self.LL_det = DLL(model = self.M, init_state = initial_conditions, data = self.dataDet, norm_order = norm_order) def get_likelihood_function(self, params): if self.LL_det is None: raise RuntimeError("Must call DeterministicInference.setup_likelihood_function before using DeterministicInference.get_likelihood_function.") #this part is the only part that is called repeatedly params_dict = {} for key, p in zip(self.params_to_estimate, params): params_dict[key] = p self.LL_det.set_init_params(params_dict) # Check prior lp = 0 lp = self.check_prior(params_dict) if not np.isfinite(lp): return -np.inf #apply cost function LL_det_cost = self.LL_det.py_log_likelihood() ln_prob = lp + LL_det_cost return ln_prob
ananswam/bioscrape
bioscrape/pid_interfaces.py
Python
mit
13,998
/** * format currency * @ndaidong **/ const { isNumber, } = require('bellajs'); const formatCurrency = (num) => { const n = Number(num); if (!n || !isNumber(n) || n < 0) { return '0.00'; } return n.toFixed(2).replace(/./g, (c, i, a) => { return i && c !== '.' && (a.length - i) % 3 === 0 ? ',' + c : c; }); }; module.exports = formatCurrency;
ndaidong/paypal-nvp-api
src/helpers/formatCurrency.js
JavaScript
mit
369
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using FilesToDatabaseImporter.Annotations; using FilesToDatabaseImporter.Helpers; using FilesToDatabaseImporter.Interfaces; namespace FilesToDatabaseImporter.ViewModels { public class SqlServerViewModel : INotifyPropertyChanged, IDataErrorInfo { private string _datasource; public string Datasource { get { return _datasource; } set { if (value == _datasource) return; _datasource = value; DatabaseHelper.SqlConnectionStringBuilder.DataSource = _datasource; OnPropertyChanged(); } } private string _username; public string Username { get { return _username; } set { if (value == _username) return; _username = value; if (!IntegratedSecurity) { DatabaseHelper.SqlConnectionStringBuilder.UserID = _username; } else { DatabaseHelper.SqlConnectionStringBuilder.UserID = null; } OnPropertyChanged(); } } private string _password; public string Password { get { return _password; } set { if (value == _password) return; _password = value; if (!IntegratedSecurity) { DatabaseHelper.SqlConnectionStringBuilder.Password = _password; } else { DatabaseHelper.SqlConnectionStringBuilder.Password = null; } OnPropertyChanged(); } } private string _database; public string Database { get { return _database; } set { if (value == _database) return; _database = value; DatabaseHelper.SqlConnectionStringBuilder.InitialCatalog = _database; OnPropertyChanged(); } } private string _table; public string Table { get { return _table; } set { if (value == _table) return; _table = value; DatabaseHelper.SetTable(_table); OnPropertyChanged(); } } private bool _integratedSecurity; public bool IntegratedSecurity { get { return _integratedSecurity; } set { if (value.Equals(_integratedSecurity)) return; _integratedSecurity = value; DatabaseHelper.SqlConnectionStringBuilder.IntegratedSecurity = _integratedSecurity; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Username")); PropertyChanged(this, new PropertyChangedEventArgs("Password")); } OnPropertyChanged(); } } private IDatabaseHelper _databaseHelper; public IDatabaseHelper DatabaseHelper { get { return _databaseHelper; } set { _databaseHelper = value; } } public SqlServerViewModel(IDatabaseHelper databaseHelper = null) { _databaseHelper = databaseHelper; IntegratedSecurity = true; Database = "FilesToDatabaseImporter"; Table = "Imports"; } public SqlServerViewModel() : this(new DatabaseHelper()) { } #region IDataErrorInfo private bool _canSave; public bool CanSave { get { return _canSave; } set { if (value.Equals(_canSave)) return; _canSave = value; OnPropertyChanged(); } } private readonly Dictionary<string, string> _errors = new Dictionary<string, string>(); string IDataErrorInfo.this[string propertyName] { get { var error = ""; if (propertyName == "Datasource") { if (string.IsNullOrEmpty(Datasource)) { error = "Datasource is mandatory"; } } if (propertyName == "Database") { if (string.IsNullOrEmpty(Database)) { error = "Database is mandatory"; } } if (propertyName == "Username") { if (string.IsNullOrEmpty(Username) && !IntegratedSecurity) { error = "Username is mandatory when SQL Authentication is used"; } } if (propertyName == "Password") { if (string.IsNullOrEmpty(Password) && !IntegratedSecurity) { error = "Password is mandatory when SQL Authentication is used"; } } if (propertyName == "Table") { if (string.IsNullOrEmpty(Table)) { error = "Table is mandatory"; } } if (_errors.ContainsKey(propertyName) && string.IsNullOrEmpty(error)) { _errors.Remove(propertyName); } if (!_errors.ContainsKey(propertyName) && !string.IsNullOrEmpty(error)) { _errors[propertyName] = error; } CanSave = !_errors.Any(); return error; } } public string Error { get { throw new NotImplementedException(); } } #endregion #region INPC public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
JeroenVinke/FilesToDatabaseImporter
FilesToDatabaseImporter/ViewModels/SqlServerViewModel.cs
C#
mit
6,773
<upgrade> <phpfox_update_settings> <setting> <group>server_settings</group> <module_id>log</module_id> <is_hidden>0</is_hidden> <type>integer</type> <var_name>active_session</var_name> <phrase_var_name>setting_active_session</phrase_var_name> <ordering>2</ordering> <version_id>2.0.0alpha1</version_id> <value>15</value> </setting> </phpfox_update_settings> <components> <component> <module_id>log</module_id> <component>users</component> <m_connection /> <module>log</module> <is_controller>0</is_controller> <is_block>1</is_block> <is_active>1</is_active> <value /> </component> </components> <blocks> <block> <type_id>0</type_id> <m_connection>forum.index</m_connection> <module_id>log</module_id> <component>active-users</component> <location>1</location> <is_active>1</is_active> <ordering>6</ordering> <disallow_access /> <can_move>0</can_move> <title>Users Online</title> <source_code /> <source_parsed /> </block> </blocks> <phpfox_update_blocks> <block> <type_id>0</type_id> <m_connection>core.index-member</m_connection> <module_id>log</module_id> <component>login</component> <location>1</location> <is_active>1</is_active> <ordering>3</ordering> <disallow_access /> <can_move>1</can_move> <title /> <source_code /> <source_parsed /> </block> <block> <type_id>0</type_id> <m_connection>core.index-visitor</m_connection> <module_id>log</module_id> <component>login</component> <location>1</location> <is_active>0</is_active> <ordering>6</ordering> <disallow_access /> <can_move>0</can_move> <title>Recent Logins</title> <source_code /> <source_parsed /> </block> </phpfox_update_blocks> </upgrade>
edbiler/BazaarCorner
module/log/install/version/3.0.0beta1.xml.php
PHP
mit
1,794
import React from 'react' import PropTypes from 'prop-types' import FormGroup from '../forms/FormGroup' import InputColor from '../forms/InputColor' const ColorStackOption = ({ label, name, value, definitions, required, onChange, error }) => { // default value may be null if (value === null) { value = '' } return ( <FormGroup label={label} htmlFor={name} error={error} required={required}> <InputColor name={name} id={name} value={value} defaultValue={definitions.default} onChange={onChange} /> </FormGroup> ) } ColorStackOption.propTypes = { label: PropTypes.string.isRequired, name: PropTypes.string.isRequired, definitions: PropTypes.object.isRequired, required: PropTypes.bool, value: PropTypes.string, onChange: PropTypes.func, error: PropTypes.string } export default ColorStackOption
rokka-io/rokka-dashboard
src/components/options/ColorStackOption.js
JavaScript
mit
884
import * as React from 'react'; import './TextBox.css'; interface Props { className: string; onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void; placeholder: string; } class TextBox extends React.Component<Props, {}> { public constructor(props: Props) { super(props); this.handleChange = this.handleChange.bind(this); } private handleChange(e: React.ChangeEvent<HTMLInputElement>) { if (this.props.onChange) { this.props.onChange(e); } return false; } public render() { return ( <input className={this.props.className} placeholder={this.props.placeholder} onChange={this.handleChange} /> ); } } export default TextBox;
Chingu-Dolphins-3/9ball-scoring-app
client/src/components/TextBox/TextBox.tsx
TypeScript
mit
723
using System; using System.Threading; using System.Threading.Tasks; namespace Tmds.DBus.Tests { class PingPong : IPingPong { public static readonly ObjectPath Path = new ObjectPath("/tmds/dbus/tests/pingpong"); public event Action<string> OnPing; public event Action OnPingNoArg; public Task PingAsync(string message) { OnPing?.Invoke(message); OnPingNoArg?.Invoke(); return Task.CompletedTask; } public Task<string> EchoAsync(string message) { return Task.FromResult(message); } public Task<IDisposable> WatchPongAsync(Action<string> reply) { return SignalWatcher.AddAsync(this, nameof(OnPing), reply); } public Task<IDisposable> WatchPongNoArgAsync(Action reply) { return SignalWatcher.AddAsync(this, nameof(OnPingNoArg), reply); } public Task<IDisposable> WatchPongWithExceptionAsync(Action<string> reply, Action<Exception> ex) { return SignalWatcher.AddAsync(this, nameof(OnPing), reply); } public ObjectPath ObjectPath { get { return Path; } } } }
tmds/Tmds.DBus
test/Tmds.DBus.Tests/PingPong.cs
C#
mit
1,208
from flask_bcrypt import generate_password_hash # Change the number of rounds (second argument) until it takes between # 0.25 and 0.5 seconds to run. generate_password_hash('password1', 8)
VaSe7u/Supernutrient_0_5
hash_check.py
Python
mit
195
<?php defined('SYSPATH') OR die('No direct script access.'); /** * Grid modeling library for creating data tables * * @package Grid * @author Kyle Treubig * @copyright (C) 2010 Kyle Treubig * @license MIT */ class Grid_Core { /** Array of table columns */ private $columns = array(); /** Array of action links */ private $links = array(); /** Table dataset */ private $dataset = array(); /** * Add a column to the table * * @param string [optional] column type * @return Grid_Column */ public function &column($type='text') { $model = 'Grid_Column_' . ucfirst($type); $column = new $model; $index = count($this->columns); array_push($this->columns, $column); Kohana::$log->add(Kohana::DEBUG, 'Added '.$type.' column to grid'); return $this->columns[$index]; } /** * Add an action link to the table * * @param string [optional] link type * @return Grid_Link */ public function &link($type='text') { $link = new Grid_Link($type); $index = count($this->links); array_push($this->links, $link); Kohana::$log->add(Kohana::DEBUG, 'Added '.$type.' link to grid'); return $this->links[$index]; } /** * Add data to the table * * @param array collection of dataset records * @return Grid */ public function data($resource) { $dataset = array(); foreach($resource as $data) { $dataset[] = $data; } array_splice($this->dataset, count($this->dataset), 0, $dataset); Kohana::$log->add(Kohana::DEBUG, 'Added data to grid'); return $this; } /** * Render the table as an HTML string * * @param string [optional] view file * @return string */ public function render($view = 'grid/table') { $view = View::factory($view); $view->columns = $this->columns; $view->links = $this->links; $view->dataset = $this->dataset; Kohana::$log->add(Kohana::DEBUG, 'Rendering the grid'); return $view->render(); } /** * Alias for Grid::render() */ public function __tostring() { return $this->render(); } }
vimofthevine/grid
classes/grid/core.php
PHP
mit
2,048
package cn.honjow.leanc.ui.Fragment; import cn.honjow.leanc.adapter.QuestionListAdapter; import cn.honjow.leanc.ui.Activice.ChoQueActivity; import cn.droidlover.xdroidmvp.base.SimpleRecAdapter; import cn.honjow.leanc.model.QuestionItem; import cn.honjow.leanc.ui.BaseLeancFragment; import cn.droidlover.xrecyclerview.RecyclerItemCallback; import cn.droidlover.xrecyclerview.XRecyclerView; /** * Created by honjow311 on 2017/5/17. */ public class ChoQueListFragment extends BaseLeancFragment { QuestionListAdapter adapter; @Override public SimpleRecAdapter getAdapter() { if (adapter == null) { adapter = new QuestionListAdapter(context); adapter.setRecItemClick(new RecyclerItemCallback<QuestionItem, QuestionListAdapter.ViewHolder>() { @Override public void onItemClick(int position, QuestionItem model, int tag, QuestionListAdapter.ViewHolder holder) { super.onItemClick(position, model, tag, holder); switch (tag) { case QuestionListAdapter.TAG_VIEW: ChoQueActivity.launch(context, model); break; } } }); } return adapter; } @Override public void setLayoutManager(XRecyclerView recyclerView) { recyclerView.verticalLayoutManager(context); } @Override public String getType() { return "1"; } public static ChoQueListFragment newInstance() { return new ChoQueListFragment(); } }
honjow/XDroidMvp_hzw
app/src/main/java/cn/honjow/leanc/ui/Fragment/ChoQueListFragment.java
Java
mit
1,611
<?php namespace JHWEB\SeguridadVialBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * SvCfgTipoVictima * * @ORM\Table(name="sv_cfg_tipo_victima") * @ORM\Entity(repositoryClass="JHWEB\SeguridadVialBundle\Repository\SvCfgTipoVictimaRepository") */ class SvCfgTipoVictima { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nombre", type="string", nullable= true) */ private $nombre; /** * @var bool * * @ORM\Column(name="activo", type="boolean", nullable=true) */ private $activo; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * * @return SvCfgTipoVictima */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set activo * * @param boolean $activo * * @return SvCfgTipoVictima */ public function setActivo($activo) { $this->activo = $activo; return $this; } /** * Get activo * * @return boolean */ public function getActivo() { return $this->activo; } }
edosgn/colossus-sit
src/JHWEB/SeguridadVialBundle/Entity/SvCfgTipoVictima.php
PHP
mit
1,536
// (C) 2004 by Khaled Daham, <khaled@w-arts.com> // // Singleton // #include <iterator> #include "Log.h" #include <stdio.h> #include <stdarg.h> #include <windows.h> namespace ps2emu { typedef std::map<int32, std::string>::iterator m_mapIterator; /////////////////////////////// PUBLIC /////////////////////////////////////// Log* Log::_instance = 0; Log* Log::Instance() { if(_instance == 0) { _instance = new Log; } return _instance; } void Log::Error(const std::string& message) { OutputDebugStringA(message.c_str()); } void Log::Error(const int32 errNumber) { } void Log::Error(const int32 errNumber, const std::string& message) { OutputDebugStringA(message.c_str()); } void Log::Warning(const std::string& message) { if ( !(message == *m_pLastMessage) ) { m_numLastMessage++; return; } OutputDebugStringA(message.c_str()); return; } void Log::Warning(const int32 errNumber) { return; } void Log::Trace(const std::string& message) { //OutputDebugStringA(message.c_str()); return; } void Log::Trace(int32 level, const std::string& message) { if (!m_isTraceActive) return; switch(level) { case 0: //m_pOut->AppendText(message); break; case 1: //m_pOut->AppendText(" " + message); break; case 2: //m_pOut->AppendText(" " + message); break; case 3: //m_pOut->AppendText(" " + message); break; default: //m_pOut->AppendText(message); break; } //OutputDebugStringA(message.c_str()); return; } void Log::SetTextCtrl(wxTextCtrl* out) { return; } std::string Log::Format(const char* fmt, ... ) { va_list args; char message[512]; va_start(args, fmt); vsnprintf(message, 512, fmt, args); va_end(args); std::string out(message); return out; } /////////////////////////////// PRIVATE /////////////////////////////////////// Log::Log() : m_isTraceActive(true), m_oldTraceState(true) { m_numLastMessage = 0; m_pLastMessage = new std::string(); object.insert(std::pair<int32, std::string>(0, "")); object.insert(std::pair<int32, std::string>(E_TIMEOUT, "Operation timed out")); object.insert(std::pair<int32, std::string>(E_NO_LINK, "No connection to ps2link server")); object.insert(std::pair<int32, std::string>(E_SOCK_CLOSE, "Connection reset by peer")); object.insert(std::pair<int32, std::string>(E_FILE_OPEN, "Unable to open file")); object.insert(std::pair<int32, std::string>(E_FILE_READ, "Unable to read from file")); object.insert(std::pair<int32, std::string>(E_FILE_WRITE, "Unable to write to file")); object.insert(std::pair<int32, std::string>(E_FILE_EOF, "EOF reached")); object.insert(std::pair<int32, std::string>(E_VIF_DECODE, "Bad VIF code")); } Log::~Log() { } }
jsvennevid/tbl-4edges
Shared/External/ps2emu/Log.cpp
C++
mit
2,995
class Post < ActiveRecord::Base belongs_to :forum, :counter_cache => true belongs_to :user, :counter_cache => true belongs_to :topic, :counter_cache => true has_one :event_log, :as => :target, :dependent => :destroy acts_as_ferret :fields => ['company_id', 'project_id', 'body', 'forum_id'] format_attribute :body before_create { |r| r.forum_id = r.topic.forum_id } after_create { |r| Topic.update_all(['replied_at = ?, replied_by = ?, last_post_id = ?', r.created_at, r.user_id, r.id], ['id = ?', r.topic_id]) if r.id l = r.create_event_log l.company_id = r.company_id l.project_id = r.project_id l.user_id = r.user_id l.event_type = EventLog::FORUM_NEW_POST l.created_at = r.created_at l.save end } after_destroy { |r| t = Topic.find(r.topic_id) ; Topic.update_all(['replied_at = ?, replied_by = ?, last_post_id = ?', t.posts.last.created_at, t.posts.last.user_id, t.posts.last.id], ['id = ?', t.id]) if t.posts.last } validates_presence_of :user_id, :body, :topic attr_accessible :body def editable_by?(user) user && (user.id == user_id || (user.admin? && topic.forum.company_id == user.company_id) || user.admin > 2 || user.moderator_of?(topic.forum_id)) end def to_xml(options = {}) options[:except] ||= [] options[:except] << :topic_title << :forum_name super end def company_id self.forum.company_id end def project_id self.forum.project_id end def started_at self.created_at end end
SpiderJack/cit
app/models/post.rb
Ruby
mit
1,537
<?php namespace UserBundle\Security; use Symfony\Component\DependencyInjection\ContainerInterface as Container; use Symfony\Component\Routing\Router; class GoogleService { protected $container; protected $router; protected $redirectRouteName = 'google_check'; protected $scopes = ['email', 'profile']; /** * GoogleService constructor. * @param Router $router * @param Container $container */ public function __construct(Router $router, Container $container) { $this->router = $router; $this->container = $container; } public function init() { $client = new \Google_Client( [ 'client_id' => $this->container->getParameter('google_client_id'), 'client_secret' => $this->container->getParameter('google_client_secret'), ] ); $client->setRedirectUri($this->generateRedirectUrl()); $client->setScopes($this->scopes); return $client; } protected function generateRedirectUrl() { return $this->router->generate($this->redirectRouteName, [], true); } }
KriBetko/rating.npu
src/UserBundle/Security/GoogleService.php
PHP
mit
1,146
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Querify.Advanced { public static class AdvancedQueryableExtensions { public interface IAdvancedQueryable<out T> { IQueryable<T> Query { get; } } private class AdvancedQueryableAdapter<T> : IAdvancedQueryable<T> { public AdvancedQueryableAdapter(IQueryable<T> query) { Query = query; } public IQueryable<T> Query { get; private set; } } public static IAdvancedQueryable<T> Advanced<T>(this IQueryable<T> queryable) { return new AdvancedQueryableAdapter<T>(queryable); } /// <summary> /// Fetches all items of the specified type using the <value>QueryableExtensions.MaxPageSize</value> for paging /// </summary> /// <typeparam name="T">The type of the items to retrieve</typeparam> /// <param name="queryable"></param> /// <returns></returns> public static IEnumerable<T> FetchAll<T>(this IAdvancedQueryable<T> queryable) { return FetchAll(queryable, null); } /// <summary> /// Fetches all items of the specified type matching the supplied expression using the <value>QueryableExtensions.MaxPageSize</value> for paging /// </summary> /// <typeparam name="T">The type of the items to retrieve</typeparam> /// <param name="queryable"></param> /// <param name="expression"></param> /// <returns></returns> public static IEnumerable<T> FetchAll<T>(this IAdvancedQueryable<T> queryable, Expression<Func<T, bool>> expression) { var page = 1; var lastPage = 1; while (page <= lastPage) { var result = queryable.Query.Find(expression, page, QueryableExtensions.MaxPageSize); foreach (var item in result.Items) { yield return item; } page++; lastPage = result.TotalPages; } } /// <summary> /// Performs an action on all items of the specified type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <param name="action"></param> /// <param name="pageSize"></param> public static void ExecuteForAll<T>(this IAdvancedQueryable<T> queryable, Action<T> action, int pageSize = QueryableExtensions.DefaultPageSize) { queryable.ExecuteForAll(action, null, pageSize); } /// <summary> /// Performs an action on all items of the specified type matching the supplied expression /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <param name="action"></param> /// <param name="expression"></param> /// <param name="pageSize"></param> public static void ExecuteForAll<T>(this IAdvancedQueryable<T> queryable, Action<T> action, Expression<Func<T, bool>> expression, int pageSize = QueryableExtensions.DefaultPageSize) { var lastPage = 1; do { var results = queryable .Query .Find(expression, lastPage, pageSize); foreach (var item in results.Items) { action(item); } if (results.TotalItems == 0 || results.TotalPages == lastPage) { break; } lastPage++; } while (true); } } }
Lotpath/Querify
src/Querify/Advanced/AdvancedQueryableExtensions.cs
C#
mit
3,810
<?php $gameinfos = array( // Game designer (or game designers, separated by commas) 'designer' => 'Bruno Faidutti, Alan R. Moon', // Game artist (or game artists, separated by commas) 'artist' => 'Matthias Catrein, Paul Mafayon', // Year of FIRST publication of this game. Can be negative. 'year' => 2006, // Game publisher 'publisher' => ' Eagle-Gryphon Games', // Url of game publisher website 'publisher_website' => 'http://www.eaglegames.net/product-p/101171.htm', // Board Game Geek ID of the publisher 'publisher_bgg_id' => 597, // Board game geek if of the game 'bgg_id' => 37759, // Players configuration that can be played (ex: 2 to 4 players) 'players' => array( 3,4,5,6,7,8 ), // Suggest players to play with this number of players. Must be null if there is no such advice, or if there is only one possible player configuration. 'suggest_player_number' => 6, // Discourage players to play with these numbers of players. Must be null if there is no such advice. 'not_recommend_player_number' => null, // 'not_recommend_player_number' => array( 2, 3 ), // <= example: this is not recommended to play this game with 2 or 3 players // Estimated game duration, in minutes (used only for the launch, afterward the real duration is computed) 'estimated_duration' => 30, // Time in second add to a player when "giveExtraTime" is called (speed profile = fast) 'fast_additional_time' => 20, // Time in second add to a player when "giveExtraTime" is called (speed profile = medium) 'medium_additional_time' => 30, // Time in second add to a player when "giveExtraTime" is called (speed profile = slow) 'slow_additional_time' => 30, // If you are using a tie breaker in your game (using "player_score_aux"), you must describe here // the formula used to compute "player_score_aux". This description will be used as a tooltip to explain // the tie breaker to the players. // Note: if you are NOT using any tie breaker, leave the empty string. // // Example: 'tie_breaker_description' => totranslate( "Number of remaining cards in hand" ), 'tie_breaker_description' => totranslate( "Ties are decided by the number of artifacts each player holds" ) , // Game is "beta". A game MUST set is_beta=1 when published on BGA for the first time, and must remains like this until all bugs are fixed. 'is_beta' => 1, // Is this game cooperative (all players wins together or loose together) 'is_coop' => 0, // Complexity of the game, from 0 (extremely simple) to 5 (extremely complex) 'complexity' => 1, // Luck of the game, from 0 (absolutely no luck in this game) to 5 (totally luck driven) 'luck' => 4, // Strategy of the game, from 0 (no strategy can be setup) to 5 (totally based on strategy) 'strategy' => 2, // Diplomacy of the game, from 0 (no interaction in this game) to 5 (totally based on interaction and discussion between players) 'diplomacy' => 0, // Games categories // You can attribute any number of "tags" to your game. // Each tag has a specific ID (ex: 22 for the category "Prototype", 101 for the tag "Science-fiction theme game") 'tags' => array( 2,103,209 ) );
AntonioSoler/bga-incangold
gameinfos.inc.php
PHP
mit
3,249
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # 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. """ Module for main window related functionality """ import PyQt4.QtGui from herculeum.ui.controllers import EndScreenController, StartGameController from herculeum.ui.gui.endscreen import EndScreen from herculeum.ui.gui.eventdisplay import EventMessageDockWidget from herculeum.ui.gui.map import PlayMapWindow from herculeum.ui.gui.menu import MenuDialog from herculeum.ui.gui.startgame import StartGameWidget from PyQt4.QtCore import QFile, Qt from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon, QMainWindow, QPixmap, QSplashScreen) class QtUserInterface(): """ Class for Qt User Interface .. versionadded:: 0.9 """ def __init__(self, application): """ Default constructor """ super().__init__() self.application = application self.splash_screen = None self.qt_app = QApplication([]) # self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor)) def show_splash_screen(self): """ Show splash screen """ file = QFile(':herculeum.qss') file.open(QFile.ReadOnly) styleSheet = str(file.readAll().data(), 'ascii') self.qt_app.setStyleSheet(styleSheet) pixmap = QPixmap(':splash.png') self.splash_screen = QSplashScreen(pixmap) self.splash_screen.show() def show_main_window(self): """ Show main window """ main_window = MainWindow(self.application, self.application.surface_manager, self.qt_app, None, Qt.FramelessWindowHint, StartGameController(self.application.level_generator_factory, self.application.creature_generator, self.application.item_generator, self.application.config.start_level)) self.splash_screen.finish(main_window) main_window.show_new_game() self.qt_app.exec_() class MainWindow(QMainWindow): """ Class for displaying main window .. versionadded:: 0.5 """ def __init__(self, application, surface_manager, qt_app, parent, flags, controller): """ Default constructor """ super().__init__(parent, flags) self.application = application self.surface_manager = surface_manager self.qt_app = qt_app self.controller = controller self.__set_layout() def __set_layout(self): exit_action = QAction(QIcon(':exit-game.png'), '&Quit', self) exit_action.setShortcut('Ctrl+Q') exit_action.setStatusTip('Quit game') exit_action.triggered.connect(PyQt4.QtGui.qApp.quit) inventory_action = QAction(QIcon(':inventory.png'), 'Inventory', self) inventory_action.setShortcut('Ctrl+I') inventory_action.setStatusTip('Show inventory') inventory_action.triggered.connect(self.__show_menu) character_action = QAction(QIcon(':character.png'), 'Character', self) character_action.setShortcut('Ctrl+C') character_action.setStatusTip('Show character') self.map_window = PlayMapWindow(parent=None, model=self.application.world, surface_manager=self.surface_manager, action_factory=self.application.action_factory, rng=self.application.rng, rules_engine=self.application.rules_engine, configuration=self.application.config) self.setCentralWidget(self.map_window) self.map_window.MenuRequested.connect(self.__show_menu) self.map_window.EndScreenRequested.connect(self.__show_end_screen) self.setGeometry(50, 50, 800, 600) self.setWindowTitle('Herculeum') self.setWindowIcon(QIcon(':rune-stone.png')) self.showMaximized() def show_new_game(self): """ Show new game dialog """ app = self.application start_dialog = StartGameWidget(generator=app.player_generator, config=self.application.config.controls, parent=self, application=self.application, surface_manager=self.surface_manager, flags=Qt.Dialog | Qt.CustomizeWindowHint) result = start_dialog.exec_() if result == QDialog.Accepted: player = start_dialog.player_character intro_text = self.controller.setup_world(self.application.world, player) player.register_for_updates(self.map_window.hit_points_widget) self.map_window.hit_points_widget.show_hit_points(player) self.map_window.hit_points_widget.show_spirit_points(player) self.map_window.message_widget.text_edit.setText(intro_text) self.__show_map_window() def __show_map_window(self): """ Show map window """ self.map_window.construct_scene() def __show_message_window(self, character): """ Show message display :param character: character which events to display :type character: Character """ messages_display = EventMessageDockWidget(self, character) self.addDockWidget(Qt.BottomDockWidgetArea, messages_display) def __show_menu(self): """ Show menu """ menu_dialog = MenuDialog(self.surface_manager, self.application.world.player, self.application.action_factory, self.application.config.controls, self, Qt.Dialog | Qt.CustomizeWindowHint) menu_dialog.exec_() def __show_end_screen(self): """ Show end screen .. versionadded:: 0.8 """ end_screen = EndScreen(self.application.world, self.application.config.controls, self, Qt.Dialog | Qt.CustomizeWindowHint, controller=EndScreenController()) end_screen.exec_() self.qt_app.quit()
tuturto/pyherc
src/herculeum/ui/gui/mainwindow.py
Python
mit
8,099
<?php namespace Anax\Comments; /** * A controller for comments and such events. */ class CommentsController implements \Anax\DI\IInjectionAware { use \Anax\DI\TInjectable; /** * Initialize the controller. * * @return void */ public function initialize() { $this->comments = new \Anax\Comments\Comment(); $this->comments->setDI($this->di); $this->users = new \Anax\Users\User(); $this->users->setDI($this->di); $this->scores = new \KGW\Discussion\Score(); $this->scores->setDI($this->di); } /** * List all comments. * * @return void */ public function viewAction($key = null, $type = null, $redirect = '') { $this->initialize(); $comments = $this->comments->findAll($key, $type); $user = $this->users; if ($this->di->request->getGet('edit-comment')) { $commentId = $this->di->request->getGet('edit-comment'); for ($i = 0; $i < count($comments); $i++) { if ($comments[$i]->id == $commentId) { $url = current(explode('?', $this->di->request->getCurrentUrl())); $redirect = $this->url->create($url); if ($user->isAuthenticated() && ($user->isCurrentUser($comments[$i]->getProperties()['userId'] || $user->isAdmin()))) { $value = $comments[$i]->content; $updateForm = new \Anax\HTMLForm\CFormCommentEdit($commentId, $value, $redirect); $updateForm->setDI($this->di); $status = $updateForm->check(); $comments[$i] = $updateForm->getHTML(); } else { $this->response->redirect($url); } } } } $form = null; if ($user->isAuthenticated() && $this->di->request->getGet('comment-reply') != null) { $commentId = $this->di->request->getGet('comment-reply'); $commentType = $this->di->request->getGet('type'); if ($key == $commentId && $type == $commentType) { $form = new \Anax\HTMLForm\CFormCommentAdd($commentId, $commentType, $redirect); $form->setDI($this->di); $status = $form->check(); $form = $form->getHTML(); } } $scores = $this->scores; $this->views->add('comment/comments', [ 'comments' => $comments, 'questionId' => $key, 'type' => $type, 'user' => $user, 'scores' => $scores, 'form' => $form, ], 'main'); } /** * Edit a comment * *@return void */ public function editAction($id = null, $key = null, $type = null) { $comment = $this->comments->find($id); $now = gmdate('Y-m-d H:i:s'); if ($comment) { if ($this->users->isAuthenticated() && ($this->users->isCurrentUser($id) || $this->users->isAdmin())) { $value = $comment->getProperties()['content']; $redirect = ''; $form = new \Anax\HTMLForm\CFormCommentEdit($id, $value, $redirect); $form->setDI($this->di); $status = $form->check(); $this->views->add('comment/form',[ 'title' => "Uppdatera kommentar", 'content' => $form->getHTML(), ], 'main'); } } } /** * Deletes a comment * * @return void */ public function deleteAction($id = null) { if (!isset($id)) { die("Missing id"); } $res = $this->comments->delete($id); $this->response->redirect($this->request->getServer('HTTP_REFERER')); } /** * Delete all comments confirmation- * * @return void */ public function deleteAllCommentsAction() { $this->theme->setTitle("Radera samtliga kommentarer"); $this->views->add('comment/delete-comments', [], 'main'); } /** * Deletes all comments. * * @return void */ public function deleteAllAction() { $this->comments->deleteAll(); $url = $this->url->create('comments'); $this->response->redirect($url); } /** * Brings the setup confirmation. * * @return void */ public function setupCommentsAction() { $this->theme->setTitle("Återställ kommentarer"); $this->views->add('comment/setup-comments', [], 'main'); } /** * Used to setup the database to it's original condition. * * @return void */ public function setupAction() { $this->comments->setup(); } }
KarlGW/fo
src/Comments/CommentsController.php
PHP
mit
3,992
package joshie.progression.api.gui; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** Implement this on rewards, triggers, filters, conditions, * if you wish to draw something special on them, other than default fields. */ public interface ICustomDrawGuiDisplay { @SideOnly(Side.CLIENT) public void drawDisplay(IDrawHelper helper, int renderX, int renderY, int mouseX, int mouseY); }
joshiejack/Progression
src/main/java/joshie/progression/api/gui/ICustomDrawGuiDisplay.java
Java
mit
449
from utils.face import Face import pygame from utils.message import Message from utils.alarm import Alarm class Button(pygame.sprite.Sprite): def __init__(self, rect, color=(0,0,255), action=None): pygame.sprite.Sprite.__init__(self) self.color = color self.action = action self.rect = pygame.Rect(rect) self.baseImage = pygame.Surface((self.rect.width, self.rect.height)) self.image = self.baseImage def update(self): rect = self.baseImage.get_rect() pygame.draw.circle(self.baseImage, self.color, rect.center, rect.width/2, 1); def touchDown(self): rect = self.baseImage.get_rect() pygame.draw.circle(self.baseImage, self.color, rect.center, rect.width/2, 0); def touchUp(self): rect = self.baseImage.get_rect() self.image.fill(pygame.Color("black")) pygame.draw.circle(self.baseImage, self.color, rect.center, rect.width/2, 1); if self.action is not None: self.action() def setAction(self, action): self.action = action class Line(Face): def __init__(self, rect, color=(0,0,255), text=""): pygame.sprite.Sprite.__init__(self) self._alarmList = {} self.color = color self.rect = pygame.Rect(rect) self.text = text self.baseImage = pygame.Surface((self.rect.width, self.rect.height)) self.image = self.baseImage self.faceSprite = pygame.sprite.GroupSingle(Message((self.text,), vector=(0,0), fontsize=45, align="left", padding=0, fgcolor=(0,0,255))) surfaceRect = self.image.get_rect() self.faceSprite.sprite.rect.midleft = surfaceRect.midleft def update(self): self.faceSprite.draw(self.baseImage) class AlarmSetting(Face): def __init__(self, rect, alarm, color=(0,0,255)): pygame.sprite.Sprite.__init__(self) self._alarmList = {} if isinstance(alarm, Alarm): self._alarmObject = alarm else: raise Exception("Not an Alarm-class object") self.color = color self.rect = pygame.Rect(rect) self.requestingFace = False self.baseImage = pygame.Surface((self.rect.width, self.rect.height)) self.image = self.baseImage self._lines = [] for i in range(4): line = pygame.sprite.GroupSingle(Line(pygame.Rect((0, 0),(rect.height/5*4, rect.height/5)), text="Hello")) line.sprite.rect.topright = (rect.width, rect.height/4*i) self._lines.append(line) def addAlarm(self): line = pygame.sprite.GroupSingle(Button(pygame.Rect((0, 0),(self.rect.height/5, self.rect.height/5)))) line.sprite.rect.topright = (self.rect.width, self.rect.height/4) line.sprite.setAction(self.addAlarm) self._lines.append(line) def update(self): for line in self._lines: line.update() # line.sprite.rect.midbottom = self.image.get_rect() line.draw(self.baseImage) def handleEvent(self, event): pos = pygame.mouse.get_pos() if event.type == pygame.MOUSEBUTTONDOWN: for butt in self._lines: if butt.sprite.rect.collidepoint(pos): butt.sprite.touchDown() if event.type == pygame.MOUSEBUTTONUP: for butt in self._lines: if butt.sprite.rect.collidepoint(pos): butt.sprite.touchUp()
khan-git/pialarmclock
faces/alarmsetting.py
Python
mit
3,537
const td = require('testdouble'); const expect = require('../../../../helpers/expect'); const RSVP = require('rsvp'); const Promise = RSVP.Promise; const adbPath = 'adbPath'; const deviceUUID = 'uuid'; const apkPath = 'apk-path'; const spawnArgs = [adbPath, ['-s', deviceUUID, 'install', '-r', apkPath]]; describe('Android Install App - Device', () => { let installAppDevice; let spawn; beforeEach(() => { let sdkPaths = td.replace('../../../../../lib/targets/android/utils/sdk-paths'); td.when(sdkPaths()).thenReturn({ adb: adbPath }); spawn = td.replace('../../../../../lib/utils/spawn'); td.when(spawn(...spawnArgs)).thenReturn(Promise.resolve({ code: 0 })); installAppDevice = require('../../../../../lib/targets/android/tasks/install-app-device'); }); afterEach(() => { td.reset(); }); it('calls spawn with correct arguments', () => { td.config({ ignoreWarnings: true }); td.when(spawn(), { ignoreExtraArgs: true }) .thenReturn(Promise.resolve({ code: 0 })); return installAppDevice(deviceUUID, apkPath).then(() => { td.verify(spawn(...spawnArgs)); td.config({ ignoreWarnings: false }); }); }); it('resolves with object containing exit code from spawned process', () => { return expect(installAppDevice(deviceUUID, apkPath)) .to.eventually.contain({ code: 0 }); }); it('bubbles up error message when spawn rejects', () => { td.when(spawn(...spawnArgs)).thenReturn(Promise.reject('spawn error')); return expect(installAppDevice(deviceUUID, apkPath)) .to.eventually.be.rejectedWith('spawn error'); }); });
isleofcode/corber
node-tests/unit/targets/android/tasks/install-app-device-test.js
JavaScript
mit
1,696
package edu.gatech.nutrack; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class Home extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.home, menu); return true; } public void callScan(View view) { Intent callScanIntent = new Intent(this, NutritionixActivity.class); startActivity(callScanIntent); } public void callTrack(View view) { Intent callTrackIntent = new Intent(this, Track.class); startActivity(callTrackIntent); } public void callSync(View view) { Intent callSyncIntent = new Intent(this, Sync.class); startActivity(callSyncIntent); } public void callReco(View view) { Intent callRecoIntent = new Intent(this, Reco.class); startActivity(callRecoIntent); } public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_scan: Intent callScanIntent = new Intent(this, NutritionixActivity.class); startActivity(callScanIntent); return true; case R.id.action_track: Intent callTrackIntent = new Intent(this, Track.class); startActivity(callTrackIntent); return true; case R.id.action_reco: Intent callReco = new Intent(this, Track.class); startActivity(callReco); return true; case R.id.action_nutrition_info: Intent callNutritionInfo = new Intent(this, Track.class); startActivity(callNutritionInfo); return true; case R.id.action_log_out: callLogout(item.getActionView()); return true; default: return super.onOptionsItemSelected(item); } } // log out. Every activity should have this method! public void callLogout(View view) { Intent callLoginIntent = new Intent(this, Login.class); startActivity(callLoginIntent); } }
i3l/NuTrack
src/edu/gatech/nutrack/Home.java
Java
mit
2,842
<?php /** * Smarty Internal Plugin Template * This file contains the Smarty template engine * * @package Smarty * @subpackage Template * @author Uwe Tews */ /** * Main class with template data structures and methods * * @package Smarty * @subpackage Template * * @property Smarty_Template_Source|Smarty_Template_Config $source * @property Smarty_Template_Compiled $compiled * @property Smarty_Template_Cached $cached * * The following methods will be dynamically loaded by the extension handler when they are called. * They are located in a corresponding Smarty_Internal_Method_xxxx class * * @method bool mustCompile() */ class Smarty_Internal_Template extends Smarty_Internal_TemplateBase { /** * This object type (Smarty = 1, template = 2, data = 4) * * @var int */ public $_objType = 2; /** * Global smarty instance * * @var Smarty */ public $smarty = null; /** * Source instance * * @var Smarty_Template_Source|Smarty_Template_Config */ public $source = null; /** * Template resource * * @var string */ public $template_resource = null; /** * flag if compiled template is invalid and must be (re)compiled * * @var bool */ public $mustCompile = null; /** * Template Id * * @var null|string */ public $templateId = null; /** * Known template functions * * @var array */ public $tpl_function = array(); /** * Scope in which variables shall be assigned * * @var int */ public $scope = 0; /** * Flag which is set while rending a cache file * * @var bool */ public $isRenderingCache = false; /** * Create template data object * Some of the global Smarty settings copied to template scope * It load the required template resources and caching plugins * * @param string $template_resource template resource string * @param Smarty $smarty Smarty instance * @param \Smarty_Internal_Template|\Smarty|\Smarty_Internal_Data $_parent back pointer to parent object * with variables or null * @param mixed $_cache_id cache id or null * @param mixed $_compile_id compile id or null * @param bool $_caching use caching? * @param int $_cache_lifetime cache life-time in seconds * * @throws \SmartyException */ public function __construct($template_resource, Smarty $smarty, Smarty_Internal_Data $_parent = null, $_cache_id = null, $_compile_id = null, $_caching = null, $_cache_lifetime = null) { $this->smarty = &$smarty; // Smarty parameter $this->cache_id = $_cache_id === null ? $this->smarty->cache_id : $_cache_id; $this->compile_id = $_compile_id === null ? $this->smarty->compile_id : $_compile_id; $this->caching = $_caching === null ? $this->smarty->caching : $_caching; if ($this->caching === true) { $this->caching = Smarty::CACHING_LIFETIME_CURRENT; } $this->cache_lifetime = $_cache_lifetime === null ? $this->smarty->cache_lifetime : $_cache_lifetime; $this->parent = $_parent; // Template resource $this->template_resource = $template_resource; $this->source = Smarty_Template_Source::load($this); parent::__construct(); } /** * render template * * @param bool $no_output_filter if true do not run output filter * @param null|bool $display true: display, false: fetch null: sub-template * * @return string * @throws \SmartyException */ public function render($no_output_filter = true, $display = null) { $parentIsTpl = isset($this->parent) && $this->parent->_objType == 2; if ($this->smarty->debugging) { $this->smarty->_debug->start_template($this, $display); } // checks if template exists if (!$this->source->exists) { if ($parentIsTpl) { $parent_resource = " in '{$this->parent->template_resource}'"; } else { $parent_resource = ''; } throw new SmartyException("Unable to load template {$this->source->type} '{$this->source->name}'{$parent_resource}"); } // disable caching for evaluated code if ($this->source->handler->recompiled) { $this->caching = false; } // read from cache or render $isCacheTpl = $this->caching == Smarty::CACHING_LIFETIME_CURRENT || $this->caching == Smarty::CACHING_LIFETIME_SAVED; if ($isCacheTpl) { if (!isset($this->cached)) { $this->loadCached(); } $this->cached->render($this, $no_output_filter); } elseif ($this->source->handler->uncompiled) { $this->source->render($this); } else { if (!isset($this->compiled)) { $this->loadCompiled(); } $this->compiled->render($this); } // display or fetch if ($display) { if ($this->caching && $this->smarty->cache_modified_check) { $this->smarty->ext->_cacheModify->cacheModifiedCheck($this->cached, $this, isset($content) ? $content : ob_get_clean()); } else { if ((!$this->caching || $this->cached->has_nocache_code || $this->source->handler->recompiled) && !$no_output_filter && (isset($this->smarty->autoload_filters[ 'output' ]) || isset($this->smarty->registered_filters[ 'output' ])) ) { echo $this->smarty->ext->_filterHandler->runFilter('output', ob_get_clean(), $this); } else { ob_end_flush(); flush(); } } if ($this->smarty->debugging) { $this->smarty->_debug->end_template($this); // debug output $this->smarty->_debug->display_debug($this, true); } return ''; } else { if ($this->smarty->debugging) { $this->smarty->_debug->end_template($this); if ($this->smarty->debugging === 2 && $display === false) { $this->smarty->_debug->display_debug($this, true); } } if ($parentIsTpl) { if (!empty($this->tpl_function)) { $this->parent->tpl_function = array_merge($this->parent->tpl_function, $this->tpl_function); } foreach ($this->compiled->required_plugins as $code => $tmp1) { foreach ($tmp1 as $name => $tmp) { foreach ($tmp as $type => $data) { $this->parent->compiled->required_plugins[ $code ][ $name ][ $type ] = $data; } } } } if (!$no_output_filter && (!$this->caching || $this->cached->has_nocache_code || $this->source->handler->recompiled) && (isset($this->smarty->autoload_filters[ 'output' ]) || isset($this->smarty->registered_filters[ 'output' ])) ) { return $this->smarty->ext->_filterHandler->runFilter('output', ob_get_clean(), $this); } // return cache content return null; } } /** * Runtime function to render sub-template * * @param string $template template name * @param mixed $cache_id cache id * @param mixed $compile_id compile id * @param integer $caching cache mode * @param integer $cache_lifetime life time of cache data * @param array $data passed parameter template variables * @param int $scope scope in which {include} should execute * @param bool $forceTplCache cache template object * @param string $uid file dependency uid * @param string $content_func function name * */ public function _subTemplateRender($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $scope, $forceTplCache, $uid = null, $content_func = null) { $tpl = clone $this; $tpl->parent = $this; $_templateId = $this->smarty->_getTemplateId($template, $cache_id, $compile_id, $caching); // recursive call ? if ($tpl->_getTemplateId() != $_templateId) { // already in template cache? if (isset($this->smarty->_cache[ 'tplObjects' ][ $_templateId ])) { // copy data from cached object $cachedTpl = &$this->smarty->_cache[ 'tplObjects' ][ $_templateId ]; $tpl->templateId = $cachedTpl->templateId; $tpl->template_resource = $cachedTpl->template_resource; $tpl->cache_id = $cachedTpl->cache_id; $tpl->compile_id = $cachedTpl->compile_id; $tpl->source = $cachedTpl->source; // if $caching mode changed the compiled resource is invalid if ((bool) $tpl->caching !== (bool) $caching) { unset($tpl->compiled); } elseif (isset($cachedTpl->compiled)) { $tpl->compiled = $cachedTpl->compiled; } else { unset($tpl->compiled); } if ($caching != 9999 && isset($cachedTpl->cached)) { $tpl->cached = $cachedTpl->cached; } else { unset($tpl->cached); } } else { $tpl->templateId = $_templateId; $tpl->template_resource = $template; $tpl->cache_id = $cache_id; $tpl->compile_id = $compile_id; if (isset($uid)) { // for inline templates we can get all resource information from file dependency list($filepath, $timestamp, $type) = $tpl->compiled->file_dependency[ $uid ]; $tpl->source = new Smarty_Template_Source(isset($tpl->smarty->_cache[ 'resource_handlers' ][ $type ]) ? $tpl->smarty->_cache[ 'resource_handlers' ][ $type ] : Smarty_Resource::load($tpl->smarty, $type), $tpl->smarty, $filepath, $type, $filepath); $tpl->source->filepath = $filepath; $tpl->source->timestamp = $timestamp; $tpl->source->exists = true; $tpl->source->uid = $uid; } else { $tpl->source = Smarty_Template_Source::load($tpl); unset($tpl->compiled); } if ($caching != 9999) { unset($tpl->cached); } } } else { // on recursive calls force caching $forceTplCache = true; } $tpl->caching = $caching; $tpl->cache_lifetime = $cache_lifetime; // set template scope $tpl->scope = $scope; if (!isset($tpl->smarty->_cache[ 'tplObjects' ][ $tpl->templateId ]) && !$tpl->source->handler->recompiled) { // check if template object should be cached if ($forceTplCache || (isset($tpl->smarty->_cache[ 'subTplInfo' ][ $tpl->template_resource ]) && $tpl->smarty->_cache[ 'subTplInfo' ][ $tpl->template_resource ] > 1) || ($tpl->_isParentTemplate() && isset($tpl->smarty->_cache[ 'tplObjects' ][ $tpl->parent->templateId ])) ) { $tpl->smarty->_cache[ 'tplObjects' ][ $tpl->templateId ] = $tpl; } } if (!empty($data)) { // set up variable values foreach ($data as $_key => $_val) { $tpl->tpl_vars[ $_key ] = new Smarty_Variable($_val, $this->isRenderingCache); } } if ($tpl->caching == 9999 && $tpl->compiled->has_nocache_code) { $this->cached->hashes[ $tpl->compiled->nocache_hash ] = true; } if (isset($uid)) { if ($this->smarty->debugging) { $this->smarty->_debug->start_template($tpl); $this->smarty->_debug->start_render($tpl); } $tpl->compiled->getRenderedTemplateCode($tpl, $content_func); if ($this->smarty->debugging) { $this->smarty->_debug->end_template($tpl); $this->smarty->_debug->end_render($tpl); } } else { if (isset($tpl->compiled)) { $tpl->compiled->render($tpl); } else { $tpl->render(); } } } /** * Get called sub-templates and save call count * */ public function _subTemplateRegister() { foreach ($this->compiled->includes as $name => $count) { if (isset($this->smarty->_cache[ 'subTplInfo' ][ $name ])) { $this->smarty->_cache[ 'subTplInfo' ][ $name ] += $count; } else { $this->smarty->_cache[ 'subTplInfo' ][ $name ] = $count; } } } /** * Check if parent is template object * * @return bool true if parent is template */ public function _isParentTemplate() { return isset($this->parent) && $this->parent->_objType == 2; } /** * Assign variable in scope * * @param string $varName variable name * @param mixed $value value * @param bool $nocache nocache flag * @param int $scope scope into which variable shall be assigned * */ public function _assignInScope($varName, $value, $nocache = false, $scope = 0) { if (isset($this->tpl_vars[ $varName ])) { $this->tpl_vars[ $varName ] = clone $this->tpl_vars[ $varName ]; $this->tpl_vars[ $varName ]->value = $value; if ($nocache || $this->isRenderingCache) { $this->tpl_vars[ $varName ]->nocache = true; } } else { $this->tpl_vars[ $varName ] = new Smarty_Variable($value, $nocache || $this->isRenderingCache); } if (isset($scope) || isset($this->scope)) { $this->smarty->ext->_updateScope->_updateScope($this, $varName, $scope); } } /** * This function is executed automatically when a compiled or cached template file is included * - Decode saved properties from compiled template and cache files * - Check if compiled or cache file is valid * * @param \Smarty_Internal_Template $tpl * @param array $properties special template properties * @param bool $cache flag if called from cache file * * @return bool flag if compiled or cache file is valid * @throws \SmartyException */ public function _decodeProperties(Smarty_Internal_Template $tpl, $properties, $cache = false) { $is_valid = true; if (Smarty::SMARTY_VERSION != $properties[ 'version' ]) { // new version must rebuild $is_valid = false; } elseif ($is_valid && !empty($properties[ 'file_dependency' ]) && ((!$cache && $tpl->smarty->compile_check) || $tpl->smarty->compile_check == 1) ) { // check file dependencies at compiled code foreach ($properties[ 'file_dependency' ] as $_file_to_check) { if ($_file_to_check[ 2 ] == 'file' || $_file_to_check[ 2 ] == 'extends' || $_file_to_check[ 2 ] == 'php' ) { if ($tpl->source->filepath == $_file_to_check[ 0 ]) { // do not recheck current template continue; //$mtime = $tpl->source->getTimeStamp(); } else { // file and php types can be checked without loading the respective resource handlers $mtime = is_file($_file_to_check[ 0 ]) ? filemtime($_file_to_check[ 0 ]) : false; } } elseif ($_file_to_check[ 2 ] == 'string') { continue; } else { $handler = Smarty_Resource::load($tpl->smarty, $_file_to_check[ 2 ]); if ($handler->checkTimestamps()) { $source = Smarty_Template_Source::load($tpl, $tpl->smarty, $_file_to_check[ 0 ]); $mtime = $source->getTimeStamp(); } else { continue; } } if (!$mtime || $mtime > $_file_to_check[ 1 ]) { $is_valid = false; break; } } } if ($cache) { // CACHING_LIFETIME_SAVED cache expiry has to be validated here since otherwise we'd define the unifunc if ($tpl->caching === Smarty::CACHING_LIFETIME_SAVED && $properties[ 'cache_lifetime' ] >= 0 && (time() > ($tpl->cached->timestamp + $properties[ 'cache_lifetime' ])) ) { $is_valid = false; } $tpl->cached->cache_lifetime = $properties[ 'cache_lifetime' ]; $tpl->cached->valid = $is_valid; $resource = $tpl->cached; } else { $tpl->mustCompile = !$is_valid; $resource = $tpl->compiled; $resource->includes = isset($properties[ 'includes' ]) ? $properties[ 'includes' ] : array(); } if ($is_valid) { $resource->unifunc = $properties[ 'unifunc' ]; $resource->has_nocache_code = $properties[ 'has_nocache_code' ]; // $tpl->compiled->nocache_hash = $properties['nocache_hash']; $resource->file_dependency = $properties[ 'file_dependency' ]; if (isset($properties[ 'tpl_function' ])) { $tpl->tpl_function = $properties[ 'tpl_function' ]; } } return $is_valid && !function_exists($properties[ 'unifunc' ]); } /** * Compiles the template * If the template is not evaluated the compiled template is saved on disk */ public function compileTemplateSource() { return $this->compiled->compileTemplateSource($this); } /** * Writes the content to cache resource * * @param string $content * * @return bool */ public function writeCachedContent($content) { return $this->smarty->ext->_updateCache->writeCachedContent($this->cached, $this, $content); } /** * Get unique template id * * @return string */ public function _getTemplateId() { return isset($this->templateId) ? $this->templateId : $this->templateId = $this->smarty->_getTemplateId($this->template_resource, $this->cache_id, $this->compile_id); } /** * runtime error not matching capture tags */ public function capture_error() { throw new SmartyException("Not matching {capture} open/close in \"{$this->template_resource}\""); } /** * Load compiled object * */ public function loadCompiled() { if (!isset($this->compiled)) { $this->compiled = Smarty_Template_Compiled::load($this); } } /** * Load cached object * */ public function loadCached() { if (!isset($this->cached)) { $this->cached = Smarty_Template_Cached::load($this); } } /** * Load compiler object * * @throws \SmartyException */ public function loadCompiler() { if (!class_exists($this->source->handler->compiler_class)) { $this->smarty->loadPlugin($this->source->handler->compiler_class); } $this->compiler = new $this->source->handler->compiler_class($this->source->handler->template_lexer_class, $this->source->handler->template_parser_class, $this->smarty); } /** * Handle unknown class methods * * @param string $name unknown method-name * @param array $args argument array * * @return mixed * @throws SmartyException */ public function __call($name, $args) { // method of Smarty object? if (method_exists($this->smarty, $name)) { return call_user_func_array(array($this->smarty, $name), $args); } // parent return parent::__call($name, $args); } /** * set Smarty property in template context * * @param string $property_name property name * @param mixed $value value * * @throws SmartyException */ public function __set($property_name, $value) { switch ($property_name) { case 'compiled': case 'cached': case 'compiler': $this->$property_name = $value; return; default: // Smarty property ? if (property_exists($this->smarty, $property_name)) { $this->smarty->$property_name = $value; return; } } throw new SmartyException("invalid template property '$property_name'."); } /** * get Smarty property in template context * * @param string $property_name property name * * @return mixed|Smarty_Template_Cached * @throws SmartyException */ public function __get($property_name) { switch ($property_name) { case 'compiled': $this->loadCompiled(); return $this->compiled; case 'cached': $this->loadCached(); return $this->cached; case 'compiler': $this->loadCompiler(); return $this->compiler; default: // Smarty property ? if (property_exists($this->smarty, $property_name)) { return $this->smarty->$property_name; } } throw new SmartyException("template property '$property_name' does not exist."); } /** * Template data object destructor */ public function __destruct() { if ($this->smarty->cache_locking && isset($this->cached) && $this->cached->is_locked) { $this->cached->handler->releaseLock($this->smarty, $this->cached); } } }
yanlyan/si_ibuhamil
system/plugins/smarty/libs/sysplugins/smarty_internal_template.php
PHP
mit
23,765
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Data; using ZyGames.Framework.Common; using ZyGames.Framework.Game.Service; using ZyGames.Tianjiexing.Lang; using ZyGames.Tianjiexing.Model; using ZyGames.Tianjiexing.BLL.Combat; using ZyGames.Tianjiexing.BLL.Base; using ZyGames.Tianjiexing.Model.Config; namespace ZyGames.Tianjiexing.BLL.Action { /// <summary> /// 6103_公会Boss战欲火重生接口 /// </summary> public class Action6103 : BaseAction { private const int GoldNum = 5; private const int MaxNum = 5; private int Ops; private double _reliveInspirePercent; private int _activeId; public Action6103(ZyGames.Framework.Game.Contract.HttpGet httpGet) : base(ActionIDDefine.Cst_Action6103, httpGet) { } public override void BuildPacket() { PushIntoStack((_reliveInspirePercent * 100).ToInt()); } public override bool GetUrlElement() { if (httpGet.GetInt("Ops", ref Ops, 1, 2) && httpGet.GetInt("ActiveId", ref _activeId)) { return true; } return false; } public override bool TakeAction() { if (!string.IsNullOrEmpty(ContextUser.MercenariesID)) { if (CombatHelper.GuildBossKill(ContextUser.MercenariesID)) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St5405_BossKilled; return false; } GuildBossCombat bossCombat = new GuildBossCombat(ContextUser.MercenariesID); UserGuild guild = bossCombat.UserGuild; if (guild != null) { if (!VipHelper.GetVipOpenFun(ContextUser.VipLv, ExpandType.BossChongSheng)) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St_VipNotEnoughNotFuntion; return false; } CombatStatus combatStatus = guild.CombatStatus; if (combatStatus != CombatStatus.Wait && combatStatus != CombatStatus.Combat) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St5402_CombatNoStart; return false; } ErrorCode = Ops; BossUser bossUser = bossCombat.GetCombatUser(Uid); if (bossUser != null && !bossUser.IsRelive) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St5403_IsLive; return false; } if (bossUser != null && bossUser.ReliveNum >= MaxNum) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St5403_IsReLiveMaxNum; return false; } int goldNum = GoldNum * (bossUser.ReliveNum + 1); if (Ops == 1) { ErrorInfo = string.Format(LanguageManager.GetLang().St5403_CombatGoldTip, goldNum); } else if (Ops == 2) { if (ContextUser.GoldNum < goldNum) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St_GoldNotEnough; return false; } if (bossUser != null && bossUser.IsRelive) { if (bossUser.IsRelive) { ContextUser.UseGold = MathUtils.Addition(ContextUser.UseGold, goldNum, int.MaxValue); //ContextUser.Update(); bossUser.IsRelive = false; bossUser.ReliveBeginDate = DateTime.MinValue; bossUser.ReliveInspirePercent = MathUtils.Addition(bossUser.ReliveInspirePercent, CountryCombat.InspireIncrease, 1); _reliveInspirePercent = bossUser.ReliveInspirePercent; bossUser.ReliveNum++; } } } } } return true; } } }
wenhulove333/ScutServer
Sample/Koudai/Server/src/ZyGames.Tianjiexing.BLL/Action/Action6103.cs
C#
mit
6,232
app.config(function ($routeProvider, $locationProvider) { "use strict"; $routeProvider.when('/', { controller: 'HomeController', templateUrl: '/static/apps/main/views/home.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, current: function (SprintService) { var sprints = SprintService.listSprints(); } } }).when('/tasks/', { controller: 'TaskController', templateUrl: '/static/apps/main/views/tasks.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, task: function () { return false; } } }).when('/tasks/:taskid', { controller: 'TaskController', templateUrl: '/static/apps/main/views/task.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, task: function (TaskService, $route) { return TaskService.getTask($route.current.params.taskid); } } }).when('/sprints/', { controller: 'SprintController', templateUrl: '/static/apps/main/views/sprints.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, sprint: function () { return false; } } }).when('/sprints/:sprintid', { controller: 'SprintController', templateUrl: '/static/apps/main/views/sprint.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, sprint: function (SprintService, $route) { return $route.current.params.sprintid; } } }).when('/categories/', { controller: 'CategoryController', templateUrl: '/static/apps/main/views/categories.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); } } }).when('/stats/', { controller: 'StatsController', templateUrl: '/static/apps/main/views/stats.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); } } }).otherwise({redirectTo: '/'}); });
mc706/task-burndown
assets/apps/main/config/routes.js
JavaScript
mit
4,692
import React from 'react'; import { getCategoryGroups } from '../selectors/categoryGroups'; import { getCategoriesByGroupId } from '../selectors/categories'; import { getSelectedMonthBudgetItemsByCategoryId, getBudgetItemsSumUpToSelectedMonthByCategoryId } from '../selectors/budgetItems'; import { getTransactionsSumUpToSelectedMonthByCategoryId, getSelectedMonthActivityByCategoryId } from '../selectors/transactions'; import {connect} from 'react-redux'; import CategoryRow from './CategoryRow'; import CategoryGroupRow from './CategoryGroupRow'; import ui from 'redux-ui'; @ui({ state: { editingCategoryId: undefined } }) class BudgetTable extends React.Component { static propTypes = { categoryGroups: React.PropTypes.array.isRequired, categoriesByGroupId: React.PropTypes.object.isRequired, getSelectedMonthActivityByCategoryId: React.PropTypes.object.isRequired, getSelectedMonthBudgetItemsByCategoryId: React.PropTypes.object.isRequired, transactionsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired, budgetItemsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired } render() { const rows = []; this.props.categoryGroups.forEach(cg => { rows.push(<CategoryGroupRow key={"cg"+cg.id} name={cg.name} />); if (this.props.categoriesByGroupId[cg.id]) { this.props.categoriesByGroupId[cg.id].forEach(c => { rows.push(<CategoryRow key={"c"+c.id} category={c} budgetItem={this.props.getSelectedMonthBudgetItemsByCategoryId[c.id]} activity={this.props.getSelectedMonthActivityByCategoryId[c.id]} available={(this.props.budgetItemsSumUpToSelectedMonthByCategoryId[c.id] || 0) + (this.props.transactionsSumUpToSelectedMonthByCategoryId[c.id] || 0)} />); }); } }); return ( <table className="table"> <thead> <tr> <th>Category</th> <th>Budgeted</th> <th>Activity</th> <th>Available</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } } const mapStateToProps = (state) => ({ categoryGroups: getCategoryGroups(state), categoriesByGroupId: getCategoriesByGroupId(state), getSelectedMonthActivityByCategoryId: getSelectedMonthActivityByCategoryId(state), getSelectedMonthBudgetItemsByCategoryId: getSelectedMonthBudgetItemsByCategoryId(state), transactionsSumUpToSelectedMonthByCategoryId: getTransactionsSumUpToSelectedMonthByCategoryId(state), budgetItemsSumUpToSelectedMonthByCategoryId: getBudgetItemsSumUpToSelectedMonthByCategoryId(state) }); export default connect(mapStateToProps)(BudgetTable);
Nauktis/inab
client/src/components/BudgetTable.js
JavaScript
mit
2,735
class EventProcessor def initialize(event) @event = event end def process return SipgateIo::XmlResponse.reject end end
superbilk/sipgate_io
test/dummy/app/models/event_processor.rb
Ruby
mit
136
class RemoveModels < ActiveRecord::Migration[4.2] def change drop_table :roles drop_table :role_names drop_table :people end end
ZeusWPI/Gandalf
db/migrate/20140308135535_remove_models.rb
Ruby
mit
145
'use strict'; module.exports = { db: 'mongodb://localhost/equinix-test', port: 3001, app: { title: 'Equinix - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
linhlam/equinix
config/env/test.js
JavaScript
mit
1,371
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class PotatoSelections extends Migration { /** * Run the migrations. * * @return void */ public function up() { \Schema::create('potato_selections', function (Blueprint $table) { $table->increments('id'); $table->enum('vote', ['potato', 'camera']); $table->string('ip'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { \Schema::drop('potato_selections'); } }
tpavlek/YEGVotes
database/migrations/2016_05_26_103345_potato_selections.php
PHP
mit
657
import { injectReducer } from '../../../../store/reducers' export default (store) => ({ path: 'admin/positions/add', /* Async getComponent is only invoked when route matches */ getComponent (nextState, cb) { /* Webpack - use 'require.ensure' to create a split point and embed an async module loader (jsonp) when bundling */ require.ensure([], (require) => { /* Webpack - use require callback to define dependencies for bundling */ const AddPosition = require('./AddPosition.component').default // const reducer = null; /* Add the reducer to the store on key 'counter' */ // injectReducer(store, { key: 'addPositions', reducer }) /* Return getComponent */ cb(null, AddPosition) /* Webpack named bundle */ }, 'addPositions') } })
kritikasoni/smsss-react
src/routes/Admin/Position/AddPosition/index.js
JavaScript
mit
828
# -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from django.forms import inlineformset_factory from djangosige.apps.financeiro.models import PlanoContasGrupo, PlanoContasSubgrupo class PlanoContasGrupoForm(forms.ModelForm): class Meta: model = PlanoContasGrupo fields = ('tipo_grupo', 'descricao',) widgets = { 'descricao': forms.TextInput(attrs={'class': 'form-control'}), 'tipo_grupo': forms.Select(attrs={'class': 'form-control'}), } labels = { 'descricao': _('Descrição'), 'tipo_grupo': _('Tipo de lançamento'), } class PlanoContasSubgrupoForm(forms.ModelForm): class Meta: model = PlanoContasSubgrupo fields = ('descricao',) widgets = { 'descricao': forms.TextInput(attrs={'class': 'form-control'}), } labels = { 'descricao': _('Descrição'), } PlanoContasSubgrupoFormSet = inlineformset_factory( PlanoContasGrupo, PlanoContasSubgrupo, form=PlanoContasSubgrupoForm, fk_name='grupo', extra=1, can_delete=True)
thiagopena/djangoSIGE
djangosige/apps/financeiro/forms/plano.py
Python
mit
1,165
/* * This code is under the MIT License * * Copyright 2016, Jonathan Alexander, All rights reserved */ using Monitor.Core.Utilities; using System.IO; namespace JunctionManager { class JunctionManager { public static void MoveWithJunction(string origin, string target) { //Copy folder and delete the original folder (essentially a move" Program.CopyFolder(origin, target); Directory.Delete(origin, true); Program.Log("INFO: Moved " + origin + " to " + target); //Create a junction at the original location pointing to the new location JunctionPoint.Create(origin, target, true); //Update the SQLite database with the new junction created SQLiteManager.AddJunction(origin, target); } public static void MoveReplaceJunction(string origin, string target) { //Delete the junction JunctionPoint.Delete(origin); //Copy the folder back and delete the original folder (essentially moving the function) Program.CopyFolder(target, origin); Directory.Delete(target, true); //Update the SQLite database with the removal of the junction SQLiteManager.RemoveJunction(origin); Program.Log("INFO: Moved " + target + " to " + origin); } } }
notdisliked/JunctionManager
JunctionManager/JunctionManager.cs
C#
mit
1,368
from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.admin import UserAdmin from django.contrib import admin from django import forms class VoterCreationForm(UserCreationForm): section = forms.CharField() def save(self, commit=True): user = super(VoterCreationForm, self).save(commit=False) user.section = self.cleaned_data['section'] if commit: user.save() return user class Meta: model = User fields = ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser') class VoterChangeForm(UserChangeForm): section = forms.CharField() def save(self, commit=True): user = super(VoterChangeForm, self).save(commit=False) user.section = self.cleaned_data['section'] if commit: user.save() return user class Meta: model = User exclude = ('',) class VoterAdmin(UserAdmin): form = VoterChangeForm add_form = VoterCreationForm list_filter = UserAdmin.list_filter + ('section',) fieldsets = ( (None, {'fields': ('username', 'password')}), (('Personal info'), {'fields': ('first_name', 'last_name', 'section')}), (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'password1', 'password2', 'section', 'first_name', 'last_name', 'is_active', 'is_staff', 'is_superuser')} ), ) admin.site.unregister(User) admin.site.register(User, VoterAdmin)
seanballais/SAElections
SAElections/voting/admin.py
Python
mit
1,715
package com.dgex.offspring.nxtCore.service; import java.util.List; import nxt.Account; import nxt.Alias; import nxt.Block; import nxt.Transaction; import com.dgex.offspring.nxtCore.core.TransactionHelper.IteratorAsList; public interface IAccount { public Account getNative(); public Long getId(); public String getStringId(); public long getBalance(); public long getUnconfirmedBalance(); public long getAssetBalance(Long assetId); public long getUnconfirmedAssetBalance(Long assetId); public String getPrivateKey(); public byte[] getPublicKey(); public List<ITransaction> getTransactions(); public List<Transaction> getNativeTransactions(); public List<Alias> getNativeAliases(); public List<Block> getForgedBlocks(); public List<IAlias> getAliases(); public List<IMessage> getMessages(); public List<IAsset> getIssuedAssets(); public int getForgedFee(); public boolean startForging(); public boolean stopForging(); public boolean isForging(); public boolean isReadOnly(); IteratorAsList getUserTransactions(); }
incentivetoken/offspring
com.dgex.offspring.nxtCore/src/com/dgex/offspring/nxtCore/service/IAccount.java
Java
mit
1,085
'use strict'; var fetchUrl = require('fetch').fetchUrl; var packageInfo = require('../package.json'); var httpStatusCodes = require('./http.json'); var urllib = require('url'); var mime = require('mime'); // Expose to the world module.exports.resolve = resolve; module.exports.removeParams = removeParams; /** * Resolves an URL by stepping through all redirects * * @param {String} url The URL to be checked * @param {Object} options Optional options object * @param {Function} callback Callback function with error and url */ function resolve(url, options, callback) { var urlOptions = {}; if (typeof options == 'function' && !callback) { callback = options; options = undefined; } options = options || {}; urlOptions.method = options.method ||  'HEAD'; urlOptions.disableGzip = true; // no need for gzipping with HEAD urlOptions.asyncDnsLoookup = true; urlOptions.timeout = options.timeout ||  10000; urlOptions.userAgent = options.userAgent ||  (packageInfo.name + '/' + packageInfo.version + ' (+' + packageInfo.homepage + ')'); urlOptions.removeParams = [].concat(options.removeParams ||  [/^utm_/, 'ref']); urlOptions.agent = options.agent || false; urlOptions.rejectUnauthorized = false; urlOptions.headers = options.headers || {}; urlOptions.maxRedirects = options.maxRedirects || 10; fetchUrl(url, urlOptions, function(error, meta) { var err, url; if (error) { err = new Error(error.message || error); err.statusCode = 0; return callback(err); } if (meta.status != 200) { err = new Error('Server responded with ' + meta.status + ' ' + (httpStatusCodes[meta.status] || 'Invalid request')); err.statusCode = meta.status; return callback(err); } url = meta.finalUrl; if (urlOptions.removeParams && urlOptions.removeParams.length) { url = removeParams(url, urlOptions.removeParams); } var fileParams = detectFileParams(meta); return callback(null, url, fileParams.filename, fileParams.contentType); }); } function detectFileParams(meta) { var urlparts = urllib.parse(meta.finalUrl); var filename = (urlparts.pathname || '').split('/').pop(); var contentType = (meta.responseHeaders['content-type'] || 'application/octet-stream').toLowerCase().split(';').shift().trim(); var fileParts; var extension = ''; var contentExtension; (meta.responseHeaders['content-disposition'] || '').split(';').forEach(function(line) { var parts = line.trim().split('='), key = parts.shift().toLowerCase().trim(); if (key == 'filename') { filename = parts.join('=').trim(); } }); if (contentType == 'application/octet-stream') { contentType = mime.lookup(filename) || 'application/octet-stream'; } else { fileParts = filename.split('.'); if (fileParts.length > 1) { extension = fileParts.pop().toLowerCase(); } contentExtension = mime.extension(contentType); if (contentExtension && extension != contentExtension) { extension = contentExtension; } if (extension) { if (!fileParts.length ||  (fileParts.length == 1 && !fileParts[0])) { fileParts = ['index']; } fileParts.push(extension); } filename = fileParts.join('.'); } return { filename: filename, contentType: contentType }; } /** * Removes matching GET params from an URL * * @param {String} url URL to be checked * @param {Array} params An array of key matches to be removed * @return {String} URL */ function removeParams(url, params) { var parts, query = {}, deleted = false; parts = urllib.parse(url, true, true); delete parts.search; if (parts.query) { Object.keys(parts.query).forEach(function(key) { for (var i = 0, len = params.length; i < len; i++) { if (params[i] instanceof RegExp && key.match(params[i])) { deleted = true; return; } else if (key == params[i]) { deleted = true; return; } } query[key] = parts.query[key]; }); parts.query = query; } return deleted ? urllib.format(parts) : url; }
andris9/resolver
lib/resolver.js
JavaScript
mit
4,516
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Clarity.Rpa.Instructions { public enum NumberCompareOperation { Equal, NotEqual, LessThan, GreaterThan, LessOrEqual, GreaterOrEqual, NumHighCompareTypes, } }
elasota/clarity
Clarity.Rpa/Instructions/NumberCompareOperation.cs
C#
mit
344
require 'tempfile' require 'fileutils' require 'config' require 'open-uri' require 'data_repository' class CI def initialize(opts=Conf.config) @url = opts.fetch(:url, "http://ci/api/json?tree=jobs[name,builds[timestamp,result,building]]") @ignored_projects = opts[:ignored_projects] || [] end def broken_projects non_ignored_projects.select{|project| project.latest_complete_build.failed?} end def in_progress_projects projects.select(&:build_in_progress?) end def recently_built_projects(n=5) non_ignored_projects.sort_by { |project| project.latest_complete_build.timestamp }.reverse.first(n) end def update DataRepository.save('ci', open(url).read) end private attr_reader :url, :ignored_projects def projects @projects ||= status["jobs"].map do |hash| Project.new(hash.merge(ignored: ignore_project?(hash["name"]))) end end def ignore_project?(name) ignored_projects.include?(name) || name.match(/branches/i) end def non_ignored_projects projects.delete_if(&:ignored?) end def status @status ||= JSON.parse(DataRepository.read("ci")) end end
reevoo/build-monitor
lib/ci.rb
Ruby
mit
1,153
"use strict" var o = require("ospec") var m = require("../../render/hyperscript") o.spec("hyperscript", function() { o.spec("selector", function() { o("throws on null selector", function(done) { try {m(null)} catch(e) {done()} }) o("throws on non-string selector w/o a view property", function(done) { try {m({})} catch(e) {done()} }) o("handles tag in selector", function() { var vnode = m("a") o(vnode.tag).equals("a") }) o("class and className normalization", function(){ o(m("a", { class: null }).attrs).deepEquals({ class: null }) o(m("a", { class: undefined }).attrs).deepEquals({ class: null }) o(m("a", { class: false }).attrs).deepEquals({ class: null, className: false }) o(m("a", { class: true }).attrs).deepEquals({ class: null, className: true }) o(m("a.x", { class: null }).attrs).deepEquals({ class: null, className: "x" }) o(m("a.x", { class: undefined }).attrs).deepEquals({ class: null, className: "x" }) o(m("a.x", { class: false }).attrs).deepEquals({ class: null, className: "x false" }) o(m("a.x", { class: true }).attrs).deepEquals({ class: null, className: "x true" }) o(m("a", { className: null }).attrs).deepEquals({ className: null }) o(m("a", { className: undefined }).attrs).deepEquals({ className: undefined }) o(m("a", { className: false }).attrs).deepEquals({ className: false }) o(m("a", { className: true }).attrs).deepEquals({ className: true }) o(m("a.x", { className: null }).attrs).deepEquals({ className: "x" }) o(m("a.x", { className: undefined }).attrs).deepEquals({ className: "x" }) o(m("a.x", { className: false }).attrs).deepEquals({ className: "x false" }) o(m("a.x", { className: true }).attrs).deepEquals({ className: "x true" }) }) o("handles class in selector", function() { var vnode = m(".a") o(vnode.tag).equals("div") o(vnode.attrs.className).equals("a") }) o("handles many classes in selector", function() { var vnode = m(".a.b.c") o(vnode.tag).equals("div") o(vnode.attrs.className).equals("a b c") }) o("handles id in selector", function() { var vnode = m("#a") o(vnode.tag).equals("div") o(vnode.attrs.id).equals("a") }) o("handles attr in selector", function() { var vnode = m("[a=b]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles many attrs in selector", function() { var vnode = m("[a=b][c=d]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles attr w/ spaces in selector", function() { var vnode = m("[a = b]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles attr w/ quotes in selector", function() { var vnode = m("[a='b']") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles attr w/ quoted square bracket", function() { var vnode = m("[x][a='[b]'].c") o(vnode.tag).equals("div") o(vnode.attrs.x).equals(true) o(vnode.attrs.a).equals("[b]") o(vnode.attrs.className).equals("c") }) o("handles attr w/ unmatched square bracket", function() { var vnode = m("[a=']'].c") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("]") o(vnode.attrs.className).equals("c") }) o("handles attr w/ quoted square bracket and quote", function() { var vnode = m("[a='[b\"\\']'].c") // `[a='[b"\']']` o(vnode.tag).equals("div") o(vnode.attrs.a).equals("[b\"']") // `[b"']` o(vnode.attrs.className).equals("c") }) o("handles attr w/ quoted square containing escaped square bracket", function() { var vnode = m("[a='[\\]]'].c") // `[a='[\]]']` o(vnode.tag).equals("div") o(vnode.attrs.a).equals("[\\]]") // `[\]]` o(vnode.attrs.className).equals("c") }) o("handles attr w/ backslashes", function() { var vnode = m("[a='\\\\'].c") // `[a='\\']` o(vnode.tag).equals("div") o(vnode.attrs.a).equals("\\") o(vnode.attrs.className).equals("c") }) o("handles attr w/ quotes and spaces in selector", function() { var vnode = m("[a = 'b']") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles many attr w/ quotes and spaces in selector", function() { var vnode = m("[a = 'b'][c = 'd']") o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles tag, class, attrs in selector", function() { var vnode = m("a.b[c = 'd']") o(vnode.tag).equals("a") o(vnode.attrs.className).equals("b") o(vnode.attrs.c).equals("d") }) o("handles tag, mixed classes, attrs in selector", function() { var vnode = m("a.b[c = 'd'].e[f = 'g']") o(vnode.tag).equals("a") o(vnode.attrs.className).equals("b e") o(vnode.attrs.c).equals("d") o(vnode.attrs.f).equals("g") }) o("handles attr without value", function() { var vnode = m("[a]") o(vnode.tag).equals("div") o(vnode.attrs.a).equals(true) }) o("handles explicit empty string value for input", function() { var vnode = m('input[value=""]') o(vnode.tag).equals("input") o(vnode.attrs.value).equals("") }) o("handles explicit empty string value for option", function() { var vnode = m('option[value=""]') o(vnode.tag).equals("option") o(vnode.attrs.value).equals("") }) }) o.spec("attrs", function() { o("handles string attr", function() { var vnode = m("div", {a: "b"}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") }) o("handles falsy string attr", function() { var vnode = m("div", {a: ""}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals("") }) o("handles number attr", function() { var vnode = m("div", {a: 1}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(1) }) o("handles falsy number attr", function() { var vnode = m("div", {a: 0}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(0) }) o("handles boolean attr", function() { var vnode = m("div", {a: true}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(true) }) o("handles falsy boolean attr", function() { var vnode = m("div", {a: false}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals(false) }) o("handles only key in attrs", function() { var vnode = m("div", {key:"a"}) o(vnode.tag).equals("div") o(vnode.attrs).deepEquals({}) o(vnode.key).equals("a") }) o("handles many attrs", function() { var vnode = m("div", {a: "b", c: "d"}) o(vnode.tag).equals("div") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles className attrs property", function() { var vnode = m("div", {className: "a"}) o(vnode.attrs.className).equals("a") }) o("handles 'class' as a verbose attribute declaration", function() { var vnode = m("[class=a]") o(vnode.attrs.className).equals("a") }) o("handles merging classes w/ class property", function() { var vnode = m(".a", {class: "b"}) o(vnode.attrs.className).equals("a b") }) o("handles merging classes w/ className property", function() { var vnode = m(".a", {className: "b"}) o(vnode.attrs.className).equals("a b") }) }) o.spec("custom element attrs", function() { o("handles string attr", function() { var vnode = m("custom-element", {a: "b"}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals("b") }) o("handles falsy string attr", function() { var vnode = m("custom-element", {a: ""}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals("") }) o("handles number attr", function() { var vnode = m("custom-element", {a: 1}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(1) }) o("handles falsy number attr", function() { var vnode = m("custom-element", {a: 0}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(0) }) o("handles boolean attr", function() { var vnode = m("custom-element", {a: true}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(true) }) o("handles falsy boolean attr", function() { var vnode = m("custom-element", {a: false}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals(false) }) o("handles only key in attrs", function() { var vnode = m("custom-element", {key:"a"}) o(vnode.tag).equals("custom-element") o(vnode.attrs).deepEquals({}) o(vnode.key).equals("a") }) o("handles many attrs", function() { var vnode = m("custom-element", {a: "b", c: "d"}) o(vnode.tag).equals("custom-element") o(vnode.attrs.a).equals("b") o(vnode.attrs.c).equals("d") }) o("handles className attrs property", function() { var vnode = m("custom-element", {className: "a"}) o(vnode.attrs.className).equals("a") }) o("casts className using toString like browsers", function() { const className = { valueOf: () => ".valueOf", toString: () => "toString" } var vnode = m("custom-element" + className, {className: className}) o(vnode.attrs.className).equals("valueOf toString") }) }) o.spec("children", function() { o("handles string single child", function() { var vnode = m("div", {}, ["a"]) o(vnode.children[0].children).equals("a") }) o("handles falsy string single child", function() { var vnode = m("div", {}, [""]) o(vnode.children[0].children).equals("") }) o("handles number single child", function() { var vnode = m("div", {}, [1]) o(vnode.children[0].children).equals("1") }) o("handles falsy number single child", function() { var vnode = m("div", {}, [0]) o(vnode.children[0].children).equals("0") }) o("handles boolean single child", function() { var vnode = m("div", {}, [true]) o(vnode.children).deepEquals([null]) }) o("handles falsy boolean single child", function() { var vnode = m("div", {}, [false]) o(vnode.children).deepEquals([null]) }) o("handles null single child", function() { var vnode = m("div", {}, [null]) o(vnode.children).deepEquals([null]) }) o("handles undefined single child", function() { var vnode = m("div", {}, [undefined]) o(vnode.children).deepEquals([null]) }) o("handles multiple string children", function() { var vnode = m("div", {}, ["", "a"]) o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("a") }) o("handles multiple number children", function() { var vnode = m("div", {}, [0, 1]) o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("0") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("1") }) o("handles multiple boolean children", function() { var vnode = m("div", {}, [false, true]) o(vnode.children).deepEquals([null, null]) }) o("handles multiple null/undefined child", function() { var vnode = m("div", {}, [null, undefined]) o(vnode.children).deepEquals([null, null]) }) o("handles falsy number single child without attrs", function() { var vnode = m("div", 0) o(vnode.children[0].children).equals("0") }) }) o.spec("permutations", function() { o("handles null attr and children", function() { var vnode = m("div", null, [m("a"), m("b")]) o(vnode.children.length).equals(2) o(vnode.children[0].tag).equals("a") o(vnode.children[1].tag).equals("b") }) o("handles null attr and child unwrapped", function() { var vnode = m("div", null, m("a")) o(vnode.children.length).equals(1) o(vnode.children[0].tag).equals("a") }) o("handles null attr and children unwrapped", function() { var vnode = m("div", null, m("a"), m("b")) o(vnode.children.length).equals(2) o(vnode.children[0].tag).equals("a") o(vnode.children[1].tag).equals("b") }) o("handles attr and children", function() { var vnode = m("div", {a: "b"}, [m("i"), m("s")]) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles attr and child unwrapped", function() { var vnode = m("div", {a: "b"}, m("i")) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("i") }) o("handles attr and children unwrapped", function() { var vnode = m("div", {a: "b"}, m("i"), m("s")) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles attr and text children", function() { var vnode = m("div", {a: "b"}, ["c", "d"]) o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("c") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("d") }) o("handles attr and single string text child", function() { var vnode = m("div", {a: "b"}, ["c"]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("c") }) o("handles attr and single falsy string text child", function() { var vnode = m("div", {a: "b"}, [""]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("") }) o("handles attr and single number text child", function() { var vnode = m("div", {a: "b"}, [1]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("1") }) o("handles attr and single falsy number text child", function() { var vnode = m("div", {a: "b"}, [0]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("0") }) o("handles attr and single boolean text child", function() { var vnode = m("div", {a: "b"}, [true]) o(vnode.attrs.a).equals("b") o(vnode.children).deepEquals([null]) }) o("handles attr and single falsy boolean text child", function() { var vnode = m("div", {a: "b"}, [0]) o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("0") }) o("handles attr and single false boolean text child", function() { var vnode = m("div", {a: "b"}, [false]) o(vnode.attrs.a).equals("b") o(vnode.children).deepEquals([null]) }) o("handles attr and single text child unwrapped", function() { var vnode = m("div", {a: "b"}, "c") o(vnode.attrs.a).equals("b") o(vnode.children[0].children).equals("c") }) o("handles attr and text children unwrapped", function() { var vnode = m("div", {a: "b"}, "c", "d") o(vnode.attrs.a).equals("b") o(vnode.children[0].tag).equals("#") o(vnode.children[0].children).equals("c") o(vnode.children[1].tag).equals("#") o(vnode.children[1].children).equals("d") }) o("handles children without attr", function() { var vnode = m("div", [m("i"), m("s")]) o(vnode.attrs).deepEquals({}) o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles child without attr unwrapped", function() { var vnode = m("div", m("i")) o(vnode.attrs).deepEquals({}) o(vnode.children[0].tag).equals("i") }) o("handles children without attr unwrapped", function() { var vnode = m("div", m("i"), m("s")) o(vnode.attrs).deepEquals({}) o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) o("handles shared attrs", function() { var attrs = {a: "b"} var nodeA = m(".a", attrs) var nodeB = m(".b", attrs) o(nodeA.attrs.className).equals("a") o(nodeA.attrs.a).equals("b") o(nodeB.attrs.className).equals("b") o(nodeB.attrs.a).equals("b") }) o("doesnt modify passed attributes object", function() { var attrs = {a: "b"} m(".a", attrs) o(attrs).deepEquals({a: "b"}) }) o("non-nullish attr takes precedence over selector", function() { o(m("[a=b]", {a: "c"}).attrs).deepEquals({a: "c"}) }) o("null attr takes precedence over selector", function() { o(m("[a=b]", {a: null}).attrs).deepEquals({a: null}) }) o("undefined attr takes precedence over selector", function() { o(m("[a=b]", {a: undefined}).attrs).deepEquals({a: undefined}) }) o("handles fragment children without attr unwrapped", function() { var vnode = m("div", [m("i")], [m("s")]) o(vnode.children[0].tag).equals("[") o(vnode.children[0].children[0].tag).equals("i") o(vnode.children[1].tag).equals("[") o(vnode.children[1].children[0].tag).equals("s") }) o("handles children with nested array", function() { var vnode = m("div", [[m("i"), m("s")]]) o(vnode.children[0].tag).equals("[") o(vnode.children[0].children[0].tag).equals("i") o(vnode.children[0].children[1].tag).equals("s") }) o("handles children with deeply nested array", function() { var vnode = m("div", [[[m("i"), m("s")]]]) o(vnode.children[0].tag).equals("[") o(vnode.children[0].children[0].tag).equals("[") o(vnode.children[0].children[0].children[0].tag).equals("i") o(vnode.children[0].children[0].children[1].tag).equals("s") }) }) o.spec("components", function() { o("works with POJOs", function() { var component = { view: function() {} } var vnode = m(component, {id: "a"}, "b") o(vnode.tag).equals(component) o(vnode.attrs.id).equals("a") o(vnode.children.length).equals(1) o(vnode.children[0]).equals("b") }) o("works with constructibles", function() { var component = o.spy() component.prototype.view = function() {} var vnode = m(component, {id: "a"}, "b") o(component.callCount).equals(0) o(vnode.tag).equals(component) o(vnode.attrs.id).equals("a") o(vnode.children.length).equals(1) o(vnode.children[0]).equals("b") }) o("works with closures", function () { var component = o.spy() var vnode = m(component, {id: "a"}, "b") o(component.callCount).equals(0) o(vnode.tag).equals(component) o(vnode.attrs.id).equals("a") o(vnode.children.length).equals(1) o(vnode.children[0]).equals("b") }) }) })
MithrilJS/mithril.js
render/tests/test-hyperscript.js
JavaScript
mit
18,028
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInitf63a394c8496bb8b8178c286d239e5ee::getLoader();
jairoserrano/SimpleBlogClase
vendor/autoload.php
PHP
mit
183
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["choose_file"] = factory(); else root["choose_file"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // __webpack_hash__ /******/ __webpack_require__.h = "05ce0eff1b9563477190"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var assign = __webpack_require__(4); var is_function = __webpack_require__(2); var is_presto = !!window.opera; var is_trident = document.all && !is_presto; var defaults = { multiple: false, accept: '*/*', success: function (input) {} }; var on = function (event, element, callback) { if (element.addEventListener) { element.addEventListener(event, callback, false); } else if (element.attachEvent) { element.attachEvent('on' + event, callback); } }; var input_remove = function (input) { is_trident || input.parentNode && input.parentNode.removeChild(input); // input.removeAttribute('accept'); // input.removeAttribute('style'); }; module.exports = function (params) { var input; var options; options = assign({}, defaults, is_function(params) ? { success: params } : params || {}); options.success = is_function(options.success) ? options.success : defaults.success; input = document.createElement('input'); input.setAttribute('style', 'position: absolute; clip: rect(0, 0, 0, 0);'); input.setAttribute('accept', options.accept); input.setAttribute('type', 'file'); input.multiple = !!options.multiple; on(is_trident ? 'input' : 'change', input, function (e) { if (is_presto) { input_remove(input); } if (input.value) { options.success(input); } }); (document.body || document.documentElement).appendChild(input); if (is_presto) { setTimeout(function () { input.click(); }, 0); } else { input.click(); input_remove(input); } }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var isObject = __webpack_require__(3); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = global.Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array constructors, and // PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 3 */ /***/ function(module, exports) { /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 4 */ /***/ function(module, exports) { /* eslint-disable no-unused-vars */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ } /******/ ]) }); ;
zobzn/choose-file
dist/choose-file.js
JavaScript
mit
6,946
function move(Restangular, $uibModal, $q, notification, $state,$http) { 'use strict'; return { restrict: 'E', scope: { selection: '=', type: '@', ngConfirmMessage: '@', ngConfirm: '&' }, link: function(scope, element, attrs) { scope.myFunction = function(){ var spanDropdown = document.querySelectorAll('span.btn-group')[0]; spanDropdown.classList.add("open"); }; scope.icon = 'glyphicon-list'; if (attrs.type == 'move_to_package') scope.button = 'Move to Package'; var vods_array = []; $http.get('../api/vodpackages?package_type_id=3&package_type_id=4').then(function(response) { var data = response.data; for(var i=0;i<data.length;i++){ vods_array.push({name:data[i].package_name,id:data[i].id}) } }); scope.list_of_vods = vods_array; var newarray = []; scope.moveto = function () { var spanDropdown = document.querySelectorAll('span.btn-group')[0]; spanDropdown.classList.remove("open"); var array_of_selection_vod = scope.selection; scope.change = function(name,id){ scope.button = name; var id_of_selected_package = id; for(var j=0;j<array_of_selection_vod.length;j++){ newarray.push({package_id:id_of_selected_package,vod_id:array_of_selection_vod[j].values.id}) } if(newarray.length === 0) { notification.log('Sorry, you have not selected any Vod item.', { addnCls: 'humane-flatty-error' }); } else { $http.post("../api/package_vod", newarray).then(function (response,data, status, headers, config,file) { notification.log('Vod successfully added', { addnCls: 'humane-flatty-success' }); window.location.replace("#/vodPackages/edit/"+id_of_selected_package); },function (data, status, headers, config) { notification.log('Something Wrong', { addnCls: 'humane-flatty-error' }); }).on(error, function(error){ winston.error("The error during post request is ") }); } }; } }, template: '<div class="btn-group" uib-dropdown is-open="status.isopen"> ' + '<button ng-click="myFunction()" id="single-button" type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disabled">' + '<span class="glyphicon {{icon}}"></span> {{button}} <span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu" uib-dropdown-menu role="menu" aria-labelledby="single-button">' + '<li role="menuitem" ng-click="change(choice.name,choice.id)" ng-repeat="choice in list_of_vods">' + '<p id="paragraph_vod" ng-click="moveto()">{{choice.name}}</p>' + '</li>' + '</ul>' + '</div>' }; } move.$inject = ['Restangular', '$uibModal', '$q', 'notification', '$state','$http']; export default move;
MAGOWARE/backoffice-administration
public/admin/js/smsbatch/move.js
JavaScript
mit
3,393
let mongoose = require('mongoose'); let URL = process.env.MONGO_URL || 'localhost'; let USER = process.env.MONGO_USR || ''; let PASSWORD = process.env.MONGO_PWD || ''; mongoose.connect(`mongodb://${USER}:${PASSWORD}@${URL}`); //TODO doens't work for localhost console.log(`Connecting to ${URL}...`); let db = mongoose.connection; db.on('error', (err) => console.error(err)); db.once('open', () => console.log('Connected!')); module.exports = db;
tmlewallen/PongPing
server/db.js
JavaScript
mit
448
<?php require_once('./config/accesscontrol.php'); require_once('./utilities.php'); // Set up/check session and get database password etc. require_once('./config/MySQL.php'); session_start(); sessionAuthenticate(); $mysql = mysql_connect($mysql_host, $mysql_user, $mysql_password); if (!mysql_select_db($mysql_database)) showerror(); check_location(32, $mysql); ?> <html> <head> <title>52 Weeks of Primeval</title> <link rel="stylesheet" href="./styles/default.css" type="text/css"> </head> <body> <?php print_header($mysql); $phase = get_user_phase($mysql); ?> <div class=main> <?php print_standard_start($mysql); ?> <div class=location> <img src=assets/location32.png> <h2>A Sandy Desert</h2> <p>You find yourself standing on a rocky outcrop in the middle of a sea of sand. The air is low in oxygen which makes it hard, but not impossible, to breathe. <?php $action_done = get_value_from_users("action_done", $mysql); if ($action_done) { print "<b>You must use breathing apparatus or take damage.</b>"; } ?> </p> </div> </body> </html>
louiseadennis/primeval_game
www/location32.php
PHP
mit
1,052
define([], function() { return Backbone.View.extend({ tagName: "a", className: "projectlink", attributes: { href: "#" }, template: _.template("<%- name %>"), events: { "click": "toggleSelection" }, initialize: function() { this.listenTo(this.model, "change:selected", function(m, selected) { this.$el.toggleClass("selected", selected); }); this.listenTo(this.model, "change:color", function(m, color) { this.$el.css("color", color); }); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; }, toggleSelection: function() { this.model.set("selected", !this.model.get("selected")); return false; } }); });
EusthEnoptEron/bakastats
js/views/projectview.js
JavaScript
mit
704
'use strict'; (function() { describe('HomeController', function() { //Initialize global variables var scope, HomeController, myFactory; // Load the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(inject(function($controller, $rootScope) { scope = $rootScope.$new(); HomeController = $controller('HomeController', { $scope: scope }); })); it('should expose the authentication service', function() { expect(scope.authentication).toBeTruthy(); }); it('should see the result', function(){ scope.feedSrc = 'http://rss.cnn.com/rss/cnn_topstories.rss'; }); }); })();
kylelin47/great-unknown
public/modules/core/tests/home.client.controller.test.js
JavaScript
mit
701
<?php namespace Droath\ConsoleForm\Field; /** * Define field interface. */ interface FieldInterface { /** * The data type the field holds. * * @return string */ public function dataType(); /** * Field question class name. * * @return string * The question class that best represents the field structure. */ public function questionClass(); /** * Field question class constructor arguments. * * @return array * An array of constructor arguments. */ public function questionClassArgs(); }
droath/console-form
src/Field/FieldInterface.php
PHP
mit
591
using System; using System.Linq; namespace GestorONG.Models { interface IPaginationCollaborators<T> where T:class { /// <summary> /// Get data paginated. /// </summary> /// <param name="filter">Filter applied by user.</param> /// <param name="initialPage">Initial page.</param> /// <param name="pageSize">Amount of records for each page.</param> /// <param name="totalRecords">Total of records.</param> /// <param name="recordsFiltered">Total records filtered when filter applied.</param> /// <param name="sortColumn">Column used to sort.</param> /// <param name="sortColumnDir">Direction to sort results (ascending, descending).</param> /// <returns>List of all elements found that matches criteria.</returns> IQueryable<T> GetPaginated(string filter, int initialPage, int pageSize, out int totalRecords, out int recordsFiltered, string sortColumn, string sortColumnDir, string country, string CIF_NIF, Single quantity, string periodicity); } }
joakDA/gestor-ongd-sps
GestorONG/Models/IPaginationCollaborators.cs
C#
mit
1,070
package com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.enums; /** * Created by natalia on 06/07/15. */ public enum BalanceType { AVAILABLE("AVAILABLE"), BOOK("BOOK"); private final String code; BalanceType(String code) { this.code = code; } public String getCode() { return this.code ; } public static BalanceType getByCode(String code) { switch (code) { case "BOOK": return BOOK; case "AVAILABLE": return AVAILABLE; default: return AVAILABLE; } } }
fvasquezjatar/fermat-unused
fermat-api/src/main/java/com/bitdubai/fermat_api/layer/dmp_basic_wallet/common/enums/BalanceType.java
Java
mit
574
<?php namespace TagProNews\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ 'Symfony\Component\HttpKernel\Exception\HttpException' ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { if ($this->isHttpException($e)) { return $this->renderHttpException($e); } else { return parent::render($request, $e); } } }
tagpronews/api
app/Exceptions/Handler.php
PHP
mit
951
/** @file This file contains the functions to adjust an existing polygon. */ /** * Creates the adjusting event * @constructor * @param {string} dom_attach - The html element where the polygon lives * @param {array} x - The x coordinates for the polygon points * @param {array} y - The y coordinates for the polygon points * @param {string} obj_name - The name of the adjusted_polygon * @param {function} ExitFunction - the_function to execute once adjusting is done * @param {float} scale - Scaling factor for polygon points */ function AdjustEvent(dom_attach,x,y,obj_name,ExitFunction,scale, bounding_box_annot) { /****************** Private variables ************************/ // ID of DOM element to attach to: this.bounding_box = bounding_box_annot; this.dom_attach = dom_attach; this.scale_button_pressed = false; // Polygon: this.x = x; this.y = y; // Object name: this.obj_name = obj_name; // Function to call when event is finished: this.ExitFunction = ExitFunction; // Scaling factor for polygon points: this.scale = scale; // Boolean indicating whether a control point has been edited: this.editedControlPoints = false; // Boolean indicating whether a control point is being edited: this.isEditingControlPoint = false; // Boolean indicating whether a scaling point is being edited: this.isEditingScalingPoint = false; // Boolean indicating whether the center of mass of the polygon is being // adjusted: this.isMovingCenterOfMass = false; // Index into which control point has been selected: this.selectedControlPoint; // Index into which scaling point has been selected: this.selectedScalingPoint; // Location of center of mass: this.center_x; this.center_y; // Element ids of drawn control points: this.control_ids = null; this.scalepoints_ids = null; // Element id of drawn center point: this.center_id = null; // ID of drawn polygon: this.polygon_id; /****************** Public functions ************************/ /** This function starts the adjusting event: */ this.StartEvent = function() { console.log('LabelMe: Starting adjust event...'); // Draw polygon: this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; FillPolygon(this.polygon_id); oVP.ShowTemporalBar(); // Set mousedown action to stop adjust event when user clicks on canvas: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); // Show control points: if (this.bounding_box){ this.ShowScalingPoints(); this.ShowCenterOfMass(); return; } this.ShowControlPoints(); // Show center of mass: this.ShowCenterOfMass(); $(window).keydown({obj: this}, function (e){ if (!e.data.obj.scale_button_pressed && e.keyCode == 17 && !e.data.obj.isEditingControlPoint){ e.data.obj.RemoveScalingPoints(); e.data.obj.RemoveControlPoints(); e.data.obj.RemoveCenterOfMass(); e.data.obj.ShowScalingPoints(); e.data.obj.scale_button_pressed = true; } }); $(window).keyup({obj: this}, function (e){ if (e.keyCode == 17 && !e.data.obj.isEditingControlPoint){ e.data.obj.scale_button_pressed = false; e.data.obj.RemoveScalingPoints(); e.data.obj.RemoveControlPoints(); e.data.obj.RemoveCenterOfMass(); e.data.obj.ShowControlPoints(); e.data.obj.ShowCenterOfMass(); } }); }; /** This function stops the adjusting event and calls the ExitFunction: */ this.StopAdjustEvent = function() { // Remove polygon: $('#'+this.polygon_id).remove(); // Remove key press action $(window).unbind("keydown"); $(window).unbind("keyup"); // Remove control points and center of mass point: this.RemoveControlPoints(); this.RemoveCenterOfMass(); this.RemoveScalingPoints(); console.log('LabelMe: Stopped adjust event.'); oVP.HideTemporalBar(); // Call exit function: this.ExitFunction(this.x,this.y,this.editedControlPoints); }; /** This function shows the scaling points for a polygon */ this.ShowScalingPoints = function (){ if(!this.scalepoints_ids) this.scalepoints_ids = new Array(); for (var i = 0; i < this.x.length; i++){ this.scalepoints_ids.push(DrawPoint(this.dom_attach,this.x[i],this.y[i],'r="5" fill="#0000ff" stroke="#ffffff" stroke-width="2.5"',this.scale)); } for (var i = 0; i < this.scalepoints_ids.length; i++) $('#'+this.scalepoints_ids[i]).mousedown({obj: this,point: i},function(e) { return e.data.obj.StartMoveScalingPoint(e.data.point); }); } /** This function removes the displayed scaling points for a polygon */ this.RemoveScalingPoints = function (){ if(this.scalepoints_ids) { for(var i = 0; i < this.scalepoints_ids.length; i++) $('#'+this.scalepoints_ids[i]).remove(); this.scalepoints_ids = null; } } /** This function shows the control points for a polygon */ this.ShowControlPoints = function() { if(!this.control_ids) this.control_ids = new Array(); for(var i = 0; i < this.x.length; i++) { // Draw control point: this.control_ids.push(DrawPoint(this.dom_attach,this.x[i],this.y[i],'r="5" fill="#00ff00" stroke="#ffffff" stroke-width="2.5"',this.scale)); // Set action: $('#'+this.control_ids[i]).mousedown({obj: this,point: i},function(e) { return e.data.obj.StartMoveControlPoint(e.data.point); }); } }; /** This function removes the displayed control points for a polygon */ this.RemoveControlPoints = function() { if(this.control_ids) { for(var i = 0; i < this.control_ids.length; i++) $('#'+this.control_ids[i]).remove(); this.control_ids = null; } }; /** This function shows the middle grab point for a polygon. */ this.ShowCenterOfMass = function() { var MarkerSize = 8; if(this.x.length==1) MarkerSize = 6; // Get center point for polygon: this.CenterOfMass(this.x,this.y); // Draw center point: this.center_id = DrawPoint(this.dom_attach,this.center_x,this.center_y,'r="' + MarkerSize + '" fill="red" stroke="#ffffff" stroke-width="' + MarkerSize/2 + '"',this.scale); // Set action: $('#'+this.center_id).mousedown({obj: this},function(e) { return e.data.obj.StartMoveCenterOfMass(); }); }; /** This function removes the middle grab point for a polygon */ this.RemoveCenterOfMass = function() { if(this.center_id) { $('#'+this.center_id).remove(); this.center_id = null; } }; /** This function is called when one scaling point is clicked * It prepares the polygon for scaling. * @param {int} i - the index of the scaling point being modified */ this.StartMoveScalingPoint = function(i) { if(!this.isEditingScalingPoint) { $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousemove({obj: this},function(e) { return e.data.obj.MoveScalingPoint(e.originalEvent, !e.data.obj.bounding_box); }); $('#body').mouseup({obj: this},function(e) { return e.data.obj.StopMoveScalingPoint(e.originalEvent); }); this.RemoveCenterOfMass(); this.selectedScalingPoint = i; this.isEditingScalingPoint = true; this.editedControlPoints = true; } }; /** This function is called when one scaling point is being moved * It computes the position of the scaling point in relation to the polygon's center of mass * and resizes the polygon accordingly * @param {event} event - Indicates a point is being moved and the index of such point */ this.MoveScalingPoint = function(event, proportion) { var x = GetEventPosX(event); var y = GetEventPosY(event); if(this.isEditingScalingPoint && (this.scale_button_pressed || this.bounding_box)) { var origx, origy, pointx, pointy, prx, pry; pointx = this.x[this.selectedScalingPoint]; pointy = this.y[this.selectedScalingPoint]; this.CenterOfMass(this.x,this.y); var sx = pointx - this.center_x; var sy = pointy - this.center_y; if (sx < 0) origx = Math.max.apply(Math, this.x); else origx = Math.min.apply(Math, this.x); if (sy < 0) origy = Math.max.apply(Math, this.y); else origy = Math.min.apply(Math, this.y); prx = (Math.round(x/this.scale)-origx)/(pointx-origx); pry = (Math.round(y/this.scale)-origy)/(pointy-origy); if (proportion) pry = prx; if (prx <= 0 || pry <= 0 ) return; for (var i = 0; i < this.x.length; i++){ // Set point: var dx = (this.x[i] - origx)*prx; var dy = (this.y[i] - origy)*pry; x = origx + dx; y = origy + dy; this.x[i] = Math.max(Math.min(x,main_media.width_orig),1); this.y[i] = Math.max(Math.min(y,main_media.height_orig),1); } // Remove polygon and redraw: console.log(this.polygon_id); $('#'+this.polygon_id).parent().remove(); $('#'+this.polygon_id).remove(); this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; // Adjust control points: this.RemoveScalingPoints(); this.ShowScalingPoints(); } }; /** This function is called when one scaling point stops being moved * It updates the xml with the new coordinates of the polygon. * @param {event} event - Indicates a point is being moved and the index of such point */ this.StopMoveScalingPoint = function(event) { console.log('Moving scaling point'); if(this.isEditingScalingPoint) { this.MoveScalingPoint(event, !this.bounding_box); FillPolygon(this.polygon_id); this.isEditingScalingPoint = false; if (video_mode) main_media.UpdateObjectPosition(select_anno, this.x, this.y); this.ShowCenterOfMass(); // Set action: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); } }; /** This function is called when one control point is clicked * @param {int} i - the index of the control point being modified */ this.StartMoveControlPoint = function(i) { if(!this.isEditingControlPoint) { $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousemove({obj: this},function(e) { return e.data.obj.MoveControlPoint(e.originalEvent); }); $('#body').mouseup({obj: this},function(e) { return e.data.obj.StopMoveControlPoint(e.originalEvent); }); this.RemoveCenterOfMass(); this.selectedControlPoint = i; this.isEditingControlPoint = true; this.editedControlPoints = true; } }; /** This function is called when one control point is being moved * @param {event} event - Indicates a point is being moved and the index of such point */ this.MoveControlPoint = function(event) { if(this.isEditingControlPoint) { var x = GetEventPosX(event); var y = GetEventPosY(event); // Set point: this.x[this.selectedControlPoint] = Math.max(Math.min(Math.round(x/this.scale),main_media.width_orig),1); this.y[this.selectedControlPoint] = Math.max(Math.min(Math.round(y/this.scale),main_media.height_orig),1); this.originalx = this.x; this.originaly = this.y; // Remove polygon and redraw: $('#'+this.polygon_id).parent().remove(); $('#'+this.polygon_id).remove(); this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; // Adjust control points: this.RemoveControlPoints(); this.ShowControlPoints(); } }; /** This function is called when one control point stops being moved * It updates the xml with the new coordinates of the polygon. * @param {event} event - Indicates a point is being moved and the index of such point */ this.StopMoveControlPoint = function(event) { console.log('Moving control point'); if(this.isEditingControlPoint) { this.MoveControlPoint(event); FillPolygon(this.polygon_id); this.ShowCenterOfMass(); this.isEditingControlPoint = false; if (video_mode) main_media.UpdateObjectPosition(select_anno, this.x, this.y); // Set action: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); } }; /** This function is called when the middle grab point is clicked * It prepares the polygon for moving. */ this.StartMoveCenterOfMass = function() { if(!this.isMovingCenterOfMass) { $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousemove({obj: this},function(e) { return e.data.obj.MoveCenterOfMass(e.originalEvent); }); $('#body').mouseup({obj: this},function(e) { return e.data.obj.StopMoveCenterOfMass(e.originalEvent); }); this.RemoveScalingPoints(); this.RemoveControlPoints(); this.isMovingCenterOfMass = true; this.editedControlPoints = true; } }; /** This function is called when the middle grab point is being moved * @param {event} event - Indicates the middle grab point is moving * It modifies the control points to be consistent with the polygon shift */ this.MoveCenterOfMass = function(event) { if(this.isMovingCenterOfMass) { var x = GetEventPosX(event); var y = GetEventPosY(event); // Get displacement: var dx = Math.round(x/this.scale)-this.center_x; var dy = Math.round(y/this.scale)-this.center_y; // Adjust dx,dy to make sure we don't go outside of the image: for(var i = 0; i < this.x.length; i++) { dx = Math.max(this.x[i]+dx,1)-this.x[i]; dy = Math.max(this.y[i]+dy,1)-this.y[i]; dx = Math.min(this.x[i]+dx,main_media.width_orig)-this.x[i]; dy = Math.min(this.y[i]+dy,main_media.height_orig)-this.y[i]; } // Adjust polygon and center point: for(var i = 0; i < this.x.length; i++) { this.x[i] = Math.round(this.x[i]+dx); this.y[i] = Math.round(this.y[i]+dy); } this.center_x = Math.round(this.scale*(dx+this.center_x)); this.center_y = Math.round(this.scale*(dy+this.center_y)); // Remove polygon and redraw: $('#'+this.polygon_id).parent().remove(); $('#'+this.polygon_id).remove(); this.polygon_id = this.DrawPolygon(this.dom_attach,this.x,this.y,this.obj_name,this.scale); select_anno.polygon_id = this.polygon_id; // Redraw center of mass: this.RemoveCenterOfMass(); this.ShowCenterOfMass(); } }; /** This function is called when the middle grab point stops being moved * It updates the xml with the new coordinates of the polygon. * @param {event} event - Indicates the middle grab point is being moved and the index of such point */ this.StopMoveCenterOfMass = function(event) { if(this.isMovingCenterOfMass) { // Move to final position: this.MoveCenterOfMass(event); // Refresh control points: if (this.bounding_box){ this.RemoveScalingPoints(); this.RemoveCenterOfMass(); this.ShowScalingPoints(); this.ShowCenterOfMass(); } else { this.RemoveControlPoints(); this.RemoveCenterOfMass(); this.ShowControlPoints(); this.ShowCenterOfMass(); } FillPolygon(this.polygon_id); this.isMovingCenterOfMass = false; if (video_mode) main_media.UpdateObjectPosition(select_anno, this.x, this.y); // Set action: $('#'+this.dom_attach).unbind(); $('#'+this.dom_attach).mousedown({obj: this},function(e) { return e.data.obj.StopAdjustEvent(); }); } }; /*************** Helper functions ****************/ /** Compute center of mass for a polygon given array of points (x,y): */ this.CenterOfMass = function(x,y) { var N = x.length; // Center of mass for a single point: if(N==1) { this.center_x = x[0]; this.center_y = y[0]; return; } // The center of mass is the average polygon edge midpoint weighted by // edge length: this.center_x = 0; this.center_y = 0; var perimeter = 0; for(var i = 1; i <= N; i++) { var length = Math.round(Math.sqrt(Math.pow(x[i-1]-x[i%N], 2) + Math.pow(y[i-1]-y[i%N], 2))); this.center_x += length*Math.round((x[i-1] + x[i%N])/2); this.center_y += length*Math.round((y[i-1] + y[i%N])/2); perimeter += length; } this.center_x /= perimeter; this.center_y /= perimeter; }; this.DrawPolygon = function(dom_id,x,y,obj_name,scale) { if(x.length==1) return DrawFlag(dom_id,x[0],y[0],obj_name,scale); var attr = 'fill="none" stroke="' + HashObjectColor(obj_name) + '" stroke-width="4"'; return DrawPolygon(dom_id,x,y,obj_name,attr,scale); }; }
joelimlimit/LabelMeAnnotationTool
annotationTools/js/adjust_event.js
JavaScript
mit
17,777
#include <algorithm> #include <map> #include <math.h> #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #ifndef HUGE_JOB_MODE #include <fj_tool/fapp.h> #include <fjcoll.h> #endif using namespace std; #include "pearson-3d.h" bool EXTEND_MISSION=false; int T_MAX; int T_MONITOR; int mpi_my_rank; const double PI=3.14159265358979323846; float frand() { return rand() / float(RAND_MAX); } double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } /* void init() { for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { double x = double(navi.offset_x + ix)/NX; double y = double(navi.offset_y + iy)/NY; double z = double(navi.offset_z + iz)/NZ; U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; if (z > 0.49 && z < 0.51 && x > 0.4 && x < 0.6) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } }*/ double gaussian(double x, double y,double z) { double d = sqrt(x*x+y*y+z*z); return 1.0/(1.0+exp( (d-3.0)*3.0 )); } typedef pair<int,pair<int,int> > Key; void init() { if (NZ<500){ const int NI=4,NJ=7; double oxs[NI*NJ], pat_x[NI] = {230,80, 40,170}; double oys[NI*NJ], pat_y[NI] = {131,131,131,131}; double ozs[NI*NJ], pat_z[NI] = { 50,80,120,190}; for (int i=0;i<NI;++i) { for (int j=0;j<NJ;++j) { oxs[j*4+i] = pat_x[i] + 2.0 * j*(2*frand()-1); oys[j*4+i] = pat_y[i] + 2.0 * j*(2*frand()-1); ozs[j*4+i] = pat_z[i] + 2.0 * j*(2*frand()-1); } } for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; double g=0; for (int i=0;i<NI*NJ;++i) { double oz=ozs[i], oy=oys[i],ox=oxs[i]; g += gaussian(iz-oz, ix-ox ,iy-oy); } if (g>=1.0) g=1.0; U[ix][iy][iz] -= 0.5 *g; V[ix][iy][iz] += 0.25 *g; } } } }else{ map<Key ,double> seeds; for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { Key k (ix/16, pair<int,int>(iy/16, iz/16)); U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; double s = seeds[k]; if (s==0) { s = frand(); seeds[k]=s; } if (s < 0.1 ) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } } } void write_monitor() { int global_position[6]; global_position[0] = navi.offset_x + navi.lower_x; global_position[1] = navi.offset_y + navi.lower_y; global_position[2] = navi.offset_z + navi.lower_z; global_position[3] = navi.upper_x - navi.lower_x; global_position[4] = navi.upper_y - navi.lower_y; global_position[5] = navi.upper_z - navi.lower_z; int x_size = navi.upper_x - navi.lower_x; int y_size = navi.upper_y - navi.lower_y; int z_size = navi.upper_z - navi.lower_z; if (navi.offset_x + navi.lower_x == 0) { char fn[256]; sprintf(fn, "out/monitorX-%06d-%d.txt", navi.time_step, mpi_my_rank); FILE *fp = fopen(fn,"wb"); fwrite(global_position, sizeof(int), 6, fp); { const int x=navi.lower_x + x_size/2; for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } fclose(fp); } if (navi.offset_y + navi.lower_y == 0) { char fn[256]; sprintf(fn, "out/monitorY-%06d-%d.txt", navi.time_step, mpi_my_rank); FILE *fp = fopen(fn,"wb"); fwrite(global_position, sizeof(int), 6, fp); { const int y=navi.lower_y + y_size/2; for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } fclose(fp); } } int main (int argc, char **argv) { MPI_Init(&argc, &argv); Formura_Init(&navi, MPI_COMM_WORLD); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank); srand(time(NULL)+mpi_my_rank*65537); if (argc <= 1) { T_MAX=8192; }else{ sscanf(argv[1], "%d", &T_MAX); } if (argc <= 2) { T_MONITOR=8192; }else{ sscanf(argv[2], "%d", &T_MONITOR); } if (argc >= 4) { EXTEND_MISSION = true; } init(); double t_begin = wctime(), t_end; int last_monitor_t = -T_MONITOR; char benchmark_name[256]; sprintf(benchmark_name,"main"); for(;;){ double t = wctime(); bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR; // if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) { // if(mpi_my_rank==0){ // //printf("marked %d step @ %lf sec\n", navi.time_step, t-t_begin); // } // } if(monitor_flag) { write_monitor(); if(mpi_my_rank==0){ printf("monitor %d step @ %lf sec\n", navi.time_step, t-t_begin); } } if(monitor_flag) { last_monitor_t += T_MONITOR; } if (navi.time_step >= T_MAX) { if (EXTEND_MISSION){ T_MAX*=2; T_MONITOR*=2; sprintf(benchmark_name,"extend-%d",T_MAX); #ifndef HUGE_JOB_MODE start_collection(benchmark_name); fapp_start(benchmark_name, 0,0); #endif }else{ break; } } if (navi.time_step == 0) { t_begin = wctime(); #ifndef HUGE_JOB_MODE start_collection(benchmark_name); fapp_start(benchmark_name, 0,0); #endif } Formura_Forward(&navi); // navi.time_step increases MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization if (navi.time_step >= T_MAX) { t_end = wctime(); #ifndef HUGE_JOB_MODE stop_collection(benchmark_name); fapp_stop(benchmark_name, 0,0); #endif } } //printf("total wct = %lf sec\n",t_end - t_begin); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); }
nushio3/formura
examples/pearson-3d-main.cpp
C++
mit
6,294
package dis func Rearrange(s string, k int) string { hm := make([]int, 26) valid := make([]int, 26) var id, maxF, numOfMaxF int for _, c := range s { id = int(c - 'a') hm[id]++ if hm[id] > maxF { maxF, numOfMaxF = hm[id], 1 } else if hm[id] == maxF { numOfMaxF++ } } if (maxF-1)*k+numOfMaxF > len(s) { return "" } ret := make([]byte, len(s)) var pos int for i := range s { pos = findValidMax(hm, valid, i) // if pos == -1 { // return "" // } hm[pos]-- valid[pos] = i + k ret[i] = byte(pos) + 'a' } return string(ret) } func findValidMax(count []int, valid []int, idx int) int { curMax, pos := 0, -1 for i := range count { if count[i] > curMax && idx >= valid[i] { curMax = count[i] pos = i } } return pos }
Catorpilor/LeetCode
358_rearrange_string_k_distance_apart/dis.go
GO
mit
768
// Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe". function findPalindromes(input) { var words = input.replace(/\W+/g, ' ').replace(/\s+/, ' ').trim().split(' '), palindromes = [], length = words.length, currentWord, i; for (i = 0; i < length; i += 1) { currentWord = words[i]; if (isPalindrome(currentWord) && currentWord.length != 1) { palindromes.push(currentWord); } } return palindromes.join(); } function isPalindrome(currentWord) { var length = currentWord.length, i; for (i = 0; i < length / 2; i += 1) { if (currentWord[i] != currentWord[currentWord.length - 1 - i]) { return false; } } return true; } var textSample = 'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".'; console.log(findPalindromes(textSample));
danisio/JavaScript-Homeworks
08.Strings/Problem10-FindPalindromes.js
JavaScript
mit
958
module MailItemsHelper end
xsunsmile/smartmail
app/helpers/mail_items_helper.rb
Ruby
mit
27
#Scripts to plot the data, currently only in the context of Q&A communites.
Nik0l/UTemPro
Plot.py
Python
mit
76
package org.shenit.tutorial.android; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class HelloWorldActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_world); } }
jgnan/edu
android/AndroidTutorial/app/src/main/java/org/shenit/tutorial/android/HelloWorldActivity.java
Java
mit
353
<?php namespace FdjBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * JoueursTennis * * @ORM\Table(name="joueurs_tennis") * @ORM\Entity(repositoryClass="FdjBundle\Repository\JoueursTennisRepository") */ class JoueursTennis { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nom", type="string", length=255) */ private $nom; /** * @var string * * @ORM\Column(name="prenom", type="string", length=255, nullable=true) */ private $prenom; /** * @var string * * @ORM\Column(name="idJoueur", type="string", length=255, nullable=true) */ private $idJoueur; /** * @var string * * @ORM\Column(name="fullIdJoueurs", type="string", length=255, nullable=true) */ private $fullIdJoueurs; /** * @var string * * @ORM\Column(name="sexe", type="string", length=255, nullable=true) */ private $sexe; /** * @var string * * @ORM\Column(name="classementAtpWta", type="string", length=255, nullable=true) */ private $classementAtpWta; /** * @var string * * @ORM\Column(name="idEvent", type="string", length=255) */ private $idEvent; /** * @var string * * @ORM\Column(name="status", type="string", length=255) */ private $status; /** * @var string * * @ORM\Column(name="cote", type="string", length=255) */ private $cote; /** * @var string * * @ORM\Column(name="coteAdversaire", type="string", length=255) */ private $coteAdversaire; /** * @var string * * @ORM\Column(name="nbSet", type="string", length=255, nullable=true) */ private $nbSet; /** * @var string * * @ORM\Column(name="idCompetiton", type="string", length=255, nullable=true) */ private $idCompetiton; /** * @var string * * @ORM\Column(name="type", type="string", length=255, nullable=true) */ private $type; /** * @var string * * @ORM\Column(name="nomAdversaire", type="string", length=255, nullable=true) */ private $nomAdversaire; /** * @var string * * @ORM\Column(name="classementAtpAdversaire", type="string", length=255, nullable=true) */ private $classementAtpAdversaire; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nom * * @param string $nom * @return JoueursTennis */ public function setNom($nom) { $this->nom = $nom; return $this; } /** * Get nom * * @return string */ public function getNom() { return $this->nom; } /** * Set prenom * * @param string $prenom * @return JoueursTennis */ public function setPrenom($prenom) { $this->prenom = $prenom; return $this; } /** * Get prenom * * @return string */ public function getPrenom() { return $this->prenom; } /** * Set idJoueur * * @param string $idJoueur * @return JoueursTennis */ public function setIdJoueur($idJoueur) { $this->idJoueur = $idJoueur; return $this; } /** * Get idJoueur * * @return string */ public function getIdJoueur() { return $this->idJoueur; } /** * Set fullIdJoueurs * * @param string $fullIdJoueurs * @return JoueursTennis */ public function setFullIdJoueurs($fullIdJoueurs) { $this->fullIdJoueurs = $fullIdJoueurs; return $this; } /** * Get fullIdJoueurs * * @return string */ public function getFullIdJoueurs() { return $this->fullIdJoueurs; } /** * Set sexe * * @param string $sexe * @return JoueursTennis */ public function setSexe($sexe) { $this->sexe = $sexe; return $this; } /** * Get sexe * * @return string */ public function getSexe() { return $this->sexe; } /** * Set classementAtpWta * * @param string $classementAtpWta * @return JoueursTennis */ public function setClassementAtpWta($classementAtpWta) { $this->classementAtpWta = $classementAtpWta; return $this; } /** * Get classementAtpWta * * @return string */ public function getClassementAtpWta() { return $this->classementAtpWta; } /** * Set idEvent * * @param string $idEvent * @return JoueursTennis */ public function setIdEvent($idEvent) { $this->idEvent = $idEvent; return $this; } /** * Get idEvent * * @return string */ public function getIdEvent() { return $this->idEvent; } /** * Set status * * @param string $status * @return JoueursTennis */ public function setStatus($status) { $this->status = $status; return $this; } /** * Get status * * @return string */ public function getStatus() { return $this->status; } /** * Set cote * * @param string $cote * @return JoueursTennis */ public function setCote($cote) { $this->cote = $cote; return $this; } /** * Get cote * * @return string */ public function getCote() { return $this->cote; } /** * Set coteAdversaire * * @param string $coteAdversaire * @return JoueursTennis */ public function setCoteAdversaire($coteAdversaire) { $this->coteAdversaire = $coteAdversaire; return $this; } /** * Get coteAdversaire * * @return string */ public function getCoteAdversaire() { return $this->coteAdversaire; } /** * Set nbSet * * @param string $nbSet * @return JoueursTennis */ public function setNbSet($nbSet) { $this->nbSet = $nbSet; return $this; } /** * Get nbSet * * @return string */ public function getNbSet() { return $this->nbSet; } /** * Set idCompetiton * * @param string $idCompetiton * @return JoueursTennis */ public function setIdCompetiton($idCompetiton) { $this->idCompetiton = $idCompetiton; return $this; } /** * Get idCompetiton * * @return string */ public function getIdCompetiton() { return $this->idCompetiton; } /** * Set type * * @param string $type * @return JoueursTennis */ public function setType($type) { $this->type = $type; return $this; } /** * Get type * * @return string */ public function getType() { return $this->type; } /** * @return string */ public function getNomAdversaire() { return $this->nomAdversaire; } /** * @param string $nomAdversaire */ public function setNomAdversaire($nomAdversaire) { $this->nomAdversaire = $nomAdversaire; } /** * @return string */ public function getClassementAtpAdversaire() { return $this->classementAtpAdversaire; } /** * @param string $classementAtpAdversaire */ public function setClassementAtpAdversaire($classementAtpAdversaire) { $this->classementAtpAdversaire = $classementAtpAdversaire; } }
Jpilosel/cote
src/FdjBundle/Entity/JoueursTennis.php
PHP
mit
8,018
namespace sharp.Serene.Administration { @Serenity.Decorators.registerClass() export class LanguageDialog extends Serenity.EntityDialog<LanguageRow, any> { protected getFormKey() { return LanguageForm.formKey; } protected getIdProperty() { return LanguageRow.idProperty; } protected getLocalTextPrefix() { return LanguageRow.localTextPrefix; } protected getNameProperty() { return LanguageRow.nameProperty; } protected getService() { return LanguageService.baseUrl; } protected form = new LanguageForm(this.idPrefix); } }
narekye/code
sharp/src/Serene/sharp.Serene/sharp.Serene.Web/Modules/Administration/Language/LanguageDialog.ts
TypeScript
mit
585
// 19. Write a JavaScript function that returns array elements larger than a number. //two agrs - an array and a number to be larger than function isGreater(arr, num) { //set up an array to contain the results var resultArray = []; //iterate through based on length of the arr for(var i = 0; i < arr.length; i++) { //if current arr value is greater than num if(arr[i] > num) { //push result to resultArray resultArray.push(arr[i]); } } //log results console.log(resultArray); }
jaj1014/w3-js-exercises
js-functions/exercise-19.js
JavaScript
mit
517
from django.conf.urls.defaults import * urlpatterns = patterns('member.views', url(r'^$', 'login', name='passport_index'), url(r'^register/$', 'register', name='passport_register'), url(r'^login/$', 'login', name='passport_login'), url(r'^logout/$', 'logout', name='passport_logout'), url(r'^active/$', 'active', name='passport_active'), url(r'^forget/$', 'forget', name='passport_forget'), url(r'^profile/$', 'profile', name='passport_profile'), )
masiqi/douquan
member/urls.py
Python
mit
478
# -*- coding: utf-8 -*- """ The following examples are used to demonstrate how to get/record analytics The method signatures are: Pushbots.get_analytics() and Pushbots.record_analytics(platform=None, data=None) In which you must specify either platform or data. """ from pushbots import Pushbots def example_get_analytics(): """Get analytics by calling Pushbots.get_analytics()""" # Define app_id and secret my_app_id = 'my_app_id' my_secret = 'my_secret' # Create a Pushbots instance pushbots = Pushbots(app_id=my_app_id, secret=my_secret) code, message = pushbots.get_analytics() print('Returned code: {0}'.format(code)) print('Returned message: {0}'.format(message)) def example_record_analytics1(): """Record analytics by passing platform directly to Pushbots.record_analytics() """ # Define app_id and secret my_app_id = 'my_app_id' my_secret = 'my_secret' # Create a Pushbots instance pushbots = Pushbots(app_id=my_app_id, secret=my_secret) # Define platform platform = Pushbots.PLATFORM_IOS code, message = pushbots.record_analytics(platform=platform) print('Returned code: {0}'.format(code)) print('Returned message: {0}'.format(message)) def example_record_analytics2(): """Record analytics by passing data defined by you to Pushbots.record_analytics() """ # Define app_id and secret my_app_id = 'my_app_id' my_secret = 'my_secret' # Create a Pushbots instance pushbots = Pushbots(app_id=my_app_id, secret=my_secret) # Define data data = {'platform': '0'} # '0' is Equivalent to Pushbots.PLATFORM_IOS code, message = pushbots.record_analytics(data=data) print('Returned code: {0}'.format(code)) print('Returned message: {0}'.format(message))
tchar/pushbots
pushbots/examples/analytics.py
Python
mit
1,805
<?php /** * simplemon * * @license ${LICENSE_LINK} * @link ${PROJECT_URL_LINK} * @version ${VERSION} * @package ${PACKAGE_NAME} * @author Casey McLaughlin <caseyamcl@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * ------------------------------------------------------------------ */ namespace SimpleMon\Utility; use Twig_Error_Loader; /** * Class TwigTryFileLoader * * Allows cascading loading of templates, first checking the given path * in the loader, and then auto-checking with prepended namespaces until the * template is found. * * @author Casey McLaughlin <caseyamcl@gmail.com> */ class TwigTryFileLoader extends \Twig_Loader_Filesystem { /** * @var array|\string[] */ private $nsSearchOrder; /** * TwigTryFileLoader constructor. * * @param array $paths * @param array|string[] $nsSearchOrder Namespace search order (without '@' characters) */ public function __construct($paths = [], array $nsSearchOrder = [self::MAIN_NAMESPACE]) { parent::__construct($paths); $this->nsSearchOrder = array_unique(array_merge([self::MAIN_NAMESPACE], $nsSearchOrder)); } protected function findTemplate($name) { // If namespaced name provided, then use default behavior if ($name{0} == '@') { return parent::findTemplate($name); } // Else try paths until finding one. foreach ($this->nsSearchOrder as $ns) { $nsName = '@' . $ns . '/' . $name; try { return parent::findTemplate($nsName); } catch (Twig_Error_Loader $e) { // pass.. } } // If made it here, then just behave normally and throw // an exception return parent::findTemplate($name); } }
caseyamcl/simplemon
app/src/Utility/TwigTryFileLoader.php
PHP
mit
1,938
# -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """ Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def test_create_queryset_with_host_dict(): """ Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def test_create_queryset_with_host_list(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar")
Yipit/pyeqs
tests/unit/test_connection.py
Python
mit
4,100
namespace DotNetGroup.Services.Rss { using DotNetGroup.Services.Generic; public class UrlConfigProvider : BaseConfigProvider { protected override string Prefix { get { return "rss."; } } } }
sergejusb/DotNetGroup
Services/Rss/UrlConfigProvider.cs
C#
mit
259
module app.domain { export interface IProduct{ productId: number; productName: string; productCode: string; releaseDate: Date; price: number; description: string; imageUrl: string; //calculateDiscount(percent:number):number; } export class Product implements IProduct{ constructor(public productId: number, public productName: string, public productCode: string, public releaseDate: Date, public price: number, public description: string, public imageUrl: string){ } calculateDiscount(percent:number):number{ return this.price - (this.price * percent / 100 ); } } }
nrock/Angular-TypeScript
APM/app/products/product.ts
TypeScript
mit
635
/* * www.javagl.de - Flow * * Copyright (c) 2012-2017 Marco Hutter - http://www.javagl.de * * 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 de.javagl.flow.gui; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.util.ArrayList; import java.util.List; /** * Utility methods related to shapes */ class Shapes { /** * Create a list containing line segments that approximate the given * shape. * * NOTE: Copied from https://github.com/javagl/Geom/blob/master/ * src/main/java/de/javagl/geom/Shapes.java * * @param shape The shape * @param flatness The allowed flatness * @return The list of line segments */ public static List<Line2D> computeLineSegments( Shape shape, double flatness) { List<Line2D> result = new ArrayList<Line2D>(); PathIterator pi = shape.getPathIterator(null, flatness); double[] coords = new double[6]; double previous[] = new double[2]; double first[] = new double[2]; while (!pi.isDone()) { int segment = pi.currentSegment(coords); switch (segment) { case PathIterator.SEG_MOVETO: previous[0] = coords[0]; previous[1] = coords[1]; first[0] = coords[0]; first[1] = coords[1]; break; case PathIterator.SEG_CLOSE: result.add(new Line2D.Double( previous[0], previous[1], first[0], first[1])); previous[0] = first[0]; previous[1] = first[1]; break; case PathIterator.SEG_LINETO: result.add(new Line2D.Double( previous[0], previous[1], coords[0], coords[1])); previous[0] = coords[0]; previous[1] = coords[1]; break; case PathIterator.SEG_QUADTO: // Should never occur throw new AssertionError( "SEG_QUADTO in flattened path!"); case PathIterator.SEG_CUBICTO: // Should never occur throw new AssertionError( "SEG_CUBICTO in flattened path!"); default: // Should never occur throw new AssertionError( "Invalid segment in flattened path!"); } pi.next(); } return result; } /** * Private constructor to prevent instantiation */ private Shapes() { // Private constructor to prevent instantiation } }
javagl/Flow
flow-gui/src/main/java/de/javagl/flow/gui/Shapes.java
Java
mit
4,028
'use strict'; const signup = require('./signup'); const handler = require('feathers-errors/handler'); const notFound = require('./not-found-handler'); const logger = require('./logger'); module.exports = function() { // Add your custom middleware here. Remember, that // just like Express the order matters, so error // handling middleware should go last. const app = this; app.post('/signup', signup(app)); app.use(notFound()); app.use(logger(app)); app.use(handler()); };
le1tuan/feathersjs
src/middleware/index.js
JavaScript
mit
492
'use strict'; var form = $('[name="uploadForm"]'); exports.getForm = function() { return form; }; exports.setDetails = function(url, id) { form.element(by.model('inputText')).sendKeys(url); form.element(by.model('snapshotId')).sendKeys(id); }; exports.submit = function() { form.element(by.css('[ng-click="upload()"]')).click(); };
cloudify-cosmo/cloudify-ui-selenium-tests-nodejs
src/components/ui/snapshots/uploadSnapshotDialog.js
JavaScript
mit
352
#include "NumberParser.hpp" #include <algorithm> /** * Operator array * Used to confirm that a token is an operator */ QChar NumberParser::m_operators[] = { '(', ')', '*', '+', '-', '/', '^', '_' }; /** * Shunting-yard algorithm * Info: http://en.wikipedia.org/wiki/Shunting-yard_algorithm * @param const QString& expression * @return int - ReturnCode enum */ int NumberParser::ToRPN(const QString& expression) { //\todo: Possibly redundant when tokenized if (expression.trimmed().isEmpty()) { return static_cast<int>(ReturnCode::EMPTY); } m_output.clear(); bool lastWasOperator = true; //! While there are tokens to be read: Read a token. for (int i = 0; i < expression.size(); i++) { const auto current = expression[i]; //! If the token is a number, then add it to the output queue. //\todo: this does not accept numbers with dots (1234.1234) if (current.digitValue() != -1 || current == '.') { QString number = current; //! Eat digits untill something else appears for (int j = i + 1; j < expression.size(); j++, i++) { if (expression[j].digitValue() == -1 && expression[j] != '.') { break; } number += expression[j]; } m_output.push_back(number); lastWasOperator = false; } //! Convert the current char to an operator char toChar = current.toLatin1(); //! No operator if (!std::binary_search(std::begin(m_operators), std::end(m_operators), toChar)) { continue; } Operator currentOperator(toChar, lastWasOperator); if (currentOperator.m_precendence > 0) { //! while there is an operator token, o2, at the top of the stack while(!m_queue.empty() && //and either o1 is left-associative and its precedence is less than or equal to that of o2 ((currentOperator.m_precendence > 0 && currentOperator.m_precendence != 4 && currentOperator.m_precendence != 10 && m_queue.top().m_precendence >= currentOperator.m_precendence) //or o1 has precedence less than that of o2, || (m_queue.top().m_precendence > currentOperator.m_precendence))) { //! pop o2 off the stack, onto the output queue; m_output.push_back(m_queue.top().m_token); m_queue.pop(); } //! push o1 onto the stack. m_queue.push(currentOperator); lastWasOperator = true; } //! If the token is a left parenthesis, then push it onto the stack. if (currentOperator.m_token == '(') { m_queue.push(Operator('(')); } //! If the token is a right parenthesis: if (currentOperator.m_token == ')') { //! Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. while (!m_queue.empty()) { if (m_queue.top().m_token == '(') { //! Pop the left parenthesis from the stack, but not onto the output queue. m_queue.pop(); break; } m_output.push_back(m_queue.top().m_token); m_queue.pop(); } //! If the stack runs out without finding a left parenthesis, then there are mismatched parentheses. if (m_queue.empty()) { return static_cast<int>(ReturnCode::PARENTHESIS); } } } //! If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses. if (!m_queue.empty() && (m_queue.top().m_token == '(' || m_queue.top().m_token == ')')) { return static_cast<int>(ReturnCode::PARENTHESIS); } //! While there are still operator tokens in the stack: while (!m_queue.empty()) { //! Pop the operator onto the output queue. m_output.push_back(m_queue.top().m_token); m_queue.pop(); } return static_cast<int>(ReturnCode::OK); } /** * Postfix algorithm * Info: http://en.wikipedia.org/wiki/Reverse_Polish_notation * @return int - ReturnCode enum */ int NumberParser::PostFixRPN() { //! Clear the result stack while (!m_result.empty()) { m_result.pop(); } //! While there are input tokens left for (const auto& e : m_output) { //! If the token is a number (Maybe they entered .1234 which is correct check for that as well) if (e[0].digitValue() != -1 || (e.size() > 1 && e[1].digitValue() != -1)) { //! Push it onto the stack. m_result.push(mpf_class(e.toStdString())); } else { if (e[0].toLatin1() == '_') { m_result.top() *= -1; continue; } //! Evaluate the operator, with the values as arguments. //! Else, Pop the top n values from the stack. const mpf_class second = m_result.top(); m_result.pop(); const mpf_class first = m_result.top(); m_result.pop(); mpf_class result; switch (e[0].toLatin1()) { case '^': mpf_pow_ui(result.get_mpf_t(), first.__get_mp(), second.get_ui()); m_result.push(result); break; case '*': m_result.push(first * second); break; case '/': if (second == 0) { return static_cast<int>(ReturnCode::ZERODIV); } m_result.push(first / second); break; case '-': m_result.push(first - second); break; case '+': m_result.push(first + second); break; } } } mp_exp_t exp; m_solution = m_result.top().get_str(exp); const int unaryOccurence = std::count(std::begin(m_solution), std::end(m_solution), '-'); const int actualSize = m_solution.size() - unaryOccurence; for (int i = actualSize + 1; i <= exp; i++) { m_solution += "0"; } if (exp != m_solution.size() - unaryOccurence) { m_solution.insert((exp + unaryOccurence < 0) ? 0 : exp + unaryOccurence, "."); } return static_cast<int>(ReturnCode::OK); } /** * Function that returns the RPN Notation * @return QString */ QString NumberParser::GetRPN() const { QString RPN = ""; for (const auto& e : m_output) { RPN += e; } return RPN; }
Futsy/LineCalculator
LineCalculator/LineCalculator/NumberParser.cpp
C++
mit
5,665
require File.expand_path('../../../lib/tinytable/layout', __FILE__) require File.expand_path('../../../lib/tinytable/row', __FILE__) require File.expand_path('../../../lib/tinytable/cell', __FILE__) describe TinyTable::Layout do let(:table) { mock(:table, :has_header? => false, :has_rows? => true, :has_footer? => false) } let(:layout) { TinyTable::Layout.new(table).analyze } it "knows how many columns a table has" do row1 = TinyTable::Row.new(["One"]) row2 = TinyTable::Row.new(["One", "Two"]) row3 = TinyTable::Row.new(["One", "Two", "Three"]) table.stub(:each_row).and_yield(row1).and_yield(row2).and_yield(row3) layout.column_count.should == 3 end it "knows the maximum width for each column in the table" do row1 = TinyTable::Row.new(["123", "1", "12"]) row2 = TinyTable::Row.new(["12345", "123", "1"]) row3 = TinyTable::Row.new(["1234567", "12", "1"]) table.stub(:each_row).and_yield(row1).and_yield(row2).and_yield(row3) layout.max_column_widths.should == [7, 3, 2] end it "includes the header row when calculating maximum column widths" do table.stub(:has_header?) { true } table.stub(:header) { TinyTable::Row.new(["12345", "1"]) } table.stub(:each_row).and_yield(TinyTable::Row.new(["123", "12"])) layout.max_column_widths.should == [5, 2] end it "includes the footer row when calculating maximum column widths" do table.stub(:has_footer?) { true } table.stub(:footer) { TinyTable::Row.new(["123", "12345"]) } table.stub(:each_row).and_yield(TinyTable::Row.new(["1234", "12"])) layout.max_column_widths.should == [4, 5] end it "correctly calculates the width of cells containing an integer" do row1 = TinyTable::Row.new(["London", 8_294_058]) row2 = TinyTable::Row.new(["Liverpool", 830_112]) table.stub(:each_row).and_yield(row1).and_yield(row2) layout.max_column_widths.should == [9, 7] end it "correctly deals with completely empty tables" do table.stub(:has_rows?) { false } layout.max_column_widths.should eq [] layout.column_count.should be_zero end end
leocassarani/tinytable
spec/tinytable/layout_spec.rb
Ruby
mit
2,108
<?php namespace SumoCoders\FrameworkMultiUserBundle\Form\Interfaces; use Symfony\Component\Form\FormTypeInterface; interface FormWithDataTransferObject extends FormTypeInterface { public static function getDataTransferObjectClass(): string; }
sumocoders/FrameworkMultiUserBundle
Form/Interfaces/FormWithDataTransferObject.php
PHP
mit
250
package net.ausiasmarch.fartman.util; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; /** * AudioManager.java * Gestiona la musica y sonidos * @author Luis * */ public class AudioManager { /** Administrador de audio */ public static final AudioManager instance = new AudioManager(); /** Musica reproduciendose*/ private Music playingMusic; /** singleton: previene la instanciacion desde otras clases */ private AudioManager () { } /** Reproduce sonido */ public void play (Sound sound) { play(sound, 1); } /** Reproduce sonido */ public void play (Sound sound, float volume) { play(sound, volume, 1); } /** Reproduce sonido */ public void play (Sound sound, float volume, float pitch) { play(sound, volume, pitch, 0); } /** Reproduce sonido */ public void play (Sound sound, float volume, float pitch, float pan) { if (!GamePreferences.instance.sound) return; sound.play(volume, pitch, pan); } /** Reproduce musica */ public void play(Music music){ play(music, 1); } /** Reproduce musica */ public void play (Music music, float volume) { stopMusic(); playingMusic = music; if (GamePreferences.instance.music) { music.setLooping(true); music.setVolume(volume); music.play(); } } /** Para la musica */ public void stopMusic () { if (playingMusic != null) playingMusic.stop(); } /** Obtiene la musica que se esta reproduciendo */ public Music getPlayingMusic () { return playingMusic; } /** Reproduce/pausa la musica segun el archivo de preferencias */ public void onSettingsUpdated () { if (playingMusic == null) return; if (GamePreferences.instance.music) { if (!playingMusic.isPlaying()) playingMusic.play(); } else { playingMusic.pause(); } } }
fluted0g/Mr.Fartman
core/src/net/ausiasmarch/fartman/util/AudioManager.java
Java
mit
1,784
<?php /** * Created by PhpStorm. * User: pkupe * Date: 2017-02-12 * Time: 19:06 */ namespace StackExchangeBundle\FormFactory; use StackExchangeBundle\Form\AnswerType; use StackExchangeBundle\Form\QuestionType; use StackExchangeBundle\Model\FormFactory; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; class AnswerFormFactory extends FormFactory { protected $class = AnswerType::class; }
Lezas/AutoShare
src/StackExchangeBundle/FormFactory/AnswerFormFactory.php
PHP
mit
484
module Runcible VERSION = '2.13.1'.freeze end
Katello/runcible
lib/runcible/version.rb
Ruby
mit
48
from typing import Union, Iterator from ...symbols import NOUN, PROPN, PRON from ...errors import Errors from ...tokens import Doc, Span def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]: """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. """ # fmt: off labels = ["nsubj", "nsubj:pass", "obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"] # fmt: on doc = doclike.doc # Ensure works on both Doc and Span. if not doc.has_annotation("DEP"): raise ValueError(Errors.E029) np_deps = [doc.vocab.strings[label] for label in labels] conj = doc.vocab.strings.add("conj") np_label = doc.vocab.strings.add("NP") prev_end = -1 for i, word in enumerate(doclike): if word.pos not in (NOUN, PROPN, PRON): continue # Prevent nested chunks from being produced if word.left_edge.i <= prev_end: continue if word.dep in np_deps: prev_end = word.right_edge.i yield word.left_edge.i, word.right_edge.i + 1, np_label elif word.dep == conj: head = word.head while head.dep == conj and head.head.i < head.i: head = head.head # If the head is an NP, and we're coordinated to it, we're an NP if head.dep in np_deps: prev_end = word.right_edge.i yield word.left_edge.i, word.right_edge.i + 1, np_label SYNTAX_ITERATORS = {"noun_chunks": noun_chunks}
spacy-io/spaCy
spacy/lang/id/syntax_iterators.py
Python
mit
1,515