repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
WojciechKo/Walletudo
app/src/main/java/com/walletudo/ui/tag/TagInputFilter.java
934
package com.walletudo.ui.tag; import android.text.InputFilter; import android.text.Spanned; public class TagInputFilter { public static class SingleTag implements InputFilter { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { StringBuilder builder = new StringBuilder(); for (int i = start; i < end; i++) { char c = source.charAt(i); if (isAllowed(c)) { builder.append(c); } } return builder.toString(); } protected boolean isAllowed(char c) { return Character.isLetterOrDigit(c) || c == '-'; } } public static class MultipleTags extends SingleTag { @Override protected boolean isAllowed(char c) { return super.isAllowed(c) || c == ' '; } } }
mit
Overbryd/adyen_client
spec/spec_helper.rb
1201
require "pathname" require "bundler" Bundler.setup(:default, :test) require "minitest/spec" require "minitest/autorun" require "webmock" require "mocha/mini_test" require "vcr" require "minispec-metadata" root = Pathname.new(File.expand_path("..", File.dirname(__FILE__))) $:.unshift(root.join("lib")) require "adyen_client" AdyenClient.configure(YAML.load_file(root.join("spec", "config.yml"))) do |c| c.environment = :test end VCR.configure do |c| c.allow_http_connections_when_no_cassette = true c.cassette_library_dir = "spec/cassettes" c.hook_into :webmock end MiniTest::Spec.before :each do |example| if options = metadata[:vcr] options = options.is_a?(Hash) ? options : {} frame = example.class stack = [] while frame != Minitest::Spec do stack.unshift(frame.desc.to_s) frame = frame.superclass end stack.push(example.name =~ /\A(test_\d{4}_)?(.*)\z/ && $2) stack.pop if options[:per_group] vcr_path = stack.map { |path| path.gsub(/[^a-zA-Z]/, "_").gsub(/^_+|_+$/, "") }.join("/") VCR.insert_cassette(vcr_path, options[:cassette] || {}) end end MiniTest::Spec.after :each do |example| VCR.eject_cassette if metadata[:vcr] end
mit
obasola/master
src/main/java/com/kumasi/journal/rest/controller/BookPublisherRestController.java
3340
/* * Created on 24 Oct 2015 ( Time 23:23:56 ) * Generated by Telosys Tools Generator ( version 2.1.1 ) */ package com.kumasi.journal.rest.controller; import java.util.LinkedList; import java.util.List; import javax.annotation.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.kumasi.journal.domain.BookPublisher; import com.kumasi.journal.business.service.BookPublisherService; import com.kumasi.journal.web.listitem.BookPublisherListItem; /** * Spring MVC controller for 'BookPublisher' management. */ @Controller public class BookPublisherRestController { @Resource private BookPublisherService bookPublisherService; @RequestMapping( value="/items/bookPublisher", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @ResponseBody public List<BookPublisherListItem> findAllAsListItems() { List<BookPublisher> list = bookPublisherService.findAll(); List<BookPublisherListItem> items = new LinkedList<BookPublisherListItem>(); for ( BookPublisher bookPublisher : list ) { items.add(new BookPublisherListItem( bookPublisher ) ); } return items; } @RequestMapping( value="/bookPublisher", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @ResponseBody public List<BookPublisher> findAll() { return bookPublisherService.findAll(); } @RequestMapping( value="/bookPublisher/{publisherId}/{bookId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @ResponseBody public BookPublisher findOne(@PathVariable("publisherId") Integer publisherId, @PathVariable("bookId") Integer bookId) { return bookPublisherService.findById(publisherId, bookId); } @RequestMapping( value="/bookPublisher", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @ResponseBody public BookPublisher create(@RequestBody BookPublisher bookPublisher) { return bookPublisherService.create(bookPublisher); } @RequestMapping( value="/bookPublisher/{publisherId}/{bookId}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @ResponseBody public BookPublisher update(@PathVariable("publisherId") Integer publisherId, @PathVariable("bookId") Integer bookId, @RequestBody BookPublisher bookPublisher) { return bookPublisherService.update(bookPublisher); } @RequestMapping( value="/bookPublisher/{publisherId}/{bookId}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @ResponseBody public void delete(@PathVariable("publisherId") Integer publisherId, @PathVariable("bookId") Integer bookId) { bookPublisherService.delete(publisherId, bookId); } }
mit
Kaytal/premier-jf-cruise
templates/content-front.php
1357
<div class="alert"> <div class="alert-content"> <div class="close">close (x)</div> <img src="<?php echo get_template_directory_uri(); ?>/assets/images/brand.png" alt="<?php bloginfo('name'); ?>" /> <p class="lead">Register by January 31st, save $100</p> <p class="small-lead">*limited rooms available, prices increase Feb. 1</p> </div> </div> <div class="front-image"> <img src="<?php echo get_template_directory_uri(); ?>/assets/images/NauticalDevice.png" alt="Nautical Device" class="img-responsive" /> <video autoplay loop> <source src="<?php echo get_template_directory_uri(); ?>/assets/images/video.mp4" type="video/mp4"> <source src="<?php echo get_template_directory_uri(); ?>/assets/images/video.webm" type="video/webm"> </video> </div> <div class="row"> <div class="col-sm-6 col-sm-offset-3 front-content"> <?php the_content(); ?> <?php if (new DateTime() < new DateTime("2016-05-16 07:30:00")) : ?> <h3 class="text-center" style="margin-bottom: 25px">Booking Begins Monday @ 8:30am EST</h3> <p class="text-center"><a class="book-btn text-uppercase">Book Now</a></p> <?php else : ?> <p class="text-center"><a href="https://reservations.premier-experience.com/Booking/Reservation/Start?tripID=2988" class="book-btn text-uppercase">Book Now</a></p> <?php endif ?> </div> </div>
mit
incentivetoken/offspring
com.dgex.offspring.ui/src/com/dgex/offspring/ui/controls/AliasControl.java
6649
package com.dgex.offspring.ui.controls; import nxt.Alias; import nxt.NxtException.ValidationException; import org.eclipse.e4.ui.di.UISynchronize; import org.eclipse.e4.ui.services.IStylingEngine; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import com.dgex.offspring.config.IContactsService; import com.dgex.offspring.nxtCore.core.AliasHelper; import com.dgex.offspring.nxtCore.service.IAlias; import com.dgex.offspring.nxtCore.service.INxtService; import com.dgex.offspring.nxtCore.service.TransactionException; import com.dgex.offspring.swt.table.PaginationContainer; import com.dgex.offspring.ui.PromptFeeDeadline; import com.dgex.offspring.user.service.IUser; import com.dgex.offspring.user.service.IUserService; public class AliasControl extends Composite { private static Image errorImage = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage(); private Text aliasNameText; private ControlDecoration decoAliasNameText; private Text aliasURIText; private Button aliasRegisterButton; private final AliasViewer aliasesViewer; private final Long accountId; private final INxtService nxt; private final IUser user; private final UISynchronize sync; private final IContactsService contactsService; private final PaginationContainer paginationContainer; public AliasControl(Composite parent, int style, Long accountId, INxtService nxt, IStylingEngine engine, IUserService userService, UISynchronize sync, IContactsService contactsService) { super(parent, style); this.accountId = accountId; this.nxt = nxt; this.user = userService.findUser(accountId); this.sync = sync; this.contactsService = contactsService; GridLayoutFactory.fillDefaults().spacing(10, 5).numColumns(3).applyTo(this); /* top bar (name, uri, register) */ if (user != null && !user.getAccount().isReadOnly()) { aliasNameText = new Text(this, SWT.BORDER); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER) .hint(100, SWT.DEFAULT).applyTo(aliasNameText); aliasNameText.setMessage("name"); decoAliasNameText = new ControlDecoration(aliasNameText, SWT.TOP | SWT.RIGHT); decoAliasNameText.setImage(errorImage); decoAliasNameText.setDescriptionText("Alias is registered"); decoAliasNameText.hide(); aliasURIText = new Text(this, SWT.BORDER); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER) .grab(true, false).applyTo(aliasURIText); aliasURIText.setMessage("uri"); aliasRegisterButton = new Button(this, SWT.PUSH); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER) .applyTo(aliasRegisterButton); aliasRegisterButton.setText("Register"); aliasRegisterButton.setEnabled(false); hookupAliasControls(); } /* bottom bar table viewer */ paginationContainer = new PaginationContainer(this, SWT.NONE); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true) .span(3, 1).applyTo(paginationContainer); aliasesViewer = new AliasViewer(paginationContainer.getViewerParent(), accountId, nxt, engine, userService, sync, contactsService); paginationContainer.setTableViewer(aliasesViewer, 100); aliasesViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) {} }); } public void refresh() { aliasesViewer.refresh(); } private void hookupAliasControls() { aliasNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String name = aliasNameText.getText().trim(); Alias alias = Alias.getAlias(name); if (alias == null) { decoAliasNameText.hide(); aliasRegisterButton.setEnabled(true); aliasRegisterButton.setText("Register"); aliasURIText.setText(""); } else if (alias.getAccount().equals(user.getAccount().getNative())) { decoAliasNameText.hide(); aliasRegisterButton.setEnabled(true); aliasRegisterButton.setText("Update"); } else { decoAliasNameText.show(); aliasRegisterButton.setEnabled(false); String value = alias.getURI(); aliasURIText.setText(value.trim().isEmpty() ? ".. registered .." : value); } } }); aliasRegisterButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { registerAlias(); } }); } private void registerAlias() { PromptFeeDeadline dialog = new PromptFeeDeadline(getShell()); if (dialog.open() != Window.OK) { return; } final int fee = dialog.getFee(); final short deadline = dialog.getDeadline(); final String name = aliasNameText.getText().trim(); final String uri = aliasURIText.getText().trim(); BusyIndicator.showWhile(getDisplay(), new Runnable() { @Override public void run() { try { nxt.createAssignAliasTransaction(user.getAccount(), name, uri, deadline, fee, 0l); aliasRegisterButton.setEnabled(true); decoAliasNameText.show(); IAlias alias = new AliasHelper(name, uri, user.getAccount() .getNative()); nxt.getPendingAliases().add(alias); aliasesViewer.refresh(); } catch (ValidationException e) { MessageDialog.openError(getShell(), "Validation Exception", e.toString()); } catch (TransactionException e) { MessageDialog.openError(getShell(), "Transaction Exception", e.toString()); } } }); } }
mit
netcredit/NetCreditHub
src/NetCreditHub.Kernel/Runtime/Validation/IntValueValidator.cs
4203
namespace NetCreditHub.Runtime.Validation { using System; using Extensions; [Serializable] public class IntValueValidator : ValidationAttributeBase { public int Min { get; set; } = 0; public bool ContainMin { get; set; } = true; public int Max { get; set; } = 0; public bool ContainMax { get; set; } = true; public string InvalidErrorMessageLocalizationSourceName { get; set; } = HubConsts.LocalizationSourceName; public string InvalidErrorMessageSourceName { get; set; } = "Validation.Int.InvalidWithValue"; public string MinErrorMessageLocalizationSourceName { get; set; } = HubConsts.LocalizationSourceName; public string MinErrorMessageSourceName { get; set; } = "Validation.Int.MorethanOrEqualto"; public string MaxErrorMessageLocalizationSourceName { get; set; } = HubConsts.LocalizationSourceName; public string MaxErrorMessageSourceName { get; set; } = "Validation.Int.LessthanOrEqualto"; public override bool IsValid(object value) { InvalidErrorMessageLocalizationSourceName = InvalidErrorMessageLocalizationSourceName.IsNullOrWhiteSpace() ? FieldSourceName : InvalidErrorMessageLocalizationSourceName; MinErrorMessageLocalizationSourceName = MinErrorMessageLocalizationSourceName.IsNullOrWhiteSpace() ? FieldSourceName : MinErrorMessageLocalizationSourceName; MaxErrorMessageLocalizationSourceName = MaxErrorMessageLocalizationSourceName.IsNullOrWhiteSpace() ? FieldSourceName : MaxErrorMessageLocalizationSourceName; var strValue = value.ToInt(); if (!value.IsInt()) { ErrorMessage = L(InvalidErrorMessageLocalizationSourceName, InvalidErrorMessageSourceName) .Replace("{$name}", FieldNameL) .Replace("{$value}", Convert.ToString(value)); return false; } if (ContainMin) { if (strValue < Min) { ErrorMessage = L(MinErrorMessageLocalizationSourceName, MinErrorMessageSourceName) .Replace("{$name}", FieldNameL) .Replace("{$minValue}", Min.ToString()) .Replace("{$maxValue}", Max.ToString()); return false; } } else { if (strValue <= Min) { ErrorMessage = L(MinErrorMessageLocalizationSourceName, MinErrorMessageSourceName) .Replace("{$name}", FieldNameL) .Replace("{$minValue}", Min.ToString()) .Replace("{$maxValue}", Max.ToString()); return false; } } if (Max > 0) { if (ContainMax) { if (strValue > Max) { ErrorMessage = L(MaxErrorMessageLocalizationSourceName, MaxErrorMessageSourceName) .Replace("{$name}", FieldNameL) .Replace("{$minValue}", Min.ToString()) .Replace("{$maxValue}", Max.ToString()); return false; } } else { if (strValue >= Max) { ErrorMessage = L(MaxErrorMessageLocalizationSourceName, MaxErrorMessageSourceName) .Replace("{$name}", FieldNameL) .Replace("{$minValue}", Min.ToString()) .Replace("{$maxValue}", Max.ToString()); return false; } } } return true; } } }
mit
BlazeMV/Blazing
src/api/payment/ShippingQuery.php
208
<?php namespace Blazing\api\payment; class ShippingQuery{ protected $shippingQuery; public function __construct($shippingQuery){ $this->shippingQuery = $shippingQuery; } }
mit
phil-smith-1/task-tracker
app/models/user.rb
173
class User < ApplicationRecord include Clearance::User has_many :tasks, dependent: :destroy has_and_belongs_to_many :companies has_and_belongs_to_many :projects end
mit
johnnyzhang1992/php-learning
php-mysql/blog/add_new.php
2372
<?php /** * Created by PhpStorm. * User: zq199 * Date: 2016/10/31 * Time: 23:04 */ //添加新blog require 'class/system.php'; //主页 ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php echo SITE_NAME ?>|新建blog</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/style.css"> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> <style> .control-label{ line-height: 34px; margin-bottom: 0; } </style> </head> <body> <?php include 'header.php'; ?> <div class="content col-md-10 col-md-offset-1"> <div class="add-blog"> <div class="breadcrumb"><a href="index.php" style="margin-right:5px ">blog</a>\<span style="margin-left: 5px">新建</span></div> <form class="form-group form-horizontal" action="controller/add_new.php" method="post" name="add-blog-form"> <div class="blog_title form-group col-sm-12 clearfix"> <label for="blog_title" class="col-sm-1 control-label" style="text-align: left">标题:</label> <div class="col-sm-11"> <input type="text" class="form-control" name="blog_title" id="blog_title" placeholder="请填写标题" /> </div> </div> <div class="blog_title form-group col-sm-12 clearfix"> <label for="blog_tag" class="col-sm-1 control-label" style="text-align: left">标签:</label> <div class="col-sm-11"> <input type="text" class="form-control" name="blog_tag" id="blog_tag" placeholder="请填写分类或者标签,多个请用英文逗号','分割开" /> </div> </div> <div class="form-group col-sm-12 clearfix"> <label for="blog_content" class="control-label" style="padding: 0 15px">内容:</label> <textarea class="form-control" rows="6" id="blog_content" name="blog_content" style=""></textarea> </div> <div class="form-group clearfix"> <div class="col-sm-12"> <button type="submit" class="btn btn-info pull-left">提交</button> </div> </div> </form> </div> </div> <?php include 'footer.php'; ?> </body> </html>
mit
Perth155/ActiviLog
client/index.js
143
import React from 'react'; import ReactDOM from 'react-dom'; import App from "./app" ReactDOM.render(<App />, document.getElementById('app'));
mit
IstiN/android_benchmark
benchmark/src/main/java/com/epam/benchmark/util/CloseableListIterator.java
206
package com.epam.benchmark.util; import java.io.Closeable; import java.util.ListIterator; /** * @author Egor Makovsky */ public interface CloseableListIterator<T> extends ListIterator<T>, Closeable { }
mit
ChristopherBiscardi/gatsby
packages/gatsby/src/schema/context.js
426
const { LocalNodeModel } = require(`./node-model`) const withResolverContext = (context, schema) => { const nodeStore = require(`../db/nodes`) const createPageDependency = require(`../redux/actions/add-page-dependency`) return { ...context, nodeModel: new LocalNodeModel({ nodeStore, schema, createPageDependency, path: context.path, }), } } module.exports = withResolverContext
mit
mattn/ccat
Godeps/_workspace/src/sourcegraph.com/sourcegraph/srclib/src/doall_cmd.go
1332
package src import ( "log" "os" "github.com/jingweno/ccat/Godeps/_workspace/src/sourcegraph.com/sourcegraph/srclib/config" ) func init() { // TODO(sqs): "do-all" is a stupid name c, err := CLI.AddCommand("do-all", "fully process (config, plan, execute, and import)", `Fully processes a tree: configures it, plans the execution, executes all analysis steps, and imports the data.`, &doAllCmd, ) if err != nil { log.Fatal(err) } setDefaultRepoURIOpt(c) setDefaultRepoSubdirOpt(c) } type DoAllCmd struct { config.Options ToolchainExecOpt `group:"execution"` BuildCacheOpt `group:"build cache"` Dir Directory `short:"C" long:"directory" description:"change to DIR before doing anything" value-name:"DIR"` } var doAllCmd DoAllCmd func (c *DoAllCmd) Execute(args []string) error { if c.Dir != "" { if err := os.Chdir(c.Dir.String()); err != nil { return err } } // config configCmd := &ConfigCmd{ Options: c.Options, ToolchainExecOpt: c.ToolchainExecOpt, BuildCacheOpt: c.BuildCacheOpt, } if err := configCmd.Execute(nil); err != nil { return err } // make makeCmd := &MakeCmd{ Options: c.Options, ToolchainExecOpt: c.ToolchainExecOpt, BuildCacheOpt: c.BuildCacheOpt, } if err := makeCmd.Execute(nil); err != nil { return err } return nil }
mit
Xeeynamo/KingdomHearts
OpenKh.Tools.Common/Models/Kh2WorldsList.cs
763
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Xe.Tools.Models; using OpenKh.Kh2; namespace OpenKh.Tools.Common.Models { public class Kh2WorldsList : IEnumerable<EnumItemModel<World>>, IEnumerable { private static List<EnumItemModel<World>> _list = Enum.GetValues(typeof(World)) .Cast<World>() .Select(e => new EnumItemModel<World>() { Value = e, Name = Constants.WorldNames[(int)e] }) .ToList(); public IEnumerator<EnumItemModel<World>> GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } }
mit
koobonil/Boss2D
Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/p2p/base/pseudotcp_unittest.cc
25862
/* * Copyright 2011 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <algorithm> #include <string> #include <vector> #include BOSS_WEBRTC_U_p2p__base__pseudotcp_h //original-code:"p2p/base/pseudotcp.h" #include BOSS_WEBRTC_U_rtc_base__gunit_h //original-code:"rtc_base/gunit.h" #include BOSS_WEBRTC_U_rtc_base__helpers_h //original-code:"rtc_base/helpers.h" #include BOSS_WEBRTC_U_rtc_base__messagehandler_h //original-code:"rtc_base/messagehandler.h" #include BOSS_WEBRTC_U_rtc_base__stream_h //original-code:"rtc_base/stream.h" #include BOSS_WEBRTC_U_rtc_base__thread_h //original-code:"rtc_base/thread.h" #include BOSS_WEBRTC_U_rtc_base__timeutils_h //original-code:"rtc_base/timeutils.h" using cricket::PseudoTcp; static const int kConnectTimeoutMs = 10000; // ~3 * default RTO of 3000ms static const int kTransferTimeoutMs = 15000; static const int kBlockSize = 4096; class PseudoTcpForTest : public cricket::PseudoTcp { public: PseudoTcpForTest(cricket::IPseudoTcpNotify* notify, uint32_t conv) : PseudoTcp(notify, conv) {} bool isReceiveBufferFull() const { return PseudoTcp::isReceiveBufferFull(); } void disableWindowScale() { PseudoTcp::disableWindowScale(); } }; class PseudoTcpTestBase : public testing::Test, public rtc::MessageHandler, public cricket::IPseudoTcpNotify { public: PseudoTcpTestBase() : local_(this, 1), remote_(this, 1), have_connected_(false), have_disconnected_(false), local_mtu_(65535), remote_mtu_(65535), delay_(0), loss_(0) { // Set use of the test RNG to get predictable loss patterns. rtc::SetRandomTestMode(true); } ~PseudoTcpTestBase() { // Put it back for the next test. rtc::SetRandomTestMode(false); } void SetLocalMtu(int mtu) { local_.NotifyMTU(mtu); local_mtu_ = mtu; } void SetRemoteMtu(int mtu) { remote_.NotifyMTU(mtu); remote_mtu_ = mtu; } void SetDelay(int delay) { delay_ = delay; } void SetLoss(int percent) { loss_ = percent; } void SetOptNagling(bool enable_nagles) { local_.SetOption(PseudoTcp::OPT_NODELAY, !enable_nagles); remote_.SetOption(PseudoTcp::OPT_NODELAY, !enable_nagles); } void SetOptAckDelay(int ack_delay) { local_.SetOption(PseudoTcp::OPT_ACKDELAY, ack_delay); remote_.SetOption(PseudoTcp::OPT_ACKDELAY, ack_delay); } void SetOptSndBuf(int size) { local_.SetOption(PseudoTcp::OPT_SNDBUF, size); remote_.SetOption(PseudoTcp::OPT_SNDBUF, size); } void SetRemoteOptRcvBuf(int size) { remote_.SetOption(PseudoTcp::OPT_RCVBUF, size); } void SetLocalOptRcvBuf(int size) { local_.SetOption(PseudoTcp::OPT_RCVBUF, size); } void DisableRemoteWindowScale() { remote_.disableWindowScale(); } void DisableLocalWindowScale() { local_.disableWindowScale(); } protected: int Connect() { int ret = local_.Connect(); if (ret == 0) { UpdateLocalClock(); } return ret; } void Close() { local_.Close(false); UpdateLocalClock(); } enum { MSG_LPACKET, MSG_RPACKET, MSG_LCLOCK, MSG_RCLOCK, MSG_IOCOMPLETE, MSG_WRITE }; virtual void OnTcpOpen(PseudoTcp* tcp) { // Consider ourselves connected when the local side gets OnTcpOpen. // OnTcpWriteable isn't fired at open, so we trigger it now. RTC_LOG(LS_VERBOSE) << "Opened"; if (tcp == &local_) { have_connected_ = true; OnTcpWriteable(tcp); } } // Test derived from the base should override // virtual void OnTcpReadable(PseudoTcp* tcp) // and // virtual void OnTcpWritable(PseudoTcp* tcp) virtual void OnTcpClosed(PseudoTcp* tcp, uint32_t error) { // Consider ourselves closed when the remote side gets OnTcpClosed. // TODO(?): OnTcpClosed is only ever notified in case of error in // the current implementation. Solicited close is not (yet) supported. RTC_LOG(LS_VERBOSE) << "Closed"; EXPECT_EQ(0U, error); if (tcp == &remote_) { have_disconnected_ = true; } } virtual WriteResult TcpWritePacket(PseudoTcp* tcp, const char* buffer, size_t len) { // Randomly drop the desired percentage of packets. // Also drop packets that are larger than the configured MTU. if (rtc::CreateRandomId() % 100 < static_cast<uint32_t>(loss_)) { RTC_LOG(LS_VERBOSE) << "Randomly dropping packet, size=" << len; } else if (len > static_cast<size_t>(std::min(local_mtu_, remote_mtu_))) { RTC_LOG(LS_VERBOSE) << "Dropping packet that exceeds path MTU, size=" << len; } else { int id = (tcp == &local_) ? MSG_RPACKET : MSG_LPACKET; std::string packet(buffer, len); rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, delay_, this, id, rtc::WrapMessageData(packet)); } return WR_SUCCESS; } void UpdateLocalClock() { UpdateClock(&local_, MSG_LCLOCK); } void UpdateRemoteClock() { UpdateClock(&remote_, MSG_RCLOCK); } void UpdateClock(PseudoTcp* tcp, uint32_t message) { long interval = 0; // NOLINT tcp->GetNextClock(PseudoTcp::Now(), interval); interval = std::max<int>(interval, 0L); // sometimes interval is < 0 rtc::Thread::Current()->Clear(this, message); rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, interval, this, message); } virtual void OnMessage(rtc::Message* message) { switch (message->message_id) { case MSG_LPACKET: { const std::string& s(rtc::UseMessageData<std::string>(message->pdata)); local_.NotifyPacket(s.c_str(), s.size()); UpdateLocalClock(); break; } case MSG_RPACKET: { const std::string& s(rtc::UseMessageData<std::string>(message->pdata)); remote_.NotifyPacket(s.c_str(), s.size()); UpdateRemoteClock(); break; } case MSG_LCLOCK: local_.NotifyClock(PseudoTcp::Now()); UpdateLocalClock(); break; case MSG_RCLOCK: remote_.NotifyClock(PseudoTcp::Now()); UpdateRemoteClock(); break; default: break; } delete message->pdata; } PseudoTcpForTest local_; PseudoTcpForTest remote_; rtc::MemoryStream send_stream_; rtc::MemoryStream recv_stream_; bool have_connected_; bool have_disconnected_; int local_mtu_; int remote_mtu_; int delay_; int loss_; }; class PseudoTcpTest : public PseudoTcpTestBase { public: void TestTransfer(int size) { uint32_t start; int32_t elapsed; size_t received; // Create some dummy data to send. send_stream_.ReserveSize(size); for (int i = 0; i < size; ++i) { char ch = static_cast<char>(i); send_stream_.Write(&ch, 1, NULL, NULL); } send_stream_.Rewind(); // Prepare the receive stream. recv_stream_.ReserveSize(size); // Connect and wait until connected. start = rtc::Time32(); EXPECT_EQ(0, Connect()); EXPECT_TRUE_WAIT(have_connected_, kConnectTimeoutMs); // Sending will start from OnTcpWriteable and complete when all data has // been received. EXPECT_TRUE_WAIT(have_disconnected_, kTransferTimeoutMs); elapsed = rtc::Time32() - start; recv_stream_.GetSize(&received); // Ensure we closed down OK and we got the right data. // TODO(?): Ensure the errors are cleared properly. // EXPECT_EQ(0, local_.GetError()); // EXPECT_EQ(0, remote_.GetError()); EXPECT_EQ(static_cast<size_t>(size), received); EXPECT_EQ(0, memcmp(send_stream_.GetBuffer(), recv_stream_.GetBuffer(), size)); RTC_LOG(LS_INFO) << "Transferred " << received << " bytes in " << elapsed << " ms (" << size * 8 / elapsed << " Kbps)"; } private: // IPseudoTcpNotify interface virtual void OnTcpReadable(PseudoTcp* tcp) { // Stream bytes to the recv stream as they arrive. if (tcp == &remote_) { ReadData(); // TODO(?): OnTcpClosed() is currently only notified on error - // there is no on-the-wire equivalent of TCP FIN. // So we fake the notification when all the data has been read. size_t received, required; recv_stream_.GetPosition(&received); send_stream_.GetSize(&required); if (received == required) OnTcpClosed(&remote_, 0); } } virtual void OnTcpWriteable(PseudoTcp* tcp) { // Write bytes from the send stream when we can. // Shut down when we've sent everything. if (tcp == &local_) { RTC_LOG(LS_VERBOSE) << "Flow Control Lifted"; bool done; WriteData(&done); if (done) { Close(); } } } void ReadData() { char block[kBlockSize]; size_t position; int rcvd; do { rcvd = remote_.Recv(block, sizeof(block)); if (rcvd != -1) { recv_stream_.Write(block, rcvd, NULL, NULL); recv_stream_.GetPosition(&position); RTC_LOG(LS_VERBOSE) << "Received: " << position; } } while (rcvd > 0); } void WriteData(bool* done) { size_t position, tosend; int sent; char block[kBlockSize]; do { send_stream_.GetPosition(&position); if (send_stream_.Read(block, sizeof(block), &tosend, NULL) != rtc::SR_EOS) { sent = local_.Send(block, tosend); UpdateLocalClock(); if (sent != -1) { send_stream_.SetPosition(position + sent); RTC_LOG(LS_VERBOSE) << "Sent: " << position + sent; } else { send_stream_.SetPosition(position); RTC_LOG(LS_VERBOSE) << "Flow Controlled"; } } else { sent = static_cast<int>(tosend = 0); } } while (sent > 0); *done = (tosend == 0); } private: rtc::MemoryStream send_stream_; rtc::MemoryStream recv_stream_; }; class PseudoTcpTestPingPong : public PseudoTcpTestBase { public: PseudoTcpTestPingPong() : iterations_remaining_(0), sender_(NULL), receiver_(NULL), bytes_per_send_(0) {} void SetBytesPerSend(int bytes) { bytes_per_send_ = bytes; } void TestPingPong(int size, int iterations) { uint32_t start, elapsed; iterations_remaining_ = iterations; receiver_ = &remote_; sender_ = &local_; // Create some dummy data to send. send_stream_.ReserveSize(size); for (int i = 0; i < size; ++i) { char ch = static_cast<char>(i); send_stream_.Write(&ch, 1, NULL, NULL); } send_stream_.Rewind(); // Prepare the receive stream. recv_stream_.ReserveSize(size); // Connect and wait until connected. start = rtc::Time32(); EXPECT_EQ(0, Connect()); EXPECT_TRUE_WAIT(have_connected_, kConnectTimeoutMs); // Sending will start from OnTcpWriteable and stop when the required // number of iterations have completed. EXPECT_TRUE_WAIT(have_disconnected_, kTransferTimeoutMs); elapsed = rtc::TimeSince(start); RTC_LOG(LS_INFO) << "Performed " << iterations << " pings in " << elapsed << " ms"; } private: // IPseudoTcpNotify interface virtual void OnTcpReadable(PseudoTcp* tcp) { if (tcp != receiver_) { RTC_LOG_F(LS_ERROR) << "unexpected OnTcpReadable"; return; } // Stream bytes to the recv stream as they arrive. ReadData(); // If we've received the desired amount of data, rewind things // and send it back the other way! size_t position, desired; recv_stream_.GetPosition(&position); send_stream_.GetSize(&desired); if (position == desired) { if (receiver_ == &local_ && --iterations_remaining_ == 0) { Close(); // TODO(?): Fake OnTcpClosed() on the receiver for now. OnTcpClosed(&remote_, 0); return; } PseudoTcp* tmp = receiver_; receiver_ = sender_; sender_ = tmp; recv_stream_.Rewind(); send_stream_.Rewind(); OnTcpWriteable(sender_); } } virtual void OnTcpWriteable(PseudoTcp* tcp) { if (tcp != sender_) return; // Write bytes from the send stream when we can. // Shut down when we've sent everything. RTC_LOG(LS_VERBOSE) << "Flow Control Lifted"; WriteData(); } void ReadData() { char block[kBlockSize]; size_t position; int rcvd; do { rcvd = receiver_->Recv(block, sizeof(block)); if (rcvd != -1) { recv_stream_.Write(block, rcvd, NULL, NULL); recv_stream_.GetPosition(&position); RTC_LOG(LS_VERBOSE) << "Received: " << position; } } while (rcvd > 0); } void WriteData() { size_t position, tosend; int sent; char block[kBlockSize]; do { send_stream_.GetPosition(&position); tosend = bytes_per_send_ ? bytes_per_send_ : sizeof(block); if (send_stream_.Read(block, tosend, &tosend, NULL) != rtc::SR_EOS) { sent = sender_->Send(block, tosend); UpdateLocalClock(); if (sent != -1) { send_stream_.SetPosition(position + sent); RTC_LOG(LS_VERBOSE) << "Sent: " << position + sent; } else { send_stream_.SetPosition(position); RTC_LOG(LS_VERBOSE) << "Flow Controlled"; } } else { sent = static_cast<int>(tosend = 0); } } while (sent > 0); } private: int iterations_remaining_; PseudoTcp* sender_; PseudoTcp* receiver_; int bytes_per_send_; }; // Fill the receiver window until it is full, drain it and then // fill it with the same amount. This is to test that receiver window // contracts and enlarges correctly. class PseudoTcpTestReceiveWindow : public PseudoTcpTestBase { public: // Not all the data are transfered, |size| just need to be big enough // to fill up the receiver window twice. void TestTransfer(int size) { // Create some dummy data to send. send_stream_.ReserveSize(size); for (int i = 0; i < size; ++i) { char ch = static_cast<char>(i); send_stream_.Write(&ch, 1, NULL, NULL); } send_stream_.Rewind(); // Prepare the receive stream. recv_stream_.ReserveSize(size); // Connect and wait until connected. EXPECT_EQ(0, Connect()); EXPECT_TRUE_WAIT(have_connected_, kConnectTimeoutMs); rtc::Thread::Current()->Post(RTC_FROM_HERE, this, MSG_WRITE); EXPECT_TRUE_WAIT(have_disconnected_, kTransferTimeoutMs); ASSERT_EQ(2u, send_position_.size()); ASSERT_EQ(2u, recv_position_.size()); const size_t estimated_recv_window = EstimateReceiveWindowSize(); // The difference in consecutive send positions should equal the // receive window size or match very closely. This verifies that receive // window is open after receiver drained all the data. const size_t send_position_diff = send_position_[1] - send_position_[0]; EXPECT_GE(1024u, estimated_recv_window - send_position_diff); // Receiver drained the receive window twice. EXPECT_EQ(2 * estimated_recv_window, recv_position_[1]); } virtual void OnMessage(rtc::Message* message) { int message_id = message->message_id; PseudoTcpTestBase::OnMessage(message); switch (message_id) { case MSG_WRITE: { WriteData(); break; } default: break; } } uint32_t EstimateReceiveWindowSize() const { return static_cast<uint32_t>(recv_position_[0]); } uint32_t EstimateSendWindowSize() const { return static_cast<uint32_t>(send_position_[0] - recv_position_[0]); } private: // IPseudoTcpNotify interface virtual void OnTcpReadable(PseudoTcp* tcp) {} virtual void OnTcpWriteable(PseudoTcp* tcp) {} void ReadUntilIOPending() { char block[kBlockSize]; size_t position; int rcvd; do { rcvd = remote_.Recv(block, sizeof(block)); if (rcvd != -1) { recv_stream_.Write(block, rcvd, NULL, NULL); recv_stream_.GetPosition(&position); RTC_LOG(LS_VERBOSE) << "Received: " << position; } } while (rcvd > 0); recv_stream_.GetPosition(&position); recv_position_.push_back(position); // Disconnect if we have done two transfers. if (recv_position_.size() == 2u) { Close(); OnTcpClosed(&remote_, 0); } else { WriteData(); } } void WriteData() { size_t position, tosend; int sent; char block[kBlockSize]; do { send_stream_.GetPosition(&position); if (send_stream_.Read(block, sizeof(block), &tosend, NULL) != rtc::SR_EOS) { sent = local_.Send(block, tosend); UpdateLocalClock(); if (sent != -1) { send_stream_.SetPosition(position + sent); RTC_LOG(LS_VERBOSE) << "Sent: " << position + sent; } else { send_stream_.SetPosition(position); RTC_LOG(LS_VERBOSE) << "Flow Controlled"; } } else { sent = static_cast<int>(tosend = 0); } } while (sent > 0); // At this point, we've filled up the available space in the send queue. int message_queue_size = static_cast<int>(rtc::Thread::Current()->size()); // The message queue will always have at least 2 messages, an RCLOCK and // an LCLOCK, since they are added back on the delay queue at the same time // they are pulled off and therefore are never really removed. if (message_queue_size > 2) { // If there are non-clock messages remaining, attempt to continue sending // after giving those messages time to process, which should free up the // send buffer. rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, 10, this, MSG_WRITE); } else { if (!remote_.isReceiveBufferFull()) { RTC_LOG(LS_ERROR) << "This shouldn't happen - the send buffer is full, " << "the receive buffer is not, and there are no " << "remaining messages to process."; } send_stream_.GetPosition(&position); send_position_.push_back(position); // Drain the receiver buffer. ReadUntilIOPending(); } } private: rtc::MemoryStream send_stream_; rtc::MemoryStream recv_stream_; std::vector<size_t> send_position_; std::vector<size_t> recv_position_; }; // Basic end-to-end data transfer tests // Test the normal case of sending data from one side to the other. TEST_F(PseudoTcpTest, TestSend) { SetLocalMtu(1500); SetRemoteMtu(1500); TestTransfer(1000000); } // Test sending data with a 50 ms RTT. Transmission should take longer due // to a slower ramp-up in send rate. TEST_F(PseudoTcpTest, TestSendWithDelay) { SetLocalMtu(1500); SetRemoteMtu(1500); SetDelay(50); TestTransfer(1000000); } // Test sending data with packet loss. Transmission should take much longer due // to send back-off when loss occurs. TEST_F(PseudoTcpTest, TestSendWithLoss) { SetLocalMtu(1500); SetRemoteMtu(1500); SetLoss(10); TestTransfer(100000); // less data so test runs faster } // Test sending data with a 50 ms RTT and 10% packet loss. Transmission should // take much longer due to send back-off and slower detection of loss. TEST_F(PseudoTcpTest, TestSendWithDelayAndLoss) { SetLocalMtu(1500); SetRemoteMtu(1500); SetDelay(50); SetLoss(10); TestTransfer(100000); // less data so test runs faster } // Test sending data with 10% packet loss and Nagling disabled. Transmission // should take about the same time as with Nagling enabled. TEST_F(PseudoTcpTest, TestSendWithLossAndOptNaglingOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetLoss(10); SetOptNagling(false); TestTransfer(100000); // less data so test runs faster } // Test sending data with 10% packet loss and Delayed ACK disabled. // Transmission should be slightly faster than with it enabled. TEST_F(PseudoTcpTest, TestSendWithLossAndOptAckDelayOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetLoss(10); SetOptAckDelay(0); TestTransfer(100000); } // Test sending data with 50ms delay and Nagling disabled. TEST_F(PseudoTcpTest, TestSendWithDelayAndOptNaglingOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetDelay(50); SetOptNagling(false); TestTransfer(100000); // less data so test runs faster } // Test sending data with 50ms delay and Delayed ACK disabled. TEST_F(PseudoTcpTest, TestSendWithDelayAndOptAckDelayOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetDelay(50); SetOptAckDelay(0); TestTransfer(100000); // less data so test runs faster } // Test a large receive buffer with a sender that doesn't support scaling. TEST_F(PseudoTcpTest, TestSendRemoteNoWindowScale) { SetLocalMtu(1500); SetRemoteMtu(1500); SetLocalOptRcvBuf(100000); DisableRemoteWindowScale(); TestTransfer(1000000); } // Test a large sender-side receive buffer with a receiver that doesn't support // scaling. TEST_F(PseudoTcpTest, TestSendLocalNoWindowScale) { SetLocalMtu(1500); SetRemoteMtu(1500); SetRemoteOptRcvBuf(100000); DisableLocalWindowScale(); TestTransfer(1000000); } // Test when both sides use window scaling. TEST_F(PseudoTcpTest, TestSendBothUseWindowScale) { SetLocalMtu(1500); SetRemoteMtu(1500); SetRemoteOptRcvBuf(100000); SetLocalOptRcvBuf(100000); TestTransfer(1000000); } // Test using a large window scale value. TEST_F(PseudoTcpTest, TestSendLargeInFlight) { SetLocalMtu(1500); SetRemoteMtu(1500); SetRemoteOptRcvBuf(100000); SetLocalOptRcvBuf(100000); SetOptSndBuf(150000); TestTransfer(1000000); } TEST_F(PseudoTcpTest, TestSendBothUseLargeWindowScale) { SetLocalMtu(1500); SetRemoteMtu(1500); SetRemoteOptRcvBuf(1000000); SetLocalOptRcvBuf(1000000); TestTransfer(10000000); } // Test using a small receive buffer. TEST_F(PseudoTcpTest, TestSendSmallReceiveBuffer) { SetLocalMtu(1500); SetRemoteMtu(1500); SetRemoteOptRcvBuf(10000); SetLocalOptRcvBuf(10000); TestTransfer(1000000); } // Test using a very small receive buffer. TEST_F(PseudoTcpTest, TestSendVerySmallReceiveBuffer) { SetLocalMtu(1500); SetRemoteMtu(1500); SetRemoteOptRcvBuf(100); SetLocalOptRcvBuf(100); TestTransfer(100000); } // Ping-pong (request/response) tests // Test sending <= 1x MTU of data in each ping/pong. Should take <10ms. TEST_F(PseudoTcpTestPingPong, TestPingPong1xMtu) { SetLocalMtu(1500); SetRemoteMtu(1500); TestPingPong(100, 100); } // Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms. TEST_F(PseudoTcpTestPingPong, TestPingPong3xMtu) { SetLocalMtu(1500); SetRemoteMtu(1500); TestPingPong(400, 100); } // Test sending 1x-2x MTU of data in each ping/pong. // Should take ~1s, due to interaction between Nagling and Delayed ACK. TEST_F(PseudoTcpTestPingPong, TestPingPong2xMtu) { SetLocalMtu(1500); SetRemoteMtu(1500); TestPingPong(2000, 5); } // Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off. // Should take <10ms. TEST_F(PseudoTcpTestPingPong, TestPingPong2xMtuWithAckDelayOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetOptAckDelay(0); TestPingPong(2000, 100); } // Test sending 1x-2x MTU of data in each ping/pong with Nagling off. // Should take <10ms. TEST_F(PseudoTcpTestPingPong, TestPingPong2xMtuWithNaglingOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetOptNagling(false); TestPingPong(2000, 5); } // Test sending a ping as pair of short (non-full) segments. // Should take ~1s, due to Delayed ACK interaction with Nagling. TEST_F(PseudoTcpTestPingPong, TestPingPongShortSegments) { SetLocalMtu(1500); SetRemoteMtu(1500); SetOptAckDelay(5000); SetBytesPerSend(50); // i.e. two Send calls per payload TestPingPong(100, 5); } // Test sending ping as a pair of short (non-full) segments, with Nagling off. // Should take <10ms. TEST_F(PseudoTcpTestPingPong, TestPingPongShortSegmentsWithNaglingOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetOptNagling(false); SetBytesPerSend(50); // i.e. two Send calls per payload TestPingPong(100, 5); } // Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed ACK. // Should take ~1s. TEST_F(PseudoTcpTestPingPong, TestPingPongShortSegmentsWithAckDelayOff) { SetLocalMtu(1500); SetRemoteMtu(1500); SetBytesPerSend(50); // i.e. two Send calls per payload SetOptAckDelay(0); TestPingPong(100, 5); } // Test that receive window expands and contract correctly. TEST_F(PseudoTcpTestReceiveWindow, TestReceiveWindow) { SetLocalMtu(1500); SetRemoteMtu(1500); SetOptNagling(false); SetOptAckDelay(0); TestTransfer(1024 * 1000); } // Test setting send window size to a very small value. TEST_F(PseudoTcpTestReceiveWindow, TestSetVerySmallSendWindowSize) { SetLocalMtu(1500); SetRemoteMtu(1500); SetOptNagling(false); SetOptAckDelay(0); SetOptSndBuf(900); TestTransfer(1024 * 1000); EXPECT_EQ(900u, EstimateSendWindowSize()); } // Test setting receive window size to a value other than default. TEST_F(PseudoTcpTestReceiveWindow, TestSetReceiveWindowSize) { SetLocalMtu(1500); SetRemoteMtu(1500); SetOptNagling(false); SetOptAckDelay(0); SetRemoteOptRcvBuf(100000); SetLocalOptRcvBuf(100000); TestTransfer(1024 * 1000); EXPECT_EQ(100000u, EstimateReceiveWindowSize()); } /* Test sending data with mismatched MTUs. We should detect this and reduce // our packet size accordingly. // TODO(?): This doesn't actually work right now. The current code // doesn't detect if the MTU is set too high on either side. TEST_F(PseudoTcpTest, TestSendWithMismatchedMtus) { SetLocalMtu(1500); SetRemoteMtu(1280); TestTransfer(1000000); } */
mit
dstockhammer/Brighter
samples/GenericListener/Ports/Events/Tasks.cs
270
namespace GenericListener.Ports.Events { public class GenericTask : EventStoredEvent { } public class GenericTaskAddedEvent : GenericTask { } public class GenericTaskEditedEvent : GenericTask { } public class GenericTaskCompletedEvent : GenericTask { } }
mit
gefei/angular_requirejs_example
tests/main-test.js
1122
/** * @author gefei */ describe('Sample application', function() { var EC = protractor.ExpectedConditions; it('should succeed', function() { browser.get('http://localhost:63342/js_testing_example/app/index.html#/'); var btn_de = element(by.buttonText('EN')); btn_de.click(); var btn_show_dialog = element(by.partialButtonText('Show')); btn_show_dialog.click(); var label_title = element(by.binding('title')); expect(label_title.isDisplayed()).toBe(true); var btn_close = element(by.buttonText('Close')); btn_close.click(); /* var EC = protractor.ExpectedConditions; var isClickable = EC.elementToBeClickable(btn_show_dialog); browser.wait(isClickable, 5000); */ var btn_2 = element(by.buttonText('2')); //btn_2.click(); browser.actions().mouseMove(btn_2).click(); browser.actions().mouseMove(btn_show_dialog).click(); expect(label_title.isDisplayed()).toBe(true); btn_close.click(); expect(btn_2.isDisplayed()).toBe(true); }); });
mit
darrynten/sage-one-php
src/Models/TaxType.php
2758
<?php /** * SageOne Library * * @category Library * @package SageOne * @author Darryn Ten <darrynten@github.com> * @license MIT <https://github.com/darrynten/sage-one-php/blob/master/LICENSE> * @link https://github.com/darrynten/sage-one-php */ namespace DarrynTen\SageOne\Models; use DarrynTen\SageOne\BaseModel; /** * Tax Type * * Details on writable properties for Tax Type: * https://accounting.sageone.co.za/api/1.1.2/Help/ResourceModel?modelName=TaxType */ class TaxType extends BaseModel { /** * The API Endpoint * * @var string $endpoint */ protected $endpoint = 'TaxType'; /** * Defines all possible fields. * * Used by the base class to decide what gets submitted in a save call, * validation, etc * * All must include a type, whether or not it's nullable, and whether or * not it's readonly. * * NB: Naming convention for keys is to lowercase the first character of the * field returned by Sage (they use PascalCase and we use camelCase) * * `ID` is automatically converted to `id` * * Details on writable properties for Account: * https://accounting.sageone.co.za/api/1.1.2/Help/ResourceModel?modelName=Account * * TODO check why/if ID is truly writable! * * @var array $fields */ protected $fields = [ 'id' => [ 'type' => 'integer', 'nullable' => false, 'readonly' => false, ], 'name' => [ 'type' => 'string', 'nullable' => false, 'readonly' => false, ], 'percentage' => [ 'type' => 'double', 'nullable' => false, 'readonly' => false, ], 'isDefault' => [ 'type' => 'boolean', 'nullable' => false, 'readonly' => false, ], 'hasActivity' => [ 'type' => 'boolean', 'nullable' => false, 'readonly' => true, ], 'isManualTax' => [ 'type' => 'boolean', 'nullable' => false, 'readonly' => false, ], 'created' => [ 'type' => 'DateTime', 'nullable' => false, 'readonly' => true, ], 'modified' => [ 'type' => 'DateTime', 'nullable' => true, 'readonly' => true, ], ]; /** * Features supported by the endpoint * * These features enable and disable certain calls from the base model * * @var array $features */ protected $features = [ 'all' => true, 'get' => true, 'save' => true, 'delete' => true, ]; }
mit
savonarola/pulse_meter-dygraphs_visualizer
lib/pulse_meter/dygraphs_visualize/sensor.rb
1551
require "pulse_meter/dygraphs_visualize/series_extractor" module PulseMeter module DygraphsVisualize class Sensor < Base def last_value(now, need_incomplete=false) sensor = real_sensor sensor_data = if need_incomplete sensor.timeline_within(now - sensor.interval, now).first else sensor.timeline_within(now - sensor.interval * 2, now).first end if sensor_data.is_a?(PulseMeter::SensorData) sensor_data.value else nil end end def last_point_data(now, need_incomplete=false) extractor.point_data(last_value(now, need_incomplete)) end def timeline_data(from, till, need_incomplete = false) sensor = real_sensor timeline_data = sensor.timeline_within(from, till) timeline_data.pop unless need_incomplete extractor.series_data(timeline_data) end def annotation real_sensor.annotation || '' end def type real_sensor.class end def interval real_sensor.interval end def value real_sensor.value end def extractor PulseMeter::DygraphsVisualize.extractor(self) end def valid? real_sensor true rescue PulseMeter::RestoreError false end protected def real_sensor # TODO add !temporarily! caching if this will be called too frequently PulseMeter::Sensor::Base.restore(name) end end end end
mit
andrewlock/blog-examples
updating-test-host-to-3-0/3.0/ExampleApp3.IntegrationTests/HttpTests.cs
917
using System; using System.Net.Http; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace ExampleApp3.IntegrationTests { public class HttpTests: IClassFixture<ExampleAppTestFixture>, IDisposable { readonly ExampleAppTestFixture _fixture; readonly HttpClient _client; public HttpTests(ExampleAppTestFixture fixture, ITestOutputHelper output) { _fixture = fixture; fixture.Output = output; _client = fixture.CreateClient(); } public void Dispose() => _fixture.Output = null; [Fact] public async Task CanCallApi() { var result = await _client.GetAsync("/"); result.EnsureSuccessStatusCode(); var content = await result.Content.ReadAsStringAsync(); Assert.Contains("Welcome", content); } } }
mit
Webiny/Htpl
test/benchmark/twig/test2.php
295
<?php require __DIR__.'/vendor/autoload.php'; // setup $loader = new Twig_Loader_Filesystem([__DIR__.'/template/']); $twig = new Twig_Environment($loader, ['cache' => false]); // assign variables $twig->addGlobal('entries', include(__DIR__.'/../entries.php')); $twig->render('template.html');
mit
petyakostova/Telerik-Academy
C#/_Demos C# 1/3. Operators and Expressions/Expressions/Expressions.cs
1314
using System; class Expressions { static void Main() { int r = (150 - 20) / 2 + 5; Console.WriteLine("r={0}", r); // r=70 // Expression for calculation of circle area double surface = Math.PI * r * r; Console.WriteLine("surface={0}", surface); // surface=15393,80400259 // Expression for calculation of circle perimeter double perimeter = 2 * Math.PI * r; Console.WriteLine("perimeter={0}", perimeter); // perimeter=439,822971502571 // Expression of type int (evaluated at compile time) int a = 2 + 3; // a = 5 Console.WriteLine("a={0}", a); // Expression of type int (evaluated at runtime) int b = (a + 3) * (a - 4) + (2 * a + 7) / 4; // b = 12 Console.WriteLine("b={0}", b); // Expression of type bool (evaluated at runtime) bool greater = (a > b) || ((a == 0) && (b == 0)); // greater = false Console.WriteLine("greater={0}", greater); // Expression of type double (evaluated at runtime) double c = (double)(a + b) / b; // c = 1.41666666666667 Console.WriteLine("c={0}", c); // Expression of type double (evaluated as int first) double d = (double)((a + b) / b); // d = 1 Console.WriteLine("d={0}", d); } }
mit
ansteh/difference-json
gulpfile.js
958
var path = require('path'); var gulp = require('gulp'); var gutil = require("gulp-util"); var jasmine = require('gulp-jasmine'); var webpack = require('webpack'); var paths = { scripts: ['lib/**/*.js'], spec: 'test/spec/*.js' }; gulp.task('test', function () { return gulp.src(paths.spec) .pipe(jasmine()); }); gulp.task('watch', ['test'], function() { gulp.watch(paths.scripts, ['test']); }); gulp.task("webpack", function(callback) { webpack({ entry: "./lib/index.js", output: { libraryTarget: "var", library: "diffrence", path: path.resolve(__dirname, 'dist'), filename: "diffrence-json.min.js" }, plugins: [ new webpack.optimize.UglifyJsPlugin() ] }, function(err, stats) { if(err) throw new gutil.PluginError("webpack", err); gutil.log("[webpack]", stats.toString({ })); callback(); }); }); gulp.task('default', ['watch']);
mit
KiPaWanG/jquery-mobile-master
demos/widgets/headers/optimized-persistant-toolbars-a.php
3259
<?php if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') { ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Navbar - jQuery Mobile Demos</title> <link rel="stylesheet" href="../../../css/themes/default/jquery.mobile.css"> <link rel="stylesheet" href="../../_assets/css/jqm-demos.css"> <link rel="shortcut icon" href="../../favicon.ico"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700"> <script src="../../../js/jquery.js"></script> <script src="../../_assets/js/"></script> <script src="../../../js/"></script> <script> $(function(){ $("[data-role='navbar']").navbar(); $("[data-role='header'], [data-role='footer']").toolbar(); }); </script> </head> <body> <div data-role="header" class="jqm-header" data-position="fixed"> <h1 class="jqm-logo"><a href="../../"><img src="../../_assets/img/jquery-logo.png" alt="jQuery Mobile Framework"></a></h1> <a href="#" class="jqm-navmenu-link" data-icon="bars" data-iconpos="notext">Navigation</a> <a href="#" class="jqm-search-link" data-icon="search" data-iconpos="notext">Search</a> </div><!-- /header --> <?php } ?> <div data-role="page" class="jqm-demos"> <div data-role="content" class="jqm-content"> <h1>Ajax Optimized Persistant Toolbars <a href="http://api.jquerymobile.com/navbar/" data-ajax="false" data-role="button" data-inline="true" data-mini="true" data-icon="carat-r" data-iconpos="right" class="jqm-api-link">API</a></h1> <p>These pages have been optimized on the server side to check if the request is coming from an ajax request and if so they only send the actual page div instead fo the entire page. If you navigate to any of the pages in the nav bar at the bottom and inspect the return data you will see it contains no head, toolbars, html tag, or body tag</p> <p>However if you refresh the page all of these things will be present</p> <p>This is done by checking the HTTP_X_REQUESTED_WITH header </p> <pre><code> if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') { </code></pre> <p>all of the markup not needed when being requested via ajax is wrapped in if statements like the one above.</p> </div><!-- /content --> <?php include( '../../global-nav.php' ); ?> </div><!-- /page --> <?php if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') { ?> <div data-role="footer" data-position="fixed"> <div data-role="navbar"> <ul> <li><a href="optimized-persistant-toolbars-a.php" data-prefetch="true" data-transition="none">Info</a></li> <li><a href="optimized-persistant-toolbars-b.php" data-prefetch="true" data-transition="flip">Friends</a></li> <li><a href="optimized-persistant-toolbars-c.php" data-prefetch="true" data-transition="turn">Albums</a></li> <li><a href="optimized-persistant-toolbars-d.php" data-prefetch="true" data-transition="slide">Emails</a></li> </ul> </div><!-- /navbar --> </div><!-- /footer --> </body> </html> <?php } ?>
mit
samuelfac/portalunico.siscomex.gov.br
src/main/java/br/gov/siscomex/portalunico/cct_ext/model/RetornoConsulta.java
12027
package br.gov.siscomex.portalunico.cct_ext.model; import java.util.List; import javax.validation.Valid; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RetornoConsulta", propOrder = { "numeroRUC", "numeroDUE", "ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado", "existeImpedimentoEmbarque", "indicadorSeCargaRUCMaster", "numeroRUCMasterDaCarga", "conteineres", "documentosDeTransporte", "listaCargasSoltasVeiculos", "listaGraneis" }) @XmlRootElement(name="RetornoConsulta") /** * Retorno da Consulta **/ @ApiModel(description="Retorno da Consulta") public class RetornoConsulta { @XmlElement(name="numeroRUC") @ApiModelProperty(example = "6BR00000000100000000000000000003477", value = "Número RUC<br>Tamanho mínimo: 13<br>Tamanho máximo: 35<br>Formato: NAANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN") /** * Número RUC<br>Tamanho mínimo: 13<br>Tamanho máximo: 35<br>Formato: NAANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN **/ private String numeroRUC = null; @XmlElement(name="numeroDUE") @ApiModelProperty(example = "16BR0000044309", value = "Número DU-E<br>Tamanho: 14<br>Formato: AABRSSSSSSSSSD<br>Descrição Formato<br>AA - Ano<br>BR - Brasil<br>SSSSSSSSS - Número Sequencial<br>D - DV") /** * Número DU-E<br>Tamanho: 14<br>Formato: AABRSSSSSSSSSD<br>Descrição Formato<br>AA - Ano<br>BR - Brasil<br>SSSSSSSSS - Número Sequencial<br>D - DV **/ private String numeroDUE = null; @XmlElement(name="ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado") @ApiModelProperty(example = "false", value = "Ocorreu desembaraço ou autorização embarque antecipado<br>Domínio: S (Sim), N (Não)") /** * Ocorreu desembaraço ou autorização embarque antecipado<br>Domínio: S (Sim), N (Não) **/ private Boolean ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado = false; @XmlElement(name="existeImpedimentoEmbarque") @ApiModelProperty(example = "false", value = "Existe Impedimento Embarque<br>Domínio: S (Sim), N (Não)") /** * Existe Impedimento Embarque<br>Domínio: S (Sim), N (Não) **/ private Boolean existeImpedimentoEmbarque = false; @XmlElement(name="indicadorSeCargaRUCMaster") @ApiModelProperty(example = "false", value = "Indicador se carga RUC Master<br>Domínio: S (Sim), N (Não)") /** * Indicador se carga RUC Master<br>Domínio: S (Sim), N (Não) **/ private Boolean indicadorSeCargaRUCMaster = false; @XmlElement(name="numeroRUCMasterDaCarga") @ApiModelProperty(example = "6BR00000000100000000000000000003475", value = "Número RUC Master da carga<br>Tamanho mínimo: 13<br>Tamanho máximo: 35<br>Formato: NAANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN") /** * Número RUC Master da carga<br>Tamanho mínimo: 13<br>Tamanho máximo: 35<br>Formato: NAANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN **/ private String numeroRUCMasterDaCarga = null; @XmlElement(name="conteineres") @ApiModelProperty(example = "[MARK016,MARK017]", value = "Contêiner<br>Tamanho: 20<br>Formato: AAAAAAAAAAAAAAAAAAAA") /** * Contêiner<br>Tamanho: 20<br>Formato: AAAAAAAAAAAAAAAAAAAA **/ private List<String> conteineres = null; @XmlElement(name="documentosDeTransporte") @ApiModelProperty(value = "Número documento de transporte<br>Tamanho mínimo: 5<br>Tamanho máximo: 15") @Valid /** * Número documento de transporte<br>Tamanho mínimo: 5<br>Tamanho máximo: 15 **/ private List<DocumentosTransporte> documentosDeTransporte = null; @XmlElement(name="listaCargasSoltasVeiculos") @ApiModelProperty(value = "") @Valid private List<DadosCargaSoltaVeiculo> listaCargasSoltasVeiculos = null; @XmlElement(name="listaGraneis") @ApiModelProperty(value = "") @Valid private List<DadosGranel> listaGraneis = null; /** * Número RUC&lt;br&gt;Tamanho mínimo: 13&lt;br&gt;Tamanho máximo: 35&lt;br&gt;Formato: NAANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN * @return numeroRUC **/ @JsonProperty("numeroRUC") public String getNumeroRUC() { return numeroRUC; } public void setNumeroRUC(String numeroRUC) { this.numeroRUC = numeroRUC; } public RetornoConsulta numeroRUC(String numeroRUC) { this.numeroRUC = numeroRUC; return this; } /** * Número DU-E&lt;br&gt;Tamanho: 14&lt;br&gt;Formato: AABRSSSSSSSSSD&lt;br&gt;Descrição Formato&lt;br&gt;AA - Ano&lt;br&gt;BR - Brasil&lt;br&gt;SSSSSSSSS - Número Sequencial&lt;br&gt;D - DV * @return numeroDUE **/ @JsonProperty("numeroDUE") public String getNumeroDUE() { return numeroDUE; } public void setNumeroDUE(String numeroDUE) { this.numeroDUE = numeroDUE; } public RetornoConsulta numeroDUE(String numeroDUE) { this.numeroDUE = numeroDUE; return this; } /** * Ocorreu desembaraço ou autorização embarque antecipado&lt;br&gt;Domínio: S (Sim), N (Não) * @return ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado **/ @JsonProperty("ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado") public Boolean isOcorreuDesembaracoOuAutorizacaoEmbarqueAntecipado() { return ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado; } public void setOcorreuDesembaracoOuAutorizacaoEmbarqueAntecipado(Boolean ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado) { this.ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado = ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado; } public RetornoConsulta ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado(Boolean ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado) { this.ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado = ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado; return this; } /** * Existe Impedimento Embarque&lt;br&gt;Domínio: S (Sim), N (Não) * @return existeImpedimentoEmbarque **/ @JsonProperty("existeImpedimentoEmbarque") public Boolean isExisteImpedimentoEmbarque() { return existeImpedimentoEmbarque; } public void setExisteImpedimentoEmbarque(Boolean existeImpedimentoEmbarque) { this.existeImpedimentoEmbarque = existeImpedimentoEmbarque; } public RetornoConsulta existeImpedimentoEmbarque(Boolean existeImpedimentoEmbarque) { this.existeImpedimentoEmbarque = existeImpedimentoEmbarque; return this; } /** * Indicador se carga RUC Master&lt;br&gt;Domínio: S (Sim), N (Não) * @return indicadorSeCargaRUCMaster **/ @JsonProperty("indicadorSeCargaRUCMaster") public Boolean isIndicadorSeCargaRUCMaster() { return indicadorSeCargaRUCMaster; } public void setIndicadorSeCargaRUCMaster(Boolean indicadorSeCargaRUCMaster) { this.indicadorSeCargaRUCMaster = indicadorSeCargaRUCMaster; } public RetornoConsulta indicadorSeCargaRUCMaster(Boolean indicadorSeCargaRUCMaster) { this.indicadorSeCargaRUCMaster = indicadorSeCargaRUCMaster; return this; } /** * Número RUC Master da carga&lt;br&gt;Tamanho mínimo: 13&lt;br&gt;Tamanho máximo: 35&lt;br&gt;Formato: NAANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN * @return numeroRUCMasterDaCarga **/ @JsonProperty("numeroRUCMasterDaCarga") public String getNumeroRUCMasterDaCarga() { return numeroRUCMasterDaCarga; } public void setNumeroRUCMasterDaCarga(String numeroRUCMasterDaCarga) { this.numeroRUCMasterDaCarga = numeroRUCMasterDaCarga; } public RetornoConsulta numeroRUCMasterDaCarga(String numeroRUCMasterDaCarga) { this.numeroRUCMasterDaCarga = numeroRUCMasterDaCarga; return this; } /** * Contêiner&lt;br&gt;Tamanho: 20&lt;br&gt;Formato: AAAAAAAAAAAAAAAAAAAA * @return conteineres **/ @JsonProperty("conteineres") public List<String> getConteineres() { return conteineres; } public void setConteineres(List<String> conteineres) { this.conteineres = conteineres; } public RetornoConsulta conteineres(List<String> conteineres) { this.conteineres = conteineres; return this; } public RetornoConsulta addConteineresItem(String conteineresItem) { this.conteineres.add(conteineresItem); return this; } /** * Número documento de transporte&lt;br&gt;Tamanho mínimo: 5&lt;br&gt;Tamanho máximo: 15 * @return documentosDeTransporte **/ @JsonProperty("documentosDeTransporte") public List<DocumentosTransporte> getDocumentosDeTransporte() { return documentosDeTransporte; } public void setDocumentosDeTransporte(List<DocumentosTransporte> documentosDeTransporte) { this.documentosDeTransporte = documentosDeTransporte; } public RetornoConsulta documentosDeTransporte(List<DocumentosTransporte> documentosDeTransporte) { this.documentosDeTransporte = documentosDeTransporte; return this; } public RetornoConsulta addDocumentosDeTransporteItem(DocumentosTransporte documentosDeTransporteItem) { this.documentosDeTransporte.add(documentosDeTransporteItem); return this; } /** * Get listaCargasSoltasVeiculos * @return listaCargasSoltasVeiculos **/ @JsonProperty("listaCargasSoltasVeiculos") public List<DadosCargaSoltaVeiculo> getListaCargasSoltasVeiculos() { return listaCargasSoltasVeiculos; } public void setListaCargasSoltasVeiculos(List<DadosCargaSoltaVeiculo> listaCargasSoltasVeiculos) { this.listaCargasSoltasVeiculos = listaCargasSoltasVeiculos; } public RetornoConsulta listaCargasSoltasVeiculos(List<DadosCargaSoltaVeiculo> listaCargasSoltasVeiculos) { this.listaCargasSoltasVeiculos = listaCargasSoltasVeiculos; return this; } public RetornoConsulta addListaCargasSoltasVeiculosItem(DadosCargaSoltaVeiculo listaCargasSoltasVeiculosItem) { this.listaCargasSoltasVeiculos.add(listaCargasSoltasVeiculosItem); return this; } /** * Get listaGraneis * @return listaGraneis **/ @JsonProperty("listaGraneis") public List<DadosGranel> getListaGraneis() { return listaGraneis; } public void setListaGraneis(List<DadosGranel> listaGraneis) { this.listaGraneis = listaGraneis; } public RetornoConsulta listaGraneis(List<DadosGranel> listaGraneis) { this.listaGraneis = listaGraneis; return this; } public RetornoConsulta addListaGraneisItem(DadosGranel listaGraneisItem) { this.listaGraneis.add(listaGraneisItem); return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RetornoConsulta {\n"); sb.append(" numeroRUC: ").append(toIndentedString(numeroRUC)).append("\n"); sb.append(" numeroDUE: ").append(toIndentedString(numeroDUE)).append("\n"); sb.append(" ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado: ").append(toIndentedString(ocorreuDesembaracoOuAutorizacaoEmbarqueAntecipado)).append("\n"); sb.append(" existeImpedimentoEmbarque: ").append(toIndentedString(existeImpedimentoEmbarque)).append("\n"); sb.append(" indicadorSeCargaRUCMaster: ").append(toIndentedString(indicadorSeCargaRUCMaster)).append("\n"); sb.append(" numeroRUCMasterDaCarga: ").append(toIndentedString(numeroRUCMasterDaCarga)).append("\n"); sb.append(" conteineres: ").append(toIndentedString(conteineres)).append("\n"); sb.append(" documentosDeTransporte: ").append(toIndentedString(documentosDeTransporte)).append("\n"); sb.append(" listaCargasSoltasVeiculos: ").append(toIndentedString(listaCargasSoltasVeiculos)).append("\n"); sb.append(" listaGraneis: ").append(toIndentedString(listaGraneis)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private static String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
mit
holmesal/hire-alonso
src/components/SexyBackground.js
6131
import React, { Component, Image, PropTypes, StyleSheet, Text, View } from 'react-native'; import { CanvasSpace, Const, Form, Point, Pair, Vector } from 'ptjs'; export default class SexyBackground extends Component { componentDidMount() { this.initPt(); } initPt() { var colors = { a1: "#ff2d5d", a2: "#42dc8e", a3: "#2e43eb", a4: "#ffe359", b1: "#96bfed", b2: "#f5ead6", b3: "#f1f3f7", b4: "#e2e6ef", lightBlue: '#4997BA' }; var space = new CanvasSpace("demo", "#202020" ).display(); var form = new Form( space ); console.info(space) //// 2. Create Elements var pairs = []; var center = space.size.$divide(2); var mouse = center.clone(); mouse.x = space.size.x + 50; mouse.y = 50; var mousing = false; // Initial direction var target = center.clone(); target.x = -50; console.info('initial target', target) //var moveSpeed = 0.003; var moveSpeed = 0.008; var nw = space.size.$multiply(0.1); console.info(nw) var north = new Point([space.size.x/2, 20, 0]); console.info(north) const bigMonitorArea = 1920 * 1200; const bigMonitorNumPoints = 100; const currentArea = space.size.x * space.size.y; const areaFraction = currentArea / bigMonitorArea; const numPoints = Math.round(bigMonitorNumPoints * Math.sqrt(Math.sqrt(areaFraction))); var steps = numPoints; var rx = space.size.x * 0.45; var ry = space.size.y * 0.45; // Alternate method - ensures bounds always covered //var dr = Math.max( space.size.x, space.size.y ) * 0.5 / steps; // Whoa try this shit out! var dr = Math.max( space.size.x, space.size.y ) * 0.4; rx = dr; ry = dr; // create points for (var i=0; i<steps; i++) { var p = new Pair( Math.random()*rx, Math.random()*ry ).to( Math.random()*-rx, Math.random()*-ry ); p.moveBy( center ).rotate2D( i*Math.PI/steps, center ); pairs.push( p ); } function pickTop() { return new Vector(Math.random() * space.size.x, -100); } function pickBottom() { return new Vector(Math.random() * space.size.x, space.size.y + 100); } function pickLeft() { return new Vector(-100, Math.random() * space.size.y); } function pickRight() { return new Vector(space.size.x + 100, Math.random() * space.size.y); } function sample(arr) { return arr[Math.floor(Math.random() * arr.length)]; } function pickNewTarget() { var newX, newY, newTarget; if (target.x < 0) { newTarget = sample([pickTop, pickRight, pickBottom]).call() } else if (target.x > space.size.x) { newTarget = sample([pickTop, pickLeft, pickBottom]).call() } else if (target.y < 0) { newTarget = sample([pickLeft, pickRight, pickBottom]).call() } else if (target.y > space.size.y) { newTarget = sample([pickLeft, pickTop, pickBottom]).call() } else { newTarget = sample([pickTop, pickLeft, pickRight, pickBottom]).call() } // var newTarget = new Vector(Math.random() * space.size.x * 0.8, Math.random() * space.size.y * 0.8); console.info('picked new target', newTarget); target = newTarget } //// 3. Visualize, Animate, Interact space.add({ animate: function(time, fps, context) { for (var i=0; i<pairs.length; i++) { // rotate each pair by 0.1 degree var pr = pairs[i]; var rotationFactor = pr.midpoint().distance(center); // pr.rotate2D( Const.one_degree/10 * rotationFactor/500, center ); // pr.rotate2D( Const.one_degree/20, center ); pr.rotate2D( Const.one_degree/16, center ); // check collinearity with mouse, and draw a line with different color var col = pr.collinear(mouse); // disable mouse col = 10000; if (!mousing) { // If we're not already at the point if (mouse.distance(target) < 1) { pickNewTarget() } // Figure out the heading to the next target var targetHeading = new Pair(mouse).to(target).direction().normalize(); mouse.moveBy(targetHeading.$multiply(moveSpeed)); } // Attract // var attractionDirection = new Pair(pr.$getAt(0), mouse).normalize(); // pr.$getAt(0).x -= 10; // form.stroke("rgba(250,250,250,0.06)"); // var point = space.size.$divide(Math.random() * 10); // form.line( pr.equal().to( north ) ); form.stroke(false ).fill(colors.lightBlue).points( pr.toArray(), 0.5) ; var dist = pr.$getAt(0).distance(mouse); var opacity = (100/dist) * 0.1; form.stroke("rgba(250,250,250,"+opacity+")"); form.line( pr.clone().to( mouse ) ); // Color this point white the closer we are var whiteOpacity = 40/dist; form.stroke(false ).fill("rgba(255,255,255,"+(whiteOpacity)+")").point( pr.$getAt(0), 0.5) ; form.stroke(false ).fill("rgba(255,255,255,"+(whiteOpacity/3)+")").point( pr.$getAt(1), 0.5) ; var dist = pr.$getAt(1).distance(mouse); var opacity = (100/dist) * 0.1; form.stroke("rgba(250,250,250,"+opacity+")"); form.line(new Pair(pr.$getAt(1)).to(mouse)) // Exact collinearity with return 0, but here we just check for a generous threshold if ( Math.abs( col ) < 200 ) { form.stroke("#fff"); form.line( pr ); form.line( pr.clone().to( mouse ) ); // not collinear, check whether mouse is on left or right side } else { // if (Math.random() > 0.99) { // form.stroke( ( (col<0) ? "rgba(255,255,0,.1)" : "rgba(0,255,255,.1)") ).line( pr ); // } } //form.fill( '#fefefe' ).stroke(false).point( mouse, 1.5, true ); } }, onMouseAction: function(type, x, y, evt) { //console.info(type) //if (space.touchesToPoints( evt ).length > 0) alert('touching!') if (type=="move") { mousing = true; mouse.set(x,y); } else if (type == 'out') { console.info('mouseout!') mousing = false; } else if (type == 'up') { pickNewTarget(); mousing = false; } } }); space.bindMouse(); space.play(); } render() { return ( <div id="pt" style={this.props.style} /> ); } } let styles = StyleSheet.create({ wrapper: { //flex: 1 backgroundColor: 'red' }, fill: { } });
mit
HexogenDev/MCProtocolLib
src/main/java/org/spacehq/mc/protocol/packet/ingame/client/player/ClientPlayerPlaceBlockPacket.java
2412
package org.spacehq.mc.protocol.packet.ingame.client.player; import org.spacehq.mc.protocol.data.game.NetItemStack; import org.spacehq.mc.protocol.data.game.NetPosition; import org.spacehq.mc.protocol.data.game.values.Face; import org.spacehq.mc.protocol.data.game.values.MagicValues; import org.spacehq.mc.protocol.util.NetUtil; import org.spacehq.packetlib.io.NetInput; import org.spacehq.packetlib.io.NetOutput; import org.spacehq.packetlib.packet.Packet; import java.io.IOException; public class ClientPlayerPlaceBlockPacket implements Packet { private NetPosition netPosition; private Face face; private NetItemStack held; private float cursorX; private float cursorY; private float cursorZ; @SuppressWarnings("unused") private ClientPlayerPlaceBlockPacket() { } public ClientPlayerPlaceBlockPacket(NetPosition netPosition, Face face, NetItemStack held, float cursorX, float cursorY, float cursorZ) { this.netPosition = netPosition; this.face = face; this.held = held; this.cursorX = cursorX; this.cursorY = cursorY; this.cursorZ = cursorZ; } public NetPosition getPosition() { return this.netPosition; } public Face getFace() { return this.face; } public NetItemStack getHeldItem() { return this.held; } public float getCursorX() { return this.cursorX; } public float getCursorY() { return this.cursorY; } public float getCursorZ() { return this.cursorZ; } @Override public void read(NetInput in) throws IOException { this.netPosition = NetUtil.readPosition(in); this.face = MagicValues.key(Face.class, in.readUnsignedByte()); this.held = NetUtil.readItem(in); this.cursorX = in.readByte() / 16f; this.cursorY = in.readByte() / 16f; this.cursorZ = in.readByte() / 16f; } @Override public void write(NetOutput out) throws IOException { NetUtil.writePosition(out, this.netPosition); out.writeByte(MagicValues.value(Integer.class, this.face)); NetUtil.writeItem(out, this.held); out.writeByte((int) (this.cursorX * 16)); out.writeByte((int) (this.cursorY * 16)); out.writeByte((int) (this.cursorZ * 16)); } @Override public boolean isPriority() { return false; } }
mit
vduseev/browspot-kinect-library
controlpanel/devicetreeitem.cpp
254
#include "devicetreeitem.h" #include "abstractdevice.h" DeviceTreeItem::DeviceTreeItem( QTreeWidget* parent, AbstractDevice* prototype ) : QTreeWidgetItem( parent ) , m_prototype( prototype ) { } DeviceTreeItem::~DeviceTreeItem() { }
mit
ludios/Protojson
protojson/error.py
83
class PbDecodeError(Exception): """ Deserializing a PbLite list has failed. """
mit
crowsonkb/style_transfer
config_system.py
8245
"""The configuration system.""" import argparse from fractions import Fraction import math import os from pathlib import Path import re import subprocess import sys import numpy as np CONFIG_PY = Path(__file__).parent.resolve() / 'config.py' def detect_devices(): try: gpu_list = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE, check=True, universal_newlines=True) gpus = list(map(int, re.findall(r'^GPU (\d+)', gpu_list.stdout, re.M))) return gpus if gpus else [-1] except (subprocess.CalledProcessError, FileNotFoundError): return [-1] def ffloat(s): """Parses fractional or floating point input strings.""" return float(Fraction(s)) class arg: def __init__(self, *args, **kwargs): self.args, self.kwargs = args, kwargs def add_args(parser, args): for a in args: parser.add_argument(*a.args, **a.kwargs) def parse_args(state_obj=None): """Parses command line arguments.""" parser = argparse.ArgumentParser(description='Neural style transfer using Caffe.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) add_args(parser, [ arg('--content-image', '-ci', help='the content image'), arg('--style-images', '-si', nargs='+', default=[], metavar='STYLE_IMAGE', help='the style images'), arg('--output-image', '-oi', help='the output image'), arg('--init-image', '-ii', metavar='IMAGE', help='the initial image'), arg('--aux-image', '-ai', metavar='IMAGE', help='the auxiliary image'), arg('--config', type=Path, help='a Python source file containing configuration options'), arg('--list-layers', action='store_true', help='list the model\'s layers'), arg('--caffe-path', help='the path to the Caffe installation'), arg('--devices', nargs='+', metavar='DEVICE', type=int, default=[-1], help='GPU device numbers to use (-1 for cpu)'), arg('--iterations', '-i', nargs='+', type=int, default=[200, 100], help='the number of iterations'), arg('--size', '-s', type=int, default=256, help='the output size'), arg('--min-size', type=int, default=182, help='the minimum scale\'s size'), arg('--style-scale', '-ss', type=ffloat, default=1, help='the style scale factor'), arg('--max-style-size', type=int, help='the maximum style size'), arg('--style-scale-up', default=False, action='store_true', help='allow scaling style images up'), arg('--style-multiscale', '-sm', type=int, nargs=2, metavar=('MIN_SCALE', 'MAX_SCALE'), default=None, help='combine styles computed at all scales into a single style'), arg('--tile-size', type=int, default=512, help='the maximum rendering tile size'), arg('--optimizer', '-o', default='adam', choices=['adam', 'lbfgs'], help='the optimizer to use'), arg('--step-size', '-st', type=ffloat, default=15, help='the initial step size for Adam'), arg('--step-decay', '-sd', nargs=2, metavar=('DECAY', 'POWER'), type=ffloat, default=[0.05, 0.5], help='on step i, divide step_size by (1 + DECAY * i)^POWER'), arg('--avg-window', type=ffloat, default=20, help='the iterate averaging window size'), arg('--layer-weights', help='a json file containing per-layer weight scaling factors'), arg('--content-weight', '-cw', type=ffloat, default=0.05, help='the content image factor'), arg('--dd-weight', '-dw', type=ffloat, default=0, help='the Deep Dream factor'), arg('--tv-weight', '-tw', type=ffloat, default=5, help='the TV smoothing factor'), arg('--tv-power', '-tp', metavar='BETA', type=ffloat, default=2, help='the TV smoothing exponent'), arg('--swt-weight', '-ww', metavar='WEIGHT', type=ffloat, default=0, help='the SWT smoothing factor'), arg('--swt-wavelet', '-wt', metavar='WAVELET', default='haar', help='the SWT wavelet'), arg('--swt-levels', '-wl', metavar='LEVELS', default=1, type=int, help='the number of levels to use for decomposition'), arg('--swt-power', '-wp', metavar='P', default=2, type=ffloat, help='the SWT smoothing exponent'), arg('--p-weight', '-pw', type=ffloat, default=2, help='the p-norm regularizer factor'), arg('--p-power', '-pp', metavar='P', type=ffloat, default=6, help='the p-norm exponent'), arg('--aux-weight', '-aw', type=ffloat, default=10, help='the auxiliary image factor'), arg('--content-layers', nargs='*', default=['conv4_2'], metavar='LAYER', help='the layers to use for content'), arg('--style-layers', nargs='*', metavar='LAYER', default=['conv1_1', 'conv2_1', 'conv3_1', 'conv4_1', 'conv5_1'], help='the layers to use for style'), arg('--dd-layers', nargs='*', metavar='LAYER', default=[], help='the layers to use for Deep Dream'), arg('--port', '-p', type=int, default=8000, help='the port to use for the http server'), arg('--display', default='browser', choices=['browser', 'gui', 'none'], help='the display method to use'), arg('--browser', default=None, help='the web browser to open the web interface in'), arg('--model', default='vgg19.prototxt', help='the Caffe deploy.prototxt for the model to use'), arg('--weights', default='vgg19.caffemodel', help='the Caffe .caffemodel for the model to use'), arg('--mean', nargs=3, metavar=('B_MEAN', 'G_MEAN', 'R_MEAN'), default=(103.939, 116.779, 123.68), help='the per-channel means of the model (BGR order)'), arg('--save-every', metavar='N', type=int, default=0, help='save the image every n steps'), arg('--seed', type=int, default=0, help='the random seed'), arg('--div', metavar='FACTOR', type=int, default=1, help='Ensure all images are divisible by FACTOR ' '(can fix some GPU memory alignment issues)'), arg('--jitter', action='store_true', help='use slower but higher quality translation-invariant rendering'), arg('--debug', action='store_true', help='enable debug messages'), ]) defaults = vars(parser.parse_args([])) config_args = {} if CONFIG_PY.exists(): config_args.update(eval_config(CONFIG_PY)) sysv_args = vars(parser.parse_args()) config2_args = {} if sysv_args['config']: config2_args.update(eval_config(sysv_args['config'])) args = {} args.update(defaults) args.update(config_args) for a, value in sysv_args.items(): if defaults[a] != value: args[a] = value args.update(config2_args) args2 = AutocallNamespace(state_obj, **args) if args2.debug: os.environ['DEBUG'] = '1' if not args2.list_layers and (not args2.content_image or not args2.style_images): parser.print_help() sys.exit(1) return args2 class ValuePlaceholder: pass class AutocallNamespace: def __init__(self, state_obj, **kwargs): self.state_obj = state_obj self.ns = argparse.Namespace(**kwargs) def __getattr__(self, name): value = getattr(self.ns, name) if callable(value): try: return value(self.state_obj) except AttributeError: return ValuePlaceholder() return value def __setattr__(self, name, value): if name in ('state_obj', 'ns'): object.__setattr__(self, name, value) return setattr(self.ns, name, value) def __iter__(self): yield from vars(self.ns) def __contains__(self, key): return key in self.ns def __repr__(self): return 'Autocall' + repr(self.ns) CONFIG_GLOBALS = dict(detect_devices=detect_devices, math=math, np=np) def eval_config(config_file): config_code = compile(config_file.read_text(), config_file.name, 'exec') locs = {} exec(config_code, CONFIG_GLOBALS, locs) # pylint: disable=exec-used return locs
mit
regexps/todo-regex
index.js
302
/*! * todo-regex <https://github.com/regexps/todo-regex> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; module.exports = function () { return /<!--[ \t]*@?(?:todo|fixme):?[ \t]*([^\n]+)[ \t]*-->|(?:@|\/\/[ \t]*)?(?:todo|fixme):?[ \t]*([^\n]+)/i; };
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_95/safe/CWE_95__GET__whitelist_using_array__echo-sprintf_%s_simple_quote.php
1366
<?php /* Safe sample input : reads the field UserData from the variable $_GET SANITIZE : use in_array to check if $tainted is in the white list construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_GET['UserData']; $legal_table = array("safe1", "safe2"); if (in_array($tainted, $legal_table, true)) { $tainted = $tainted; } else { $tainted = $legal_table[0]; } $query = sprintf("echo $'%s';", $tainted); $res = eval($query); ?>
mit
Lisennk/Slack-Events
src/Events/PinAdded.php
273
<?php namespace Lisennk\LaravelSlackEvents\Events; use Lisennk\LaravelSlackEvents\Events\Base\SlackEvent; /** * Slack Events API event * * @see https://api.slack.com/events * @package Lisennk\LaravelSlackEvents\Events */ class PinAdded extends SlackEvent { // }
mit
Gracker/ZhiHuDaily-React-Native
ListScreen.js
12870
'use strict'; var React = require('react-native'); var { AsyncStorage, Platform, Dimensions, ListView, Image, StyleSheet, Text, View, DrawerLayoutAndroid, ToolbarAndroid, ToastAndroid, BackAndroid, TouchableOpacity, } = React var TimerMixin = require('react-timer-mixin'); var StoryItem = require('./StoryItem'); var ThemesList = require('./ThemesList'); var DataRepository = require('./DataRepository'); var SwipeRefreshLayoutAndroid = require('./SwipeRereshLayout'); var ViewPager = require('./ViewPager'); var API_LATEST_URL = 'http://news.at.zhihu.com/api/4/news/latest'; var API_HISTORY_URL = 'http://news.at.zhihu.com/api/4/news/before/'; var API_THEME_URL = 'http://news-at.zhihu.com/api/4/theme/'; var LOADING = {}; // var lastDate = null; // var latestDate = null; // var dataBlob = {}; var WEEKDAY = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; var DRAWER_WIDTH_LEFT = 56; var toolbarActions = [ {title: '提醒', icon: require('image!ic_message_white'), show: 'always'}, {title: '夜间模式', show: 'never'}, {title: '设置选项', show: 'never'}, ]; var HOME_LIST_KEY = 'home_list_key_'; var THEME_LIST_KEY = 'theme_list_key_'; var repository = new DataRepository(); var dataCache = { dataForTheme: {}, topDataForTheme: {}, sectionsForTheme: {}, lastID: {}, }; function parseDateFromYYYYMMdd(str) { if (!str) return new Date(); return new Date(str.slice(0, 4),str.slice(4, 6) - 1,str.slice(6, 8)); } Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear().toString(); var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based var dd = this.getDate().toString(); return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding }; var ListScreen = React.createClass({ mixins: [TimerMixin], getInitialState: function() { var dataSource = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, sectionHeaderHasChanged: (s1, s2) => s1 !== s2, }); var headerDataSource = new ViewPager.DataSource({ pageHasChanged: (p1, p2) => p1 !== p2, }); return { isLoading: false, isLoadingTail: false, theme: null, dataSource: dataSource, headerDataSource: headerDataSource, }; }, componentWillMount: function() { BackAndroid.addEventListener('hardwareBackPress', this._handleBackButtonPress); }, componentWillUnmount: function() { repository.saveStories(dataCache.dataForTheme, dataCache.topDataForTheme); }, _handleBackButtonPress: function() { if (this.state.theme) { this.onSelectTheme(null); return true; } return false; }, componentDidMount: function() { this.fetchStories(this.state.theme, true); }, fetchStories: function(theme, isRefresh) { var themeId = theme ? theme.id : 0; var isInTheme = themeId !== 0 var lastID = isRefresh ? null : dataCache.lastID[themeId]; var dataBlob = dataCache.dataForTheme[themeId]; if (!dataBlob) { dataBlob = isInTheme ? [] : {}; } var sectionIDs = dataCache.sectionsForTheme[themeId]; var topData = dataCache.topDataForTheme[themeId]; this.setState({ isLoading: isRefresh, isLoadingTail: !isRefresh, theme: this.state.theme, dataSource: this.state.dataSource, }); repository.fetchThemeStories(themeId, lastID) .then((responseData) => { var newLastID; var dataSouce; var headerDataSource = this.state.headerDataSource; if (!isInTheme) { newLastID = responseData.date; var newDataBlob = {}; var newSectionIDs = sectionIDs ? sectionIDs.slice() : [] if (newSectionIDs.indexOf(newLastID) < 0) { newSectionIDs.push(newLastID); newSectionIDs.sort((a, b) => (b - a)); } for (var i = 0; i < newSectionIDs.length; i++) { newDataBlob[newSectionIDs[i]] = dataBlob[newSectionIDs[i]]; } newDataBlob[newLastID] = responseData.stories; dataCache.sectionsForTheme[themeId] = newSectionIDs; dataBlob = newDataBlob; sectionIDs = newSectionIDs; if (responseData.topData) { topData = responseData.topData; headerDataSource = headerDataSource.cloneWithPages(topData.slice()) } dataSouce = this.state.dataSource.cloneWithRowsAndSections(newDataBlob, newSectionIDs, null); } else { var length = responseData.stories.length; if (length > 0) { newLastID = responseData.stories[length - 1].id; } var newDataBlob; if (isRefresh) { newDataBlob = responseData.stories; } else { newDataBlob = dataBlob.concat(responseData.stories); } if (responseData.topData) { topData = responseData.topData; } dataBlob = newDataBlob; dataSouce = this.state.dataSource.cloneWithRows(newDataBlob); } dataCache.lastID[themeId] = newLastID; dataCache.dataForTheme[themeId] = dataBlob; dataCache.topDataForTheme[themeId] = topData; // console.log('lastID: ' + lastID); // console.log('newLastID: ' + newLastID); LOADING[themeId] = false; this.setState({ isLoading: (isRefresh ? false : this.state.isLoading), isLoadingTail: (isRefresh ? this.state.isLoadingTail : false), theme: this.state.theme, dataSource: dataSouce, headerDataSource: headerDataSource, }); this.swipeRefreshLayout && this.swipeRefreshLayout.finishRefresh(); }) .catch((error) => { console.error(error); this.setState({ isLoading: (isRefresh ? false : this.state.isLoading), isLoadingTail: (isRefresh ? this.state.isLoadingTail : false), theme: this.state.theme, dataSource: this.state.dataSource.cloneWithRows([]), }); this.swipeRefreshLayout && this.swipeRefreshLayout.finishRefresh(); }) .done(); }, _renderPage: function( story: Object, pageID: number | string,) { return ( <TouchableOpacity style={{flex: 1}} onPress={() => {this.selectStory(story)}}> <Image source={{uri: story.image}} style={styles.headerItem} > <View style={styles.headerTitleContainer}> <Text style={styles.headerTitle} numberOfLines={2}> {story.title} </Text> </View> </Image> </TouchableOpacity> ) }, _renderHeader: function() { if (this.state.theme) { var themeId = this.state.theme ? this.state.theme.id : 0; var topData = dataCache.topDataForTheme[themeId]; if (!topData) { return null; } var editorsAvator = []; topData.editors.forEach((editor) => { editorsAvator.push(<Image style={styles.editorAvatar} source={{uri: editor.avatar}} />) }); return ( <View style={{flex: 1}}> {this._renderPage({image: topData.background, title: topData.description}, 0)} <View style={styles.editors}> <Text style={styles.editorsLable}>主编:</Text> {editorsAvator} </View> </View> ); } else { return ( <View style={{flex: 1, height: 200}}> <ViewPager dataSource={this.state.headerDataSource} style={styles.listHeader} renderPage={this._renderPage} isLoop={true} autoPlay={true} /> </View> ); } }, getSectionTitle: function(str) { var date = parseDateFromYYYYMMdd(str); if (date.toDateString() == new Date().toDateString()) { return '今日热闻'; } var title = str.slice(4, 6) + '月' + str.slice(6, 8) + '日'; title += ' ' + WEEKDAY[date.getDay()]; return title; }, renderSectionHeader: function(sectionData: Object, sectionID: number | string) { if (this.state.theme) { return ( <View></View> ); } else { return ( <Text style={styles.sectionHeader}> {this.getSectionTitle(sectionID)} </Text> ); } }, selectStory: function(story: Object) { story.read = true; if (Platform.OS === 'ios') { this.props.navigator.push({ title: story.title, component: StoryScreen, passProps: {story}, }); } else { this.props.navigator.push({ title: story.title, name: 'story', story: story, }); } }, renderRow: function( story: Object, sectionID: number | string, rowID: number | string, highlightRowFunc: (sectionID: ?number | string, rowID: ?number | string) => void, ) { return ( <StoryItem key={story.id} onSelect={() => this.selectStory(story)} onHighlight={() => highlightRowFunc(sectionID, rowID)} onUnhighlight={() => highlightRowFunc(null, null)} story={story} /> ); }, onEndReached: function() { console.log('onEndReached() ' + this.state.isLoadingTail); if (this.state.isLoadingTail) { return; } this.fetchStories(this.state.theme, false); }, onSelectTheme: function(theme) { // ToastAndroid.show('选择' + theme.name, ToastAndroid.SHORT); this.drawer.closeDrawer(); this.setState({ isLoading: this.state.isLoading, isLoadingTail: this.state.isLoadingTail, theme: theme, dataSource: this.state.dataSource, }); this.fetchStories(theme, true); }, _renderNavigationView: function() { return ( <ThemesList onSelectItem={this.onSelectTheme} /> ); }, onRefresh: function() { this.onSelectTheme(this.state.theme); }, render: function() { var content = this.state.dataSource.getRowCount() === 0 ? <View style={styles.centerEmpty}> <Text>{this.state.isLoading ? '正在加载...' : '加载失败'}</Text> </View> : <ListView ref="listview" dataSource={this.state.dataSource} renderRow={this.renderRow} onEndReached={this.onEndReached} renderSectionHeader={this.renderSectionHeader} automaticallyAdjustContentInsets={false} keyboardDismissMode="on-drag" keyboardShouldPersistTaps={true} showsVerticalScrollIndicator={false} renderHeader={this._renderHeader} />; var title = this.state.theme ? this.state.theme.name : '首页'; return ( <DrawerLayoutAndroid ref={(drawer) => { this.drawer = drawer; }} drawerWidth={Dimensions.get('window').width - DRAWER_WIDTH_LEFT} keyboardDismissMode="on-drag" drawerPosition={DrawerLayoutAndroid.positions.Left} renderNavigationView={this._renderNavigationView}> <View style={styles.container}> <ToolbarAndroid navIcon={require('image!ic_menu_white')} title={title} titleColor="white" style={styles.toolbar} actions={toolbarActions} onIconClicked={() => this.drawer.openDrawer()} onActionSelected={this.onActionSelected} /> <SwipeRefreshLayoutAndroid ref={(swipeRefreshLayout) => { this.swipeRefreshLayout = swipeRefreshLayout; }} onRefresh={this.onRefresh}> {content} </SwipeRefreshLayoutAndroid> </View> </DrawerLayoutAndroid> ); } }); var styles = StyleSheet.create({ centerEmpty: { flex: 1, alignItems: 'center', justifyContent: 'center', }, container: { flex: 1, flexDirection: 'column', backgroundColor: '#FAFAFA', }, toolbar: { backgroundColor: '#00a2ed', height: 56, }, rator: { height: 1, backgroundColor: '#eeeeee', }, scrollSpinner: { marginVertical: 20, }, sectionHeader: { fontSize: 14, color: '#888888', margin: 10, marginLeft: 16, }, headerPager: { height: 200, }, headerItem: { flex: 1, height: 200, flexDirection: 'row', }, headerTitleContainer: { flex: 1, alignSelf: 'flex-end', padding: 10, backgroundColor: 'rgba(0,0,0,0.2)', }, headerTitle: { fontSize: 18, fontWeight: '500', color: 'white', marginBottom: 10, }, editors: { flex: 1, flexDirection: 'row', alignItems: 'center', padding: 8, }, editorsLable: { fontSize: 14, color: '#888888', }, editorAvatar: { width: 30, height: 30, borderRadius: 15, borderWidth: 1, borderColor: '#AAAAAA', margin: 4, } }); module.exports = ListScreen;
mit
kompyang/UnityGamePlayPocketLab
LeapMotionTest/Assets/LeapMotion/Modules/InteractionEngine/Scripts/Internal/SlidingWindowThrow.cs
5706
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using InteractionEngineUtility; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Leap.Unity.Interaction { /// <summary> /// The sliding window throw handler implements a simple heuristic that provides a /// reasonably accurate measure of the user's intended "throw direction" for a physical /// object. It is used as the default implementation of an Interaction Behaviour's /// throw handler. /// </summary> public class SlidingWindowThrow : IThrowHandler { /// <summary> /// The length of the averaging window in seconds. /// </summary> private float _windowLength = 0.05F; /// <summary> /// The delay between the averaging window and the current time. /// </summary> private float _windowDelay = 0.02F; /// <summary> /// A curve that maps the speed of the object upon release to a multiplier to apply /// to that speed as the throw occurs. /// </summary> private AnimationCurve _velocityMultiplierCurve = new AnimationCurve( new Keyframe(0.0F, 1.0F, 0, 0), new Keyframe(3.0F, 1.5F, 0, 0)); private struct VelocitySample { public float time; public Vector3 position; public Quaternion rotation; public VelocitySample(Vector3 position, Quaternion rotation, float time) { this.position = position; this.rotation = rotation; this.time = Time.fixedTime; } public static VelocitySample Interpolate(VelocitySample a, VelocitySample b, float time) { float alpha = Mathf.Clamp01(Mathf.InverseLerp(a.time, b.time, time)); return new VelocitySample(Vector3.Lerp(a.position, b.position, alpha), Quaternion.Slerp(a.rotation, b.rotation, alpha), time); } } private Queue<VelocitySample> _velocityQueue = new Queue<VelocitySample>(64); /// <summary> /// Samples the current velocity and adds it to a rolling average. /// </summary> public void OnHold(InteractionBehaviour intObj, ReadonlyList<InteractionController> controllers) { _velocityQueue.Enqueue(new VelocitySample(intObj.rigidbody.position, intObj.rigidbody.rotation, Time.fixedTime)); while (true) { VelocitySample oldestVelocity = _velocityQueue.Peek(); // Dequeue conservatively if the oldest velocity is more than 4 frames later // than the start of the window. if (oldestVelocity.time + (Time.fixedDeltaTime * 4) < Time.fixedTime - _windowLength - _windowDelay) { _velocityQueue.Dequeue(); } else { break; } } } /// <summary> /// Transfers the averaged velocity to the released object. /// </summary> public void OnThrow(InteractionBehaviour intObj, InteractionController throwingController) { if (_velocityQueue.Count < 2) { intObj.rigidbody.velocity = Vector3.zero; intObj.rigidbody.angularVelocity = Vector3.zero; return; } float windowEnd = Time.fixedTime - _windowDelay; float windowStart = windowEnd - _windowLength; // 0 occurs before 1, // start occurs before end. VelocitySample start0, start1; VelocitySample end0, end1; VelocitySample s0, s1; s0 = s1 = start0 = start1 = end0 = end1 = _velocityQueue.Dequeue(); while (_velocityQueue.Count != 0) { s0 = s1; s1 = _velocityQueue.Dequeue(); if (s0.time < windowStart && s1.time >= windowStart) { start0 = s0; start1 = s1; } if (s0.time < windowEnd && s1.time >= windowEnd) { end0 = s0; end1 = s1; // We have assigned both start and end and can break out of the loop. _velocityQueue.Clear(); break; } } VelocitySample start = VelocitySample.Interpolate(start0, start1, windowStart); VelocitySample end = VelocitySample.Interpolate(end0, end1, windowEnd); Vector3 interpolatedVelocity = PhysicsUtility.ToLinearVelocity(start.position, end.position, _windowLength); intObj.rigidbody.velocity = interpolatedVelocity; intObj.rigidbody.angularVelocity = PhysicsUtility.ToAngularVelocity(start.rotation, end.rotation, _windowLength); intObj.rigidbody.velocity *= _velocityMultiplierCurve.Evaluate(intObj.rigidbody.velocity.magnitude); } } }
mit
dip712204123/kidskula
mychat/includes/json/send/send_message.php
4466
<?php /* || #################################################################### || || # ArrowChat # || || # ---------------------------------------------------------------- # || || # Copyright ©2010-2012 ArrowSuites LLC. All Rights Reserved. # || || # This file may not be redistributed in whole or significant part. # || || # ---------------- ARROWCHAT IS NOT FREE SOFTWARE ---------------- # || || # http://www.arrowchat.com | http://www.arrowchat.com/license/ # || || #################################################################### || */ header("Expires: Mon, 26 Jul 1990 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // ########################## INCLUDE BACK-END ########################### require_once (dirname(dirname(dirname(dirname(__FILE__)))) . DIRECTORY_SEPARATOR . 'bootstrap.php'); require_once (dirname(dirname(dirname(dirname(__FILE__)))) . DIRECTORY_SEPARATOR . AC_FOLDER_INCLUDES . DIRECTORY_SEPARATOR . 'init.php'); require_once (dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'functions_send.php'); // ########################### GET POST DATA ############################# $to = get_var('to'); $message = get_var('message'); // ######################### START POST MESSAGE ########################## if (!empty($_POST['to']) AND !empty($_POST['message'])) { if (logged_in($userid)) { $result = $db->execute(" SELECT block_chats FROM arrowchat_status WHERE userid = '" . $db->escape_string($to) . "' "); if ($result AND $db->count_select() > 0) { $row = $db->fetch_array($result); $block_chats_unserialized = unserialize($row['block_chats']); if (!is_array($block_chats_unserialized)) { $block_chats_unserialized = array(); } if (in_array($userid, $block_chats_unserialized)) { echo "-1"; close_session(); exit(0); } } $db->execute(" INSERT INTO arrowchat ( arrowchat.from, arrowchat.to, arrowchat.message, arrowchat.sent, arrowchat.read ) VALUES ( '" . $db->escape_string($userid) . "', '" . $db->escape_string($to) . "', '" . $db->escape_string(sanitize($message)) . "', '" . time() . "', '0' ) "); $last_id = $db->last_insert_id(); // Update message history totals $result = $db->execute(" SELECT sent FROM arrowchat ORDER BY id DESC LIMIT 1, 1 "); $date = time(); $insert_date = date('Ymd', $date); if ($row = $db->fetch_array($result)) { $last_date = date('Ymd', $row['sent']); if ($last_date != $insert_date && !empty($last_date)) { $date1 = strtotime( $last_date ); $date2 = strtotime( $insert_date ); $days = count_days($date1, $date2); for ($i = 0; $i < $days; $i++) { $db->execute(" INSERT INTO arrowchat_graph_log ( date, user_messages ) VALUES ( '" . date('Ymd', $date1+(86400*$i)) . "', '0' ) ON DUPLICATE KEY UPDATE user_messages = user_messages "); } } $db->execute(" INSERT INTO arrowchat_graph_log ( date, user_messages ) VALUES ( '" . $db->escape_string($insert_date) . "', '1' ) ON DUPLICATE KEY UPDATE user_messages = (user_messages + 1) "); } else { $db->execute(" INSERT INTO arrowchat_graph_log ( date, user_messages ) VALUES ( '" . $db->escape_string($insert_date) . "', '1' ) "); } if ($push_on == 1) { $arrowpush->publish(array( 'channel' => 'u' . $_POST['to'], 'message' => array('messages' => array("id" => $last_id, "from" => $userid, "message" => sanitize($message), "sent" => time(), "self" => "0", "old" => "0")) )); $arrowpush->publish(array( 'channel' => 'u' . $userid, 'message' => array('messages' => array("id" => $last_id, "from" => $_POST['to'], "message" => sanitize($message), "sent" => time(), "self" => "1", "old" => "0")) )); } echo $last_id; close_session(); exit(0); } } ?>
mit
calben/UE4-TiledBoardGameTemplate
Source/TiledGameEditor.Target.cs
551
// Fill out your copyright notice in the Description page of Project Settings. using UnrealBuildTool; using System.Collections.Generic; public class TiledGameEditorTarget : TargetRules { public TiledGameEditorTarget(TargetInfo Target) { Type = TargetType.Editor; } // // TargetRules interface. // public override void SetupBinaries( TargetInfo Target, ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations, ref List<string> OutExtraModuleNames ) { OutExtraModuleNames.AddRange( new string[] { "TiledGame" } ); } }
mit
amardaxini/ups_pickup
lib/ups_pickup/pickup_cancel.rb
1596
module UpsPickup class PickupCancel < PickupRequest def initialize(user_name, password, license, options={}) super(user_name, password, license, options) @cancel_by = options[:cancel_by] || "02" @prn = options[:prn] end def to_ups_hash { "ns2:CancelBy"=>@cancel_by, "ns2:PRN"=>@prn } end def build_request self.to_ups_hash end def commit begin @client_response = @client.request :ns2,"PickupCancelRequest" do #soap.namespaces["xmlns:S"] = "http://schemas.xmlsoap.org/soap/envelope/" #soap.namespaces["xmlns:upss"] = "http://www.ups.com/XMLschema/XOLTWS/UPSS/v1.0" #soap.namespaces["xmlns:ns1"] = "http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0" soap.namespaces["xmlns:ns3"] = "http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" soap.namespaces["xmlns:ns2"] = "http://www.ups.com/XMLSchema/XOLTWS/Pickup/v1.1" # soap.header = SOAP_HEADER1 soap.header = access_request soap.body = build_request end rescue Savon::SOAP::Fault => fault @client_response = fault rescue Savon::Error => error @client_response = error end build_response end def build_response if success? @response = UpsPickup::PickupCancelSuccess.new(@client_response) elsif soap_fault? fault_response = UpsPickup::FaultResponse.new(@client,@client_response) @error = UpsPickup::ErrorResponse.new(fault_response.response) end end end end
mit
byllyfish/pylibofp
doc/presentation/faucet-20171020/src/02_example.py
397
import zof APP = zof.Application(__name__) def role_request(role, generation_id): return { 'type': 'ROLE_REQUEST', 'msg': { 'role': role, 'generation_id': generation_id } } @APP.message('CHANNEL_UP') def channel_up(event): ofmsg = role_request('ROLE_MASTER', 1) zof.compile(ofmsg).send() if __name__ == '__main__': zof.run()
mit
cheshire137/overwatch-team-comps
db/migrate/20170304164544_create_heroes.rb
187
class CreateHeroes < ActiveRecord::Migration[5.0] def change create_table :heroes do |t| t.string :name, null: false t.string :role t.timestamps end end end
mit
rhewitt22/atl-kickball
app/scorekeeper/ScorekeeperController.js
488
'use strict'; angular.module('kickballApp.controllers') .controller('ScorekeeperController', ['$scope', 'Team', function ( $scope, Team ) { $scope.team = Team.getTeam(); $scope.count = {balls: 0, strikes: 0, fouls: 0}; $scope.inning = {outs: 0, half: "Top", num: 1}; $scope.bases = {atBat: $scope.team[1], first: null, second: null, third: null}; $scope.atBatState = 'pitch'; $scope.resetCount = function () { $scope.count = {balls: 0, strikes: 0, fouls: 0}; } }]);
mit
vitorfs/cmdbox
cmdbox/snippets/migrations/0001_initial.py
2421
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-28 21:26 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Review', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField(max_length=255, verbose_name='slug')), ('content', models.TextField(verbose_name='content')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('revision', models.PositiveIntegerField(default=1, verbose_name='revision')), ], options={ 'ordering': ('-revision',), 'verbose_name': 'review', 'verbose_name_plural': 'reviews', }, ), migrations.CreateModel( name='Snippet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField(max_length=255, verbose_name='slug')), ('description', models.TextField(max_length=1000, verbose_name='description')), ('content', models.TextField(verbose_name='content')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'snippet', 'verbose_name_plural': 'snippets', }, ), migrations.AddField( model_name='review', name='snippet', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to='snippets.Snippet'), ), migrations.AlterUniqueTogether( name='snippet', unique_together=set([('user', 'slug')]), ), ]
mit
shooterman/ideasbulb
db/migrate/20120328030907_add_fail_to_ideas.rb
106
class AddFailToIdeas < ActiveRecord::Migration def change add_column :ideas,:fail,:string end end
mit
gertjvr/ChatterBox
src/Server/ChatterBox.ChatServer/Handlers/Users/AllowedRoomsRequestHandler.cs
2307
using System; using System.Linq; using System.Threading.Tasks; using ChatterBox.Core.Infrastructure; using ChatterBox.Core.Mapping; using ChatterBox.Domain.Aggregates.RoomAggregate; using ChatterBox.Domain.Aggregates.UserAggregate; using ChatterBox.Domain.Extensions; using ChatterBox.MessageContracts.Dtos; using ChatterBox.MessageContracts.Users.Requests; using Nimbus.Handlers; namespace ChatterBox.ChatServer.Handlers.Users { public class AllowedRoomsRequestHandler : IHandleRequest<AllowedRoomsRequest, AllowedRoomsResponse> { private readonly IUnitOfWork _unitOfWork; private readonly IRepository<User> _userRepository; private readonly IRepository<Room> _roomRepository; private readonly IMapToNew<Room, RoomDto> _mapper; public AllowedRoomsRequestHandler( IUnitOfWork unitOfWork, IRepository<User> userRepository, IRepository<Room> roomRepository, IMapToNew<Room, RoomDto> mapper) { if (unitOfWork == null) throw new ArgumentNullException("unitOfWork"); if (userRepository == null) throw new ArgumentNullException("userRepository"); if (roomRepository == null) throw new ArgumentNullException("roomRepository"); if (mapper == null) throw new ArgumentNullException("mapper"); _unitOfWork = unitOfWork; _userRepository = userRepository; _roomRepository = roomRepository; _mapper = mapper; } public async Task<AllowedRoomsResponse> Handle(AllowedRoomsRequest request) { try { var callingUser = _userRepository.VerifyUser(request.CallingUserId); var targetUser = _userRepository.VerifyUser(request.TargetUserId); var results = _roomRepository.GetAllowedRoomsByUserId(targetUser); var response = new AllowedRoomsResponse(results.Select(_mapper.Map).ToArray()); _unitOfWork.Complete(); return response; } catch { _unitOfWork.Abandon(); throw; } } } }
mit
Dunduro/SonataPageBundle
Tests/Cache/BlockEsiCacheTest.php
2835
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\PageBundle\Tests\Page; use Sonata\PageBundle\Cache\BlockEsiCache; use Sonata\PageBundle\Tests\Helpers\PHPUnit_Framework_TestCase; class BlockEsiCacheTest extends PHPUnit_Framework_TestCase { /** * @expectedException \RuntimeException * @dataProvider getExceptionCacheKeys */ public function testExceptions($keys) { $router = $this->createMock('Symfony\Component\Routing\RouterInterface'); $blockRenderer = $this->createMock('Sonata\BlockBundle\Block\BlockRendererInterface'); $contextManager = $this->createMock('Sonata\BlockBundle\Block\BlockContextManagerInterface'); $cache = new BlockEsiCache('My Token', array(), $router, 'ban', $blockRenderer, $contextManager); $cache->get($keys, 'data'); } public static function getExceptionCacheKeys() { return array( array(array()), array(array('block_id' => 7)), array(array('block_id' => 7, 'page_id' => 8)), array(array('block_id' => 7, 'manager' => 8)), array(array('manager' => 7, 'page_id' => 8)), array(array('manager' => 7, 'page_id' => 8)), array(array('updated_at' => 'foo')), ); } public function testInitCache() { $router = $this->createMock('Symfony\Component\Routing\RouterInterface'); $router->expects($this->any())->method('generate')->will($this->returnValue('https://sonata-project.org/cache/XXX/page/esi/page/5/4?updated_at=as')); $blockRenderer = $this->createMock('Sonata\BlockBundle\Block\BlockRendererInterface'); $contextManager = $this->createMock('Sonata\BlockBundle\Block\BlockContextManagerInterface'); $cache = new BlockEsiCache('My Token', array(), $router, 'ban', $blockRenderer, $contextManager); $this->assertTrue($cache->flush(array())); $this->assertTrue($cache->flushAll()); $keys = array( 'block_id' => 4, 'page_id' => 5, 'updated_at' => 'as', 'manager' => 'page', ); $cacheElement = $cache->set($keys, 'data'); $this->assertInstanceOf('Sonata\Cache\CacheElement', $cacheElement); $this->assertTrue($cache->has(array('id' => 7))); $cacheElement = $cache->get($keys); $this->assertInstanceOf('Sonata\Cache\CacheElement', $cacheElement); $this->assertEquals('<esi:include src="https://sonata-project.org/cache/XXX/page/esi/page/5/4?updated_at=as" />', $cacheElement->getData()->getContent()); } }
mit
rejinka/fluent-symfony
tests/CreateTest.php
6771
<?php namespace Fluent\Test; use function Fluent\create; use function Fluent\get; use Fluent\PhpConfigLoader; use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Test create() definitions. */ class CreateTest extends TestCase { public function test_create_with_class_name_provided() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'foo' => create('stdClass'), ]); self::assertInstanceOf('stdClass', $container->get('foo')); } public function test_create_with_class_name_as_array_key() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'stdClass' => create(), ]); self::assertInstanceOf('stdClass', $container->get('stdClass')); } public function test_inject_constructor_arguments() { $fixture = new class() { public function __construct() { $this->arguments = func_get_args(); } }; $className = get_class($fixture); $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'foo' => create($className) ->arguments('abc', 'def'), ]); self::assertEquals(['abc', 'def'], $container->get('foo')->arguments); } public function test_inject_in_public_property() { $fixture = new class() { public $foo; }; $className = get_class($fixture); $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'foo' => create($className) ->property('foo', 'bar'), ]); self::assertEquals('bar', $container->get('foo')->foo); } public function test_inject_in_method() { $fixture = new class() { public function setSomething() { $this->arguments = func_get_args(); } }; $className = get_class($fixture); $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'foo' => create($className) ->method('setSomething', 'abc', 'def'), ]); self::assertEquals(['abc', 'def'], $container->get('foo')->arguments); } public function test_same_method_can_be_called_multiple_times() { $fixture = new class() { public $count = 0; public function increment() { $this->count++; } }; $className = get_class($fixture); $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ $className => create() ->method('increment') ->method('increment'), ]); $class = $container->get($className); self::assertEquals(2, $class->count); } /** * @test */ public function services_can_be_injected() { $fixture = new class(null) { public function __construct($argument) { $this->argument = $argument; } }; $className = get_class($fixture); $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'foo' => create($className) ->arguments(get('stdClass')), 'stdClass' => create(), ]); self::assertInstanceOf('stdClass', $container->get('foo')->argument); } /** * @test */ public function parameters_can_be_injected() { $fixture = new class(null) { public function __construct($argument) { $this->argument = $argument; } }; $className = get_class($fixture); $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'foo' => create($className) ->arguments('%abc%'), 'abc' => 'def', ]); self::assertEquals('def', $container->get('foo')->argument); } /** * @test */ public function services_can_be_tagged() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'bar' => create('stdClass') ->tag('foo'), ]); self::assertTrue($container->findDefinition('bar')->hasTag('foo')); self::assertArrayHasKey('bar', $container->findTaggedServiceIds('foo')); } /** * @test */ public function services_can_be_tagged_with_attributes() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'bar' => create('stdClass') ->tag('foo', ['alias' => 'baz']), ]); $tagged = $container->findTaggedServiceIds('foo'); self::assertArrayHasKey('alias', $tagged['bar'][0]); self::assertEquals('baz', $tagged['bar'][0]['alias']); } /** * @test */ public function services_can_be_tagged_multiple_times() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'bar' => create('stdClass') ->tag('foo') ->tag('baz'), ]); self::assertTrue($container->findDefinition('bar')->hasTag('foo')); self::assertTrue($container->findDefinition('bar')->hasTag('baz')); } /** * @test */ public function services_can_be_marked_as_private() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'bar' => create('stdClass') ->private() ]); self::assertFalse($container->findDefinition('bar')->isPublic()); } /** * @test */ public function services_can_be_deprecated() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'bar' => create('stdClass') ->deprecate() ]); self::assertTrue($container->findDefinition('bar')->isDeprecated()); } /** * @test */ public function services_can_be_deprecated_providing_a_template_message() { $container = new ContainerBuilder; (new PhpConfigLoader($container))->load([ 'bar' => create('stdClass') ->deprecate('The "%service_id%" service is deprecated.') ]); self::assertTrue($container->findDefinition('bar')->isDeprecated()); self::assertEquals('The "bar" service is deprecated.', $container->findDefinition('bar')->getDeprecationMessage('bar')); } }
mit
Heroes-Academy/IntroPython_Winter_2016
code/week2/formulas.py
1359
""" I will provide the equations in the comments and you must write the code that reflects the equations. I will also specify which variable you should input. You should write a message indicating what the person is inputting. I have done the first one for you. """ # this is an import for the pi number # it is used for your questions below from math import pi ### Area of a Square # equation: area = side_length ** 2 # input the side length print("I will calculate the area of a square") side_length = float(input("Please tell me the side length: ")) area = side_length ** 2 print("The area of a the square with side_length {} is {}".format(side_length, area)) ### Area of a Circle # equation: area = pi * radius**2 # input the radius ### Volume of a Sphere # equation: area = 4/3 * pi * radius**3 # input the radius ### Weight on Pluto # explanation: ### if we know how much less gravity a planet has ### then we can calculate our weight on that planet ### pluto has 5% of our gravity, which leads to the equation # equation: weight_on_pluto = 0.05 * weight_on_earth # input: your weight on earth ### Bonus ## Given the weight that was input ## Calculate the weights for the other planets. # Mercury has 38% of our gravity # Venus has 90% # The Moon has 16% # Mars has 38% # Jupiter has 236% # Saturn has 108% # Uranus has 80% # Nepture has 112%
mit
namics/eslint-config-namics
test/es5-node/rules/node/no-sync.js
107
// DESCRIPTION = disallow use of synchronous methods (off by default) // STATUS = 0 // <!START // END!>
mit
wxh7777/oas
oas/src/com/pfkj/oas/model/qx/QxRole.java
1671
package com.pfkj.oas.model.qx; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @Table(name = "GLXT_QX_ROLE") //管理系统权限相关-角色 public class QxRole { @GeneratedValue(generator="tableIdGenerator") @GenericGenerator(name="tableIdGenerator", strategy="com.pfkj.oas.util.KeyUtil", parameters={@Parameter(name="pkLen",value="20")}) @Id @Column(name = "ID", unique = true, length=20, nullable=false) private String id; @Column(name = "ROLE_ACT_GROUP_ID",length=64) private String actGroupId; @Column(name = "ROLE_NAME", unique = true, nullable=false) private String name; @Column(name = "ROLE_DESC") private String desc; @Column(name = "ISENABLED") private boolean isEnabled; public QxRole() { super(); this.isEnabled = true; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getActGroupId() { return actGroupId; } public void setActGroupId(String actGroupId) { this.actGroupId = actGroupId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public boolean isEnabled() { return isEnabled; } public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } }
mit
r1dd1ck777/td
app/DoctrineMigrations/Version20131020181804.php
2124
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20131020181804 extends AbstractMigration { public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'."); $this->addSql("DROP TABLE `Order`"); $this->addSql("ALTER TABLE cart_order CHANGE comments comments VARCHAR(255) DEFAULT NULL"); $this->addSql("ALTER TABLE Mention ADD product_id INT NOT NULL"); $this->addSql("ALTER TABLE Mention ADD CONSTRAINT FK_2DBF60514584665A FOREIGN KEY (product_id) REFERENCES Product (id)"); $this->addSql("CREATE INDEX IDX_2DBF60514584665A ON Mention (product_id)"); } public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'."); $this->addSql("CREATE TABLE `Order` (id INT AUTO_INCREMENT NOT NULL, cart_id INT NOT NULL, user_id INT DEFAULT NULL, fio VARCHAR(255) NOT NULL, town VARCHAR(255) NOT NULL, address VARCHAR(255) NOT NULL, phone VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, paymentType VARCHAR(255) NOT NULL, comments VARCHAR(255) NOT NULL, deliveryType VARCHAR(255) NOT NULL, createdAt DATETIME NOT NULL, INDEX IDX_34E8BC9C1AD5CDBF (cart_id), INDEX IDX_34E8BC9CA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); $this->addSql("ALTER TABLE Mention DROP FOREIGN KEY FK_2DBF60514584665A"); $this->addSql("DROP INDEX IDX_2DBF60514584665A ON Mention"); $this->addSql("ALTER TABLE Mention DROP product_id"); $this->addSql("ALTER TABLE cart_order CHANGE comments comments VARCHAR(255) NOT NULL"); } }
mit
tomvodi/QTail
src/gui/highlighting/HighlightingDialog.cpp
11561
/** * @author Thomas Baumann <teebaum@ymail.com> * * @section LICENSE * See LICENSE for more informations. * */ #include "HighlightListItemDelegate.h" #include "HighlightingDialog.h" #include "ui_HighlightingDialog.h" int HighlightingDialog::HighlightRuleDataRole = Qt::UserRole + 1; HighlightingDialog::HighlightingDialog(QWidget *parent) : QDialog(parent), ui(new Ui::HighlightingDialog) { ui->setupUi(this); ui->fontPicker->setFontFilters(QFontComboBox::MonospacedFonts); ui->wordRulesListWidget->setItemDelegate(new HighlightListItemDelegate(this)); ui->lineRulesListWidget->setItemDelegate(new HighlightListItemDelegate(this)); createConnections(); } void HighlightingDialog::createConnections() { connect(ui->wordRulesListWidget, &QListWidget::itemSelectionChanged, [this] { if (ui->wordRulesListWidget->selectedItems().count()) { ui->lineRulesListWidget->selectionModel()->clear(); } setUiForCurrentSelectedItem(); }); connect(ui->lineRulesListWidget, &QListWidget::itemSelectionChanged, [this] { if (ui->lineRulesListWidget->selectedItems().count()) { ui->wordRulesListWidget->selectionModel()->clear(); } setUiForCurrentSelectedItem(); }); connect(ui->foregroundColorPicker, &ColorPicker::currentColorChanged, this, &HighlightingDialog::updateCurrentSelectedRuleValues); connect(ui->backgroundColorPicker, &ColorPicker::currentColorChanged, this, &HighlightingDialog::updateCurrentSelectedRuleValues); connect(ui->fontPicker, &FontPicker::currentFontChanged, this, &HighlightingDialog::updateCurrentSelectedRuleValues); connect(ui->regexLineEdit, &QLineEdit::textChanged, this, &HighlightingDialog::updateCurrentSelectedRuleValues); connect(ui->caseSensitiveCheckBox, &QCheckBox::toggled, this, &HighlightingDialog::updateCurrentSelectedRuleValues); } QList<HighlightingRule> HighlightingDialog::rulesFromListWidget(QListWidget *listWidget) const { QList<HighlightingRule> rules; for (int i = 0; i < listWidget->count(); ++i) { QListWidgetItem *item = listWidget->item(i); if (!item) { continue; } QVariant highlightingRuleData = item->data(HighlightRuleDataRole); HighlightingRule highlightingRule = highlightingRuleData.value<HighlightingRule>(); rules << highlightingRule; } return rules; } HighlightingDialog::~HighlightingDialog() { delete ui; } void HighlightingDialog::setHighlightingRules(const QList<HighlightingRule> &lineRules, const QList<HighlightingRule> &wordRules) { foreach (const HighlightingRule &rule, lineRules) { addNewRuleToListWidget(ui->lineRulesListWidget, rule); } foreach (const HighlightingRule &rule, wordRules) { addNewRuleToListWidget(ui->wordRulesListWidget, rule); } } void HighlightingDialog::addWordHighlightingRule(const HighlightingRule &rule) { addNewRuleToListWidget(ui->wordRulesListWidget, rule); } void HighlightingDialog::addLineHighlightingRule(const HighlightingRule &rule) { addNewRuleToListWidget(ui->lineRulesListWidget, rule); } QList<HighlightingRule> HighlightingDialog::wordHighlightingRules() const { return rulesFromListWidget(ui->wordRulesListWidget); } QList<HighlightingRule> HighlightingDialog::lineHighlightingRules() const { return rulesFromListWidget(ui->lineRulesListWidget); } void HighlightingDialog::on_addRuleButton_clicked() { QListWidgetItem *currentItem = currentSelectedItem(); QListWidget *listWidget = nullptr; if (!currentItem) { listWidget = ui->wordRulesListWidget; } else { listWidget = currentItem->listWidget(); } int currentItemIndex = 0; if (currentItem) { currentItemIndex = listWidget->row(currentItem); } addNewRuleToListWidget(listWidget, highlightingRuleFromGui(), currentItemIndex + 1); } void HighlightingDialog::on_deleteRuleButton_clicked() { deleteCurrentSelectedRule(); } void HighlightingDialog::on_buttonBox_clicked(QAbstractButton *button) { QDialogButtonBox::StandardButton standardButton = ui->buttonBox->standardButton(button); if (standardButton == QDialogButtonBox::Apply || standardButton == QDialogButtonBox::Ok) { emit highlightingRulesChanged(lineHighlightingRules(), wordHighlightingRules()); } } void HighlightingDialog::on_downButton_clicked() { QListWidgetItem *currentItem = currentSelectedItem(); if (!currentItem) { return; } QListWidget *listWidget = currentItem->listWidget(); int currentItemRow = listWidget->row(currentItem); if (currentItemRow >= (listWidget->count() - 1)) { return; } listWidget->takeItem(currentItemRow); listWidget->insertItem(currentItemRow + 1, currentItem); selectListWidgetItem(currentItem); } void HighlightingDialog::on_upButton_clicked() { QListWidgetItem *currentItem = currentSelectedItem(); if (!currentItem) { return; } QListWidget *listWidget = currentItem->listWidget(); int currentItemRow = listWidget->row(currentItem); if (currentItemRow <= 0) { return; } listWidget->takeItem(currentItemRow); listWidget->insertItem(currentItemRow - 1, currentItem); selectListWidgetItem(currentItem); } void HighlightingDialog::on_bottomButton_clicked() { QListWidgetItem *currentItem = currentSelectedItem(); if (!currentItem) { return; } QListWidget *listWidget = currentItem->listWidget(); int currentItemRow = listWidget->row(currentItem); if (currentItemRow >= (listWidget->count() - 1)) { return; } listWidget->takeItem(currentItemRow); listWidget->insertItem(listWidget->count(), currentItem); selectListWidgetItem(currentItem); } void HighlightingDialog::on_topButton_clicked() { QListWidgetItem *currentItem = currentSelectedItem(); if (!currentItem) { return; } QListWidget *listWidget = currentItem->listWidget(); int currentItemRow = listWidget->row(currentItem); if (currentItemRow <= 0) { return; } listWidget->takeItem(currentItemRow); listWidget->insertItem(0, currentItem); selectListWidgetItem(currentItem); } void HighlightingDialog::updateCurrentSelectedRuleValues() { QListWidgetItem *currentItem = currentSelectedItem(); if (!currentItem) { return; } HighlightingRule highlightingRule = currentItem->data(HighlightRuleDataRole).value<HighlightingRule>(); // Foreground color highlightingRule.setForegroundColor(ui->foregroundColorPicker->currentColor()); currentItem->setForeground(ui->foregroundColorPicker->currentColor()); // Background color highlightingRule.setBackgroundColor(ui->backgroundColorPicker->currentColor()); currentItem->setBackground(ui->backgroundColorPicker->currentColor()); // Font highlightingRule.setFont(ui->fontPicker->currentFont()); currentItem->setFont(ui->fontPicker->currentFont()); // Text highlightingRule.setText(ui->regexLineEdit->text()); currentItem->setText(ui->regexLineEdit->text()); // Case sensitivity highlightingRule.setCaseSensitivity((ui->caseSensitiveCheckBox->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive)); currentItem->setData(HighlightRuleDataRole, QVariant::fromValue<HighlightingRule>(highlightingRule)); } void HighlightingDialog::changeEvent(QEvent *event) { if (event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } QDialog::changeEvent(event); } HighlightingRule HighlightingDialog::highlightingRuleFromGui() const { HighlightingRule rule; rule.setBackgroundColor(ui->backgroundColorPicker->currentColor()); rule.setForegroundColor(ui->foregroundColorPicker->currentColor()); rule.setFont(ui->fontPicker->currentFont()); rule.setText(ui->regexLineEdit->text()); rule.setCaseSensitivity(ui->caseSensitiveCheckBox->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive); return rule; } /*! * \brief HighlightingDialog::addNewRuleToListWidget * Adds a new rule to a list widget. If position is a valid position, the new rule will be inserted * at this position. If the position isn't valid, the rule will be appended to the list. * \param listWidget * \param rule * \param position */ void HighlightingDialog::addNewRuleToListWidget(QListWidget *listWidget, const HighlightingRule &rule, int position) { QListWidgetItem *listItem = new QListWidgetItem; listItem->setBackground(rule.backgroundColor()); listItem->setForeground(rule.foregroundColor()); listItem->setFont(rule.font()); listItem->setText(rule.text()); listItem->setData(HighlightRuleDataRole, QVariant::fromValue<HighlightingRule>(rule)); int insertIndex = position; if (insertIndex < 0 || insertIndex >= listWidget->count()) { insertIndex = listWidget->count(); } listWidget->insertItem(insertIndex, listItem); selectListWidgetItem(listItem); } void HighlightingDialog::deleteCurrentSelectedRule() { QListWidgetItem *selectedItem = currentSelectedItem(); int currentSelectedRow = selectedItem->listWidget()->row(selectedItem); if (!selectedItem) { return; } QListWidget *listWidget = selectedItem->listWidget(); if (!listWidget) { return; } QWidget *itemWidget = listWidget->itemWidget(selectedItem); listWidget->takeItem(listWidget->row(selectedItem)); if (itemWidget) { delete itemWidget; } delete selectedItem; if (listWidget->count() == 0) { return; } int selectIndex = currentSelectedRow; if (currentSelectedRow >= listWidget->count()) { selectIndex = listWidget->count() - 1; } listWidget->selectionModel()->clear(); QModelIndex itemIndex = listWidget->model()->index(selectIndex, 0); listWidget->selectionModel()->select(itemIndex, QItemSelectionModel::Select); } void HighlightingDialog::setUiForCurrentSelectedItem() { QListWidgetItem *selectedItem = currentSelectedItem(); if (!selectedItem) { return; } HighlightingRule highlightingRule = selectedItem->data(HighlightRuleDataRole).value<HighlightingRule>(); ui->foregroundColorPicker->setCurrentColor(highlightingRule.foregroundColor()); ui->backgroundColorPicker->setCurrentColor(highlightingRule.backgroundColor()); ui->fontPicker->setCurrentFont(highlightingRule.font()); ui->regexLineEdit->setText(highlightingRule.text()); ui->caseSensitiveCheckBox->setChecked(highlightingRule.caseSensitivity() == Qt::CaseSensitive); } QListWidgetItem *HighlightingDialog::currentSelectedItem() const { QListWidgetItem *selectedItem = nullptr; if (ui->wordRulesListWidget->selectedItems().count()) { selectedItem = ui->wordRulesListWidget->selectedItems().at(0); } if (ui->lineRulesListWidget->selectedItems().count()) { selectedItem = ui->lineRulesListWidget->selectedItems().at(0); } return selectedItem; } void HighlightingDialog::selectListWidgetItem(QListWidgetItem *item) { QListWidget *listWidget = item->listWidget(); if (!listWidget) { return; } int itemRow = listWidget->row(item); QModelIndex itemIndex = listWidget->model()->index(itemRow, 0); if (!itemIndex.isValid()) { return; } listWidget->selectionModel()->clear(); listWidget->selectionModel()->select(itemIndex, QItemSelectionModel::Select); }
mit
c-bata/Flask-Angular-PyJWT
client/gulpfile.babel.js
775
import gulp from 'gulp'; import babelify from 'babelify'; import browserify from 'browserify'; import source from 'vinyl-source-stream'; import buffer from 'vinyl-buffer'; import sourcemaps from 'gulp-sourcemaps'; let paths = { test: "./static/test/*.js", src: "./static/js/", dist_src: "./static/build/js/" }; gulp.task('build', () => { browserify({entries: [paths.src + "app.js"]}) .transform(babelify) .bundle() .pipe(source("bundle.js")) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(paths.dist_src)); }); gulp.task('watch', () => { gulp.watch(paths.src + '**/*', ['browserify']) }); gulp.task('default', ['watch']);
mit
psenger/Jersey2-Security-JWT
src/main/java/com/sample/mappers/AuthenticationExceptionMapper.java
904
/** * Created by Philip A Senger on November 10, 2015 */ package com.sample.mappers; import com.sample.domain.GenericErrorMessage; import javax.ws.rs.NotAuthorizedException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class AuthenticationExceptionMapper implements ExceptionMapper<NotAuthorizedException> { @Override public Response toResponse(NotAuthorizedException exception) { GenericErrorMessage e = new GenericErrorMessage(); e.setMessage(exception.getMessage()); e.setCode(Status.UNAUTHORIZED.getStatusCode()); e.setChallenges(exception.getChallenges()); return Response .status(Status.UNAUTHORIZED) .type("application/json") .entity(e) .build(); } }
mit
MattSurabian/webpack-audio-sprite-plugin
test/fixtures/manifestEntryModule.js
489
'use strict'; var path = require('path'); module.exports = function(fileName, fileInfo, metadataFileName) { var manifest = { path: path.join('fixtures', fileName), duration: fileInfo.duration, size: fileInfo.size, format: "mp3", metadata: metadataFileName ? 'REPLACE' : {} }; if (!metadataFileName) { metadataFileName = ''; } return 'module.exports = ' + JSON.stringify(manifest).replace('"REPLACE"', 'require("' + metadataFileName + '")') + ';'; };
mit
Emiliya93/TelerikAcademy
DataStructuresAndAlgorithms/WorkshopDataStructures/WorkshopDataStructures/JediMeditation/Jedi.cs
1275
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //namespace JediMeditation //{ // public class Jedi : IComparable<Jedi> // { // static readonly Dictionary<char, int> priorities = new Dictionary<char,int> // { // {'m', 1}, // {'k', 2}, // {'p', 3}, // }; // private string name; // private int index; // public Jedi(string name, int index) // { // this.name = name; // this.index = index; // } // public int CompareTo(Jedi other) // { // if (this.name == other.name) // { // return 0; // } // var thisName = this.name[0]; // var otherName = other.name[0]; // var thisPriority = priorities[thisName] + this.name; // var otherPriority = priorities[otherName] + other.name; // if (thisPriority == otherPriority) // { // return this.index.CompareTo(other.index); // } // return thisPriority.CompareTo(otherPriority); // } // public override string ToString() // { // return this.name; // } // } //}
mit
jonstokes/shine
lib/shine/engine.rb
220
module Shine class Engine < ::Rails::Engine isolate_namespace Shine config.generators do |g| g.test_framework :rspec g.fixture_replacement :factory_girl, :dir => 'spec/factories' end end end
mit
Rebilly/ReDoc
src/components/Fields/Field.tsx
3056
import { observer } from 'mobx-react'; import * as React from 'react'; import { ClickablePropertyNameCell, RequiredLabel } from '../../common-elements/fields'; import { FieldDetails } from './FieldDetails'; import { InnerPropertiesWrap, PropertyBullet, PropertyCellWithInner, PropertyDetailsCell, PropertyNameCell, } from '../../common-elements/fields-layout'; import { ShelfIcon } from '../../common-elements/'; import { FieldModel } from '../../services/models'; import { Schema, SchemaOptions } from '../Schema/Schema'; export interface FieldProps extends SchemaOptions { className?: string; isLast?: boolean; showExamples?: boolean; field: FieldModel; expandByDefault?: boolean; renderDiscriminatorSwitch?: (opts: FieldProps) => JSX.Element; } @observer export class Field extends React.Component<FieldProps> { toggle = () => { if (this.props.field.expanded === undefined && this.props.expandByDefault) { this.props.field.expanded = false; } else { this.props.field.toggle(); } }; handleKeyPress = e => { if (e.key === 'Enter') { e.preventDefault(); this.toggle(); } }; render() { const { className, field, isLast, expandByDefault } = this.props; const { name, deprecated, required, kind } = field; const withSubSchema = !field.schema.isPrimitive && !field.schema.isCircular; const expanded = field.expanded === undefined ? expandByDefault : field.expanded; const paramName = withSubSchema ? ( <ClickablePropertyNameCell className={deprecated ? 'deprecated' : ''} kind={kind} title={name} > <PropertyBullet /> <button onClick={this.toggle} onKeyPress={this.handleKeyPress} aria-label="expand properties" > <span>{name}</span> <ShelfIcon direction={expanded ? 'down' : 'right'} /> </button> {required && <RequiredLabel> required </RequiredLabel>} </ClickablePropertyNameCell> ) : ( <PropertyNameCell className={deprecated ? 'deprecated' : undefined} kind={kind} title={name}> <PropertyBullet /> <span>{name}</span> {required && <RequiredLabel> required </RequiredLabel>} </PropertyNameCell> ); return ( <> <tr className={isLast ? 'last ' + className : className}> {paramName} <PropertyDetailsCell> <FieldDetails {...this.props} /> </PropertyDetailsCell> </tr> {expanded && withSubSchema && ( <tr key={field.name + 'inner'}> <PropertyCellWithInner colSpan={2}> <InnerPropertiesWrap> <Schema schema={field.schema} skipReadOnly={this.props.skipReadOnly} skipWriteOnly={this.props.skipWriteOnly} showTitle={this.props.showTitle} /> </InnerPropertiesWrap> </PropertyCellWithInner> </tr> )} </> ); } }
mit
hxjp/simekiri-bot
ts/conversations/on-update-message.ts
4181
import {OnMessage} from './on-message'; import {Sequelize, Model} from 'sequelize'; import * as moment from 'moment'; import {INPUT_DATE_FORMATS, UserType} from '../constants'; import {formatSchedule} from './util'; import {messages} from '../messages-ja'; const usage = ` usage: update (-i | --id) <id> [(-t | --title) <タイトル>] [(-d | --deadline) <シメキリ>] [(-w | --writer) @<書く人>] [(-e | --editor) @<担当者>] `; const commandlineArgs = require('command-line-args'); const parser = commandlineArgs([ {name: 'id', alias: 'i', type: String}, {name: 'title', alias: 't', type: String}, {name: 'deadline', alias: 'd', type: String}, {name: 'writer', alias: 'w', type: String}, {name: 'editor', alias: 'e', type: String}, ]); function parseMessage(line: string): { id: string; title: string; deadline: Date; writerSlackId: string; editorSlackId: string; } { const args = line.split(/\s/); const options = parser.parse(args); if (!options.id) { throw new Error(); } let id = parseInt(options.id, 10); if (!id) { throw new Error(); } let deadline; if (options.deadline) { deadline = moment(options.deadline, INPUT_DATE_FORMATS).toDate(); } let writerSlackId = options.writer; if (writerSlackId) { if (/\<\@(.+)\>/.test(writerSlackId)) { writerSlackId = RegExp.$1; } else { throw new Error(); } } let editorSlackId = options.editor; if (editorSlackId) { if (/\<\@(.+)\>/.test(editorSlackId)) { editorSlackId = RegExp.$1; } else { throw new Error(); } } return { id: options.id, title: options.title, deadline, writerSlackId, editorSlackId, }; } export class OnUpdateMessage extends OnMessage { private User: Model<any, any>; private Schedule: Model<any, any>; constructor( protected sequelize: Sequelize, protected bot: any ) { super(sequelize, bot); this.User = <any> sequelize.model('User'); this.Schedule = <any> sequelize.model('Schedule'); } getPatterns(): string[] { return ['^update (.+)']; } getTypes(): string[] { return ['direct_mention']; } protected onMessage(bot: any, message: any): void { const line: string = message.match[1]; let params; try { params = parseMessage(line); } catch (e) { bot.reply(message, `${messages.wrongCommand}\n${usage}`); return; } const {id, title, deadline, editorSlackId, writerSlackId} = params; this.sequelize.transaction(() => { let schedule; return this.Schedule.findById(params.id, { include: [ {model: this.User, as: 'writer'}, {model: this.User, as: 'editor'} ]}) .then(sche => { if (!sche) { bot.reply(message, `${messages.wrongDeadlineId}[${id}]`); return Promise.reject(new Error('IDが不正です')); } schedule = sche; if (title) { schedule.title = title; } if (deadline) { schedule.deadline = deadline; } const queries = []; if (editorSlackId) { queries.push(this.User['findOrCreateUserBySlackId'](editorSlackId, UserType.EDITOR)); } if (writerSlackId) { queries.push(this.User['findOrCreateUserBySlackId'](writerSlackId, UserType.WRITER)); } if (queries.length > 0) { return Promise.all(queries) .then(results => { const [editor, writer] = results; if (editor) { schedule.editor = editor; schedule.editor_id = editor.id; } if (writer) { schedule.writer = writer; schedule.writer_id = writer.id; } }); } }) .then(() => { return schedule.save() .then(() => { return bot.reply(message, `シメキリが更新されました。\n${formatSchedule(schedule)}`); }); }); }); } }
mit
MrVibe/bp-profile-cover
includes/class.settings.php
9248
<?php /** * Setup BP Profile Cover settings * * @class BP_Profile_Cover_Settings * @author VibeThemes * @category Admin * @package BP Profile Cover * @version 1.2 */ if ( ! defined( 'ABSPATH' ) ) { exit; } class BP_Profile_Cover_Settings{ var $settings; var $temp; public static $instance; public static function init(){ if ( is_null( self::$instance ) ) self::$instance = new BP_Profile_Cover_Settings(); return self::$instance; } private function __construct(){ $this->option = 'bp-profile-cover'; $this->settings=$this->get(); add_action('admin_menu',array($this,'add_options_link')); } function add_options_link(){ add_options_page(__('BP Profile Coversettings','bp-profile-cover'),__('BP Profile Cover','bp-profile-cover'),'manage_options','bp-profile-cover',array($this,'settings')); } function settings(){ $tab = isset( $_GET['tab'] ) ? $_GET['tab'] : 'general'; $this->settings_tabs($tab); $this->$tab(); } function settings_tabs( $current = 'general' ) { $tabs = array( 'general' => __('General','bp-profile-cover'), ); echo '<div id="icon-themes" class="icon32"><br></div>'; echo '<h2 class="nav-tab-wrapper">'; foreach( $tabs as $tab => $name ){ $class = ( $tab == $current ) ? ' nav-tab-active' : ''; echo "<a class='nav-tab$class' href='?page=bp-profile-cover&tab=$tab'>$name</a>"; } echo '</h2>'; if(isset($_POST['save'])){ $this->save(); } } function general(){ echo '<h3>'.__('General Settings','bp-profile-cover').'</h3>'; $settings=array( array( 'label' => __('Default Image','bp-profile-cover' ), 'name' =>'default_image', 'type' => 'upload', 'button'=> __('Upload Default Image','bp-profile-cover' ), 'desc' => __('Set Login redirect settings','bp-profile-cover' ) ), array( 'label' => __('Background Size','bp-profile-cover' ), 'name' =>'background_size', 'type' => 'select', 'options'=> array( 'auto' => __('auto','bp-profile-cover' ), 'cover' => __('Cover','bp-profile-cover' ), 'contain' => __('Contain','bp-profile-cover' ), ), 'desc' => __('Set default cover background size ','bp-profile-cover' ).' <a href="http://www.w3schools.com/cssref/css3_pr_background-size.asp" target="_blank">'.__('Learn more','bp-profile-cover').'</a>' ), array( 'label' => __('Background Attachment','bp-profile-cover' ), 'name' =>'background_attachment', 'type' => 'select', 'options'=> array( 'scroll' => __('Scroll','bp-profile-cover' ), 'fixed' => __('Fixed','bp-profile-cover' ), '' => __('inherit','bp-profile-cover' ), ), 'desc' => __('Set default cover background attachment ','bp-profile-cover' ).' <a href="http://www.w3schools.com/cssref/pr_background-attachment.asp" target="_blank">'.__('Learn more','bp-profile-cover').'</a>' ), ); $this->generate_form('general',$settings); } function generate_form($tab,$settings=array()){ echo '<form method="post"> <table class="form-table">'; wp_nonce_field('save_settings','_wpnonce'); echo '<ul class="save-settings">'; foreach($settings as $setting ){ echo '<tr valign="top">'; global $wpdb,$bp; switch($setting['type']){ case 'textarea': echo '<th scope="row" class="titledesc">'.$setting['label'].'</th>'; echo '<td class="forminp"><textarea name="'.$setting['name'].'">'.(isset($this->settings[$setting['name']])?$this->settings[$setting['name']]:(isset($setting['std'])?$setting['std']:'')).'</textarea>'; echo '<span>'.$setting['desc'].'</span></td>'; break; case 'select': echo '<th scope="row" class="titledesc">'.$setting['label'].'</th>'; echo '<td class="forminp"><select name="'.$setting['name'].'" class="chzn-select">'; foreach($setting['options'] as $key=>$option){ echo '<option value="'.$key.'" '.(isset($this->settings[$setting['name']])?selected($key,$this->settings[$setting['name']]):'').'>'.$option.'</option>'; } echo '</select>'; echo '<span>'.$setting['desc'].'</span></td>'; break; case 'checkbox': echo '<th scope="row" class="titledesc">'.$setting['label'].'</th>'; echo '<td class="forminp"><input type="checkbox" name="'.$setting['name'].'" '.(isset($this->settings[$setting['name']])?'CHECKED':'').' />'; echo '<span>'.$setting['desc'].'</span></td>'; break; case 'number': echo '<th scope="row" class="titledesc">'.$setting['label'].'</th>'; echo '<td class="forminp"><input type="number" name="'.$setting['name'].'" value="'.(isset($this->settings[$setting['name']])?$this->settings[$setting['name']]:'').'" />'; echo '<span>'.$setting['desc'].'</span></td>'; break; case 'hidden': echo '<input type="hidden" name="'.$setting['name'].'" value="1"/>'; break; case 'upload': echo '<th scope="row" class="titledesc">'.$setting['label'].'</th>'; echo '<td class="forminp">'; echo '<div class="upload_button">'; wp_enqueue_media(); $setting['value'] =$this->settings[$setting['name']]; if(is_numeric($setting['value'])) { $attachment = wp_get_attachment_image_src($setting['value']); if(empty($attachment)){ echo '<a id="'.$setting['name'].'" data-input-name="'.$setting['name'].'" data-uploader-title="'.$setting['label'].'" data-uploader-button-text="'.$setting['button'].'"><span class="dashicons dashicons-format-image"></span></a>'; }else{ $url = $attachment[0]; echo '<a id="'.$setting['name'].'" data-input-name="'.$setting['name'].'" data-uploader-title="'.$setting['label'].'" data-uploader-button-text="'.$setting['button'].'"><img src="'.$url.'" class="submission_thumb thumbnail" /><input type="hidden" value="'.$setting['value'].'" /></a>'; } }else{ echo '<a id="'.$setting['name'].'" data-input-name="'.$setting['name'].'" data-uploader-title="'.$setting['label'].'" data-uploader-button-text="'.$setting['button'].'"><span class="dashicons dashicons-format-image"></span></a>'; } echo '<style>.upload_button img{width:200px;border-radius:2px;}.upload_button>a>span{ width: 60px;overflow: hidden;border-radius: 2px;display: inline-block;text-align: center;padding: 20px 0;font-size: 20px;color: #888;border: 2px solid #ccc;}</style><script> var media_uploader'.$setting['name'].'; jQuery("#'.$setting['name'].'").on("click", function( event ){ var button = jQuery( this ); if ( media_uploader'.$setting['name'].' ) { media_uploader'.$setting['name'].'.open(); return; } // Create the media uploader. media_uploader'.$setting['name'].' = wp.media.frames.media_uploader'.$setting['name'].' = wp.media({ title: button.attr( "data-uploader-title"), library: { type: "image", query: false }, button: { text: button.attr("data-uploader-button-text"), }, }); // Create a callback when the uploader is called media_uploader'.$setting['name'].'.on( "select", function() { var selection = media_uploader'.$setting['name'].'.state().get("selection"), input_name = button.data( "input-name"); selection.map( function( attachment ) { attachment = attachment.toJSON(); console.log(attachment); button.html("<img src=\'"+attachment.url+"\' class=\'submission_thumb thumbnail\' /><input id=\'"+input_name +"\' class=\'form-control post_field\' name=\'"+input_name+"\' data-id=\''.$setting['name'].'\' type=\'hidden\' value=\'"+attachment.id+"\' />"); }); }); // Open the uploader media_uploader'.$setting['name'].'.open(); }); </script>'; echo '<span>'.$setting['desc'].'</span></td>'; break; default: echo '<th scope="row" class="titledesc">'.$setting['label'].'</th>'; echo '<td class="forminp"><input type="text" name="'.$setting['name'].'" value="'.(isset($this->settings[$setting['name']])?$this->settings[$setting['name']]:(isset($setting['std'])?$setting['std']:'')).'" />'; echo '<span>'.$setting['desc'].'</span></td>'; break; } echo '</tr>'; } echo '</tbody> </table>'; echo '<input type="submit" name="save" value="'.__('Save Settings','bp-profile-cover').'" class="button button-primary" /></form>'; } function get(){ return get_option($this->option); } function put($value){ update_option($this->option,$value); } function save(){ $none = $_POST['save_settings']; if ( !isset($_POST['save']) || !isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'],'save_settings') ){ _e('Security check Failed. Contact Administrator.','bp-profile-cover'); die(); } unset($_POST['_wpnonce']); unset($_POST['_wp_http_referer']); unset($_POST['save']); foreach($_POST as $key => $value){ $this->settings[$key]=$value; } $this->put($this->settings); } } BP_Profile_Cover_Settings::init();
mit
uppercounty/uppercounty
web/forms.py
1731
from __future__ import absolute_import from __future__ import unicode_literals # Copyright (c) 2015 Upper County Dolphins # # 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. """Admin forms to input data. .. moduleauthor:: Andrew Wang <wangandrewt@gmail.com> """ from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UniqueEmailUser class UniqueEmailUserCreationForm(UserCreationForm): """A form to create a UniqueEmailUser.""" class Meta: model = UniqueEmailUser fields = ("email",) class UniqueEmailUserChangeForm(UserChangeForm): """A form to update a UniqueEmailUser.""" class Meta: model = UniqueEmailUser fields = ("email",)
mit
cheminfo/database-aggregator
front/src/components/svg/ChevronRight.js
272
import React from 'react'; export default function(props) { return ( <svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M12.95 10.707l.707-.707L8 4.343 6.586 5.757 10.828 10l-4.242 4.243L8 15.657l4.95-4.95z" /> </svg> ); }
mit
argerim/address_by_cep
lib/generators/address_by_cep/model_generator.rb
867
module AddressByCep class ModelGenerator < Base include Rails::Generators::Migration source_root File.expand_path('../templates', __FILE__) def initialize(*args, &block) super end def create_partial copy_file 'partial_addressable_form.html.erb', "app/views/addresses/_addressable_form.html.erb" end def add_js_in_application_js add_js_reference end def create_model template 'address_model.rb', "app/models/address.rb" end def self.next_migration_number(dirname) if ActiveRecord::Base.timestamped_migrations Time.now.utc.strftime("%Y%m%d%H%M%S") else "%.3d" % (current_migration_number(dirname) + 1) end end def create_migration migration_template 'migration.rb', "db/migrate/create_table_addresses.rb" end end end
mit
csmeal/accord
backend-library/lib.models/card.ts
793
import { GameObject } from './gameObject'; import { v4 as uuid } from 'uuid'; export abstract class Card implements GameObject { name: string; id: string; mana: number; type: string; imageUrl: string = 'http://conceptartworld.com/wp-content/uploads/2015/03/Magdalena_Radziej_Concept_Art_Illustration_fossil-soldier.jpg'; text: string = 'You text here.'; constructor(name: string, mana: number) { this.name = name; this.mana = mana; this.id = uuid(); } } export class Creature extends Card { type = 'creature'; attack: number; defense: number; damageTaken: number; constructor(name: string, mana: number, attack: number, defense: number) { super(name, mana); this.attack = attack; this.defense = defense; this.damageTaken = 0; } }
mit
elcct/amazingwebsite
system/core.go
2835
package system import ( "encoding/json" "encoding/gob" "github.com/golang/glog" "net/http" "reflect" "github.com/zenazn/goji/web" "github.com/gorilla/sessions" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" "html/template" "io" "io/ioutil" "os" "path/filepath" "strings" ) type Application struct { Configuration *Configuration Template *template.Template Store *sessions.CookieStore DBSession *mgo.Session } func (application *Application) Init(filename *string) { gob.Register(bson.ObjectId("")) data, err := ioutil.ReadFile(*filename) if err != nil { glog.Fatalf("Can't read configuration file: %s", err) panic(err) } application.Configuration = &Configuration{} err = json.Unmarshal(data, &application.Configuration) if err != nil { glog.Fatalf("Can't parse configuration file: %s", err) panic(err) } application.Store = sessions.NewCookieStore([]byte(application.Configuration.Secret)) } func (application *Application) LoadTemplates() error { var templates []string fn := func(path string, f os.FileInfo, err error) error { if f.IsDir() != true && strings.HasSuffix(f.Name(), ".html") { templates = append(templates, path) } return nil } err := filepath.Walk(application.Configuration.TemplatePath, fn) if err != nil { return err } application.Template = template.Must(template.ParseFiles(templates...)) return nil } func (application *Application) ConnectToDatabase() { var err error application.DBSession, err = mgo.Dial(application.Configuration.Database.Hosts) if err != nil { glog.Fatalf("Can't connect to the database: %v", err) panic(err) } } func (application *Application) Close() { glog.Info("Bye!") application.DBSession.Close() } func (application *Application) Route(controller interface{}, route string) interface{} { fn := func(c web.C, w http.ResponseWriter, r *http.Request) { c.Env["Content-Type"] = "text/html" methodValue := reflect.ValueOf(controller).MethodByName(route) methodInterface := methodValue.Interface() method := methodInterface.(func(c web.C, r *http.Request) (string, int)) body, code := method(c, r) if session, exists := c.Env["Session"]; exists { err := session.(*sessions.Session).Save(r, w) if err != nil { glog.Errorf("Can't save session: %v", err) } } switch code { case http.StatusOK: if _, exists := c.Env["Content-Type"]; exists { w.Header().Set("Content-Type", c.Env["Content-Type"].(string)) } io.WriteString(w, body) case http.StatusSeeOther, http.StatusFound: http.Redirect(w, r, body, code) default: w.WriteHeader(code) io.WriteString(w, body) } } return fn }
mit
TheLastCard/react-redux-mvc
react-mvc/DBContexts/Migrations/Configuration.cs
1123
namespace react_mvc.DBContexts.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<CRUDDB> { public Configuration() { AutomaticMigrationsEnabled = false; MigrationsDirectory = @"DBContexts\Migrations"; ContextKey = "react_mvc.DBContexts.CRUDDB"; } //protected override void Seed( // CRUDDB context) //{ // // This method will be called after migrating to the latest version. // // You can use the DbSet<T>.AddOrUpdate() helper extension method // // to avoid creating duplicate seed data. E.g. // // // // context.People.AddOrUpdate( // // p => p.FullName, // // new Person { FullName = "Andrew Peters" }, // // new Person { FullName = "Brice Lambson" }, // // new Person { FullName = "Rowan Miller" } // // ); // // //} } }
mit
teddymacn/CoreProfiler
CoreProfiler/Data/ProfiledDbDataReader.cs
17603
using System; using System.Data.Common; using System.IO; using System.Threading; using System.Threading.Tasks; namespace CoreProfiler.Data { /// <summary> /// Represents a profiled <see cref="DbDataReader"/> /// which will call <see cref="IDbProfiler"/>.DataReaderFinished() automatically /// when the data reader is closed. /// </summary> public class ProfiledDbDataReader : DbDataReader { private readonly DbDataReader _dataReader; private readonly IDbProfiler _dbProfiler; #region Constructors /// <summary> /// Initializes a <see cref="ProfiledDbDataReader"/>. /// </summary> /// <param name="dataReader">The <see cref="DbDataReader"/> to be profiled.</param> /// <param name="dbProfiler"> /// The <see cref="IDbProfiler"/> which profiles the <see cref="DbDataReader"/> /// </param> public ProfiledDbDataReader(DbDataReader dataReader, IDbProfiler dbProfiler) { if (dataReader == null) { throw new ArgumentNullException("dataReader"); } if (dbProfiler == null) { throw new ArgumentNullException("dbProfiler"); } _dataReader = dataReader; _dbProfiler = dbProfiler; } #endregion #region Override Equals so that ProfiledDataReader could checks Equals by its dataReader /// <summary> /// Gets hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return _dataReader.GetHashCode(); } /// <summary> /// Equals. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (ReferenceEquals(obj, this)) { return true; } var profilingDataReader = obj as ProfiledDbDataReader; if (!ReferenceEquals(profilingDataReader, null)) { return ReferenceEquals(profilingDataReader._dataReader, _dataReader); } var dataReader = obj as DbDataReader; if (dataReader != null) { return ReferenceEquals(dataReader, _dataReader); } return false; } /// <summary> /// Equals. /// </summary> /// <param name="a">a</param> /// <param name="b">b</param> /// <returns>Return true if equals.</returns> public static bool operator ==(ProfiledDbDataReader a, ProfiledDbDataReader b) { if (ReferenceEquals(a, b)) { return true; } if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return a.Equals(b); } /// <summary> /// Equals. /// </summary> /// <param name="a">a</param> /// <param name="b">b</param> /// <returns>Return true if equals.</returns> public static bool operator ==(ProfiledDbDataReader a, DbDataReader b) { if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return a.Equals(b); } /// <summary> /// Equals. /// </summary> /// <param name="a">a</param> /// <param name="b">b</param> /// <returns>Return true if equals.</returns> public static bool operator ==(DbDataReader a, ProfiledDbDataReader b) { if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return b.Equals(a); } /// <summary> /// Not equals. /// </summary> /// <param name="a">a</param> /// <param name="b">b</param> /// <returns>Return true if not equals.</returns> public static bool operator !=(ProfiledDbDataReader a, ProfiledDbDataReader b) { if (ReferenceEquals(a, b)) { return false; } if ((ReferenceEquals(a, null) || ReferenceEquals(b, null))) { return true; } return !a.Equals(b); } /// <summary> /// Not equals. /// </summary> /// <param name="a">a</param> /// <param name="b">b</param> /// <returns>Return true if not equals.</returns> public static bool operator !=(ProfiledDbDataReader a, DbDataReader b) { if ((ReferenceEquals(a, null) || ReferenceEquals(b, null))) { return true; } return !a.Equals(b); } /// <summary> /// Not equals. /// </summary> /// <param name="a">a</param> /// <param name="b">b</param> /// <returns>Return true if not equals.</returns> public static bool operator !=(DbDataReader a, ProfiledDbDataReader b) { if ((ReferenceEquals(a, null) || ReferenceEquals(b, null))) { return true; } return !b.Equals(a); } #endregion #region DbDataReader Members protected override void Dispose(bool disposing) { _dbProfiler.DataReaderFinished(this); base.Dispose(disposing); } /// <summary> /// Gets the depth. /// </summary> public override int Depth { get { return _dataReader.Depth; } } /// <summary> /// Gets the field count. /// </summary> public override int FieldCount { get { return _dataReader.FieldCount; } } /// <summary> /// Gets boolean. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override bool GetBoolean(int ordinal) { return _dataReader.GetBoolean(ordinal); } /// <summary> /// Gets byte. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override byte GetByte(int ordinal) { return _dataReader.GetByte(ordinal); } /// <summary> /// Gets bytes. /// </summary> /// <param name="ordinal"></param> /// <param name="dataOffset"></param> /// <param name="buffer"></param> /// <param name="bufferOffset"></param> /// <param name="length"></param> /// <returns></returns> public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) { return _dataReader.GetBytes(ordinal, dataOffset, buffer, bufferOffset, length); } /// <summary> /// Gets char. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override char GetChar(int ordinal) { return _dataReader.GetChar(ordinal); } /// <summary> /// Gets chars. /// </summary> /// <param name="ordinal"></param> /// <param name="dataOffset"></param> /// <param name="buffer"></param> /// <param name="bufferOffset"></param> /// <param name="length"></param> /// <returns></returns> public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) { return _dataReader.GetChars(ordinal, dataOffset, buffer, bufferOffset, length); } /// <summary> /// Gets the name of data type. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override string GetDataTypeName(int ordinal) { return _dataReader.GetDataTypeName(ordinal); } /// <summary> /// Gets datetime. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override DateTime GetDateTime(int ordinal) { return _dataReader.GetDateTime(ordinal); } /// <summary> /// Gets decimal. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override decimal GetDecimal(int ordinal) { return _dataReader.GetDecimal(ordinal); } /// <summary> /// Gets double. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override double GetDouble(int ordinal) { return _dataReader.GetDouble(ordinal); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public override System.Collections.IEnumerator GetEnumerator() { return _dataReader.GetEnumerator(); } /// <summary> /// Gets the type of field. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override Type GetFieldType(int ordinal) { return _dataReader.GetFieldType(ordinal); } /// <summary> /// Gets float. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override float GetFloat(int ordinal) { return _dataReader.GetFloat(ordinal); } /// <summary> /// Gets guid. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override Guid GetGuid(int ordinal) { return _dataReader.GetGuid(ordinal); } /// <summary> /// Gets short. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override short GetInt16(int ordinal) { return _dataReader.GetInt16(ordinal); } /// <summary> /// Gets int. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override int GetInt32(int ordinal) { return _dataReader.GetInt32(ordinal); } /// <summary> /// Gets long. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override long GetInt64(int ordinal) { return _dataReader.GetInt64(ordinal); } /// <summary> /// Gets name of field. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override string GetName(int ordinal) { return _dataReader.GetName(ordinal); } /// <summary> /// Gets ordinal by name. /// </summary> /// <param name="name"></param> /// <returns></returns> public override int GetOrdinal(string name) { return _dataReader.GetOrdinal(name); } /// <summary> /// Gets string. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override string GetString(int ordinal) { return _dataReader.GetString(ordinal); } /// <summary> /// Gets value. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override object GetValue(int ordinal) { return _dataReader.GetValue(ordinal); } /// <summary> /// Gets values. /// </summary> /// <param name="values"></param> /// <returns></returns> public override int GetValues(object[] values) { return _dataReader.GetValues(values); } /// <summary> /// Has rows. /// </summary> public override bool HasRows { get { return _dataReader.HasRows; } } /// <summary> /// Whether or not the reader is closed. /// </summary> public override bool IsClosed { get { return _dataReader.IsClosed; } } /// <summary> /// Whether or not is db null. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override bool IsDBNull(int ordinal) { return _dataReader.IsDBNull(ordinal); } /// <summary> /// Whether or not has next result. /// </summary> /// <returns></returns> public override bool NextResult() { return _dataReader.NextResult(); } /// <summary> /// Whether or not has next row. /// </summary> /// <returns></returns> public override bool Read() { return _dataReader.Read(); } /// <summary> /// Gets # of records affected. /// </summary> public override int RecordsAffected { get { return _dataReader.RecordsAffected; } } /// <summary> /// Gets value by name. /// </summary> /// <param name="name"></param> /// <returns></returns> public override object this[string name] { get { return _dataReader[name]; } } /// <summary> /// Gets value by ordinal. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override object this[int ordinal] { get { return _dataReader[ordinal]; } } /// <summary> /// Gets field value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ordinal"></param> /// <returns></returns> public override T GetFieldValue<T>(int ordinal) { return _dataReader.GetFieldValue<T>(ordinal); } /// <summary> /// Gets field value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ordinal"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { return _dataReader.GetFieldValueAsync<T>(ordinal, cancellationToken); } /// <summary> /// Gets provider specific field type. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override Type GetProviderSpecificFieldType(int ordinal) { return _dataReader.GetProviderSpecificFieldType(ordinal); } /// <summary> /// Gets provider specific value. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override object GetProviderSpecificValue(int ordinal) { return _dataReader.GetProviderSpecificValue(ordinal); } /// <summary> /// Gets provider specific values. /// </summary> /// <param name="values"></param> /// <returns></returns> public override int GetProviderSpecificValues(object[] values) { return _dataReader.GetProviderSpecificValues(values); } /// <summary> /// Gets stream. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override Stream GetStream(int ordinal) { return _dataReader.GetStream(ordinal); } /// <summary> /// Gets text reader. /// </summary> /// <param name="ordinal"></param> /// <returns></returns> public override TextReader GetTextReader(int ordinal) { return _dataReader.GetTextReader(ordinal); } /// <summary> /// Is DBNull. /// </summary> /// <param name="ordinal"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { return _dataReader.IsDBNullAsync(ordinal, cancellationToken); } /// <summary> /// Gets next result. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task<bool> NextResultAsync(CancellationToken cancellationToken) { return _dataReader.NextResultAsync(cancellationToken); } /// <summary> /// Reads next row. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task<bool> ReadAsync(CancellationToken cancellationToken) { return _dataReader.ReadAsync(cancellationToken); } #endregion } }
mit
tobowers/barking-dog
spec/barking-dog/internal-services/configuration_service_spec.rb
1293
require 'spec_helper' require 'barking-dog/internal-services/configuration_service' module BarkingDog describe ConfigurationService do let(:receiver) { EventReceiver.new } before do @publisher = EventPublisher.new @config_service = ConfigurationService.create_isolated end after do @publisher.terminate @config_service.terminate receiver.terminate end it "should have a default config" do @config_service.configuration.should == {} end describe "updating the config" do let(:event_name) { "configuration_service/saved" } let(:event_name_with_root) { "#{BarkingDog.resources.root_event_path}/#{event_name}"} let(:new_config) { {:foo => :bar} } before do @future = receiver.future.wait_for(event_name) @publisher.trigger("configuration_service/new", payload: new_config) end it "should update configs on events" do val = @future.value(1) val.first.should == event_name_with_root @config_service.configuration.should == new_config end it "should publish config changes" do val = @future.value(1) val.first.should == event_name_with_root val.last.payload.should == new_config end end end end
mit
andresmm07/slider
examples/slider.js
2884
/* eslint react/no-multi-comp: 0 */ require('rc-slider/assets/index.less'); const React = require('react'); const ReactDOM = require('react-dom'); const Slider = require('rc-slider'); const style = { width: 400, margin: 50 }; function log(value) { console.log(value); //eslint-disable-line } function percentFormatter(v) { return `${v} %`; } const CustomizedSlider = React.createClass({ getInitialState() { return { value: 50, }; }, onSliderChange(value) { log(value); this.setState({ value, }); }, onAfterChange(value) { console.log(value); //eslint-disable-line }, render() { return ( <Slider value={this.state.value} onChange={this.onSliderChange} onAfterChange={this.onAfterChange} /> ); }, }); const DynamicBounds = React.createClass({ getInitialState() { return { min: 0, max: 100, }; }, onSliderChange(value) { log(value); }, onMinChange(e) { this.setState({ min: +e.target.value || 0, }); }, onMaxChange(e) { this.setState({ max: +e.target.value || 100, }); }, render() { return ( <div> <label>Min: </label> <input type="number" value={this.state.min} onChange={this.onMinChange} /> <br /> <label>Max: </label> <input type="number" value={this.state.max} onChange={this.onMaxChange} /> <br /><br /> <Slider defaultValue={50} min={this.state.min} max={this.state.max} onChange={this.onSliderChange} /> </div> ); }, }); ReactDOM.render( <div> <div style={style}> <p>Basic Slider</p> <Slider tipTransitionName="rc-slider-tooltip-zoom-down" onChange={log} /> </div> <div style={style}> <p>Basic Slider,`step=20`</p> <Slider step={20} defaultValue={50} onBeforeChange={log} /> </div> <div style={style}> <p>Basic Slider,`step=20, dots`</p> <Slider dots step={20} defaultValue={100} onAfterChange={log} /> </div> <div style={style}> <p>Basic Slider with `tipFormatter`</p> <Slider tipFormatter={percentFormatter} tipTransitionName="rc-slider-tooltip-zoom-down" onChange={log} /> </div> <div style={style}> <p>Basic Slider without tooltip</p> <Slider tipFormatter={null} onChange={log} /> </div> <div style={style}> <p>Basic Slider, disabled</p> <Slider tipTransitionName="rc-slider-tooltip-zoom-down" onChange={log} disabled /> </div> <div style={style}> <p>Controlled Slider</p> <Slider value={50} /> </div> <div style={style}> <p>Customized Slider</p> <CustomizedSlider /> </div> <div style={style}> <p>Slider with dynamic `min` `max`</p> <DynamicBounds /> </div> </div> , document.getElementById('__react-content'));
mit
okfde/froide-theme
froide_theme/settings.py
866
# -*- coding: utf-8 -*- import os from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa class CustomThemeBase(ThemeBase): FROIDE_THEME = 'froide_theme.theme' SITE_NAME = "My Froide" SITE_EMAIL = "info@example.com" SITE_URL = 'http://localhost:8000' SECRET_URLS = { "admin": "admin", } @property def LOCALE_PATHS(self): return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [ os.path.abspath( os.path.join(os.path.dirname(__file__), '..', "locale") ) ] class Dev(CustomThemeBase, Base): pass class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark): pass class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3): pass try: from .local_settings import * # noqa except ImportError: pass
mit
kashike/SpongeCommon
src/main/java/org/spongepowered/common/service/pagination/PlayerPaginationCalculator.java
6958
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.service.pagination; import com.flowpowered.math.GenericMath; import com.google.common.base.Strings; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.service.pagination.PaginationCalculator; import org.spongepowered.api.text.LiteralText; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.TranslatableText; import org.spongepowered.api.text.format.TextStyles; import org.spongepowered.api.command.CommandMessageFormatting; import java.io.IOException; import java.util.List; /** * Pagination calculator for players. */ public class PlayerPaginationCalculator implements PaginationCalculator<Player> { private static final String NON_UNICODE_CHARS; private static final int[] NON_UNICODE_CHAR_WIDTHS; private static final byte[] UNICODE_CHAR_WIDTHS; private static final int LINE_WIDTH = 320; static { ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder() .setURL(PlayerPaginationCalculator.class.getResource("font-sizes.json")) .setPreservesHeader(false).build(); try { ConfigurationNode node = loader.load(); NON_UNICODE_CHARS = node.getNode("non-unicode").getString(); List<? extends ConfigurationNode> charWidths = node.getNode("char-widths").getChildrenList(); int[] nonUnicodeCharWidths = new int[charWidths.size()]; for (int i = 0; i < nonUnicodeCharWidths.length; ++i) { nonUnicodeCharWidths[i] = charWidths.get(i).getInt(); } NON_UNICODE_CHAR_WIDTHS = nonUnicodeCharWidths; List<? extends ConfigurationNode> glyphWidths = node.getNode("glyph-widths").getChildrenList(); byte[] unicodeCharWidths = new byte[glyphWidths.size()]; for (int i = 0; i < nonUnicodeCharWidths.length; ++i) { unicodeCharWidths[i] = (byte) glyphWidths.get(i).getInt(); } UNICODE_CHAR_WIDTHS = unicodeCharWidths; } catch (IOException e) { throw new ExceptionInInitializerError(e); } } @Override public int getLinesPerPage(Player source) { return 20; } @Override public int getLines(Player source, Text text) { return (int) Math.ceil((double) getLength(source, text) / LINE_WIDTH); } private double getWidth(int codePoint, boolean isBold) { int nonUnicodeIdx = NON_UNICODE_CHARS.indexOf(codePoint); double width; if (nonUnicodeIdx != -1) { width = NON_UNICODE_CHAR_WIDTHS[nonUnicodeIdx]; if (isBold) { width += 1; } } else { // MC unicode -- what does this even do? but it's client-only so we can't use it directly :/ int j = UNICODE_CHAR_WIDTHS[codePoint] >>> 4; int k = UNICODE_CHAR_WIDTHS[codePoint] & 15; if (k > 7) { k = 15; j = 0; } width = ((k + 1) - j) / 2 + 1; if (isBold) { width += 0.5; } } return width; } private int getLength(Player source, Text text) { double columnCount = 0d; for (Text child : text.withChildren()) { final String txt; if (child instanceof LiteralText) { txt = ((LiteralText) child).getContent(); } else if (child instanceof TranslatableText) { txt = child.toPlain(); } else { continue; } boolean isBold = child.getStyle().contains(TextStyles.BOLD); for (int i = 0; i < txt.length(); ++i) { columnCount += getWidth(txt.codePointAt(i), isBold); } } return (int) Math.ceil(columnCount); } @Override public Text center(Player source, Text text, String padding) { int length = getLength(source, text); if (length >= LINE_WIDTH) { return text; } int paddingLength = getLength(source, Text.builder(padding).style(text.getStyle()).build()); double paddingNecessary = LINE_WIDTH - length; Text.Builder build = Text.builder(); if (length == 0) { build.append(Text.of(Strings.repeat(padding, GenericMath.floor((double) LINE_WIDTH / paddingLength)))); } else { paddingNecessary -= getWidth(' ', text.getStyle().contains(TextStyles.BOLD)) * 2; int paddingCount = GenericMath.floor(paddingNecessary / paddingLength); int beforePadding = GenericMath.floor(paddingCount / 2.0); int afterPadding = (int) Math.ceil(paddingCount / 2.0); if (beforePadding > 0) { if (beforePadding > 1) { build.append(Text.of(Strings.repeat(padding, beforePadding))); } build.append(CommandMessageFormatting.SPACE_TEXT); } build.append(text); if (afterPadding > 0) { build.append(CommandMessageFormatting.SPACE_TEXT); if (afterPadding > 1) { build.append(Text.of(Strings.repeat(padding, afterPadding))); } } } build.color(text.getColor()) .style(text.getStyle()); return build.build(); } }
mit
mitselek/pildimaag
jobrunner.js
4127
var fs = require('fs') var path = require('path') var debug = require('debug')('app:' + path.basename(__filename).replace('.js', '')) var async = require('async') var op = require('object-path') var Promise = require('bluebird') var entu = require('entulib') Promise.onPossiblyUnhandledRejection(function (error) { throw error }) var jobQueue = require('./asyncQ.js') var TS_DIR = path.join(__dirname, '/timestamps') if (!fs.existsSync(TS_DIR)) { fs.mkdirSync(TS_DIR) } var jobIncrement = 0 function runJob (job, entuOptions) { function updateTs (ts) { if (entuOptions.timestamp < ts) { entuOptions.timestamp = ts + 0.5 fs.writeFileSync(jobFilename, ts + 0.5) } } debug('1. Sanity check: ' + op.get(job, ['tasks',0,'targets',0,'subs','text'], 'fail!!!') + op.get(job, ['tasks'])) var jobFilename = path.join(TS_DIR, job.entuUrl.split('//')[1]) if (!fs.existsSync(jobFilename)) { fs.writeFileSync(jobFilename, '1') } // debug('Task: ', JSON.stringify({task:task, entuOptions:entuOptions}, null, 4)) return new Promise(function (fulfill, reject) { // debug('jobFilename: ' + jobFilename) async.forever(function (next) { entuOptions.timestamp = Number(fs.readFileSync(jobFilename, 'utf8')) entuOptions.limit = job.pageSize debug('=== tick forever ' + job.name + ' from ts:' + new Date(entuOptions.timestamp * 1e3) + ' ===') entu.pollUpdates(entuOptions) .then(function (result) { var skipChanged = 0 var skipDefinition = 0 // debug(job.name + ' got ' + result.count + ' updates.') result.updates.sort(function (a, b) { return a.timestamp - b.timestamp }) // debug('----- sorted ' + JSON.stringify(result.updates)) result.updates.forEach(function (item) { updateTs(item.timestamp) if (item.action !== 'changed at') { skipChanged++ return } // If task exists for given definition else if ( op.get(job, ['tasks'], []) .reduce(function (_defs, a) { return _defs.concat(op.get(a, ['source', 'definitions'], [])) }, []) .some(function (_def) { return _def === item.definition }) ) { jobIncrement = jobIncrement + 1 ;(function (jobIncrement, job, item) { if (!jobQueue.tasks.some(function (t) { return t.data.job.name === job.name && t.data.item.id === item.id })) { debug('<X + #' + jobIncrement + '/' + (jobQueue.length() + 1) + '> Enqueue ' + job.name + ' ' + JSON.stringify(item) + ' ' + new Date(item.timestamp * 1e3)) jobQueue.push({ jobIncrement, job, item, entuOptions }, function (err) { if (err) { debug('<X - #' + jobIncrement + '/' + jobQueue.length() + '> Errored ' + job.name + ' ' + JSON.stringify(item) + ' ' + new Date(item.timestamp * 1e3)) return reject(err) } debug('<X - #' + jobIncrement + '/' + jobQueue.length() + '> Processed ' + job.name + ' ' + JSON.stringify(item) + ' ' + new Date(item.timestamp * 1e3)) }) } })(jobIncrement, job, item) return } else { skipDefinition++ return } }) // debug(job.name + ' skipped(c/d): ' + (skipChanged + skipDefinition) + '(' + skipChanged + '/' + skipDefinition + ')') }) .then(function () { // debug(job.name + ' Relaxing for ' + job.relaxBetween.roundtripMinutes + ' minutes.') setTimeout(next, job.relaxBetween.roundtripMinutes * 6e3) }) .catch(function (reason) { debug('Job ' + job.name + ' stumbled.', reason, 'Relaxing for ' + job.relaxBetween.roundtripMinutes + ' minutes.') setTimeout(next, job.relaxBetween.roundtripMinutes * 6e3) }) }, function (err) { if (err) { return reject(err) } }) }) } module.exports = runJob
mit
valarion/JAGE
JAGEgradle/JAGEmodules/src/main/java/com/valarion/gameengine/events/menu/battlemenu/MenuShield.java
2341
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2015 Rubén Tomás Gracia * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package com.valarion.gameengine.events.menu.battlemenu; import org.newdawn.slick.GameContainer; import org.newdawn.slick.SlickException; import com.valarion.gameengine.core.tiled.SubTiledMap; import com.valarion.gameengine.events.rpgmaker.FlowEventClass; import com.valarion.gameengine.gamestates.BattleState; /** * Exit option of the ingame menu. * @author Rubén Tomás Gracia * */ public class MenuShield extends FlowEventClass implements ToolTip { protected BattleState state; public MenuShield(BattleState state) { this.state = state; } @Override public void paralelupdate(GameContainer container, int delta, SubTiledMap map) throws SlickException { state.setPlayerAttack(BattleState.Attack.shielddefense); } @Override public String toString() { return "Shield Defense"; } @Override public boolean isWorking() { return true; } @Override public String getToolTip() { // TODO Auto-generated method stub return null; } }
mit
rwestbrookjr/riverandraintracker
lib/api.js
295
/*jshint esversion: 6 */ /* * Library to handle services associated with this application/api */ // Container for services const api = {}; // Import service files api.users = require('./userservice'); api.waterData = require('./waterdataservice'); // Export services module.exports = api;
mit
harvard-lil/nuremberg
nuremberg/documents/migrations/0002_auto_20160525_2155.py
814
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-25 21:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0001_initial'), ] operations = [ migrations.AlterField( model_name='documentimage', name='height', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='documentimage', name='physical_page_number', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='documentimage', name='width', field=models.IntegerField(blank=True, null=True), ), ]
mit
redox-os/orbtk
utils/src/thickness.rs
4870
use crate::Value; /// Used to describes a thickness e.g a border thickness. #[derive(Copy, Clone, Default, Debug, PartialEq)] pub struct Thickness { /// Left of thickness. pub left: f64, /// Top of thickness. pub top: f64, /// Right of thickness. pub right: f64, /// Bottom of thickness. pub bottom: f64, } impl Thickness { /// Create a new thickness with the given parameters. pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Self { Thickness { left, top, right, bottom, } } /// Gets left. pub fn left(&self) -> f64 { self.left } /// Sets left. pub fn set_left(&mut self, left: f64) { self.left = left; } /// Gets top. pub fn top(&self) -> f64 { self.top } /// Sets top. pub fn set_top(&mut self, top: f64) { self.top = top; } /// Gets right. pub fn right(&self) -> f64 { self.right } /// Sets right. pub fn set_right(&mut self, right: f64) { self.right = right; } /// Gets bottom. pub fn bottom(&self) -> f64 { self.bottom } /// Sets bottom. pub fn set_bottom(&mut self, bottom: f64) { self.bottom = bottom; } /// Gets thickness. pub fn thickness(&self) -> Thickness { *self } /// Sets thickness. pub fn set_thickness<T: Into<Thickness>>(&mut self, thickness: T) { let other = thickness.into(); self.set_left(other.left()); self.set_top(other.top()); self.set_right(other.right()); self.set_bottom(other.bottom()); } } // --- Trait implementations --- impl From<(i32, i32, i32, i32)> for Thickness { fn from(t: (i32, i32, i32, i32)) -> Self { Thickness::new(t.0 as f64, t.1 as f64, t.2 as f64, t.3 as f64) } } impl From<(i32, i32)> for Thickness { fn from(t: (i32, i32)) -> Self { Thickness::new(t.0 as f64, t.1 as f64, t.0 as f64, t.1 as f64) } } impl From<i32> for Thickness { fn from(t: i32) -> Self { Thickness::new(t as f64, t as f64, t as f64, t as f64) } } impl From<(f64, f64, f64, f64)> for Thickness { fn from(t: (f64, f64, f64, f64)) -> Self { Thickness::new(t.0, t.1, t.2, t.3) } } impl From<(f64, f64)> for Thickness { fn from(t: (f64, f64)) -> Self { Thickness::new(t.0, t.1, t.0, t.1) } } impl From<f64> for Thickness { fn from(t: f64) -> Self { Thickness::new(t, t, t, t) } } impl From<Value> for Thickness { fn from(v: Value) -> Self { match v.0 { ron::Value::Number(value) => Thickness::from(value.into_f64()), ron::Value::Map(map) => { let mut left = 0.0; let mut top = 0.0; let mut right = 0.0; let mut bottom = 0.0; for (key, value) in map.iter() { if let Ok(key) = key.clone().into_rust::<String>() { let value = if let Ok(value) = value.clone().into_rust::<f64>() { value } else { 0.0 }; if key.as_str().eq("left") { left = value; } if key.as_str().eq("top") { top = value; } if key.as_str().eq("right") { right = value; } if key.as_str().eq("bottom") { bottom = value; } } } Thickness::from((left, top, right, bottom)) } _ => Thickness::default(), } } } #[cfg(test)] mod tests { use crate::prelude::*; #[test] fn test_new() { let rect = Thickness::new(5.0, 10.0, 20.0, 30.0); assert!(crate::f64_cmp(rect.left, 5.0)); assert!(crate::f64_cmp(rect.top, 10.0)); assert!(crate::f64_cmp(rect.right, 20.0)); assert!(crate::f64_cmp(rect.bottom, 30.0)); } #[test] fn test_into() { let thickness: Thickness = (10.0, 12.0, 13.0, 14.0).into(); assert!(crate::f64_cmp(thickness.left, 10.0)); assert!(crate::f64_cmp(thickness.top, 12.0)); assert!(crate::f64_cmp(thickness.right, 13.0)); assert!(crate::f64_cmp(thickness.bottom, 14.0)); let thickness: Thickness = 10.0.into(); assert!(crate::f64_cmp(thickness.left, 10.0)); assert!(crate::f64_cmp(thickness.top, 10.0)); assert!(crate::f64_cmp(thickness.right, 10.0)); assert!(crate::f64_cmp(thickness.bottom, 10.0)); } }
mit
haydnKing/seqJS
src/melting.js
9962
/* * seqJS * https://github.com/haydnKing/seqJS * * Copyright (c) 2014 Haydn King * Licensed under the MIT license. */ var seqJS = seqJS || {}; /** * @namespace seqJS.Melt */ seqJS.Melt = {}; (function(){ /* * Data from SantaLucia 1996 */ var DH = 0, DS = 1, //DG = 2, ALL_PAIRS = ['AA','AT','AG','AC','TA','TT','TG','TC','GA','GT','GG','GC', 'CA','CT','CG','CC'], default_data = 'Allawi1997', data = { SantaLucia1996: { pairs: { AA: [-8.4 , -23.6, -1.02], AC: [-8.6 , -23.0, -1.43], AG: [-6.1 , -16.1, -1.16], AT: [-6.5 , -18.8, -0.73], CA: [-7.4 , -19.3, -1.38], CC: [-6.7 , -15.6, -1.77], CG: [-10.1, -25.5, -2.09], CT: [-6.1 , -16.1, -1.16], GA: [-7.7 , -20.3, -1.46], GC: [-11.1, -28.4, -2.28], GG: [-6.7 , -15.6, -1.77], GT: [-8.6 , -23.0, -1.43], TA: [-6.3 , -18.5, -0.60], TC: [-7.7 , -20.3, -1.46], TG: [-7.4 , -19.3, -1.38], TT: [-8.4 , -23.6, -1.02], }, init: { G: [0, -5.9, +1.82], C: [0, -5.9, +1.82], A: [0, -9.0, +2.8], T: [0, -9.0, +2.8] }, sym: [0, -1.4, +0.4], TA_pen: [+0.4, 0, +0.4] }, Allawi1997: { pairs: { AA: [-7.9 , -22.2, -1.00], AC: [-8.4 , -22.4, -1.44], AG: [-7.8 , -21.0, -1.28], AT: [-7.2 , -20.4, -0.88], CA: [-8.5 , -22.7, -1.45], CC: [-8.0 , -19.9, -1.84], CG: [-10.6, -27.2, -2.17], CT: [-7.8 , -21.0, -1.28], GT: [-8.4 , -22.4, -1.44], GA: [-8.2 , -22.2, -1.30], GC: [-9.8 , -24.4, -2.24], GG: [-8.0 , -19.9, -1.84], TA: [-7.2 , -21.3, -0.58], TC: [-8.2 , -22.2, -1.30], TG: [-8.5 , -22.7, -1.45], TT: [-7.9 , -22.2, -1.00], }, init: { C: [0.1, -2.8, 0.98], G: [0.1, -2.8, 0.98], T: [2.3, 4.1 , 1.03], A: [2.3, 4.1 , 1.03], }, sym: [0, -1.4, +0.4], TA_pen: [0, 0, 0], }, oligocalc: { pairs: { AA : [-8.0 , -21.9], AT : [-5.6 , -15.2], AG : [-6.6 , -16.4], AC : [-9.4 , -25.5], TA : [-6.6 , -18.4], TT : [-8.0 , -21.9], TC : [-8.8 , -23.5], TG : [-8.2 , -21.0], CA : [-8.2 , -21.0], CT : [-6.6 , -16.4], CG : [-11.8, -29.0], CC : [-10.9, -28.4], GT : [-9.4 , -25.5], GA : [-8.8 , -23.5], GC : [-10.5, -26.4], GG : [-10.9, -28.4], }, init: { G: [0, 0, 0], C: [0, 0, 0], A: [0, 0, 0], T: [0, 0, 0] }, sym: [0, 0, 0], TA_pen: [0, 0, 0], dH_adjust: 3.4 } }; var r_default = { Na: 1000.0, K: 0.0, Tris: 0.0, Mg: 0.0, dNTP: 0.0, Oligo: 0.5, }, r_units = { Na: 'mM', K: 'mM', Tris: 'mM', Mg: 'mM', dNTP: 'mM', Oligo: 'uM', }, r_presets = { Phusion: { Na: 50.0, K: 0.0, Tris: 0.0, Mg: 1.5, dNTP: 0.2, Oligo: 0.5, }, Q5: { Na: 50.0, K: 0.0, Tris: 0.0, Mg: 2.0, dNTP: 0.2, Oligo: 0.5, }, }; var count_pairs = function(s){ var r = {}; ALL_PAIRS.forEach(function(p){r[p] = 0;}); var prev = null; s.split('').forEach(function(b){ if(prev!==null){ r[prev+b] += 1; } prev = b; }); return r; }; var count_end_ta = function(s){ return s.match(/T*$/)[0].length; }; var get_init = function(s,e,thermo){ var r = [0.0,0.0]; r[DH] = thermo.init[s][DH] + thermo.init[e][DH]; r[DS] = thermo.init[s][DS] + thermo.init[e][DS]; return r; }; /** * Compute the melting temperature of the given sequence * @param {String|seqJS.Seq} seq The sequence to be melted * @param {String|object} settings The settings for the reaction * @param {String} [dataset] the name of the dataset to use * @returns {float} the predicted melting temperature */ seqJS.Melt.melt = function(seq, settings, dataset){ settings = seqJS.Melt.getReactionParameters(settings); dataset = (dataset===undefined ? default_data : dataset); var thermo = data[dataset]; //convert to a Seq if(!(seq.seq instanceof Function)){ seq = new seqJS.Seq(seq, 'DNA'); } var dH = 0.0, dS = 0.0, c = count_pairs(seq.seq()), Ct = settings.Oligo * Math.pow(10,-6); ALL_PAIRS.forEach(function(p){ dH = dH + c[p] * thermo.pairs[p][DH]; dS = dS + c[p] * thermo.pairs[p][DS]; }); if(seq.seq() === seq.reverseComplement().seq()){ dS = dS + thermo.sym[DS]; } var ta = count_end_ta(seq.seq()); var init = get_init(seq.seq()[0], seq.seq()[seq.length()-1], thermo); dH = dH + init[DH] + ta * thermo.TA_pen[DH]; dS = dS + init[DS] + ta * thermo.TA_pen[DS]; dH = dH + (thermo.hasOwnProperty('dH_adjust') ? thermo.dH_adjust : 0.0); var Tm = 1000.0 * dH / (dS + 1.987 * Math.log(Ct)); return seqJS.Melt.getSaltCorrection(settings, seq, Tm) - 273.15; }; /** * Return a list of supported datasets * @returns {String[]} available datasets */ seqJS.Melt.getDatasets = function(){ return Object.getOwnPropertyNames(data); }; /** * Returns the name of the default dataset * @returns {String} the name of the dataset */ seqJS.Melt.getDefaultDataset = function(){ return default_data; }; /** * Return a list of reaction parameters * @returns {String[]} reaction parameters */ seqJS.Melt.getReactionParameterNames = function(){ return Object.getOwnPropertyNames(r_default); }; /** * Return the units for the given parameter * @param {String} param The name of the reaction param * @returns {String} The units that param should be expressed in */ seqJS.Melt.getReactionParameterUnits = function(param){ return r_units[param]; }; /** * Return a list of reaction presets * @returns {String[]} reaction preset parametrs */ seqJS.Melt.getReactionPresets = function(){ return Object.getOwnPropertyNames(r_presets); }; /** * Return a dictionary containing the reaction parameters. If settings is a * string, return parameters from the preset values, otherwise make sure that * the object contains all required values (filling from the default if not) * and return it * @param {String|Object} [settings] The settings to use. Returns default * settings if left blank * @returns {Object} reaction parameters */ seqJS.Melt.getReactionParameters = function(s){ s = (s===undefined ? {} : s); if(typeof s === 'string' || s instanceof String){ if(Object.getOwnPropertyNames(r_presets).indexOf(s) < 0){ throw('Unknown reaction preset \''+s+'\''); } return r_presets[s]; } var r = {}; seqJS.Melt.getReactionParameterNames().forEach(function(v){ if(!s.hasOwnProperty(v)){ r[v] = r_default[v]; } else { r[v] = s[v]; } }); return r; }; /** * Get the salt correction for the reaction settings, according to * "Predicting Stability of DNA Duplexes in Solutions Containing Magnesium and * Monovalent Cations", R. Owczarzy, 2008. DOI: 10.1021/bi702363u * @param {String|Object} settings The reaction parameters to use * @param {seqJS.Seq} seq the sequence * @returns {Float} the number of degrees to adjust the melting temparature by */ seqJS.Melt.getSaltCorrection = function(s, seq, Tm){ s = seqJS.Melt.getReactionParameters(s); var fGC = seq.seq().match(/[GC]/g).length / seq.length(), Mon = (s.K + 0.5 * s.Tris + s.Na) * Math.pow(10,-3), Mg = (s.Mg * Math.pow(10,-3) - s.dNTP * Math.pow(10,-6)), R; if(Mon === 0){ return eq16_fixed(Mon, Mg,fGC,seq.length(),Tm); } R = Math.pow(Mg, 0.5) / Mon; if(R < 0.22){ return eq4(Mon, Mg, fGC, Tm); } else if(R < 6.0){ return eq16_var(Mon, Mg, fGC, seq.length(), Tm); } return eq16_fixed(Mon, Mg, fGC, seq.length(), Tm); }; //Equation numbers below refer to equations in Owczarzy2008 var T2 = { a: 3.92 * Math.pow(10, -5), b: -9.11 * Math.pow(10, -6), c: 6.26 * Math.pow(10, -5), d: 1.42 * Math.pow(10, -5), e: -4.82 * Math.pow(10, -4), f: 5.25 * Math.pow(10, -4), g: 8.31 * Math.pow(10, -5), }; var eq16_fixed = function(Mon, Mg,fGC,N,Tm,p){ p = (p===undefined ? T2 : p); var lMg = Math.log(Mg); var TmI = (1.0/Tm) + p.a + p.b * lMg + fGC * (p.c+p.d*lMg) + (0.5/(N-1)) * ( (p.e+p.f*lMg) + p.g*lMg*lMg); return 1.0 / TmI; }; var eq16_var = function(Mon, Mg,fGC,N,Tm){ var lMon = Math.log(Mon), m5 = Math.pow(10,-5), m3 = Math.pow(10,-3), p = { a: 3.92*m5*(0.843-0.352*Math.sqrt(Mon)*lMon), b: T2.b, c: T2.c, d: 1.42*m5*(1.279-4.03*m3*lMon-8.03*m3*lMon*lMon), e: T2.e, f: T2.f, g: 8.31*m5*(0.486-0.258*lMon+5.25*m3*lMon*lMon*lMon), }; return eq16_fixed(Mon, Mg, fGC, N, Tm, p); }; var eq4 = function(Mon, Mg,fGC,Tm){ var lMon = Math.log(Mon); var TmI = (1.0/Tm) + (4.29*fGC-3.95)*Math.pow(10,-5)*lMon + 9.4*Math.pow(10,-6)*lMon*lMon; return 1.0 / TmI; }; }());
mit
danmcclain/octolure
lib/octolure.rb
171
require 'octolure/version' require 'thor' require 'io/console' require 'netrc' require 'octokit' module Octolure end require 'octolure/templates' require 'octolure/cli'
mit
superfaz/corniro.api
tests/unit/Corniro/Controller/ConnectControllerTest.php
2266
<?php /** * Corniro API * * @link https://github.com/superfaz/corniro.api * @copyright 2016 Francois Karman * @license https://opensource.org/licenses/MIT MIT */ namespace Corniro\Controller; use Corniro\BaseInitializedTest; use Slim\Http\Response; /** * Tests the Corniro\Controller\ConnectController class. */ class ConnectControllerTest extends BaseInitializedTest { /** * Gets a dataset containing only one user with id 1. * * @return PHPUnit_Extensions_Database_DataSet_IDataSet */ public function getDataSet() { $data = [ 't_user' => [ [ 'user_id' => 1, 'display_name' => 'Unit test user', 'primary_email' => 'user.test@example.com', 'hashed_password' => password_hash('unittest', PASSWORD_DEFAULT) ] ], 't_picture' => [] ]; return $this->createArrayDataSet($data); } /** * @covers Corniro\Controller\ConnectController::__construct */ public function testConstruct() { $container = $this->createContainer(); $instance = new ConnectController($container); $this->assertAttributeEquals($container, 'ci', $instance); } /** * @covers Corniro\Controller\ConnectController::currentUser */ public function testCurrentUser() { $container = $this->createContainer(); $user = $container->em->find('Corniro\Model\User', 1); $container['currentUser'] = $user; $instance = new ConnectController($container); $request = $this->createRequest('GET', '/current-user'); $response = new Response(); $actualResponse = $instance->currentUser($request, $response); $this->assertEquals(200, $actualResponse->getStatusCode()); $actual = json_decode($actualResponse->getBody(), true); $expected = [ 'identifier' => 1, 'displayName' => 'Unit test user', 'primaryEmail' => 'user.test@example.com', 'self' => 'http://unit.test/users/1' ]; $this->assertArraySubset($expected, $actual); $this->assertEquals(4, count($actual)); } }
mit
digisec/Payum
src/Payum/Payex/Request/Api/CreateAgreementRequest.php
137
<?php namespace Payum\Payex\Request\Api; use Payum\Request\BaseModelRequest; class CreateAgreementRequest extends BaseModelRequest { }
mit
tauheedahmed/ecosys
project_files/frmProfileOrgs.aspx.cs
2590
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmProfileOrgs : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; protected System.Web.UI.WebControls.Label Label2; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Load_Procedures(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void Load_Procedures() { lblOrg.Text=Session["OrgName"].ToString(); lblContents.Text="Household Characteristics"; Session["Type"]="Consumer"; if (!IsPostBack) { loadData(); } } private void loadData () { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveProfileOrg"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"ProfileOrg"); if (ds.Tables["ProfileOrg"].Rows.Count == 0) { lblContents.Text="Please click on 'Add/Remove' to identify" + " characteristics for this household."; DataGrid1.Visible=false; } Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); } protected void btnAdd_Click(object sender, System.EventArgs e) { Session["CSProfilesCon"]="frmProfileOrgs"; Response.Redirect (strURL + "frmProfilesCon.aspx?"); } protected void btnExit_Click(object sender, System.EventArgs e) { Response.Redirect (strURL + Session["CProfileOrgs"].ToString() + ".aspx?"); } } }
mit
ItsCosmo/jscs-styleguide
src/rules/disallowArrowFunctions.js
315
export const disallowArrowFunctions = () => { let message, right, wrong; message = "ES6 arrow functions are not allowed."; right = "function square(a) {\r return a * a;\r}"; wrong = "const square = (a) => { return a * a };"; return { message, right, wrong } };
mit
antjs/ant.js
src/token.js
1092
var tokenReg = /{{({([^}\n]+)}|[^}\n]+)}}/g; //字符串中是否包含模板占位符标记 function hasToken(str) { tokenReg.lastIndex = 0; return str && tokenReg.test(str); } function parseToken(value) { var tokens = [] , textMap = [] , start = 0 , val, token ; tokenReg.lastIndex = 0; while((val = tokenReg.exec(value))){ if(tokenReg.lastIndex - start > val[0].length){ textMap.push(value.slice(start, tokenReg.lastIndex - val[0].length)); } token = { escape: !val[2] , path: (val[2] || val[1]).trim() , position: textMap.length , textMap: textMap }; tokens.push(token); //一个引用类型(数组)作为节点对象的文本图, 这样当某一个引用改变了一个值后, 其他引用取得的值都会同时更新 textMap.push(val[0]); start = tokenReg.lastIndex; } if(value.length > start){ textMap.push(value.slice(start, value.length)); } tokens.textMap = textMap; return tokens; } exports.hasToken = hasToken; exports.parseToken = parseToken;
mit
screepers/screeps_console
screeps_console/command.py
12525
from autocomplete import Autocomplete import calendar import settings import re from themes import themes import time import urwid class Processor(object): shard = 'shard0' lastkey = False apiclient = False aliases = { 'theme': 'themes', 'time': 'Game.time', 'help': 'list' } def __init__(self, connectionname): self.connectionname = connectionname self.lastkeytime = 0 self.listbox = False self.listwalker = False self.consolemonitor = False self.edit = False self.getApiClient() self.autocomplete = Autocomplete(self) def setDisplayWidgets(self, loop, frame, listbox, listwalker, edit, consolemonitor): self.listbox = listbox # console self.listwalker = listwalker self.edit = edit self.loop = loop self.consolemonitor = consolemonitor def getApiClient(self): return settings.getApiClient(self.connectionname) def onInput(self, key): lastkeytime = self.lastkeytime self.lastkeytime = calendar.timegm(time.gmtime()) if self.lastkeytime - lastkeytime > 1: self.lastkey = False lastkey = self.lastkey self.lastkey = key if not self.listbox: return if key == 'enter': self.onEnter(key) return if key == 'tab' and lastkey == 'tab': self.onTab(key) return if key == 'page up': self.onPageUp(key) return if key == 'page down': self.onPageDown(key) return if key == 'meta up': self.onMetaUp(key) return if key == 'meta down': self.onMetaDown(key) return return def onEnter(self, key): self.listbox.setAutoscroll(True) userInput = self.edit user_text = userInput.get_edit_text() # Check for builtin commands before passing to the screeps api. user_command_split = user_text.split(' ') first_command = user_command_split[0] # Check to see if command is actually an alias if first_command in self.aliases: first_command = self.aliases[first_command] user_command_split[0] = first_command user_text = ' '.join(user_command_split) # Look for built in commands before attempting API call. builtin = Builtin() if hasattr(builtin, first_command): self.listwalker.append( urwid.Text(('logged_input', '> ' + user_text))) builtin_command = getattr(builtin, first_command) builtin_command(self) self.listbox.autoscroll() userInput.set_edit_text('') return # Send command to Screeps API. Output will come from the console stream. if len(user_text) > 0: self.listwalker.append( urwid.Text(('logged_input', '> ' + user_text))) self.listbox.scrollBottom() userInput.set_edit_text('') apiclient = self.getApiClient() apiclient.console(user_text, self.shard) def onTab(self, key): self.autocomplete.complete() pass def onPageUp(self, key): info = self.loop.screen.get_cols_rows() self.listbox.scrollUp(int(info[1] / 3)) def onPageDown(self, key): info = self.loop.screen.get_cols_rows() self.listbox.scrollDown(int(info[1] / 3)) def onMetaUp(self, key): self.listbox.scrollUp(1) def onMetaDown(self, key): self.listbox.scrollDown(1) class Builtin(object): def about(self, comp): about = 'Screeps Interactive Console by Robert Hafner <tedivm@tedivm.com>' # noqa comp.listwalker.append(urwid.Text(('logged_response', about))) about = 'https://github.com/screepers/screeps_console' comp.listwalker.append(urwid.Text(('logged_response', about))) return def buffer(self, comp): comp.listwalker.append(urwid.Text(('logged_response', str(len(comp.listwalker))))) return def clear(self, comp): comp.listbox.set_focus_pending = 0 comp.listwalker[:] = [urwid.Text('')] return def console(self, comp): helpmessage = 'Control console output. `console quiet` to suppress console output and `console reset` to turn it back on.' userInput = comp.edit user_text = userInput.get_edit_text() user_command_split = user_text.split(' ') if len(user_command_split) < 2: comp.listwalker.append(urwid.Text(('logged_response', helpmessage))) return False command = user_command_split[1] if command == 'quiet': comp.consolemonitor.quiet = True comp.listwalker.append(urwid.Text(('logged_response', 'Limiting display to user interactions only.'))) elif command == 'reset' or command == 'verbose': comp.consolemonitor.quiet = False comp.listwalker.append(urwid.Text(('logged_response', 'Displaying all console output.'))) else: comp.listwalker.append(urwid.Text(('logged_response', helpmessage))) def disconnect(self, comp): comp.consolemonitor.disconnect() comp.listwalker.append(urwid.Text(('logged_response', 'disconnecting'))) comp.listbox.autoscroll() def exit(self, comp): raise urwid.ExitMainLoop() def filter(self, comp): user_text = comp.edit.get_edit_text() user_command_split = user_text.split(' ') if len(user_command_split) <= 1: subcommand = 'list' else: subcommand = user_command_split[1] if subcommand == 'list': filters = comp.consolemonitor.filters[:] if len(filters) <= 0: comp.listwalker.append(urwid.Text(('logged_response', 'No filters'))) comp.listbox.autoscroll() return else: for index, pattern in enumerate(filters): comp.listwalker.append(urwid.Text(('logged_response', str(index) + '. ' + pattern))) comp.listbox.autoscroll() return elif subcommand == 'add': regex = user_command_split[2:] comp.consolemonitor.filters.append(' '.join(regex)) elif subcommand == 'clear': comp.consolemonitor.filters = [] elif subcommand == 'contains': remaining_commands = user_command_split[2:] matchstring = ' '.join(remaining_commands) matchstring_escaped = '.*' + re.escape(matchstring) + '.*' comp.consolemonitor.filters.append(matchstring_escaped) elif subcommand == 'remove': if len(user_command_split) > 2: toRemove = int(user_command_split[2]) if len(comp.consolemonitor.filters) > toRemove: comp.consolemonitor.filters.pop(toRemove) else: comp.listwalker.append(urwid.Text(('logged_response', 'filter out of range'))) comp.listbox.autoscroll() def gcl(self, comp): control_points = int(comp.getApiClient().me()['gcl']) gcl = str(int((control_points/1000000) ** (1/2.4))+1) comp.listwalker.append(urwid.Text(('logged_response', gcl))) def list(self, comp): command_list = '' aliases = list(comp.aliases) builtin_list = [method for method in dir(self) if callable(getattr(self, method))] commands = builtin_list for alias in aliases: alias_real = comp.aliases[alias] if alias_real not in builtin_list: commands.append(alias) commands.sort() commands.reverse() for builtin_command in commands: if builtin_command != 'turtle' and not builtin_command.startswith('__'): command_list = builtin_command + ' ' + command_list comp.listwalker.append(urwid.Text(('logged_response', command_list))) return def pause(self, comp): comp.listbox.setAutoscroll(False) def reconnect(self, comp): comp.consolemonitor.reconnect() comp.listwalker.append(urwid.Text(('logged_response', 'reconnecting'))) comp.listbox.autoscroll() def shard(self, comp): userInput = comp.edit user_text = userInput.get_edit_text() user_command_split = user_text.split(' ') if len(user_command_split) < 2 or user_command_split[1] == 'current': comp.listwalker.appendText(comp.shard) return if user_command_split[1] == 'clear': comp.consolemonitor.focus = False comp.listwalker.appendText('Clearing shard settings') return if user_command_split[1] == 'focus': if len(user_command_split) < 3: comp.consolemonitor.focus = False comp.listwalker.appendText('Disabled shard focus') else: shard = user_command_split[2] comp.consolemonitor.focus = shard comp.shard = shard message = 'Enabled shard focus on %s' % (shard) comp.listwalker.appendText(message) return comp.shard = user_command_split[1] response = 'Setting active shard to %s' % (comp.shard,) comp.listwalker.appendText(response) def themes(self, comp): userInput = comp.edit user_text = userInput.get_edit_text() user_command_split = user_text.split(' ') if len(user_command_split) < 2 or user_command_split[1] == 'list': theme_names = themes.keys() theme_names.reverse() theme_list = '' for theme in theme_names: theme_list = theme + ' ' + theme_list comp.listwalker.appendText(theme_list) return if user_command_split[1] == 'test': comp.listwalker.append(urwid.Text(('logged_input', 'logged_input'))) comp.listwalker.append(urwid.Text(('logged_response', 'logged_response'))) comp.listwalker.append(urwid.Text(('error', 'error'))) comp.listwalker.append(urwid.Text(('default', 'default'))) comp.listwalker.append(urwid.Text(('severity0', 'severity0'))) comp.listwalker.append(urwid.Text(('severity1', 'severity1'))) comp.listwalker.append(urwid.Text(('severity2', 'severity2'))) comp.listwalker.append(urwid.Text(('severity3', 'severity3'))) comp.listwalker.append(urwid.Text(('severity4', 'severity4'))) comp.listwalker.append(urwid.Text(('severity5', 'severity5'))) comp.listwalker.append(urwid.Text(('highlight', 'highlight'))) comp.listbox.set_focus(len(comp.listwalker)-1) return theme = user_command_split[1] if theme in themes: comp.loop.screen.register_palette(themes[theme]) comp.loop.screen.clear() return def turtle(self, comp): turtle = ''' ________________ < How you doing? > ---------------- \ ___-------___ \ _-~~ ~~-_ \ _-~ /~-_ /^\__/^\ /~ \ / \\ /| O|| O| / \_______________/ \\ | |___||__| / / \ \\ | \ / / \ \\ | (_______) /______/ \_________ \\ | / / \ / \\ \ \^\\\ \ / \ / \ || \______________/ _-_ //\__// \ ||------_-~~-_ ------------- \ --/~ ~\ || __/ ~-----||====/~ |==================| |/~~~~~ (_(__/ ./ / \_\ \. (_(___/ \_____)_) ''' comp.listwalker.appendText(turtle) comp.listwalker.appendText('') def whoami(self, comp): me = comp.getApiClient().me()['username'] comp.listwalker.append(urwid.Text(('logged_response', me)))
mit
gangadharkadam/office_frappe
frappe/templates/includes/login.js
3138
window.disable_signup = {{ disable_signup and "true" or "false" }}; window.login = {}; login.bind_events = function() { $(window).on("hashchange", function() { login.route(); }); $(".form-login").on("submit", function(event) { event.preventDefault(); var args = {}; args.cmd = "login"; args.usr = ($("#login_email").val() || "").trim(); args.pwd = $("#login_password").val(); if(!args.usr || !args.pwd) { frappe.msgprint(__("Both login and password required")); return false; } login.call(args); }); $(".form-signup").on("submit", function(event) { event.preventDefault(); var args = {}; args.cmd = "frappe.core.doctype.user.user.sign_up"; args.email = ($("#signup_email").val() || "").trim(); args.full_name = ($("#signup_fullname").val() || "").trim(); if(!args.email || !valid_email(args.email) || !args.full_name) { frappe.msgprint(__("Valid email and name required")); return false; } login.call(args); }); $(".form-forgot").on("submit", function(event) { event.preventDefault(); var args = {}; args.cmd = "frappe.core.doctype.user.user.reset_password"; args.user = ($("#forgot_email").val() || "").trim(); if(!args.user) { frappe.msgprint(__("Valid Login id required.")); return false; } login.call(args); }); } login.route = function() { var route = window.location.hash.slice(1); if(!route) route = "login"; login[route](); } login.login = function() { $("form").toggle(false); $(".form-login").toggle(true); } login.forgot = function() { $("form").toggle(false); $(".form-forgot").toggle(true); } login.signup = function() { $("form").toggle(false); $(".form-signup").toggle(true); } // Login login.call = function(args) { $('.btn-primary').prop("disabled", true); $.ajax({ type: "POST", url: "/", data: args, dataType: "json", statusCode: login.login_handlers }).always(function(){ $('.btn-primary').prop("disabled", false); }) } login.login_handlers = (function() { var get_error_handler = function(default_message) { return function(xhr, data) { if(xhr.responseJSON) { data = xhr.responseJSON; } var message = data._server_messages ? JSON.parse(data._server_messages).join("\n") : default_message; frappe.msgprint(message); }; } var login_handlers = { 200: function(data) { if(data.message=="Logged In") { window.location.href = "desk"; } else if(data.message=="No App") { if(localStorage) { var last_visited = localStorage.getItem("last_visited") || "/index"; localStorage.removeItem("last_visited"); window.location.href = last_visited; } else { window.location.href = "/index"; } } else if(["#signup", "#forgot"].indexOf(window.location.hash)!==-1) { frappe.msgprint(data.message); } }, 401: get_error_handler(__("Invalid Login")), 417: get_error_handler(__("Oops! Something went wrong")) }; return login_handlers; })(); frappe.ready(function() { window.location.hash = "#login"; login.bind_events(); login.login(); $(".form-signup, .form-forgot").removeClass("hide"); $(document).trigger('login_rendered'); });
mit
jedray/factoring
dixon.cpp
10114
#include <list> // lists #include <vector> // vector #include <iostream> // #include <gmpxx.h> // mpz_class and large numbers #include <assert.h> #define myTime(t0) ((float)clock()-(t0))/CLOCKS_PER_SEC void seive_erastothen(int B, std::vector<int> & factor_base){ bool isPrime[B]; for(int i=0;i<B;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int p=2; p*p < B; p++){ if(isPrime[p]){ int k = 2; while (k*p < B){ isPrime[k*p] = false; k++; } } } int b = 0; for(int i=0; i<B; i++){ if(isPrime[i]) b++; } factor_base.resize(b+1); factor_base[0] = -1; int j = 1; for(int i=2; i<B; i++){ if(isPrime[i]){ factor_base[j] = i; j++; } } } bool gauss_elimination( const std::list< std::vector<int> > & Q_factors_ , int b, std::list<int> &dependent_rows){ int m = b + 1; // m columns int n = Q_factors_.size(); // n rows bool mark[n]; // row marker for(int i=0; i< n; i++) mark[i] = false; std::list< std::vector<int> > Q_factors = Q_factors_; std::list< std::vector<int> >::iterator i,l; int d; // triangulize the matrix for(int j=0; j<m; j++){ i = Q_factors.begin(); d = 0; while (i != Q_factors.end()){ if((*i)[j] == 1) break; ++i; ++d; } if (i != Q_factors.end()){ mark[d] = true; for(int k=0; k<m; k++){ if(k!=j and (*i)[k] == 1){ for(l=Q_factors.begin(); l!=Q_factors.end(); ++l){ (*l)[k] = ((*l)[k] + (*l)[j])%2; } } } } } // std::cout << " after elimination \n"; // for(int i = 0; i<n; i++){ // for(int j = 0; j<m; j++){ // std::cout << matrix[i][j]; // if (j != m-1) // std::cout << " , "; // else // std::cout << std::endl; // } // } // find dependent rows // find unmarked row i = Q_factors.begin(); d = 0; while (d<n && mark[d]){ ++i; ++d; } if(d>=n) return false; dependent_rows.push_back(d); // find linear combination for unmarked row for (int j = 0; j<m; j++){ if((*i)[j] == 1){ d = 0; for(l = Q_factors.begin(); l != Q_factors.end(); ++l){ if(l != i and (*l)[j] == 1){ // save row k dependent_rows.push_back(d); break; } d++; } } } return true; } // checks whether Q² mod N is factorizable in the factor base bool isBsmooth(mpz_class N, mpz_class Q, mpz_class &q, std::list< std::vector<int> > & Q_factors, int b, const std::vector<int> & factor_base){ std::cout << " b=" << b; std::vector<int> f(b+1); // b+1 is the size of the base factor std::cout << "why ? \n"; // compute Q² mod N // take smallest absolute value q = Q*Q % N; mpz_class q_ = N - (Q*Q % N); if (q_< q){ q = q_; f[0] = 1; } int sum = f[0]; // find factors in the factor base for(int i=1; i<b+1; i++){ // check if p_i in base factor divides //std::cout << "here \n"; while(q % (factor_base[i]) == 0){ q /= (factor_base[i]); f[i] = (f[i] + 1) % 2; std::cout << factor_base[i] <<", "; } sum += f[i]; //std::cout << "or here \n"; } //std::cout << "q=" << q << "\n"; if (q != 1 or sum == 0) return false; std::cout << " not even once \n"; // add vector to list Q_factors.push_back(f); return true; } // main factoring function bool ce_factoring(mpz_class & N, mpz_class & p, int b, const std::vector<int> & factor_base, float time_allocated, clock_t t){ // init search mpz_class Q,q; mpz_class prod_Q, prod_q; mpz_sqrt(Q.get_mpz_t(), N.get_mpz_t()); std::list< std::vector<int> > Q_factors; // list of vectors<b+1> std::list< std::vector<int> >::iterator l; std::list< mpz_class > Qs,qs; // list of saved Qis std::list< mpz_class >::iterator i,j; gmp_randstate_t STATE_; gmp_randinit_mt(STATE_); mpz_class a_(1), b_(0), root_a_N, a_N(N); mpz_sqrt (root_a_N.get_mpz_t(),a_N.get_mpz_t()); std::cout << "[3.1.1] Entering main loop ... \n"; while (true){ if(myTime(t)>time_allocated) return true; // generate random Q in the range 0..N-1 // mpz_urandomm(Q.get_mpz_t(), STATE_, N.get_mpz_t()); if(b_ < 15){ Q = root_a_N + b_; b_++; }else{ a_++; a_N = a_*N; mpz_sqrt (root_a_N.get_mpz_t(),a_N.get_mpz_t()); b = -15; } if(Q == 0) continue; // if Q is B-smooth than add it to our lists std::cout << "[3.1.1.1] is it B-smooth ? \n"; if( isBsmooth(N, Q, q, Q_factors, b, factor_base) ){ Qs.push_back(Q); Qs.push_back(q); } // if picked B-smooth numbers are enough then proceed if(Q_factors.size()> 2){ std::list<int> dependent_rows; std::list<int>::iterator k; int d; std::cout << "starting gauss elimination .... \n"; // if dependent rows exist then proceed if (gauss_elimination(Q_factors,b,dependent_rows)){ std::cout << "gauss elimination done \n "; prod_Q = 1; prod_q = 1; k = dependent_rows.begin(); i = Qs.begin(); j = qs.begin(); d = 0; // generate the perfect squares x² and y² while(k != dependent_rows.end()){ if(d == (*k)){ prod_Q *= (*i)*(*i); prod_q *= (*j); ++k; } ++d; ++i; ++j; } mpz_class x,y; mpz_sqrt(x.get_mpz_t(), prod_Q.get_mpz_t()); mpz_sqrt(y.get_mpz_t(), prod_q.get_mpz_t()); // compute the gcd(x+y,N) or gcd(x-y) mpz_class candidate; candidate = x+y; mpz_gcd(p.get_mpz_t(),candidate.get_mpz_t(), N.get_mpz_t()); // if success return factor gcd(x+y,N) if(p>1 and p<N){ std::cout << "successefuly factorized \n"; N = N/p; return false; } candidate = x-y; mpz_gcd(p.get_mpz_t(),candidate.get_mpz_t(), N.get_mpz_t()); // if success return factor gcd(x-y,N) if(p>1 and q<N){ N = N/p; return false; } // if failure remove first Q in dependent row i = Qs.begin(); j = qs.begin(); k = dependent_rows.begin(); l = Q_factors.begin(); d = 0; while(d<(*k)){ ++i; ++j; ++l; ++d; } Qs.erase(i); qs.erase(j); Q_factors.erase(l); } } } return true; } bool dixon_recursive(mpz_class N, std::list<mpz_class> & factors, int b, const std::vector<int> & factor_base, float time_allocated, clock_t t){ if(myTime(t)> time_allocated) return true; if(N==1) return false; if(1 <= mpz_probab_prime_p(N.get_mpz_t(),20)){ factors.push_back(N); return false; } std::cout << "[3.1] Entering ... \n"; mpz_class p; if(ce_factoring(N,p,b,factor_base,time_allocated,t)) return true; std::cout << "[3.1] done. \n"; mpz_class b_; mpz_root(b_.get_mpz_t(),p.get_mpz_t(),12); b = mpz_get_si(b_.get_mpz_t()); std::cout << "[3.2] Entering recursion over p ... \n"; if(dixon_recursive(p,factors,b,factor_base,time_allocated,t)) return true; std::cout << "[3.2] Done. \n"; mpz_root(b_.get_mpz_t(),N.get_mpz_t(),12); b = mpz_get_si(b_.get_mpz_t()); std::cout << "[3.3] Entering recursion ever q ... \n"; if(dixon_recursive(N,factors,b,factor_base,time_allocated,t)) return true; std::cout << "[3.3] Done. \n"; return false; } bool dixon_factoring(mpz_class N, std::list<mpz_class> & factors, int B, const std::vector<int> & factor_base, float time_allocated, clock_t t){ std::cout << "[DIXON] Running .... \n"; // we choose pi(B) to be the 12th rooth of n such that the // gauss elimnation wo'nt take more than n^4 mpz_class b; mpz_root(b.get_mpz_t(),N.get_mpz_t(),4); //std::cout << "Dixon Factoring START ..... \n"; // step 1: // first check if the primes in the factor base are factors of N // and if find size of the factor base int i = 1; std::cout << "[1] trial devisions .... \n"; while( factor_base[i] < B){ while( N % factor_base[i] == 0){ N = N/factor_base[i]; factors.push_back(factor_base[i]); } i++; if(i>b) break; } //return false; // step 2: // apply dixon's factoring std::cout << "[2] recursivity starts .... \n"; return(dixon_recursive(N,factors,mpz_get_si(b.get_mpz_t()), factor_base, time_allocated,t)); }
mit
Deletescape-Media/Primitives
src/test/java/ch/deletescape/primitives/CharsTest.java
1480
package ch.deletescape.primitives; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class CharsTest { @Test public void fromLong() { assertThat(Chars.from(1L), is((char) 1)); assertThat(Chars.from(Long.MAX_VALUE), is((char) -1)); assertThat(Chars.from(Long.MAX_VALUE - 1), is((char) -2)); } @Test public void fromInt() { assertThat(Chars.from(1), is((char) 1)); assertThat(Chars.from(Integer.MAX_VALUE), is((char) -1)); } @Test public void fromByte() { assertThat(Chars.from((byte) 1), is((char) 1)); assertThat(Chars.from(Byte.MAX_VALUE), is((char) 127)); } @Test public void fromShort() { assertThat(Chars.from((short) 1), is((char) 1)); assertThat(Chars.from(Short.MAX_VALUE), is((char) 32767)); } @Test public void fromDouble() { assertThat(Chars.from(1.0), is((char) 1)); assertThat(Chars.from(1.3), is((char) 1)); assertThat(Chars.from(Double.MAX_VALUE), is((char) -1)); } @Test public void fromFloat() { assertThat(Chars.from(1f), is((char) 1)); assertThat(Chars.from(1.3f), is((char) 1)); assertThat(Chars.from(Float.MAX_VALUE), is((char) -1)); } @Test public void fromBoolean() { assertThat(Chars.from(true), is((char) 1)); assertThat(Chars.from(false), is((char) 0)); } // Calls the #random() method for coverage reasons @Test public void random() { Chars.random(); } }
mit
tilap/tilapp
tilapp/src/Router.js
5944
import React from 'react'; // import { StatusBar } from "react-native"; import { TabNavigator, DrawerNavigator, StackNavigator } from 'react-navigation'; import { getCurrentRouteName } from '~/lib/reactNavigation/helpers'; import Drawer from '~/containers/Drawer'; import EmptyPage from '~/containers/Scenes/EmptyPage/Index/'; import About from '~/containers/Scenes/About/'; import AccountView from '~/containers/Scenes/Account/View/'; import AccountEdition from '~/containers/Scenes/Account/Edition/'; import AccountEditionPlace from '~/containers/Scenes/Account/EditionPlace/'; import Auth from '~/containers/Scenes/Auth/Index/'; import Contact from '~/containers/Scenes/Contact/'; import Book from '~/containers/Scenes/Book/Index/'; import BookSell from '~/containers/Scenes/Book/Sell/'; import BookSellPlace from '~/containers/Scenes/Book/Sell/Place/'; import Capture from '~/containers/Scenes/Capture/Index/'; import CaptureHelp from '~/containers/Scenes/Capture/Help/'; import PresentationScene from '~/containers/Scenes/Presentation/'; import SalesScene from '~/containers/Scenes/Sales/'; import WebviewScene from '~/containers/Scenes/Webview/'; import NavigationButton from '~/components/NavigationButton'; import { setScreens } from '~/services/navigation/'; import theme from '~/theme/colors'; const applicationRoutes = { About: { screen: About, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="menu" onPress={() => props.navigation.navigate('DrawerOpen')} />, }), }, Account: { screen: StackNavigator( { AccountView: { screen: AccountView, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="menu" onPress={() => props.navigation.navigate('DrawerOpen')} />, }), }, AccountEdition: { screen: AccountEdition, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="back" onPress={() => props.navigation.goBack()} />, }), }, AccountEditionPlace: { screen: AccountEditionPlace, }, }, { initialRouteName: 'AccountView', headerMode: 'none', lazy: true, } ), }, Contact: { screen: Contact, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="menu" onPress={() => props.navigation.navigate('DrawerOpen')} />, }), }, Sales: { screen: StackNavigator( { CaptureIndex: { screen: Capture, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="back" onPress={() => props.navigation.goBack()} />, }), }, CaptureHelp: { screen: CaptureHelp, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="back" onPress={() => props.navigation.goBack()} />, }), }, Book: { screen: Book, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="back" onPress={() => props.navigation.goBack()} />, }), }, BookSell: { screen: BookSell, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="back" onPress={() => props.navigation.goBack()} />, }), }, BookSellPlace: { screen: BookSellPlace, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="back" onPress={() => props.navigation.goBack()} />, }), }, SalesView: { screen: SalesScene, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="menu" onPress={() => props.navigation.navigate('DrawerOpen')} />, }), }, }, { initialRouteName: 'SalesView', headerMode: 'none', lazy: true, } ), }, Messages: { screen: EmptyPage, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="menu" onPress={() => props.navigation.navigate('DrawerOpen')} />, }), }, }; const Application = TabNavigator(applicationRoutes, { animationEnabled: false, initialRouteName: 'Sales', lazy: true, swipeEnabled: false, tabBarComponent: () => null, }); const ApplicationRouter = DrawerNavigator({ Main: { screen: StackNavigator({ Application: { screen: Application }, Auth: { screen: Auth, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="close" onPress={() => props.navigation.goBack()} />, }), }, Presentation: { screen: PresentationScene }, Webview: { screen: WebviewScene, navigationOptions: (props) => ({ headerLeft: <NavigationButton icon="close" onPress={() => props.navigation.goBack()} />, }), } }, { initialRouteName: 'Application', mode: 'modal', navigationOptions: { headerTitleStyle: { color: theme.navigationColor, }, headerTintColor: theme.navigationColor, headerBackTitleStyle: { color: theme.navigationColor, }, headerStyle: { backgroundColor: theme.navigationBackground, borderBottomColor: theme.navigationBackground, }, headerPressColorAndroid: theme.navigationRippleColor, }, }), } }, { contentComponent: (props) => <Drawer {...props} />, // eslint-disable-line react/display-name }); // const defaultGetStateForAction = ApplicationRouter.router.getStateForAction; // ApplicationRouter.router.getStateForAction = (action, state) => { // if(state && action.type === 'Navigation/NAVIGATE') { // if (action.routeName === 'DrawerClose') { // StatusBar.setHidden(false); // } else if(action.routeName === 'DrawerOpen') { // StatusBar.setHidden(true); // } // } // return defaultGetStateForAction(action, state); // }; const setStateForDifferentRoutes = (prevState, currentState) => { const currentScreen = getCurrentRouteName(currentState); const prevScreen = prevState ? getCurrentRouteName(prevState) : ''; if (prevScreen !== currentScreen) { setScreens({ current: currentScreen, previous: prevScreen }); } } const Router = () => ( <ApplicationRouter onNavigationStateChange={setStateForDifferentRoutes} /> ); export default Router;
mit
vivaxy/design
number-animations/index.js
643
/** * @since 150523 10:36 * @author vivaxy */ var animate = function() { new NumberAnimation({ container: document.querySelector('.number1'), targetNumber: 12345.67, }); new NumberAnimation({ container: document.querySelector('.number2'), targetNumber: 54321.09, }); new NumberAnimation({ container: document.querySelector('.number3'), baseNumber: 12345.67, targetNumber: 54321.09, }); }; // in ios : click event not fired // http://stackoverflow.com/questions/14054272/click-event-listener-works-in-safari-in-osx-but-not-in-ios window.addEventListener('touchstart', animate, false); animate();
mit
Rodz3rd2/my-framework
functions/config.php
267
<?php function config($string) { $temp = explode(".", $string); $filename = array_shift($temp); $keys = $temp; $content = include config_path("{$filename}.php"); $active = $content; foreach ($keys as $key) { $active = $active[$key]; } return $active; }
mit
Tosch110/SuperNET-Lite-3
js/nrs.news.js
3580
/****************************************************************************** * Copyright © 2013-2016 The Nxt Core Developers. * * * * See the AUTHORS.txt, DEVELOPER-AGREEMENT.txt and LICENSE.txt files at * * the top-level directory of this distribution for the individual copyright * * holder information and the developer policies on copyright and licensing. * * * * Unless otherwise agreed in a custom licensing agreement, no part of the * * Nxt software, including this file, may be copied, modified, propagated, * * or distributed except according to the terms contained in the LICENSE.txt * * file. * * * * Removal or modification of this copyright notice is prohibited. * * * ******************************************************************************/ /** * @depends {nrs.js} */ var NRS = (function(NRS, $, undefined) { NRS.pages.news = function() { if (NRS.settings.news != 1) { $("#rss_news_container").hide(); $("#rss_news_disabled").show(); return; } else { $("#rss_news_container").show(); $("#rss_news_disabled").hide(); } $(".rss_news").empty().addClass("data-loading").html("<img src='img/loading_indicator.gif' width='32' height='32' />"); var ssl = ""; if (window.location.protocol == "https:") { ssl = "s"; } var settings = { "limit": 5, "layoutTemplate": "<div class='list-group'>{entries}</div>", "entryTemplate": "<a href='{url}' target='_blank' class='list-group-item'><h4 class='list-group-item-heading'>{title}</h4><p class='list-group-item-text'>{shortBodyPlain}</p><i>{date}</i></a>", "ssl": ssl }; var settingsReddit = { "limit": 7, "filterLimit": 5, "layoutTemplate": "<div class='list-group'>{entries}</div>", "entryTemplate": "<a href='{url}' target='_blank' class='list-group-item'><h4 class='list-group-item-heading'>{title}</h4><p class='list-group-item-text'>{shortBodyReddit}</p><i>{date}</i></a>", "tokens": { "shortBodyReddit": function(entry, tokens) { return entry.contentSnippet.replace("&lt;!-- SC_OFF --&gt;", "").replace("&lt;!-- SC_ON --&gt;", "").replace("[link]", "").replace("[comment]", ""); } }, "filter": function(entry, tokens) { return tokens.title.indexOf("Donations toward") == -1 && tokens.title.indexOf("NXT tipping bot has arrived") == -1 }, "ssl": ssl }; $("#nxtforum_news").rss("https://nxtforum.org/index.php?type=rss;action=.xml", settings, NRS.newsLoaded); $("#reddit_news").rss("http://www.reddit.com/r/NXT/.rss", settingsReddit, NRS.newsLoaded); $("#nxtcoin_blogspot_news").rss("http://nxtcoin.blogspot.com/feeds/posts/default", settings, NRS.newsLoaded); $("#nxter_news").rss("http://nxter.org/feed/", settings, NRS.newsLoaded); NRS.pageLoaded(); }; NRS.newsLoaded = function($el) { $el.removeClass("data-loading").find("img").remove(); }; $("#rss_news_enable").on("click", function() { NRS.updateSettings("news", 1); NRS.loadPage("news"); }); return NRS; }(NRS || {}, jQuery));
mit
sebastienros/yessql
src/YesSql.Core/Provider/ServiceCollectionExtensions.cs
814
using System; using YesSql; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { public static IServiceCollection AddDbProvider( this IServiceCollection services, Action<IConfiguration> setupAction) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (setupAction == null) { throw new ArgumentNullException(nameof(setupAction)); } var config = new Configuration(); setupAction.Invoke(config); services.AddSingleton<IStore>(StoreFactory.CreateAndInitializeAsync(config).GetAwaiter().GetResult()); return services; } } }
mit
SYCstudio/OI
Practice/2017/2017.10.5/Luogu1563.cpp
502
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; const int maxN=100100; const int inf=2147483647; int n,m; int Op[maxN]; char name[maxN][50]; int main() { scanf("%d%d",&n,&m); for (int i=0;i<n;i++) scanf("%d%s",&Op[i],name[i]); int pos=0; for (int i=1;i<=m;i++) { int op,num; scanf("%d%d",&op,&num); num=num%n; if (op==Op[pos]) pos=(pos-num+n)%n; else pos=(pos+num)%n; } printf("%s\n",name[pos]); return 0; }
mit
jarves/Propel2
src/Propel/Generator/Command/DatabaseReverseCommand.php
3424
<?php /** * This file is part of the Propel package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License */ namespace Propel\Generator\Command; use Propel\Generator\Schema\Dumper\XmlDumper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Propel\Generator\Manager\ReverseManager; /** * @author William Durand <william.durand1@gmail.com> */ class DatabaseReverseCommand extends AbstractCommand { const DEFAULT_OUTPUT_DIRECTORY = 'generated-reversed-database'; const DEFAULT_DATABASE_NAME = 'default'; const DEFAULT_SCHEMA_NAME = 'schema'; /** * {@inheritdoc} */ protected function configure() { parent::configure(); $this ->addOption('output-dir', null, InputOption::VALUE_REQUIRED, 'The output directory', self::DEFAULT_OUTPUT_DIRECTORY) ->addOption('database-name', null, InputOption::VALUE_REQUIRED, 'The database name used in the created schema.xml', self::DEFAULT_DATABASE_NAME) ->addOption('schema-name', null, InputOption::VALUE_REQUIRED, 'The schema name to generate', self::DEFAULT_SCHEMA_NAME) ->addArgument('connection', InputArgument::OPTIONAL, 'Connection to use. Example: \'mysql:host=127.0.0.1;dbname=test;user=root;password=foobar\' (don\'t forget the quote)') ->setName('database:reverse') ->setAliases(array('reverse')) ->setDescription('Reverse-engineer a XML schema file based on given database') ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $configOptions = array(); if ($this->hasInputArgument('connection', $input)) { $configOptions += $this->connectionToProperties('reverseconnection='.$input->getArgument('connection'), 'reverse'); $configOptions['propel']['reverse']['parserClass'] = sprintf('\\Propel\\Generator\\Reverse\\%sSchemaParser', ucfirst($configOptions['propel']['database']['connections']['reverseconnection']['adapter'])); } $generatorConfig = $this->getGeneratorConfig($configOptions, $input); $this->createDirectory($input->getOption('output-dir')); $manager = new ReverseManager(new XmlDumper()); $manager->setGeneratorConfig($generatorConfig); $manager->setLoggerClosure(function ($message) use ($input, $output) { if ($input->getOption('verbose')) { $output->writeln($message); } }); $manager->setWorkingDirectory($input->getOption('output-dir')); $manager->setDatabaseName($input->getOption('database-name')); $manager->setSchemaName($input->getOption('schema-name')); if (true === $manager->reverse()) { $output->writeln('<info>Schema reverse engineering finished.</info>'); } else { $more = $input->getOption('verbose') ? '' : ' You can use the --verbose option to get more information.'; $output->writeln(sprintf('<error>Schema reverse engineering failed.%s</error>', $more)); return 1; } } }
mit
TylerDrinkard/Comp-1210
Labs/Activity 5/NumberOpsDriver.java
1866
import java.util.Scanner; import java.util.ArrayList; /** * Demonstrates the NumberOperations class. * *@author Tyler Drinkard *@version 2/19/17 */ public class NumberOpsDriver { /** * Reads a set of positive numbers from the user until the user enters 0. * Prints odds under and powers of 2 under for each number. * * @param args - Standard commandline arguments */ public static void main(String[] args) { Scanner in = new Scanner(System.in); // declare and instantiate ArrayList with generic type <NumberOperations> ArrayList<NumberOperations> numOpsList = new ArrayList<NumberOperations>(); // prompt user for set of numbers System.out.println("Enter a list of positive integers separated " + "with a space followed by 0:"); // get first user input using in.nextInt() int userInput = in.nextInt(); // add a while loop as described below: // while the input is not equal to 0 // add a new NumberOperations object to numOpsList based on user input // get the next user input using in.nextInt() while (userInput != 0) { NumberOperations enter = new NumberOperations(userInput); numOpsList.add(enter); userInput = in.nextInt(); } int index = 0; while (index < numOpsList.size()) { NumberOperations num = numOpsList.get(index); System.out.println("For: " + num); // add print statement for odds under num // add print statement for powers of 2 under num System.out.println(" Odds under:\t" + num.oddsUnder()); System.out.println(" Powers of 2 under:\t" + num.powersTwoUnder()); index++; } } }
mit
BCNC/bcnc.github.io
public/javascripts/table.js
3070
/* var retrieve = function(id) { var link = '/resume?filename=' + id; window.open(link); document.getElementById('ifram1').src = link; $.ajax({ type: "GET", url: '/resume', data: { 'filename': id }, success: function(resp) { window.open('/resume?filename=' + id); //window.open('http://stackoverflow.com/', '_blank'); //window.open("data:application/pdf," + encodeURI(resp)); //console.log('done'); } }); };*/ var accept = function(id) { var user = {}; user = JSON.parse(sessionStorage.getItem('userEntity')); // deliberate with yes $.ajax({ url: '/deliberate', type: 'POST', data: {'id': id, // 1 means accept 'accept': 1, 'userEmail': user.email }, success: function(result) { // change the color of the row console.log('Result: ' + result) if (result >= 5) { document.getElementById(id).setAttribute('class', 'accept'); } else { document.getElementById(id).setAttribute('class', 'new'); } } }); }; var reject = function(id) { var user = {}; user = JSON.parse(sessionStorage.getItem('userEntity')); // deliberate with no $.ajax({ url: '/deliberate', type: 'POST', data: { 'id': id, // 2 means reject 'accept': 2, 'userEmail': user.email }, success: function(result) { // change the color of the row console.log('Result: ' + result) if (result >= 5) { document.getElementById(id).setAttribute('class', 'accept'); } else { document.getElementById(id).setAttribute('class', 'new'); } } }); }; $(document).ready(function() { var user = {}; user = JSON.parse(sessionStorage.getItem('userEntity')); var currentUser; if(sessionStorage.getItem('userEntity') === null) { currentUser = ""; } else { currentUser = user.email; } // find specific officer and determine whether or not to move on to the webpage $.ajax({ url: '/findOfficer', type: 'POST', data: { 'email': currentUser }, success: function(results) { if(results == currentUser) { // if(true) { console.log(user.Name + " is logged in!"); // load up the table $('#table').removeClass('table-hover'); $(".fancybox").fancybox({ openEffect : 'fade', closeEffect : 'elastic', iframe : { preload: false } }); } else { window.location.href = 'login'; window.alert("You must be an officer to access this page."); } } }); });
mit
deminy/jieba-php
src/Jieba/Data/TopArrayElement.php
1229
<?php namespace Jieba\Data; use Jieba\Exception; /** * Class TopArrayElement * * @package Jieba */ class TopArrayElement { /** * @var mixed */ protected $key; /** * @var mixed */ protected $value; /** * TopArrayElement constructor. * * @param array $array * @throws Exception */ public function __construct(array $array) { if (empty($array)) { throw new Exception('class not designed for empty array'); } arsort($array); $this->setValue(reset($array))->setKey(key($array)); unset($array); } /** * @return mixed */ public function getKey() { return $this->key; } /** * @param mixed $key * @return TopArrayElement */ public function setKey($key): TopArrayElement { $this->key = $key; return $this; } /** * @return mixed */ public function getValue() { return $this->value; } /** * @param mixed $value * @return TopArrayElement */ public function setValue($value): TopArrayElement { $this->value = $value; return $this; } }
mit
nick-ma/wechat-enterprise
test/api_common.test.js
3680
var expect = require('expect.js'); var urllib = require('urllib'); var muk = require('muk'); var config = require('./config'); var API = require('../').API; describe('common.js', function () { describe('mixin', function () { it('should ok', function () { API.mixin({sayHi: function () {}}); expect(API.prototype).to.have.property('sayHi'); }); it('should not ok when override method', function () { var obj = {sayHi: function () {}}; expect(API.mixin).withArgs(obj).to.throwException(/Don't allow override existed prototype method\./); }); }); describe('getAccessToken', function () { it('should ok', function (done) { var api = new API(config.corpid, config.corpsecret); api.getAccessToken(function (err, token) { expect(err).not.to.be.ok(); expect(token).to.only.have.keys('accessToken'); done(); }); }); it('should not ok', function (done) { var api = new API('corpid', 'corpsecret'); api.getAccessToken(function (err, token) { expect(err).to.be.ok(); expect(err).to.have.property('name', 'WeChatAPIError'); expect(err).to.have.property('code', 40013); expect(err).to.have.property('message', 'invalid corpid'); done(); }); }); describe('mock urllib err', function () { before(function () { muk(urllib, 'request', function (url, args, callback) { var err = new Error('Urllib Error'); err.name = 'UrllibError'; callback(err); }); }); after(function () { muk.restore(); }); it('should get mock error', function (done) { var api = new API('appid', 'secret'); api.getAccessToken(function (err, token) { expect(err).to.be.ok(); expect(err.name).to.be('WeChatAPIUrllibError'); expect(err.message).to.be('Urllib Error'); done(); }); }); }); describe('mock token', function () { before(function () { muk(urllib, 'request', function (url, args, callback) { process.nextTick(function () { callback(null, {"access_token": "ACCESS_TOKEN","expires_in": 7200}); }); }); }); after(function () { muk.restore(); }); it('should ok', function (done) { var api = new API('appid', 'secret'); api.getAccessToken(function (err, token) { expect(err).to.not.be.ok(); expect(token).to.have.property('accessToken', 'ACCESS_TOKEN'); done(); }); }); }); }); describe('getLatestToken', function () { it('should ok', function (done) { var api = new API(config.corpid, config.corpsecret); api.getLatestToken(function (err, token) { expect(err).not.to.be.ok(); expect(token).to.only.have.keys('accessToken'); done(); }); }); it('should get mock error', function (done) { var api = new API(config.corpid, config.corpsecret, 1, function (callback) { callback(new Error('mock error')); }); api.getLatestToken(function (err, token) { expect(err).to.be.ok(); expect(err).to.have.property('message', 'mock error'); done(); }); }); it('should get ok', function (done) { var api = new API(config.corpid, config.corpsecret, 1, function (callback) { callback(null, {accessToken: 'token'}); }); api.getLatestToken(function (err, token) { expect(err).not.to.be.ok(); expect(token).to.have.property('accessToken', 'token'); done(); }); }); }); });
mit
objective-audio/ui
ui/layout/yas_ui_layout.cpp
9086
// // yas_ui_layout.cpp // #include "yas_ui_layout.h" #include <ui/yas_ui_layout_dependency.h> #include <ui/yas_ui_layout_guide.h> using namespace yas; using namespace yas::ui; #pragma mark - value source observing::syncable ui::layout(std::shared_ptr<layout_value_source> const &src_guide, std::shared_ptr<layout_value_target> const &dst_target, std::function<float(float const &)> &&convert) { return src_guide->observe_layout_value( [weak_target = to_weak(dst_target), convert = std::move(convert)](float const &value) { if (auto const target = weak_target.lock()) { target->set_layout_value(convert(value)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_value_source> const &src_guide, std::shared_ptr<layout_point_target> const &dst_target, std::function<ui::point(float const &)> &&convert) { return src_guide->observe_layout_value( [weak_target = to_weak(dst_target), convert = std::move(convert)](float const &value) { if (auto const target = weak_target.lock()) { target->set_layout_point(convert(value)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_value_source> const &src_guide, std::shared_ptr<layout_range_target> const &dst_target, std::function<ui::range(float const &)> &&convert) { return src_guide->observe_layout_value( [weak_target = to_weak(dst_target), convert = std::move(convert)](float const &value) { if (auto const target = weak_target.lock()) { target->set_layout_range(convert(value)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_value_source> const &src_guide, std::shared_ptr<layout_region_target> const &dst_target, std::function<ui::region(float const &)> &&convert) { return src_guide->observe_layout_value( [weak_target = to_weak(dst_target), convert = std::move(convert)](float const &value) { if (auto const target = weak_target.lock()) { target->set_layout_region(convert(value)); } }); } #pragma mark - point source observing::syncable ui::layout(std::shared_ptr<layout_point_source> const &src_guide, std::shared_ptr<layout_value_target> const &dst_target, std::function<float(ui::point const &)> &&convert) { return src_guide->observe_layout_point( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::point const &point) { if (auto const target = weak_target.lock()) { target->set_layout_value(convert(point)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_point_source> const &src_guide, std::shared_ptr<layout_point_target> const &dst_target, std::function<ui::point(ui::point const &)> &&convert) { return src_guide->observe_layout_point( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::point const &point) { if (auto const target = weak_target.lock()) { target->set_layout_point(convert(point)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_point_source> const &src_guide, std::shared_ptr<layout_range_target> const &dst_target, std::function<ui::range(ui::point const &)> &&convert) { return src_guide->observe_layout_point( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::point const &point) { if (auto const target = weak_target.lock()) { target->set_layout_range(convert(point)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_point_source> const &src_guide, std::shared_ptr<layout_region_target> const &dst_target, std::function<ui::region(ui::point const &)> &&convert) { return src_guide->observe_layout_point( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::point const &point) { if (auto const target = weak_target.lock()) { target->set_layout_region(convert(point)); } }); } #pragma mark - range source observing::syncable ui::layout(std::shared_ptr<layout_range_source> const &src_guide, std::shared_ptr<layout_value_target> const &dst_target, std::function<float(ui::range const &)> &&convert) { return src_guide->observe_layout_range( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::range const &range) { if (auto const target = weak_target.lock()) { target->set_layout_value(convert(range)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_range_source> const &src_guide, std::shared_ptr<layout_point_target> const &dst_target, std::function<ui::point(ui::range const &)> &&convert) { return src_guide->observe_layout_range( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::range const &range) { if (auto const target = weak_target.lock()) { target->set_layout_point(convert(range)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_range_source> const &src_guide, std::shared_ptr<layout_range_target> const &dst_target, std::function<ui::range(ui::range const &)> &&convert) { return src_guide->observe_layout_range( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::range const &range) { if (auto const target = weak_target.lock()) { target->set_layout_range(convert(range)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_range_source> const &src_guide, std::shared_ptr<layout_region_target> const &dst_target, std::function<ui::region(ui::range const &)> &&convert) { return src_guide->observe_layout_range( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::range const &range) { if (auto const target = weak_target.lock()) { target->set_layout_region(convert(range)); } }); } #pragma mark - region source observing::syncable ui::layout(std::shared_ptr<layout_region_source> const &src_guide, std::shared_ptr<layout_value_target> const &dst_target, std::function<float(ui::region const &)> &&convert) { return src_guide->observe_layout_region( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::region const &region) { if (auto const target = weak_target.lock()) { target->set_layout_value(convert(region)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_region_source> const &src_guide, std::shared_ptr<layout_point_target> const &dst_target, std::function<ui::point(ui::region const &)> &&convert) { return src_guide->observe_layout_region( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::region const &region) { if (auto const target = weak_target.lock()) { target->set_layout_point(convert(region)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_region_source> const &src_guide, std::shared_ptr<layout_range_target> const &dst_target, std::function<ui::range(ui::region const &)> &&convert) { return src_guide->observe_layout_region( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::region const &region) { if (auto const target = weak_target.lock()) { target->set_layout_range(convert(region)); } }); } observing::syncable ui::layout(std::shared_ptr<layout_region_source> const &src_guide, std::shared_ptr<layout_region_target> const &dst_target, std::function<ui::region(ui::region const &)> &&convert) { return src_guide->observe_layout_region( [weak_target = to_weak(dst_target), convert = std::move(convert)](ui::region const &region) { if (auto const target = weak_target.lock()) { target->set_layout_region(convert(region)); } }); }
mit
miaowjs/miaow-thirdparty-plugin
test/fixtures/miaow.config.js
324
var Plugin = require('../..'); var path = require('path'); module.exports = { // 工作目录 context: __dirname, // 输出目录 output: path.resolve(__dirname, '../output'), // 缓存目录 cache: '', // 静态文件的域名 domain: 'http://127.0.0.1', plugins: [new Plugin()], hashLength: 0 };
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-project-setup-mgt-service/src/main/java/org/innovateuk/ifs/project/grantofferletter/populator/AcademicFinanceTableModelPopulator.java
1982
package org.innovateuk.ifs.project.grantofferletter.populator; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.finance.resource.ProjectFinanceResource; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.project.grantofferletter.viewmodel.AcademicFinanceTableModel; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Populator for the grant offer letter academic finance table */ @Component public class AcademicFinanceTableModelPopulator extends BaseGrantOfferLetterTablePopulator { public AcademicFinanceTableModel createTable(Map<OrganisationResource, ProjectFinanceResource> finances, CompetitionResource competition) { Map<String, ProjectFinanceResource> academicFinances = finances .entrySet() .stream() .filter(e -> isAcademic(e.getKey(), competition)) .collect(Collectors.toMap(e -> e.getKey().getName(), Map.Entry::getValue)); if (academicFinances.isEmpty()) { // to make it easier to reference if the table shouldn't show in the template return null; } else { List<String> organisations = new ArrayList<>(academicFinances.keySet()); BigDecimal totalEligibleCosts = calculateEligibleTotalFromFinances(academicFinances.values()); BigDecimal totalGrant = calculateTotalGrantFromFinances(academicFinances.values()); return new AcademicFinanceTableModel( academicFinances.size() > 1, academicFinances, organisations, totalEligibleCosts, totalGrant); } } }
mit