repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
you21979/node-hashpjw | example/es6.js | 190 | const hash = require('hashpjw');
let w = [
"qwerty",
"123456",
"12345678",
"00000001",
"NPC0001",
"@@@@@@@@"
].map(v => ({ key: hash(v), value: v}))
console.log(w);
| mit |
lcustodio/angular-grunt-to-webpack | app/scripts/vendor.js | 747 | 'use strict';
module.exports = function () {
/* Styles */
//require('../index.scss');
//require('../../node_modules/mdi/css/materialdesignicons.min.css');
//require('../../node_modules/node-lumx/dist/scss/_lumx.scss');
/* JS */
global.$ = global.jQuery = require('jquery');
//require('velocity-animate');
require('angular');
require("angular-animate/angular-animate.js");
require("angular-route/angular-route.js");
require("angular-resource/angular-resource.js");
//require('ngAnimate');
//require('ngCookies');
//require('ngResource');
//require('ngRoute');
//require('ngSanitize');
//require('ngTouch');
//global.moment = require('moment');
//require('node-lumx');
}; | mit |
ls1intum/ArTEMiS | src/main/webapp/app/entities/entity.module.ts | 1588 | import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { ArTEMiSCourseModule } from './course/course.module';
import { ArTEMiSExerciseModule } from './exercise/exercise.module';
import { ArTEMiSQuizExerciseModule } from './quiz-exercise/quiz-exercise.module';
import { ArTEMiSParticipationModule } from './participation/participation.module';
import { ArTEMiSProgrammingExerciseModule } from './programming-exercise/programming-exercise.module';
import { ArTEMiSModelingExerciseModule } from './modeling-exercise/modeling-exercise.module';
import { ArTEMiSResultModule } from 'app/entities/result';
import { ArTEMiSTextExerciseModule } from './text-exercise/text-exercise.module';
import { ArTEMiSFileUploadExerciseModule } from './file-upload-exercise/file-upload-exercise.module';
import { ArtemisLectureModule } from 'app/entities/lecture/lecture.module';
/* jhipster-needle-add-entity-module-import - JHipster will add entity modules imports here */
@NgModule({
imports: [
ArTEMiSCourseModule,
ArTEMiSExerciseModule,
ArTEMiSQuizExerciseModule,
ArTEMiSParticipationModule,
ArTEMiSProgrammingExerciseModule,
ArTEMiSModelingExerciseModule,
ArTEMiSResultModule,
ArTEMiSTextExerciseModule,
ArTEMiSFileUploadExerciseModule,
ArtemisLectureModule,
/* jhipster-needle-add-entity-module - JHipster will add entity modules here */
],
declarations: [],
entryComponents: [],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class ArTEMiSEntityModule {}
| mit |
pacopablo/gp10 | gp10/__init__.py | 822 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009 John Hampton <pacopablo@pacopablo.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# Author: John Hampton <pacopablo@pacopablo.com>
# Third Party Imports
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()
class UnboundMetadataError(Exception):
pass
def get_session():
""" Return a session
The metadata.bind property of the Base class must be set prior to calling
the function.
"""
if Base.metadata.bind:
engine = Base.metadata.bind
else:
raise UnboundMetadataError
sm = sessionmaker(bind=engine)
return scoped_sesison(sm)
| mit |
Teknologica/js-sdk | src/resources/blacklists-resource.js | 740 | export default function BlacklistsResource({apiHandler}) {
return {
async getAll({limit = null, offset = null, sort = null, q = null, filter = null} = {}) {
const params = {
limit,
offset,
sort,
q,
filter
};
return await apiHandler.getAll(`blacklists`, params);
},
async get({id}) {
return await apiHandler.get(`blacklists/${id}`);
},
async create({id = '', data}) {
return await apiHandler.create(`blacklists/${id}`, id, data);
},
async delete({id}) {
return await apiHandler.delete(`blacklists/${id}`);
}
};
};
| mit |
activecollab/promises | src/Promise/Promise.php | 967 | <?php
/*
* This file is part of the Active Collab Promises.
*
* (c) A51 doo <info@activecollab.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace ActiveCollab\Promises\Promise;
use InvalidArgumentException;
/**
* @package ActiveCollab\Promises\Promise
*/
class Promise implements PromiseInterface
{
/**
* @var string
*/
private $signature;
/**
* @param string $signature
*/
public function __construct($signature)
{
if (empty($signature)) {
throw new InvalidArgumentException("Promise signature can't be empty");
}
$this->signature = (string) $signature;
}
/**
* {@inheritdoc}
*/
public function getSignature()
{
return $this->signature;
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->signature;
}
}
| mit |
rlbaltha/engDept | src/English/DonateBundle/Controller/DonateController.php | 6112 | <?php
namespace English\DonateBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use English\DonateBundle\Entity\Donate;
use English\DonateBundle\Form\DonateType;
/**
* Donate controller.
*
* @Route("/donate")
*/
class DonateController extends Controller
{
/**
* Lists all Donate entities.
*
* @Route("/", name="donate")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$dql1 = "SELECT d FROM EnglishDonateBundle:Donate d ORDER BY d.sortorder";
$funds = $em->createQuery($dql1)->getResult();
return array('funds' => $funds);
}
/**
* Finds and displays a Donate entity.
*
* @Route("/{id}/show", name="donate_show")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$fund = $em->getRepository('EnglishDonateBundle:Donate')->find($id);
if (!$fund) {
throw $this->createNotFoundException('Unable to find Donate entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'fund' => $fund,
'delete_form' => $deleteForm->createView(), );
}
/**
* Displays a form to create a new Donate entity.
*
* @Route("/new", name="donate_new")
* @Template()
*/
public function newAction()
{
if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
$fund = new Donate();
$form = $this->createForm(new DonateType(), $fund);
return array(
'fund' => $fund,
'form' => $form->createView()
);
}
/**
* Creates a new Donate entity.
*
* @Route("/create", name="donate_create")
* @Method("post")
* @Template("EnglishDonateBundle:Donate:new.html.twig")
*/
public function createAction()
{
if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
$fund = new Donate();
$request = $this->getRequest();
$form = $this->createForm(new DonateType(), $fund);
$form->submit($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($fund);
$em->flush();
return $this->redirect($this->generateUrl('donate', array('id' => $fund->getId())));
}
return array(
'fund' => $fund,
'form' => $form->createView()
);
}
/**
* Displays a form to edit an existing Donate entity.
*
* @Route("/{id}/edit", name="donate_edit")
* @Template()
*/
public function editAction($id)
{
if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
$em = $this->getDoctrine()->getManager();
$fund = $em->getRepository('EnglishDonateBundle:Donate')->find($id);
if (!$fund) {
throw $this->createNotFoundException('Unable to find Donate entity.');
}
$editForm = $this->createForm(new DonateType(), $fund);
$deleteForm = $this->createDeleteForm($id);
return array(
'fund' => $fund,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Edits an existing Donate entity.
*
* @Route("/{id}/update", name="donate_update")
* @Method("post")
* @Template("EnglishDonateBundle:Donate:edit.html.twig")
*/
public function updateAction($id)
{
if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
$em = $this->getDoctrine()->getManager();
$fund = $em->getRepository('EnglishDonateBundle:Donate')->find($id);
if (!$fund) {
throw $this->createNotFoundException('Unable to find Donate entity.');
}
$editForm = $this->createForm(new DonateType(), $fund);
$deleteForm = $this->createDeleteForm($id);
$request = $this->getRequest();
$editForm->submit($request);
if ($editForm->isValid()) {
$em->persist($fund);
$em->flush();
return $this->redirect($this->generateUrl('donate', array('id' => $id)));
}
return array(
'fund' => $fund,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Donate entity.
*
* @Route("/{id}/delete", name="donate_delete")
* @Method("post")
*/
public function deleteAction($id)
{
if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
$form = $this->createDeleteForm($id);
$request = $this->getRequest();
$form->submit($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$fund = $em->getRepository('EnglishDonateBundle:Donate')->find($id);
if (!$fund) {
throw $this->createNotFoundException('Unable to find Donate entity.');
}
$em->remove($fund);
$em->flush();
}
return $this->redirect($this->generateUrl('donate'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
| mit |
selesse/WineDB | src/main/java/com/selesse/android/winedb/activity/SingleWineViewActivity.java | 4475 | package com.selesse.android.winedb.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.selesse.android.winedb.R;
import com.selesse.android.winedb.database.Wine;
import com.selesse.android.winedb.database.WineDatabaseHandler;
import com.selesse.android.winedb.model.RequestCode;
public class SingleWineViewActivity extends ActionBarActivity {
private static final String TAG = SingleWineViewActivity.class.getSimpleName();
private ViewPager viewPager;
private Wine wine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_wine);
int position = 0;
Bundle args = getIntent().getExtras();
if (args != null) {
position = args.getInt("position", 0);
}
WineCollectionPagerAdapter wineCollectionPagerAdapter =
new WineCollectionPagerAdapter(getSupportFragmentManager(), this);
viewPager = (ViewPager) findViewById(R.id.wine_pager);
viewPager.setAdapter(wineCollectionPagerAdapter);
viewPager.setCurrentItem(position);
// remove the icon from the ActionBar
getSupportActionBar().setIcon(new ColorDrawable(android.R.color.transparent));
}
@Override
protected void onResume() {
super.onResume();
getSupportActionBar().setIcon(new ColorDrawable(android.R.color.transparent));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.single_wine, menu);
return true;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long savedId = savedInstanceState.getLong("id");
if (savedId != 0) {
wine = WineDatabaseHandler.getInstance(this).getWine(savedId);
Log.i(TAG, "Restoring " + wine.getName());
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (wine != null && wine.getId() > 0) {
Log.i(TAG, "Saving " + wine.getName());
outState.putLong("id", wine.getId());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
viewPager.getAdapter().notifyDataSetChanged();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
wine = WineDatabaseHandler.getInstance(this).getWineNumber(viewPager.getCurrentItem());
Log.i(TAG, "Selected options for " + wine.getName());
switch (item.getItemId()) {
case R.id.edit_wine_button:
Intent intent = new Intent(this, CreateOrEditWineActivity.class);
intent.putExtra("id", wine.getId());
startActivityForResult(intent, RequestCode.EDIT_WINE.ordinal());
return true;
case R.id.delete_wine_button:
confirmDeleteDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void confirmDeleteDialog() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.confirm_delete).setMessage(R.string.confirm_delete_message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
WineDatabaseHandler.getInstance(getApplicationContext()).removeWine(wine);
viewPager.getAdapter().notifyDataSetChanged();
if (viewPager.getAdapter().getCount() == 0) {
finish();
}
}
}).setNegativeButton(R.string.no, null).show();
}
} | mit |
foxnewsnetwork/arrows | spec/spec_helper.rb | 217 | # TODO: move the specs in also lol
require 'pry'
require File.expand_path("../../lib/arrows", __FILE__)
module Composable
def compose(f, g)
-> (x) { f.(g.(x)) }
end
def *(g)
compose(self, g)
end
end
| mit |
terraria-crafting/tui | src/app/search/index.js | 188 | import angular from 'angular';
import {searchBar} from './searchBar';
export const searchModule = 'search';
angular
.module(searchModule, [])
.component('tcSearch', searchBar);
| mit |
c14410312/FrenchMadeEasy | src/CurrentCategory.java | 177 | public class CurrentCategory {
String fr;
String eng;
CurrentCategory(String line){
String[] parts = line.split(",");
fr = parts[0];
eng = parts[1];
}
}
| mit |
theill/billedid | test/functional/photos_controller_test.rb | 84 | require 'test_helper'
class PhotosControllerTest < ActionController::TestCase
end
| mit |
enlim/core | app/Http/Controllers/VisitTransfer/Site/Reference.php | 1581 | <?php
namespace App\Http\Controllers\VisitTransfer\Site;
use App\Http\Controllers\BaseController;
use App\Http\Requests\VisitTransfer\ReferenceSubmitRequest;
use App\Models\Sys\Token;
use Exception;
use Input;
use Redirect;
class Reference extends BaseController
{
public function getComplete(Token $token)
{
$reference = $token->related;
$this->authorize('complete', $reference);
return $this->viewMake('visit-transfer.site.reference.complete')
->with('token', $token)
->with('reference', $reference)
->with('application', $reference->application);
}
public function postComplete(ReferenceSubmitRequest $request, Token $token)
{
$reference = $token->related;
try {
$reference->submit(Input::get('reference'));
$token->consume();
} catch (Exception $e) {
dd($e);
return Redirect::route('visiting.reference.complete', [$token->code])->withError($e->getMessage());
}
return Redirect::route('visiting.landing')->withSuccess('You have successfully completed a reference for '.$reference->application->account->name.'. Thank you.');
}
public function postCancel(Token $token)
{
$reference = $token->related;
$reference->cancel();
$reference->application->markAsUnderReview();
return Redirect::route('visiting.landing')->withSuccess('You have canceled your reference for '.$reference->application->account->name.'. Thank you.');
}
}
| mit |
scalableminds/scala-presseportal | src/main/scala/com/scalableminds/presseportal/PressePortalJSONProtocol.scala | 2785 | package com.scalableminds.presseportal
import org.joda.time.DateTime
import play.api.libs.json._
import play.api.libs.functional.syntax._
trait APIResult { val success: Boolean }
case class APISuccess(success: Boolean, request: RequestInfo, content: List[Article]) extends APIResult
case class APIFailure(success: Boolean, error: APIError) extends APIResult
case class APIError(code: String, msg: String)
case class RequestInfo(uri: String, start: Int, limit: Int, format: String)
case class Article(id: String,
url: String,
title: String,
body: String,
published: DateTime,
language: String,
ressort: String,
company: Company,
keywords: List[String])
case class Company(id: String, name: String)
case class KeyWordObject(keyword: List[String])
object PressePortalJsonProtocol {
def statusReads(implicit r: Reads[String]): Reads[Boolean] = r.map(status => if (status == "1") true else false)
def stringToIntReads(implicit r: Reads[String]): Reads[Int] = r.map(s => s.toInt)
def stringToDateReads(implicit r: Reads[String]): Reads[DateTime] = r.map(s => DateTime.parse(s))
def emptyStringToEmptyList(implicit r: Reads[String]): Reads[List[String]] = r.map(s => List[String]())
def flattenKeyWordObject(implicit r: Reads[KeyWordObject]): Reads[List[String]] = r.map(kwo => kwo.keyword)
implicit val keyWordObjectReads: Reads[KeyWordObject] = Json.reads[KeyWordObject]
implicit val companyReads: Reads[Company] = Json.reads[Company]
implicit val apiErrorReads: Reads[APIError] = Json.reads[APIError]
implicit val articleReads = (
(__ \ "id").read[String] and
(__ \ "url").read[String] and
(__ \ "title").read[String] and
(__ \ "body").read[String] and
(__ \ "published").read(stringToDateReads) and
(__ \ "language").read[String] and
(__ \ "ressort").read[String] and
(__ \ "company").read[Company] and
(__ \ "keywords").read(flattenKeyWordObject or emptyStringToEmptyList))(Article)
implicit val requestInfoReads = (
(__ \ "uri").read[String] and
(__ \ "start").read(stringToIntReads) and
(__ \ "limit").read(stringToIntReads) and
(__ \ "format").read[String])(RequestInfo)
val apiSuccessReads: Reads[APIResult] = (
(__ \ "success").read(statusReads) and
(__ \ "request").read[RequestInfo] and
(__ \ "content" \ "story").read[List[Article]])(APISuccess)
val apiFailureReads: Reads[APIResult] = (
(__ \ "success").read(statusReads) and
(__ \ "error").read[APIError])(APIFailure)
implicit val apiResultReads: Reads[APIResult] = (
(__).read(apiSuccessReads or apiFailureReads))
}
object PressePortalProperJsonFormat {
implicit val companyFormat: Format[Company] = Json.format[Company]
implicit val articleFormat: Format[Article] = Json.format[Article]
}
| mit |
tulios/kafkajs | src/consumer/offsetManager/__tests__/isInvalidOffset.spec.js | 809 | const isInvalidOffset = require('../isInvalidOffset')
describe('Consumer > OffsetMananger > isInvalidOffset', () => {
it('returns true for negative offsets', () => {
expect(isInvalidOffset(-1)).toEqual(true)
expect(isInvalidOffset('-1')).toEqual(true)
expect(isInvalidOffset(-2)).toEqual(true)
expect(isInvalidOffset('-3')).toEqual(true)
})
it('returns true for blank values', () => {
expect(isInvalidOffset(null)).toEqual(true)
expect(isInvalidOffset(undefined)).toEqual(true)
expect(isInvalidOffset('')).toEqual(true)
})
it('returns false for positive offsets', () => {
expect(isInvalidOffset(0)).toEqual(false)
expect(isInvalidOffset(1)).toEqual(false)
expect(isInvalidOffset('2')).toEqual(false)
expect(isInvalidOffset('3')).toEqual(false)
})
})
| mit |
CS2103JAN2017-F14-B3/main | src/test/java/onlythree/imanager/model/task/NameTest.java | 1653 | package onlythree.imanager.model.task;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class NameTest {
//@@author A0140023E
@Test
public void isValidName_invalidName_falseReturned() {
assertFalse(Name.isValidName("")); // empty string
assertFalse(Name.isValidName(" ")); // space only (0x20)
assertFalse(Name.isValidName("\t")); // tab only
assertFalse(Name.isValidName("\n")); // new line only
assertFalse(Name.isValidName("\u000B")); // Vertical tab only
assertFalse(Name.isValidName("\f")); // form feed only
assertFalse(Name.isValidName("\r")); // carriage return only
assertFalse(Name.isValidName("//")); // only slashes
assertFalse(Name.isValidName("fetch colleague/boss")); // contains forward slashes
}
@Test
public void isValidName_validName_trueReturned() {
assertTrue(Name.isValidName("assignment")); // alphabets only
assertTrue(Name.isValidName("12345")); // numbers only
assertTrue(Name.isValidName("2nd draft")); // alphanumeric characters
assertTrue(Name.isValidName("Software Engineering Exam")); // with capital letters
assertTrue(Name.isValidName("Super duper the long task")); // long names
assertTrue(Name.isValidName("#$!$#!$!@#$!@!~@~!")); // tons of random symbols
assertTrue(Name.isValidName("Whee~~~~")); // alphabets with symbols
assertTrue(Name.isValidName("Omg!!")); // alphabets with symbols
assertTrue(Name.isValidName("你好吗?")); // Valid UTF-16 string with symbols
}
}
| mit |
mathiasbynens/unicode-data | 4.0.1/blocks/Tai-Le-regex.js | 108 | // Regular expression that matches all symbols in the Tai Le block as per Unicode v4.0.1:
/[\u1950-\u197F]/; | mit |
yunta-mb/dashboard | config/application.rb | 1046 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Dashboard
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
#config.middleware.use Faye::RackAdapter, mount: '/live', timeout: 25
end
end
| mit |
tonikarttunen/tonikarttunen-com | src/components/MenuToggle/MenuToggle.js | 991 | // MenuToggle
import React from 'react/addons';
import styles from './MenuToggle.less';
import withStyles from '../../decorators/withStyles';
import MenuActions from '../../actions/MenuActions';
const MenuToggleInternal = React.createClass({
propTypes: {
isOpen: React.PropTypes.bool
},
getDefaultProps: () => {
return {
isOpen: false
};
},
openMenu() {
MenuActions.openMenu(true);
},
closeMenu() {
MenuActions.openMenu(false);
},
render() {
const arrow = this.props.isOpen ? 'ion-arrow-up-b' : 'ion-arrow-down-b';
const menuToggleAction = this.props.isOpen ? this.closeMenu : this.openMenu;
return (
<div className='MenuToggleContainer visible-sm visible-xs'>
<span className='NavigationLink MenuToggle' onClick={() => { menuToggleAction(); }}>
Menu <span className={arrow}/>
</span>
</div>
);
}
});
@withStyles(styles)
export default class MenuToggle extends MenuToggleInternal {}
| mit |
rahulpneo/symfonyAdminPanel | app/cache/prod/twig/42/4248f4ac595644236d0b2658b3857e212e06b90dc2cf79527627d754342203fa.php | 1385 | <?php
/* @Framework/Form/range_widget.html.php */
class __TwigTemplate_8800f2ed6e14f89deae53b0e4e79f2b5ddd9269e85bf269ac16b7c74c70bbbb7 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<?php echo \$view['form']->block(\$form, 'form_widget_simple', array('type' => isset(\$type) ? \$type : 'range'));
";
}
public function getTemplateName()
{
return "@Framework/Form/range_widget.html.php";
}
public function getDebugInfo()
{
return array ( 19 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("", "@Framework/Form/range_widget.html.php", "/var/www/html/symfonyAdminPanel/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/range_widget.html.php");
}
}
| mit |
chjj/dilated | lib/utils.js | 3094 | /**
* dilated: utils.js
* Copyright (c) 2011-2014, Christopher Jeffrey (MIT License)
*/
/**
* Utilities
*/
var crypto = require('crypto');
exports.hash = function(str) {
return crypto
.createHash('sha256')
.update(str)
.digest('hex');
};
exports.escapeHTML = function(html, once) {
return (html || '')
.replace(once ? /&(?![^\s;]+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
/**
* Time Functions
*/
exports.date = function(date) {
if (!date.getUTCFullYear) {
date = new Date(date);
}
date = date
.toLocaleDateString()
.split(/,\s+|\s+/);
date = {
day: date[0],
month: date[1],
date: date[2],
year: date[3]
};
return date.month
+ ' ' + date.date
+ ', ' + date.year;
};
exports.time = function(date) {
if (!date.getUTCFullYear) {
date = new Date(date);
}
var hours = +date.getHours()
, minutes = date.getMinutes().toString()
, meridiem = hours < 12 ? 'am' : 'pm';
if (hours === 0) hours = 12;
if (hours > 12) hours -= 12;
if (minutes.length < 2) minutes = '0' + '' + minutes;
return hours + ':' + minutes + ' ' + meridiem;
};
exports.datetime = function(date) {
return exports.date(date)
+ ' ' + exports.time(date);
};
exports.prettyTime = function(time) {
var date = time.getUTCFullYear ? time : new Date(time)
, sec = Math.floor(new Date(Date.now() - date) / 1000)
, days = Math.floor(sec / 86400);
if (days === 0) {
if (sec <= 1) {
return '1 second ago';
}
if (sec < 60) {
return sec + ' seconds ago';
}
if (sec < 120) {
return '1 minute ago';
}
if (sec < 3600) {
return Math.floor(sec / 60)
+ ' minutes ago';
}
if (sec < 7200) {
return '1 hour ago';
}
return Math.floor(sec / 3600)
+ ' hours ago';
}
if (days < 31) {
if (days === 1) {
return 'Yesterday';
}
if (days < 14) {
return days + ' days ago';
}
return Math.floor(days / 7)
+ ' weeks ago';
}
if (days >= 31) {
var months = Math.floor(days / 31);
if (months === 1) {
return '1 month ago';
}
if (months >= 12) {
var years = Math.floor(months / 12);
if (years === 1) {
return '1 year ago';
}
return years + ' years ago';
}
return months + ' months ago';
}
};
/**
* Markdown
*/
exports.markdown = (function() {
var marked = require('marked');
return function(text) {
return marked(text);
};
})();
/**
* Async
*/
exports.forEach = function(obj, iter, done) {
var pending = obj.length
, err;
function next(e) {
if (e) err = e;
if (!--pending) done(err);
}
return obj.forEach(function(item, i) {
return iter(item, next, i);
});
};
exports.forEachSeries = function(obj, iter, done) {
var i = 0;
(function next(err) {
if (err) return done(err);
var item = obj[i++];
if (!item) return done();
return iter(item, next, i - 1);
})();
};
| mit |
SYCstudio/OI | Practice/2018/2018.7.30/BZOJ5130.cpp | 961 | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=14;
const int Mod=998244353;
const int inf=2147483647;
int n,m;
int St[maxN],Next[maxN];
int Ans=0,Cnt[maxN];
void dfs(int depth,int limit);
int GetNext();
int main()
{
scanf("%d%d",&n,&m);
Cnt[0]=1;
for (int i=1;i<=n;i++) Cnt[i]=1ll*Cnt[i-1]*(m-i+1)%Mod;
dfs(1,0);
printf("%d\n",Ans);
return 0;
}
void dfs(int depth,int limit){
if (depth>n){
Ans=(Ans+1ll*Cnt[limit]*GetNext()%Mod)%Mod;
return;
}
for (int i=1;i<=limit;i++){
St[depth]=i;dfs(depth+1,limit);
}
St[depth]=limit+1;dfs(depth+1,limit+1);
return;
}
int GetNext(){
Next[0]=Next[1]=0;
for (int i=2,j=0;i<=n;i++){
while ((j!=0)&&(St[j+1]!=St[i])) j=Next[j];
if (St[j+1]==St[i]) j++;
Next[i]=j;
}
int ret=1;
for (int i=1;i<=n;i++) ret=1ll*ret*(i-Next[i])%Mod;
return ret;
}
| mit |
vicobu/DistributedSystem | src/main/scala/actors/node/protocol/how/HowAlgorithm.scala | 860 | /**
* @author Victor Caballero (vicaba)
* @author Xavier Domingo (xadobu)
*/
package actors.node.protocol.how
/**
* HowAlgorithm companion object. Defines three actions with the transactions.
* Active: execute the transaction and replicate the result.
* Passive: Replicate the transaction and execute it.
* Core: Save the transaction into the DataBase
*/
object HowAlgorithm {
val Active = "Active"
val Passive = "Passive"
val Core = "Core"
}
/**
* Trait to define The replication policy of a node.
*/
trait HowAlgorithm {
protected val how: String
}
/**
* Active policy.
*/
trait Active extends HowAlgorithm {
val how = HowAlgorithm.Active
}
/**
* Passive policy.
*/
trait Passive extends HowAlgorithm {
val how = HowAlgorithm.Passive
}
/**
* Core policy.
*/
trait Core extends HowAlgorithm {
val how = HowAlgorithm.Core
}
| mit |
EconocomGrenoble/MvvX.Plugins.Open-XML-SDK | src/OpenXMLSDK.Engine/Word/ReportEngine/Models/UniformGrid.cs | 1245 | namespace OpenXMLSDK.Engine.Word.ReportEngine.Models
{
/// <summary>
/// Uniform Grid
/// </summary>
public class UniformGrid : Table
{
/// <summary>
/// Model of each cell
/// </summary>
public Cell CellModel { get; set; }
/// <summary>
/// Indicate if rows can be splited in multiple pages
/// </summary>
public bool CantSplitRows { get; set; }
/// <summary>
/// Key indicating the number of column for spliting the grid
/// </summary>
public string ColumnNumberKey { get; set; }
/// <summary>
/// Key indicating if there are column Headers
/// </summary>
public string AreColumnHeadersKey { get; set; }
/// <summary>
/// Key indicating if there are row Headers
/// </summary>
public string AreRowHeadersKey { get; set; }
/// <summary>
/// Headers background color in hex value (RRGGBB format)
/// </summary>
public string HeadersColor { get; set; }
/// <summary>
/// Constructor
/// </summary>
public UniformGrid()
: base(typeof(UniformGrid).Name)
{
}
}
}
| mit |
ahansb/BeerApp | Source/Data/BeerApp.Data.Models/VoteType.cs | 146 | namespace BeerApp.Data.Models
{
public enum VoteType
{
Negative = -1,
Neutral = 0,
Positive = 1
}
} | mit |
tijhaart/webpack-foundation | src/components/todo/todo-editor/todo-editor.controller.js | 3178 | import Rx from 'rx';
import _ from 'lodash';
import u from 'updeep';
import angular from 'angular';
import classNames from 'classnames';
export default class TodoEditorController {
constructor($ngRedux, $element, $scope, TodoDataService) {
'ngInject';
const ctrl = this;
activate();
function activate() {
// @TODO use ctrl.setState
ctrl.state = {
isContentEditable: !!ctrl.isContentEditable,
isNewItem: !!ctrl.isNewItem,
isFocused: false,
};
ctrl.mutableItem = angular.copy(ctrl.item || {});
ctrl.classList = {};
handleInputEvents();
handleClasslists();
}
ctrl.saveTodo = _.curry(_saveTodo)({ $ngRedux, ctrl, TodoDataService });
ctrl.remove = () => _remove({ TodoDataService, ctrl });
ctrl.onTitleInputKeyEvent = _.curry(_onTitleInputKeyEvent)({ ctrl });
function handleInputEvents() {
const onInputFocus$ = Rx.Observable.fromEvent($element.find('input'), 'focus blur');
const observer = onInputFocus$
// @TODO Implement ctrl.setState
.map(({type}) => {
return u({
isFocused: type === 'focus'
}, ctrl.state);
})
.do((x) => {
ctrl.state = x;
})
.do(() => {
$scope.$digest();
})
.subscribe()
;
$scope.$on('$destroy', observer.dispose.bind(observer));
}
function handleClasslists() {
Object.defineProperty(ctrl.classList, 'submitBtn', {
get: () => classNames({
'disabled _is_disabled': ctrl.todoItemForm.$invalid || ctrl.todoItemForm.$pristine
})
});
Object.defineProperty(ctrl.classList, 'clearBtn', {
get: () => classNames({
'disabled _is_disabled': ctrl.todoItemForm.$pristine || _.isEmpty(ctrl.mutableItem.title)
})
});
Object.defineProperty(ctrl.classList, 'removeBtn', {
get: () => classNames({
'_is_hidden': !ctrl.state.isFocused
})
});
}
}
submit() {
const ctrl = this;
if (ctrl.todoItemForm.$invalid) {
// @TODO Inform user
return;
}
ctrl.saveTodo(ctrl.mutableItem);
ctrl.reset();
}
reset() {
const ctrl = this;
// reset field when not saving an existing item
if (!ctrl.item) {
ctrl.mutableItem = {};
}
}
}
function _onTitleInputKeyEvent({ ctrl }, { which: keyCode, type }) {
const actions = {
// 13: Enter
13: ctrl.submit,
// 27: Esc
27: ctrl.reset
};
const action = actions[keyCode];
action && action.call(ctrl);
}
function _saveTodo({ $ngRedux, ctrl, TodoDataService }, item) {
const { ordering: todoItemsOrdering } = $ngRedux.getState().todos;
if (ctrl.isNewItem) {
TodoDataService.addItem(item);
} else {
TodoDataService.saveItem(item);
}
// @NOTE Should middleware be responsible for reordering?
const { orderProp, order } = todoItemsOrdering;
$ngRedux.dispatch({
type: 'TODO_ITEMS_ORDER_BY',
payload: { orderProp, order }
});
}
function _remove({ TodoDataService, ctrl }) {
TodoDataService.removeItem(
ctrl.mutableItem.id || ctrl.item.id
);
}
| mit |
davidlung/vection | src/Common/ArrayObject.php | 8021 | <?php
namespace Vection\Common;
/**
* Class ArrayObject
* @package Vection\Common
*/
class ArrayObject implements \ArrayAccess, \JsonSerializable, \Serializable, \Countable
{
/** @var array */
protected $data;
/**
* ArrayObject constructor.
* @param array $data
*/
public function __construct(array $data = [])
{
$this->data = $data;
}
/**
* @param $index
* @return mixed|null
*/
public function get($index)
{
return $this->data[$index] ?? null;
}
/**
* @param $index
* @param $value
*/
public function set($index, $value)
{
$this->data[$index] = $value;
}
/**
* @return array
*/
public function toArray()
{
return $this->data;
}
/**
* @TODO Array contains recursive
* @param $element
* @param bool $recursive
* @return bool
*/
public function contain($element, $recursive = false)
{
return in_array($element, $this->data);
}
/**
* @param $key
* @return bool
*/
public function has($key)
{
return array_key_exists($key, $this->data);
}
///////////////////////////////////////////////////////////////////////////
// region | Interface ArrayAccess
///////////////////////////////////////////////////////////////////////////
/**
* Whether a offset exists
* @link http://php.net/manual/en/arrayaccess.offsetexists.php
* @param mixed $offset <p>
* An offset to check for.
* </p>
* @return boolean true on success or false on failure.
* </p>
* <p>
* The return value will be casted to boolean if non-boolean was returned.
* @since 5.0.0
*/
public function offsetExists($offset)
{
return array_key_exists($offset, $this->data);
}
/**
* Offset to retrieve
* @link http://php.net/manual/en/arrayaccess.offsetget.php
* @param mixed $offset <p>
* The offset to retrieve.
* </p>
* @return mixed Can return all value types.
* @since 5.0.0
*/
public function offsetGet($offset)
{
return $this->data[$offset] ?? null;
}
/**
* Offset to set
* @link http://php.net/manual/en/arrayaccess.offsetset.php
* @param mixed $offset <p>
* The offset to assign the value to.
* </p>
* @param mixed $value <p>
* The value to set.
* </p>
* @return void
* @since 5.0.0
*/
public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
}
/**
* Offset to unset
* @link http://php.net/manual/en/arrayaccess.offsetunset.php
* @param mixed $offset <p>
* The offset to unset.
* </p>
* @return void
* @since 5.0.0
*/
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
// endregion | ArrayAccess Interface
///////////////////////////////////////////////////////////////////////////
// region | Interface JsonSerializable
///////////////////////////////////////////////////////////////////////////
/**
* Specify data which should be serialized to JSON
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
function jsonSerialize()
{
return $this->data;
}
// endregion | Interface JsonSerializable
///////////////////////////////////////////////////////////////////////////
// region | Interface Serializable
///////////////////////////////////////////////////////////////////////////
/**
* String representation of object
* @link http://php.net/manual/en/serializable.serialize.php
* @return string the string representation of the object or null
* @since 5.1.0
*/
public function serialize()
{
return json_encode($this->data);
}
/**
* Constructs the object
* @link http://php.net/manual/en/serializable.unserialize.php
* @param string $serialized <p>
* The string representation of the object.
* </p>
* @return void
* @since 5.1.0
*/
public function unserialize($serialized)
{
$this->data = json_decode($serialized, true);
}
// endregion | Static Serializable creation
///////////////////////////////////////////////////////////////////////////
// region | Interface Countable
///////////////////////////////////////////////////////////////////////////
/**
* Count elements of an object
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* </p>
* <p>
* The return value is cast to an integer.
* @since 5.1.0
*/
public function count()
{
return count($this->data);
}
// endregion | Interface Countable
///////////////////////////////////////////////////////////////////////////
// region | Magic methods
///////////////////////////////////////////////////////////////////////////
/**
* @return array
*/
public function __debugInfo()
{
return $this->data;
}
/**
* @param $name
* @return mixed|null
*/
public function __get($name)
{
return $this->get($name);
}
/**
* @param $name
* @param $value
*/
public function __set($name, $value)
{
$this->set($name, $value);
}
/**
* @return ArrayObject
*/
public function __clone()
{
return new ArrayObject($this->data);
}
// endregion | Magic methods
///////////////////////////////////////////////////////////////////////////
// region | Static ArrayList creation
///////////////////////////////////////////////////////////////////////////
/**
* @param string $path
* @return ArrayObject
* @throws \Exception
*/
public static function fromFile( string $path )
{
if( ! file_exists($path) ){
throw new \Exception("File not exists ($path)");
}
$data = [];
$extension = pathinfo($path, PATHINFO_EXTENSION);
if( $extension === 'json' ){
$data = json_decode( file_get_contents($path), true );
if( json_last_error() !== JSON_ERROR_NONE ){
throw new \Exception("JSON parse error in file ($path) - ".json_last_error_msg());
}
}
if( $extension === 'yml' || $extension === 'yaml' ){
if( ! extension_loaded('yaml') || ! function_exists('yaml_parse_file') ){
throw new \Exception('Could not parse YAML file - Please check PHP yaml extension.');
}
$data = yaml_parse_file($path);
if( ! $data ){
throw new \Exception("YAML parse error in file ($path)");
}
}
// TODO Other file type support
return new ArrayObject($data);
}
/**
* @param $object
* @return ArrayObject
*/
public static function fromObject( $object )
{
if( ! is_object($object) ){
throw new \InvalidArgumentException(__METHOD__." expected param 1 to be object, ".gettype($object)." given.");
}
if( $object instanceof \JsonSerializable){
$data = (array) $object->jsonSerialize();
return new ArrayObject($data);
}
if( method_exists($object, 'toArray') ){
return new ArrayObject($object->toArray());
}
return new ArrayObject(json_decode(json_encode($object), true));
}
/**
* @param string $input
*/
public static function fromInput( string $input )
{
// TODO Implementation
new ArrayObject();
}
// endregion | Static ArrayList creation
} | mit |
hiendv/octicons-modular | packages/octicons-modular/es/icons/telescope.js | 593 | import factory from '../octicon.js';
// This is an auto-generated ES2015 icon from the modularize script. Please do not modify this file.
var telescope = factory('telescope', 14, 16, {"fill-rule":"evenodd","d":"M8 9l3 6h-1l-2-4v5H7v-6l-2 5H4l2-5 2-1zM7 0H6v1h1V0zM5 3H4v1h1V3zM2 1H1v1h1V1zM.63 9a.52.52 0 0 0-.16.67l.55.92c.13.23.41.31.64.2l1.39-.66-1.16-2-1.27.86.01.01zm7.89-5.39l-5.8 3.95L3.95 9.7l6.33-3.03-1.77-3.06h.01zm4.22 1.28l-1.47-2.52a.51.51 0 0 0-.72-.17l-1.2.83 1.84 3.2 1.33-.64c.27-.13.36-.44.22-.7z"}, ["science","space","look","view","explore"]);
export default telescope;
| mit |
jiadaizhao/LeetCode | 0501-0600/0552-Student Attendance Record II/0552-Student Attendance Record II.cpp | 1624 | class Solution {
public:
int checkRecord(int n) {
int dp[1 + n][2][3] = {1, 1, 1, 1, 1, 1};
int m = 1000000007;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= 1; ++j) {
for (int k = 0; k <= 2; ++k) {
int val = dp[i - 1][j][2]; // P
if (k > 0) {
val = (val + dp[i - 1][j][k - 1]) % m; // L
}
if (j > 0) {
val = (val + dp[i - 1][j - 1][2]) % m; // A
}
dp[i][j][k] = val;
}
}
}
return dp[n][1][2];
}
};
// O(1) space
class Solution {
public:
int checkRecord(int n) {
int dp00 = 1, dp01 = 0, dp02 = 0, dp10 = 0, dp11 = 0, dp12 = 0;
int m = 1000000007;
for (int i = 1; i <= n; ++i) {
int t00 = ((long)dp00 + dp01 + dp02) % m; // Add P, new state: 0A, 0L
int t01 = dp00; // Add L, new state: 0A, 1L
int t02 = dp01; // Add L, new state: 0A, 2L
int t10 = ((long)dp00 + dp01 + dp02 + dp10 + dp11 + dp12) % m; // Add A or P, new state: 1A, 0L
int t11 = dp10; // Add L, new state: 1A, 1L
int t12 = dp11; // Add L, new state: 1A, 2L
dp00 = t00;
dp01 = t01;
dp02 = t02;
dp10 = t10;
dp11 = t11;
dp12 = t12;
}
return ((long)dp00 + dp01 + dp02 + dp10 + dp11 + dp12) % m;
}
};
| mit |
koobonil/Boss2D | Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/video_coding/video_sender_unittest.cc | 18367 | /*
* Copyright (c) 2013 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 <memory>
#include <vector>
#include BOSS_WEBRTC_U_api__video__i420_buffer_h //original-code:"api/video/i420_buffer.h"
#include BOSS_WEBRTC_U_modules__video_coding__codecs__vp8__include__vp8_h //original-code:"modules/video_coding/codecs/vp8/include/vp8.h"
#include BOSS_WEBRTC_U_modules__video_coding__codecs__vp8__temporal_layers_h //original-code:"modules/video_coding/codecs/vp8/temporal_layers.h"
#include "modules/video_coding/include/mock/mock_vcm_callbacks.h"
#include "modules/video_coding/include/mock/mock_video_codec_interface.h"
#include BOSS_WEBRTC_U_modules__video_coding__include__video_coding_h //original-code:"modules/video_coding/include/video_coding.h"
#include BOSS_WEBRTC_U_modules__video_coding__utility__default_video_bitrate_allocator_h //original-code:"modules/video_coding/utility/default_video_bitrate_allocator.h"
#include BOSS_WEBRTC_U_modules__video_coding__utility__simulcast_rate_allocator_h //original-code:"modules/video_coding/utility/simulcast_rate_allocator.h"
#include BOSS_WEBRTC_U_modules__video_coding__video_coding_impl_h //original-code:"modules/video_coding/video_coding_impl.h"
#include BOSS_WEBRTC_U_system_wrappers__include__clock_h //original-code:"system_wrappers/include/clock.h"
#include "test/frame_generator.h"
#include "test/gtest.h"
#include "test/testsupport/fileutils.h"
#include "test/video_codec_settings.h"
using ::testing::_;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::Field;
using ::testing::NiceMock;
using ::testing::Pointee;
using ::testing::Return;
using ::testing::FloatEq;
using std::vector;
using webrtc::test::FrameGenerator;
namespace webrtc {
namespace vcm {
namespace {
static const int kDefaultHeight = 720;
static const int kDefaultWidth = 1280;
static const int kMaxNumberOfTemporalLayers = 3;
static const int kNumberOfLayers = 3;
static const int kNumberOfStreams = 3;
static const int kUnusedPayloadType = 10;
struct Vp8StreamInfo {
float framerate_fps[kMaxNumberOfTemporalLayers];
int bitrate_kbps[kMaxNumberOfTemporalLayers];
};
MATCHER_P(MatchesVp8StreamInfo, expected, "") {
bool res = true;
for (int tl = 0; tl < kMaxNumberOfTemporalLayers; ++tl) {
if (fabs(expected.framerate_fps[tl] - arg.framerate_fps[tl]) > 0.5) {
*result_listener << " framerate_fps[" << tl
<< "] = " << arg.framerate_fps[tl] << " (expected "
<< expected.framerate_fps[tl] << ") ";
res = false;
}
if (abs(expected.bitrate_kbps[tl] - arg.bitrate_kbps[tl]) > 10) {
*result_listener << " bitrate_kbps[" << tl
<< "] = " << arg.bitrate_kbps[tl] << " (expected "
<< expected.bitrate_kbps[tl] << ") ";
res = false;
}
}
return res;
}
class EmptyFrameGenerator : public FrameGenerator {
public:
EmptyFrameGenerator(int width, int height) : width_(width), height_(height) {}
VideoFrame* NextFrame() override {
frame_.reset(new VideoFrame(I420Buffer::Create(width_, height_),
webrtc::kVideoRotation_0, 0));
return frame_.get();
}
private:
const int width_;
const int height_;
std::unique_ptr<VideoFrame> frame_;
};
class EncodedImageCallbackImpl : public EncodedImageCallback {
public:
explicit EncodedImageCallbackImpl(Clock* clock)
: clock_(clock), start_time_ms_(clock_->TimeInMilliseconds()) {}
virtual ~EncodedImageCallbackImpl() {}
Result OnEncodedImage(const EncodedImage& encoded_image,
const CodecSpecificInfo* codec_specific_info,
const RTPFragmentationHeader* fragmentation) override {
assert(codec_specific_info);
frame_data_.push_back(
FrameData(encoded_image._length, *codec_specific_info));
return Result(Result::OK, encoded_image._timeStamp);
}
void Reset() {
frame_data_.clear();
start_time_ms_ = clock_->TimeInMilliseconds();
}
float FramerateFpsWithinTemporalLayer(int temporal_layer) {
return CountFramesWithinTemporalLayer(temporal_layer) *
(1000.0 / interval_ms());
}
float BitrateKbpsWithinTemporalLayer(int temporal_layer) {
return SumPayloadBytesWithinTemporalLayer(temporal_layer) * 8.0 /
interval_ms();
}
Vp8StreamInfo CalculateVp8StreamInfo() {
Vp8StreamInfo info;
for (int tl = 0; tl < 3; ++tl) {
info.framerate_fps[tl] = FramerateFpsWithinTemporalLayer(tl);
info.bitrate_kbps[tl] = BitrateKbpsWithinTemporalLayer(tl);
}
return info;
}
private:
struct FrameData {
FrameData() : payload_size(0) {}
FrameData(size_t payload_size, const CodecSpecificInfo& codec_specific_info)
: payload_size(payload_size),
codec_specific_info(codec_specific_info) {}
size_t payload_size;
CodecSpecificInfo codec_specific_info;
};
int64_t interval_ms() {
int64_t diff = (clock_->TimeInMilliseconds() - start_time_ms_);
EXPECT_GT(diff, 0);
return diff;
}
int CountFramesWithinTemporalLayer(int temporal_layer) {
int frames = 0;
for (size_t i = 0; i < frame_data_.size(); ++i) {
EXPECT_EQ(kVideoCodecVP8, frame_data_[i].codec_specific_info.codecType);
const uint8_t temporal_idx =
frame_data_[i].codec_specific_info.codecSpecific.VP8.temporalIdx;
if (temporal_idx <= temporal_layer || temporal_idx == kNoTemporalIdx)
frames++;
}
return frames;
}
size_t SumPayloadBytesWithinTemporalLayer(int temporal_layer) {
size_t payload_size = 0;
for (size_t i = 0; i < frame_data_.size(); ++i) {
EXPECT_EQ(kVideoCodecVP8, frame_data_[i].codec_specific_info.codecType);
const uint8_t temporal_idx =
frame_data_[i].codec_specific_info.codecSpecific.VP8.temporalIdx;
if (temporal_idx <= temporal_layer || temporal_idx == kNoTemporalIdx)
payload_size += frame_data_[i].payload_size;
}
return payload_size;
}
Clock* clock_;
int64_t start_time_ms_;
vector<FrameData> frame_data_;
};
class TestVideoSender : public ::testing::Test {
protected:
// Note: simulated clock starts at 1 seconds, since parts of webrtc use 0 as
// a special case (e.g. frame rate in media optimization).
TestVideoSender() : clock_(1000), encoded_frame_callback_(&clock_) {}
void SetUp() override {
sender_.reset(new VideoSender(&clock_, &encoded_frame_callback_));
}
void AddFrame() {
assert(generator_.get());
sender_->AddVideoFrame(*generator_->NextFrame(), NULL);
}
SimulatedClock clock_;
EncodedImageCallbackImpl encoded_frame_callback_;
// Used by subclassing tests, need to outlive sender_.
std::unique_ptr<VideoEncoder> encoder_;
std::unique_ptr<VideoSender> sender_;
std::unique_ptr<FrameGenerator> generator_;
};
class TestVideoSenderWithMockEncoder : public TestVideoSender {
public:
TestVideoSenderWithMockEncoder() {}
~TestVideoSenderWithMockEncoder() override {}
protected:
void SetUp() override {
TestVideoSender::SetUp();
sender_->RegisterExternalEncoder(&encoder_, false);
webrtc::test::CodecSettings(kVideoCodecVP8, &settings_);
settings_.numberOfSimulcastStreams = kNumberOfStreams;
ConfigureStream(kDefaultWidth / 4, kDefaultHeight / 4, 100,
&settings_.simulcastStream[0]);
ConfigureStream(kDefaultWidth / 2, kDefaultHeight / 2, 500,
&settings_.simulcastStream[1]);
ConfigureStream(kDefaultWidth, kDefaultHeight, 1200,
&settings_.simulcastStream[2]);
settings_.plType = kUnusedPayloadType; // Use the mocked encoder.
generator_.reset(
new EmptyFrameGenerator(settings_.width, settings_.height));
EXPECT_EQ(0, sender_->RegisterSendCodec(&settings_, 1, 1200));
rate_allocator_.reset(new DefaultVideoBitrateAllocator(settings_));
}
void TearDown() override { sender_.reset(); }
void ExpectIntraRequest(int stream) {
ExpectEncodeWithFrameTypes(stream, false);
}
void ExpectInitialKeyFrames() { ExpectEncodeWithFrameTypes(-1, true); }
void ExpectEncodeWithFrameTypes(int intra_request_stream, bool first_frame) {
if (intra_request_stream == -1) {
// No intra request expected, keyframes on first frame.
FrameType frame_type = first_frame ? kVideoFrameKey : kVideoFrameDelta;
EXPECT_CALL(
encoder_,
Encode(_, _,
Pointee(ElementsAre(frame_type, frame_type, frame_type))))
.Times(1)
.WillRepeatedly(Return(0));
return;
}
ASSERT_FALSE(first_frame);
ASSERT_GE(intra_request_stream, 0);
ASSERT_LT(intra_request_stream, kNumberOfStreams);
std::vector<FrameType> frame_types(kNumberOfStreams, kVideoFrameDelta);
frame_types[intra_request_stream] = kVideoFrameKey;
EXPECT_CALL(
encoder_,
Encode(_, _,
Pointee(ElementsAreArray(&frame_types[0], frame_types.size()))))
.Times(1)
.WillRepeatedly(Return(0));
}
static void ConfigureStream(int width,
int height,
int max_bitrate,
SimulcastStream* stream) {
assert(stream);
stream->width = width;
stream->height = height;
stream->maxBitrate = max_bitrate;
stream->numberOfTemporalLayers = kNumberOfLayers;
stream->qpMax = 45;
}
VideoCodec settings_;
NiceMock<MockVideoEncoder> encoder_;
std::unique_ptr<DefaultVideoBitrateAllocator> rate_allocator_;
};
TEST_F(TestVideoSenderWithMockEncoder, TestIntraRequests) {
// Initial request should be all keyframes.
ExpectInitialKeyFrames();
AddFrame();
EXPECT_EQ(0, sender_->IntraFrameRequest(0));
ExpectIntraRequest(0);
AddFrame();
ExpectIntraRequest(-1);
AddFrame();
EXPECT_EQ(0, sender_->IntraFrameRequest(1));
ExpectIntraRequest(1);
AddFrame();
ExpectIntraRequest(-1);
AddFrame();
EXPECT_EQ(0, sender_->IntraFrameRequest(2));
ExpectIntraRequest(2);
AddFrame();
ExpectIntraRequest(-1);
AddFrame();
EXPECT_EQ(-1, sender_->IntraFrameRequest(3));
ExpectIntraRequest(-1);
AddFrame();
}
TEST_F(TestVideoSenderWithMockEncoder, TestSetRate) {
// Let actual fps be half of max, so it can be distinguished from default.
const uint32_t kActualFrameRate = settings_.maxFramerate / 2;
const int64_t kFrameIntervalMs = 1000 / kActualFrameRate;
const uint32_t new_bitrate_kbps = settings_.startBitrate + 300;
// Initial frame rate is taken from config, as we have no data yet.
VideoBitrateAllocation new_rate_allocation = rate_allocator_->GetAllocation(
new_bitrate_kbps * 1000, settings_.maxFramerate);
EXPECT_CALL(encoder_,
SetRateAllocation(new_rate_allocation, settings_.maxFramerate))
.Times(1)
.WillOnce(Return(0));
sender_->SetChannelParameters(new_bitrate_kbps * 1000, 0, 200,
rate_allocator_.get(), nullptr);
AddFrame();
clock_.AdvanceTimeMilliseconds(kFrameIntervalMs);
// Expect no call to encoder_.SetRates if the new bitrate is zero.
EXPECT_CALL(encoder_, SetRateAllocation(_, _)).Times(0);
sender_->SetChannelParameters(0, 0, 200, rate_allocator_.get(), nullptr);
AddFrame();
}
TEST_F(TestVideoSenderWithMockEncoder, TestIntraRequestsInternalCapture) {
// De-register current external encoder.
sender_->RegisterExternalEncoder(nullptr, false);
// Register encoder with internal capture.
sender_->RegisterExternalEncoder(&encoder_, true);
EXPECT_EQ(0, sender_->RegisterSendCodec(&settings_, 1, 1200));
// Initial request should be all keyframes.
ExpectInitialKeyFrames();
AddFrame();
ExpectIntraRequest(0);
EXPECT_EQ(0, sender_->IntraFrameRequest(0));
ExpectIntraRequest(1);
EXPECT_EQ(0, sender_->IntraFrameRequest(1));
ExpectIntraRequest(2);
EXPECT_EQ(0, sender_->IntraFrameRequest(2));
// No requests expected since these indices are out of bounds.
EXPECT_EQ(-1, sender_->IntraFrameRequest(3));
}
TEST_F(TestVideoSenderWithMockEncoder, TestEncoderParametersForInternalSource) {
// De-register current external encoder.
sender_->RegisterExternalEncoder(nullptr, false);
// Register encoder with internal capture.
sender_->RegisterExternalEncoder(&encoder_, true);
EXPECT_EQ(0, sender_->RegisterSendCodec(&settings_, 1, 1200));
// Update encoder bitrate parameters. We expect that to immediately call
// SetRates on the encoder without waiting for AddFrame processing.
const uint32_t new_bitrate_kbps = settings_.startBitrate + 300;
VideoBitrateAllocation new_rate_allocation = rate_allocator_->GetAllocation(
new_bitrate_kbps * 1000, settings_.maxFramerate);
EXPECT_CALL(encoder_, SetRateAllocation(new_rate_allocation, _))
.Times(1)
.WillOnce(Return(0));
sender_->SetChannelParameters(new_bitrate_kbps * 1000, 0, 200,
rate_allocator_.get(), nullptr);
}
TEST_F(TestVideoSenderWithMockEncoder,
NoRedundantSetChannelParameterOrSetRatesCalls) {
const uint8_t kLossRate = 4;
const uint8_t kRtt = 200;
const int64_t kRateStatsWindowMs = 2000;
const uint32_t kInputFps = 20;
int64_t start_time = clock_.TimeInMilliseconds();
// Expect initial call to SetChannelParameters. Rates are initialized through
// InitEncode and expects no additional call before the framerate (or bitrate)
// updates.
EXPECT_CALL(encoder_, SetChannelParameters(kLossRate, kRtt))
.Times(1)
.WillOnce(Return(0));
sender_->SetChannelParameters(settings_.startBitrate * 1000, kLossRate, kRtt,
rate_allocator_.get(), nullptr);
while (clock_.TimeInMilliseconds() < start_time + kRateStatsWindowMs) {
AddFrame();
clock_.AdvanceTimeMilliseconds(1000 / kInputFps);
}
// Call to SetChannelParameters with changed bitrate should call encoder
// SetRates but not encoder SetChannelParameters (that are unchanged).
uint32_t new_bitrate_bps = 2 * settings_.startBitrate * 1000;
VideoBitrateAllocation new_rate_allocation =
rate_allocator_->GetAllocation(new_bitrate_bps, kInputFps);
EXPECT_CALL(encoder_, SetRateAllocation(new_rate_allocation, kInputFps))
.Times(1)
.WillOnce(Return(0));
sender_->SetChannelParameters(new_bitrate_bps, kLossRate, kRtt,
rate_allocator_.get(), nullptr);
AddFrame();
}
class TestVideoSenderWithVp8 : public TestVideoSender {
public:
TestVideoSenderWithVp8()
: codec_bitrate_kbps_(300), available_bitrate_kbps_(1000) {}
void SetUp() override {
TestVideoSender::SetUp();
const char* input_video = "foreman_cif";
const int width = 352;
const int height = 288;
generator_ = FrameGenerator::CreateFromYuvFile(
std::vector<std::string>(1, test::ResourcePath(input_video, "yuv")),
width, height, 1);
codec_ = MakeVp8VideoCodec(width, height, 3);
codec_.minBitrate = 10;
codec_.startBitrate = codec_bitrate_kbps_;
codec_.maxBitrate = codec_bitrate_kbps_;
rate_allocator_.reset(new SimulcastRateAllocator(codec_));
encoder_ = VP8Encoder::Create();
sender_->RegisterExternalEncoder(encoder_.get(), false);
EXPECT_EQ(0, sender_->RegisterSendCodec(&codec_, 1, 1200));
}
static VideoCodec MakeVp8VideoCodec(int width,
int height,
int temporal_layers) {
VideoCodec codec;
webrtc::test::CodecSettings(kVideoCodecVP8, &codec);
codec.width = width;
codec.height = height;
codec.VP8()->numberOfTemporalLayers = temporal_layers;
return codec;
}
void InsertFrames(float framerate, float seconds) {
for (int i = 0; i < seconds * framerate; ++i) {
clock_.AdvanceTimeMilliseconds(1000.0f / framerate);
AddFrame();
// SetChannelParameters needs to be called frequently to propagate
// framerate from the media optimization into the encoder.
// Note: SetChannelParameters fails if less than 2 frames are in the
// buffer since it will fail to calculate the framerate.
if (i != 0) {
EXPECT_EQ(VCM_OK, sender_->SetChannelParameters(
available_bitrate_kbps_ * 1000, 0, 200,
rate_allocator_.get(), nullptr));
}
}
}
Vp8StreamInfo SimulateWithFramerate(float framerate) {
const float short_simulation_interval = 5.0;
const float long_simulation_interval = 10.0;
// It appears that this 5 seconds simulation is needed to allow
// bitrate and framerate to stabilize.
InsertFrames(framerate, short_simulation_interval);
encoded_frame_callback_.Reset();
InsertFrames(framerate, long_simulation_interval);
return encoded_frame_callback_.CalculateVp8StreamInfo();
}
protected:
VideoCodec codec_;
int codec_bitrate_kbps_;
int available_bitrate_kbps_;
std::unique_ptr<SimulcastRateAllocator> rate_allocator_;
};
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
#define MAYBE_FixedTemporalLayersStrategy DISABLED_FixedTemporalLayersStrategy
#else
#define MAYBE_FixedTemporalLayersStrategy FixedTemporalLayersStrategy
#endif
TEST_F(TestVideoSenderWithVp8, MAYBE_FixedTemporalLayersStrategy) {
const int low_b =
codec_bitrate_kbps_ *
webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(3, 0);
const int mid_b =
codec_bitrate_kbps_ *
webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(3, 1);
const int high_b =
codec_bitrate_kbps_ *
webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(3, 2);
{
Vp8StreamInfo expected = {{7.5, 15.0, 30.0}, {low_b, mid_b, high_b}};
EXPECT_THAT(SimulateWithFramerate(30.0), MatchesVp8StreamInfo(expected));
}
{
Vp8StreamInfo expected = {{3.75, 7.5, 15.0}, {low_b, mid_b, high_b}};
EXPECT_THAT(SimulateWithFramerate(15.0), MatchesVp8StreamInfo(expected));
}
}
} // namespace
} // namespace vcm
} // namespace webrtc
| mit |
DiabHelp/DiabHelp-Website | src/DH/APIBundle/Controller/ProchePatientController.php | 15175 | <?php
namespace DH\APIBundle\Controller;
use DH\APIBundle\Entity\ProchePatientLink;
use DH\APIBundle\Controller\CommonController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class ProchePatientController extends Controller
{
public function getAllPatientByUserIdAction(Request $request, $id_user) {
$encoders = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object;
});
$this->serializer = new Serializer(array($normalizer), array($encoders));
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHAPIBundle:ProchePatientLink');
$links = $repository->findByProche($id_user);
foreach ($links as $key => $link) {
$link->getPatient()->setPassword("");
$link->getPatient()->setSalt("");
$link->getProche()->setPassword("");
$link->getProche()->setSalt("");
}
if ($links == null) {
$errors[] = "Users not found";
$jsonContent = $this->serializer->serialize(array("success" => false, "errors" => $errors), 'json');
} else
$jsonContent = $this->serializer->serialize(array("success" => true, "users" => $links), 'json');
return new Response($jsonContent);
}
public function managePatientListAction(Request $request) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$this->serializer = new Serializer($normalizers, $encoders);
$errors = array();
$id_proche = $request->get('id_proche', null);
$id_patient = $request->get('id_patient', null);
$status = $request->get('status', null);
if ($id_proche == null)
$errors[] = "Missing id_proche";
if ($id_patient == null)
$errors[] = "Missing id_patient";
if ($status == null)
$errors[] = "Missing status";
if (count($errors) > 0) {
$resp = array("success" => false, "errors" => $errors);
$jsonContent = $this->serializer->serialize($resp, 'json');
return new Response($jsonContent);
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('DHAPIBundle:ProchePatientLink');
$link = $repo->findOneBy(array(
'proche' => $id_proche,
'patient' => $id_patient
));
if ($link == null) {
$link = new ProchePatientLink();
$user_repo = $em->getRepository('DHAPIBundle:User');
$proche = $user_repo->findOneById($id_proche);
$patient = $user_repo->findOneById($id_patient);
if ($proche == null)
$errors[] = "Proche not found";
if ($patient == null)
$errors[] = "Patient not found";
if (count($errors) > 0) {
$resp = array("success" => false, "errors" => $errors);
$jsonContent = $this->serializer->serialize($resp, 'json');
return new Response($jsonContent);
}
$link->setProche($proche);
$link->setPatient($patient);
$link->setStatus($status);
} else
$link->setStatus($status);
$em->persist($link);
$em->flush();
return new Response($this->serializer->serialize(array("success" => true), 'json'));
}
public function getPatientPositionAction(Request $request, $id_user) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$this->serializer = new Serializer($normalizers, $encoders);
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHUserBundle:User');
$user = $repository->find($id_user);
$errors = array();
if ($user == null) {
$errors[] = "User not found";
$response = array("success" => false, "errors" => $errors);
} else {
$position = $user->getPosition();
$response = array("success" => true, "position" => $position);
}
return new Response($this->serializer->serialize($response, 'json'));
}
public function alertAllProcheAction(Request $request, $id_patient) {
$encoders = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object;
});
$this->serializer = new Serializer(array($normalizer), array($encoders));
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHAPIBundle:ProchePatientLink');
$links = $repository->findByProche($id_patient);
$errors = array();
foreach ($links as $key => $link) {
$token = $link->getProche()->getGCMToken();
$message = $request->get('message', null);
// Send notif with message
$errors[] = "TROUVE";
}
if ($message == null)
$errors[] = "Missing message";
if ($links == null)
$errors[] = "Users not found";
if (count($errors > 0))
$jsonContent = $this->serializer->serialize(array("success" => false, "errors" => $errors), 'json');
else
$jsonContent = $this->serializer->serialize(array("success" => true), 'json');
return new Response($jsonContent);
}
public function alertOneProcheAction(Request $request, $id_patient, $id_proche) {
$encoders = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object;
});
$this->serializer = new Serializer(array($normalizer), array($encoders));
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHAPIBundle:ProchePatientLink');
$links = $repository->findByProche($id_patient);
$errors = array();
$message = $request->get('message', null);
foreach ($links as $key => $link) {
$token = $link->getProche()->getGCMToken();
if ($id_proche == $link->getProche()->getId())
// Send notif with message
$errors[] = "TROUVE";
}
if ($message == null)
$errors[] = "Missing message";
if ($links == null)
$errors[] = "Users not found";
if (count($errors > 0))
$jsonContent = $this->serializer->serialize(array("success" => false, "errors" => $errors), 'json');
else
$jsonContent = $this->serializer->serialize(array("success" => true), 'json');
return new Response($jsonContent);
}
public function searchPatientAction(Request $request, $id_user, $search) {
$encoders = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object;
});
$this->serializer = new Serializer(array($normalizer), array($encoders));
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHUserBundle:User');
$qb = $repository->createQueryBuilder('cm');
$qb->select('cm')
->where($qb->expr()->orX(
$qb->expr()->eq('cm.firstname', ':search'),
$qb->expr()->eq('cm.lastname', ':search'),
$qb->expr()->eq('cm.phone', ':search')
))
->setParameter('search', $search);
$users = $qb->getQuery()->getResult();
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHAPIBundle:ProchePatientLink');
$links = $repository->findByProche($id_user);
foreach ($users as $key_u => $user) {
foreach ($links as $key_l => $link) {
if ($user->getId() == $link->getPatient()->getId()) {
unset($users[$key_u]);
}
}
$user->setPassword("");
$user->setSalt("");
}
if ($users == null) {
$errors = array();
$errors[] = "Users not found";
$jsonContent = $this->serializer->serialize(array("success" => false, "errors" => $errors), 'json');
} else
$jsonContent = $this->serializer->serialize(array("success" => true, "users" => $users), 'json');
return new Response($jsonContent);
}
public function getAllProcheByUserIdAction(Request $request, $id_user) {
$encoders = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object;
});
$this->serializer = new Serializer(array($normalizer), array($encoders));
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHAPIBundle:ProchePatientLink');
$links = $repository->findByPatient($id_user);
foreach ($links as $key => $link) {
$link->getPatient()->setPassword("");
$link->getPatient()->setSalt("");
$link->getProche()->setPassword("");
$link->getProche()->setSalt("");
}
if ($links == null) {
$errors[] = "Users not found";
$jsonContent = $this->serializer->serialize(array("success" => false, "errors" => $errors), 'json');
} else
$jsonContent = $this->serializer->serialize(array("success" => true, "users" => $links), 'json');
return new Response($jsonContent);
}
public function manageProcheListAction(Request $request) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$this->serializer = new Serializer($normalizers, $encoders);
$errors = array();
$id_proche = $request->get('id_proche', null);
$id_patient = $request->get('id_patient', null);
$status = $request->get('status', null);
if ($id_proche == null)
$errors[] = "Missing id_proche";
if ($id_patient == null)
$errors[] = "Missing id_patient";
if ($status == null)
$errors[] = "Missing status";
if (count($errors) > 0) {
$resp = array("success" => false, "errors" => $errors);
$jsonContent = $this->serializer->serialize($resp, 'json');
return new Response($jsonContent);
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('DHAPIBundle:ProchePatientLink');
$link = $repo->findOneBy(array(
'proche' => $id_proche,
'patient' => $id_patient
));
if ($link == null) {
$link = new ProchePatientLink();
$user_repo = $em->getRepository('DHAPIBundle:User');
$proche = $user_repo->findOneById($id_proche);
$patient = $user_repo->findOneById($id_patient);
if ($proche == null)
$errors[] = "Proche not found";
if ($patient == null)
$errors[] = "Patient not found";
if (count($errors) > 0) {
$resp = array("success" => false, "errors" => $errors);
$jsonContent = $this->serializer->serialize($resp, 'json');
return new Response($jsonContent);
}
$link->setProche($proche);
$link->setPatient($patient);
$link->setStatus($status);
} else
$link->setStatus($status);
$em->persist($link);
$em->flush();
return new Response($this->serializer->serialize(array("success" => true), 'json'));
}
public function setPatientPositionAction(Request $request) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$this->serializer = new Serializer($normalizers, $encoders);
$id_user = $request->get('id_user', null);
$position = $request->get('position', null);
$errors = array();
if ($id_user == null || $position == null)
$errors[] = "Missing parameters";
else {
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('DHUserBundle:User');
$user = $repo->find($id_user);
if ($user == null)
$errors[] = "User not found";
}
if (count($errors) > 0) {
$response = array("success" => false, "errors" => $errors);
return new Response($this->serializer->serialize($response, 'json'));
}
if ($position)
$user->setPosition($position);
$em->persist($user);
$em->flush();
$response = array("success" => true);
return new Response($this->serializer->serialize($response, 'json'));
}
public function searchProcheAction(Request $request, $id_user, $search) {
$encoders = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object;
});
$this->serializer = new Serializer(array($normalizer), array($encoders));
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHUserBundle:User');
$qb = $repository->createQueryBuilder('cm');
$qb->select('cm')
->where($qb->expr()->orX(
$qb->expr()->eq('cm.firstname', ':search'),
$qb->expr()->eq('cm.lastname', ':search'),
$qb->expr()->eq('cm.phone', ':search')
))
->setParameter('search', $search);
$users = $qb->getQuery()->getResult();
$repository = $this->getDoctrine()
->getManager()
->getRepository('DHAPIBundle:ProchePatientLink');
$links = $repository->findByPatient($id_user);
foreach ($users as $key_u => $user) {
foreach ($links as $key_l => $link) {
if ($user->getId() == $link->getProche()->getId()) {
unset($users[$key_u]);
}
}
$user->setPassword("");
$user->setSalt("");
}
if ($users == null) {
$errors = array();
$errors[] = "Users not found";
$jsonContent = $this->serializer->serialize(array("success" => false, "errors" => $errors), 'json');
} else
$jsonContent = $this->serializer->serialize(array("success" => true, "users" => $users), 'json');
return new Response($jsonContent);
}
}
| mit |
Azure/azure-sdk-for-go | services/preview/logic/mgmt/2018-07-01-preview/logic/integrationaccountcertificates.go | 17808 | package logic
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// IntegrationAccountCertificatesClient is the REST API for Azure Logic Apps.
type IntegrationAccountCertificatesClient struct {
BaseClient
}
// NewIntegrationAccountCertificatesClient creates an instance of the IntegrationAccountCertificatesClient client.
func NewIntegrationAccountCertificatesClient(subscriptionID string) IntegrationAccountCertificatesClient {
return NewIntegrationAccountCertificatesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewIntegrationAccountCertificatesClientWithBaseURI creates an instance of the IntegrationAccountCertificatesClient
// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI
// (sovereign clouds, Azure stack).
func NewIntegrationAccountCertificatesClientWithBaseURI(baseURI string, subscriptionID string) IntegrationAccountCertificatesClient {
return IntegrationAccountCertificatesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates an integration account certificate.
// Parameters:
// resourceGroupName - the resource group name.
// integrationAccountName - the integration account name.
// certificateName - the integration account certificate name.
// certificate - the integration account certificate.
func (client IntegrationAccountCertificatesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, integrationAccountName string, certificateName string, certificate IntegrationAccountCertificate) (result IntegrationAccountCertificate, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountCertificatesClient.CreateOrUpdate")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: certificate,
Constraints: []validation.Constraint{{Target: "certificate.IntegrationAccountCertificateProperties", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "certificate.IntegrationAccountCertificateProperties.Key", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "certificate.IntegrationAccountCertificateProperties.Key.KeyVault", Name: validation.Null, Rule: true, Chain: nil},
{Target: "certificate.IntegrationAccountCertificateProperties.Key.KeyName", Name: validation.Null, Rule: true, Chain: nil},
}},
}}}}}); err != nil {
return result, validation.NewError("logic.IntegrationAccountCertificatesClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, integrationAccountName, certificateName, certificate)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "CreateOrUpdate", resp, "Failure responding to request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client IntegrationAccountCertificatesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, certificateName string, certificate IntegrationAccountCertificate) (*http.Request, error) {
pathParameters := map[string]interface{}{
"certificateName": autorest.Encode("path", certificateName),
"integrationAccountName": autorest.Encode("path", integrationAccountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}", pathParameters),
autorest.WithJSON(certificate),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client IntegrationAccountCertificatesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client IntegrationAccountCertificatesClient) CreateOrUpdateResponder(resp *http.Response) (result IntegrationAccountCertificate, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes an integration account certificate.
// Parameters:
// resourceGroupName - the resource group name.
// integrationAccountName - the integration account name.
// certificateName - the integration account certificate name.
func (client IntegrationAccountCertificatesClient) Delete(ctx context.Context, resourceGroupName string, integrationAccountName string, certificateName string) (result autorest.Response, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountCertificatesClient.Delete")
defer func() {
sc := -1
if result.Response != nil {
sc = result.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.DeletePreparer(ctx, resourceGroupName, integrationAccountName, certificateName)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "Delete", resp, "Failure responding to request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client IntegrationAccountCertificatesClient) DeletePreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, certificateName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"certificateName": autorest.Encode("path", certificateName),
"integrationAccountName": autorest.Encode("path", integrationAccountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client IntegrationAccountCertificatesClient) DeleteSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client IntegrationAccountCertificatesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets an integration account certificate.
// Parameters:
// resourceGroupName - the resource group name.
// integrationAccountName - the integration account name.
// certificateName - the integration account certificate name.
func (client IntegrationAccountCertificatesClient) Get(ctx context.Context, resourceGroupName string, integrationAccountName string, certificateName string) (result IntegrationAccountCertificate, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountCertificatesClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, resourceGroupName, integrationAccountName, certificateName)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client IntegrationAccountCertificatesClient) GetPreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, certificateName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"certificateName": autorest.Encode("path", certificateName),
"integrationAccountName": autorest.Encode("path", integrationAccountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client IntegrationAccountCertificatesClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client IntegrationAccountCertificatesClient) GetResponder(resp *http.Response) (result IntegrationAccountCertificate, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets a list of integration account certificates.
// Parameters:
// resourceGroupName - the resource group name.
// integrationAccountName - the integration account name.
// top - the number of items to be included in the result.
func (client IntegrationAccountCertificatesClient) List(ctx context.Context, resourceGroupName string, integrationAccountName string, top *int32) (result IntegrationAccountCertificateListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountCertificatesClient.List")
defer func() {
sc := -1
if result.iaclr.Response.Response != nil {
sc = result.iaclr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, resourceGroupName, integrationAccountName, top)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.iaclr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "List", resp, "Failure sending request")
return
}
result.iaclr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "List", resp, "Failure responding to request")
return
}
if result.iaclr.hasNextLink() && result.iaclr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListPreparer prepares the List request.
func (client IntegrationAccountCertificatesClient) ListPreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, top *int32) (*http.Request, error) {
pathParameters := map[string]interface{}{
"integrationAccountName": autorest.Encode("path", integrationAccountName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if top != nil {
queryParameters["$top"] = autorest.Encode("query", *top)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client IntegrationAccountCertificatesClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client IntegrationAccountCertificatesClient) ListResponder(resp *http.Response) (result IntegrationAccountCertificateListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client IntegrationAccountCertificatesClient) listNextResults(ctx context.Context, lastResults IntegrationAccountCertificateListResult) (result IntegrationAccountCertificateListResult, err error) {
req, err := lastResults.integrationAccountCertificateListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.IntegrationAccountCertificatesClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client IntegrationAccountCertificatesClient) ListComplete(ctx context.Context, resourceGroupName string, integrationAccountName string, top *int32) (result IntegrationAccountCertificateListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountCertificatesClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx, resourceGroupName, integrationAccountName, top)
return
}
| mit |
bitcake/bitstrap | Assets/Editor/Inspector/ScriptTemplate/ScriptTemplatePreferences.cs | 2501 | using UnityEditor;
using UnityEngine;
namespace BitStrap
{
/// <summary>
/// Draws the preferences for editor script templates (<see cref="ScriptTemplatePreference"/>).
/// This class also provides access to the defined templates as well as other settings from
/// its static properties.
/// To use script templates go to Edit -> Preferences -> BitStrap.
/// </summary>
[InitializeOnLoadAttribute]
public static class ScriptTemplatePreferences
{
public static EditorPrefProperty<string> ScriptTemplateDefaultPath = new EditorPrefString( "ScriptTemplate_DefaultFilePath", "" );
public static EditorPrefProperty<bool> ScriptTemplateUseWindowsLineEnding = new EditorPrefBool( "ScriptTemplate_UseWindowsLineEnding", true );
private static ScriptTemplatePreference cSharpScriptTemplate = new ScriptTemplatePreference
( "C# Script", "ScriptTemplate_CSharpScript",
@"using UnityEngine;
public sealed class #SCRIPTNAME# : MonoBehaviour
{
}
" );
private static ScriptTemplatePreference cSharpEditorScriptTemplate = new ScriptTemplatePreference
( "C# EditorScript", "ScriptTemplate_CSharpEditorScript",
@"using UnityEditor;
using UnityEngine;
public sealed class #SCRIPTNAME# : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
}
}
" );
private static Vector2 scroll = Vector2.zero;
public static string CSharpScriptDefaultCode
{
get { return cSharpScriptTemplate.TemplateCode; }
}
public static string CSharpEditorScriptDefaultCode
{
get { return cSharpEditorScriptTemplate.TemplateCode; }
}
static ScriptTemplatePreferences()
{
BitStrapPreferences.RegisterPreference( OnPreferencesGUI );
}
public static void OnPreferencesGUI()
{
using( BoxGroup.Do( ref scroll, "Script Templates" ) )
{
bool windowsLineEnding = EditorGUILayout.Toggle( "Use windows line ending format", ScriptTemplateUseWindowsLineEnding.Value );
if( windowsLineEnding != ScriptTemplateUseWindowsLineEnding.Value )
{
ScriptTemplateUseWindowsLineEnding.Value = windowsLineEnding;
cSharpScriptTemplate.UpdateLineEnding();
cSharpEditorScriptTemplate.UpdateLineEnding();
}
cSharpScriptTemplate.OnPreferencesGUI();
EditorGUILayout.Space();
cSharpEditorScriptTemplate.OnPreferencesGUI();
}
}
public static void SaveDefaultPathFromFilePath( string filePath )
{
ScriptTemplateDefaultPath.Value = filePath.Substring( 0, filePath.LastIndexOf( "/", System.StringComparison.Ordinal ) );
}
}
} | mit |
SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts.Web.UnitTests/Controllers/EmployerAccountControllerTests/GatewayInform/When_I_Call_GatewayInform_Without_HashedAccountId.cs | 3395 | using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Web.Mvc;
using System.Web.Routing;
using MediatR;
using Moq;
using NUnit.Framework;
using SFA.DAS.Authentication;
using SFA.DAS.Authorization;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.Web.Controllers;
using SFA.DAS.EmployerAccounts.Web.Models;
using SFA.DAS.EmployerAccounts.Web.Orchestrators;
using SFA.DAS.EmployerAccounts.Web.ViewModels;
using SFA.DAS.NLog.Logger;
namespace SFA.DAS.EmployerAccounts.Web.UnitTests.Controllers.EmployerAccountControllerTests.GatewayInform
{
[ExcludeFromCodeCoverage]
public class When_I_Call_GatewayInform_Without_HashedAccountId : ControllerTestBase
{
private EmployerAccountController _employerAccountController;
private Mock<EmployerAccountOrchestrator> _orchestrator;
private Mock<IAuthenticationService> _owinWrapper;
private Mock<ICookieStorageService<HashedAccountIdModel>> _mockAccountCookieStorage;
private string _cookieKeyName;
[SetUp]
public void Arrange()
{
base.Arrange();
_cookieKeyName = typeof(HashedAccountIdModel).FullName;
_orchestrator = new Mock<EmployerAccountOrchestrator>();
_owinWrapper = new Mock<IAuthenticationService>();
new Mock<IMultiVariantTestingService>();
var logger = new Mock<ILog>();
new Mock<ICookieStorageService<FlashMessageViewModel>>();
_orchestrator.Setup(x => x.RenameEmployerAccount(It.IsAny<RenameEmployerAccountViewModel>(), It.IsAny<string>()))
.ReturnsAsync(new OrchestratorResponse<RenameEmployerAccountViewModel>
{
Status = HttpStatusCode.OK,
Data = new RenameEmployerAccountViewModel()
});
_mockAccountCookieStorage = new Mock<ICookieStorageService<HashedAccountIdModel>>();
_employerAccountController = new EmployerAccountController(_owinWrapper.Object,
Mock.Of<EmployerAccountOrchestrator>(),
Mock.Of<IMultiVariantTestingService>(),
Mock.Of<ILog>(),
Mock.Of<ICookieStorageService<FlashMessageViewModel>>(),
Mock.Of<IMediator>(),
Mock.Of<ICookieStorageService<ReturnUrlModel>>(),
_mockAccountCookieStorage.Object)
{
ControllerContext = _controllerContext.Object,
Url = new UrlHelper(new RequestContext(_httpContext.Object, new RouteData()), _routes)
};
}
[TestCase("")]
[TestCase(null)]
[TestCase(" ")]
public void Then_The_HashedAccountId_Is_Not_Stored(string hashedAccountId)
{
_employerAccountController.GatewayInform(hashedAccountId: hashedAccountId);
_mockAccountCookieStorage
.Verify(
m =>
m.Delete(It.IsAny<string>()),
Times.Never());
_mockAccountCookieStorage
.Verify(
m => m.Create(
It.IsAny<HashedAccountIdModel>(),
It.IsAny<string>(),
It.IsAny<int>()),
Times.Never
);
}
}
} | mit |
mojo00/TicTacToe-Java | CPUPlayer.java | 1578 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* CPU player class. Implements Player interface.
* Does not find best move. Chooses random move.
*
*
* @author jkwong
*/
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class CPUPlayer implements Player{
String name;
char marker;
int playerType;
CPUPlayer(String name, char marker){
this.name = name;
this.marker = marker;
this.playerType = 1;
}
public void SetMarker(char marker){
// sets marker; not user settable because always either x or o
this.marker = marker;
}
public char GetMarker(){
return(marker);
}
public void SetName(){
Scanner userInput = new Scanner(System.in);
this.name = userInput.next();
}
public int GetMove(Board b){
// get all possible moves
boolean [] possibleMovesMask = b.FindMoves();
// possibleMovesMask = b.FindMoves();
ArrayList<Integer> possibleMoves = new ArrayList<Integer>();
// get an ArrayList of possible moves;
for (int i = 0; i< 8; i++){
if (possibleMovesMask[i]){
possibleMoves.add(i);
}
}
// For now the cpu just chooses a random move
Random randGenerator = new Random();
System.out.println(possibleMoves.size());
int index = randGenerator.nextInt(possibleMoves.size());
return(possibleMoves.get(index));
}
}
| mit |
ernieyu/pfcviewer | src/pfc/export/ExportException.java | 1689 | /*
* Copyright (c) 2002 Ernest Yu. All rights reserved.
*
* 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 pfc.export;
/**
* Represents a problem while exporting a cabinet folder.
* @author Ernie Yu
*/
public class ExportException extends java.lang.Exception {
/** Creates a new instance of <code>ExportException</code> without
* detail message.
*/
public ExportException() {
}
/** Constructs an instance of <code>ExportException</code> with the
* specified detail message.
* @param msg the detail message.
*/
public ExportException(String msg) {
super(msg);
}
}
| mit |
johnnoone/salt-targeting | src/salt/targeting/rules.py | 11990 | '''
salt.targeting.rules
~~~~~~~~~~~~~~~~~~~~
'''
from abc import abstractmethod
import logging
log = logging.getLogger(__name__)
from salt.utils.matching import glob_match, pcre_match, pcre_compile, ipcidr_match
__all__ = [
'Rule',
'AllRule',
'AnyRule',
'NotRule',
'GlobRule',
'PCRERule',
'GrainRule',
'PillarRule',
'GrainPCRERule',
'SubnetIPRule',
'ExselRule',
'LocalStoreRule',
'YahooRangeRule',
]
class Doubtful(object):
def __init__(self, obj, doubt=None):
self.__dict__.update({
'obj': obj,
'doubt': doubt
})
def __getattr__(self, name):
if name in self.__dict__.keys():
return object.__getattr__(self, name)
return getattr(self.obj, name)
def mark_doubt(obj):
"""Match methods may return a misguidance"""
if hasattr(obj, 'doubt'):
obj.doubt = True
return obj
def is_deceipt(obj):
return getattr(obj, 'doubt', False)
def rule_cmp(rule, other, *attrs):
return isinstance(other, rule.__class__) \
and all(getattr(rule, attr) == getattr(other, attr) for attr in attrs) \
and Rule.__eq__(rule, other)
def rule_flatten(container, rules):
merged = set()
for rule in rules:
if isinstance(rule, container.__class__):
merged.update(rule_flatten(container, rule.rules))
else:
yield rule
for rule in merged:
yield rule
def rule_str(rule, *attrs):
name = rule.__class__.__name__
args = [repr(getattr(rule, attr)) for attr in attrs]
return '{0}({1})'.format(name, ', '.join(args))
class Rule(object):
"""
Abstract class for rules.
.. todo:: force __init__ to have at least 1 non-default args
"""
#: used for sorting in order to avoid doing some heavy computations
priority = None
def check(self, objs):
"""
Optimistic check by master.
"""
results = self.filter(objs)
return set(results)
@abstractmethod
def filter(self, objs):
return objs
@abstractmethod
def match(self, obj):
"""
Exact matching by obj.
"""
return obj
def __and__(self, other):
return AllRule(self, other)
def __or__(self, other):
return AnyRule(self, other)
def __neg__(self):
return NotRule(self)
def __eq__(self, other):
return isinstance(other, self.__class__) \
and self.priority == other.priority
def __lt__(self, other):
"""
Ordering is 10, 20, 30 ... None.
"""
if self.priority is None:
return False
if isinstance(other, Rule):
if other.priority is None:
return True
return self.priority <= other.priority
return True
class AllRule(Rule):
priority = 70
def __init__(self, *rules):
self.rules = set(rule_flatten(self, rules))
def filter(self, objs):
for rule in self:
results, objs = rule.filter(objs), set()
for obj in results:
if is_deceipt(obj):
yield obj
else:
objs.add(obj)
if not objs:
raise StopIteration
for obj in objs:
yield obj
def match(self, obj):
return all(obj for rule in self if rule.match(obj))
def __and__(self, rule):
self.rules.update(rule_flatten(self, [rule]))
return self
def __eq__(self, other):
return rule_cmp(self, other, 'rules')
def __iter__(self):
"""
Iterate rules by priority.
"""
for rule in sorted(self.rules):
yield rule
def __str__(self):
name = self.__class__.__name__
args = [str(rule) for rule in self.rules]
return "{0}({1})".format(name, ', '.join(args))
class AnyRule(Rule):
priority = 80
def __init__(self, *rules):
self.rules = set(rule_flatten(self, rules))
def filter(self, objs):
if not objs:
raise StopIteration
remaining = set(objs)
for rule in self:
try:
found = rule.filter(remaining)
for obj in found:
yield obj
except Exception as e:
log.exception('Exception thrown %s . current rule %s', e, rule)
raise e
remaining -= set(found)
if not remaining:
raise StopIteration
def match(self, obj):
return any(obj for rule in self if rule.match(obj))
def __or__(self, rule):
self.rules.update(rule_flatten(self, [rule]))
return self
def __eq__(self, other):
return rule_cmp(self, other, 'rules')
def __iter__(self):
"""
Iterate rules by priority.
"""
for rule in sorted(self.rules):
yield rule
def __str__(self):
name = self.__class__.__name__
args = [str(rule) for rule in self.rules]
return "{0}({1})".format(name, ', '.join(args))
class NotRule(Rule):
def __init__(self, rule):
self.rule = rule
def filter(self, objs):
# do not discard misleading objs
# they don't always implements required attrs
doubtful_objs = [Doubtful(obj) for obj in objs]
found = self.rule.filter(doubtful_objs)
removable = set([d.obj for d in found if not d.doubt])
return set(objs) - removable
def match(self, obj):
return not self.rule.match(obj)
def __neg__(self):
return self.rule
def __eq__(self, other):
return rule_cmp(self, other, 'rule')
def __str__(self):
name = self.__class__.__name__
args = [str(self.rule)]
return "{0}({1})".format(name, ', '.join(args))
class GlobRule(Rule):
priority = 10
def __init__(self, expr):
self.expr = expr
def filter(self, objs):
for obj in objs:
if glob_match(self.expr, obj.id):
yield obj
def match(self, obj):
return glob_match(self.expr, obj.id)
def __eq__(self, other):
return rule_cmp(self, other, 'expr')
def __str__(self):
return rule_str(self, 'expr')
class PCRERule(Rule):
priority = 20
def __init__(self, expr):
self.expr = expr
def filter(self, objs):
pattern = pcre_compile(self.expr)
for obj in objs:
if pattern.match(obj.id):
yield obj
def match(self, obj):
pattern = pcre_compile(self.expr)
return pattern.match(obj.id)
def __eq__(self, other):
return rule_cmp(self, other, 'expr')
def __str__(self):
return rule_str(self, 'expr')
class GrainRule(Rule):
priority = 40
def __init__(self, expr, delim):
self.expr = expr
self.delim = delim
def filter(self, objs):
for obj in objs:
if obj.grains is None:
yield mark_doubt(obj)
elif self.match(obj):
yield obj
def match(self, obj):
if obj.grains is None:
log.warning('grains are missing {0}'.format(obj.id))
return False
return glob_match(self.expr, obj.grains, self.delim)
def __eq__(self, other):
return rule_cmp(self, other, 'expr', 'delim')
def __str__(self):
return rule_str(self, 'expr', 'delim')
class PillarRule(Rule):
priority = 40
def __init__(self, expr, delim):
self.expr = expr
self.delim = delim
def filter(self, objs):
for obj in objs:
if obj.pillar is None:
yield mark_doubt(obj)
elif self.match(obj):
yield obj
def match(self, obj):
if obj.pillar is None:
log.warning('pillar is missing {0}'.format(obj.id))
return False
return glob_match(self.expr, obj.pillar, self.delim)
def __eq__(self, other):
return rule_cmp(self, other, 'expr', 'delim')
def __str__(self):
return rule_str(self, 'expr', 'delim')
class GrainPCRERule(Rule):
priority = 40
def __init__(self, expr, delim):
self.expr = expr
self.delim = delim
def filter(self, objs):
for obj in objs:
if obj.grains is None:
yield mark_doubt(obj)
elif self.match(obj):
yield obj
def match(self, obj):
if obj.grains is None:
log.warning('grains are missing {0}'.format(obj.id))
return False
return pcre_match(self.expr, obj.grains, self.delim)
def __eq__(self, other):
return rule_cmp(self, other, 'expr', 'delim')
def __str__(self):
return rule_str(self, 'expr', 'delim')
class SubnetIPRule(Rule):
priority = 30
def __init__(self, expr):
self.expr = expr
def filter(self, objs):
for obj in objs:
if obj.ipv4 is None:
yield mark_doubt(obj)
elif self.match(obj):
yield obj
def match(self, obj):
if obj.ipv4 is None:
log.warning('ipv4 is missing {0}'.format(obj.id))
return False
return ipcidr_match(self.expr, obj.ipv4)
def __eq__(self, other):
return rule_cmp(self, other, 'expr')
def __str__(self):
return rule_str(self, 'expr')
class ExselRule(Rule):
priority = 60
def __init__(self, expr):
self.expr = expr
def filter(self, objs):
for obj in objs:
if obj.functions is None:
yield mark_doubt(obj)
elif self.match(obj):
yield obj
def match(self, obj):
if obj.functions is None:
log.warning('functions is None {0}'.format(obj.id))
return False
if self.expr not in obj.functions:
log.warning('functions is missing {0}'.format(obj.id))
return False
return bool(obj.functions[self.expr]())
def __eq__(self, other):
return rule_cmp(self, other, 'expr')
def __str__(self):
return rule_str(self, 'expr')
class LocalStoreRule(Rule):
priority = 40
def __init__(self, expr, delim):
self.expr = expr
self.delim = delim
def filter(self, objs):
for obj in objs:
if obj.data is None:
yield mark_doubt(obj)
elif self.match(obj):
yield obj
def match(self, obj):
if obj.data is None:
log.warning('data is None {0}'.format(obj.id))
return False
return glob_match(self.expr, obj.data, self.delim)
def __eq__(self, other):
return rule_cmp(self, other, 'expr', 'delim')
def __str__(self):
return rule_str(self, 'expr', 'delim')
class YahooRangeRule(Rule):
"""
see https://github.com/ytoolshed/range
https://github.com/grierj/range/wiki/Introduction-to-Range-with-YAML-files
"""
priority = 50
def __init__(self, expr, provider):
self.expr = expr
self.provider = provider
def filter(self, objs):
remains = {}
for obj in objs:
if obj.fqdn is None:
yield mark_doubt(obj)
else:
remains[obj.fqdn] = obj
if remains:
for host in self.provider.get(self.expr):
if host in remains:
yield remains.pop(host)
if not remains:
raise StopIteration
def match(self, obj):
if obj.fqdn is None:
log.warning('fqdn is None {0}'.format(obj.id))
return False
return obj.fqdn in self.provider.get(self.expr)
def __eq__(self, other):
return rule_cmp(self, other, 'expr')
def __str__(self):
return rule_str(self, 'expr', 'provider')
| mit |
baptiste333/le-drone | php/membre.php | 236 | <?php
/* Redirection de la personne en fonction de si elle est connecté ou non */
session_start();
if(isset($_SESSION['login'])) {
header('Location: ../profil.php');
} else {
header('Location: ../connection.php');
}
?> | mit |
olark/txroutes | txroutes/__init__.py | 8046 | import logging
import routes
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.python.failure import Failure
DEFAULT_404_HTML = '<html><head><title>404 Not Found</title></head>' \
'<body><h1>Not found</h1></body></html>'
DEFAULT_500_HTML = '<html><head><title>500 Internal Server Error</title>' \
'</head><body><h1>Internal Server Error</h1></body></html>'
class Dispatcher(Resource):
'''
Provides routes-like dispatching for twisted.web.server.
Frequently, it's much easier to describe your website layout using routes
instead of Resource from twisted.web.resource. This small library lets you
dispatch with routes in your twisted.web application. It also handles some
of the bookkeeping with deferreds, so you don't have to return NOT_DONE_YET
yourself.
Usage:
from twisted.internet import defer, reactor, task
from twisted.web.server import Site
from txroutes import Dispatcher
# Create a Controller
class Controller(object):
def index(self, request):
return '<html><body>Hello World!</body></html>'
def docs(self, request, item):
return '<html><body>Docs for %s</body></html>' % item.encode('utf8')
def post_data(self, request):
return '<html><body>OK</body></html>'
@defer.inlineCallbacks
def deferred_example(self, request):
request.write('<html><body>Wait a tic...</body></html>')
yield task.deferLater(reactor, 5, lambda: request.finish())
c = Controller()
dispatcher = Dispatcher()
dispatcher.connect(name='index', route='/', controller=c, action='index')
dispatcher.connect(name='docs', route='/docs/{item}', controller=c,
action='docs')
dispatcher.connect(name='data', route='/data', controller=c,
action='post_data', conditions=dict(method=['POST']))
dispatcher.connect(name='deferred_example', route='/wait', controller=c,
action='deferred_example')
factory = Site(dispatcher)
reactor.listenTCP(8000, factory)
reactor.run()
Helpful background information:
- Python routes: http://routes.groovie.org/
- Using twisted.web.resources: http://twistedmatrix.com/documents/current/web/howto/web-in-60/dynamic-dispatch.html
'''
def __init__(self, logger=logging.getLogger('txroutes')):
Resource.__init__(self)
self.__controllers = {}
self.__mapper = routes.Mapper()
self.__logger = logger
def connect(self, name, route, controller, **kwargs):
self.__controllers[name] = controller
self.__mapper.connect(name, route, controller=name, **kwargs)
def getChild(self, name, request):
return self
def render(self, request):
wsgi_environ = {}
wsgi_environ['REQUEST_METHOD'] = request.method
wsgi_environ['PATH_INFO'] = request.path
result = self.__mapper.match(environ=wsgi_environ)
handler = self._render_404
if result is not None:
controller = result.get('controller', None)
controller = self.__controllers.get(controller)
if controller is not None:
del result['controller']
action = result.get('action', None)
if action is not None:
del result['action']
func = getattr(controller, action, None)
if func:
handler = lambda request: func(request, **result)
render = self.__execute_handler(request, handler)
render.addErrback(self.__execute_failure, request)
return NOT_DONE_YET
# Subclasses can override with their own 404 rendering.
def _render_404(self, request):
request.setResponseCode(404)
return DEFAULT_404_HTML
# Subclasses can override with their own failure rendering.
def _render_failure(self, request, failure):
self.__logger.error(failure.getTraceback())
request.setResponseCode(500)
return DEFAULT_500_HTML
@inlineCallbacks
def __execute_handler(self, request, handler):
# Detect the content and whether the request is complete based
# on what the handler returns.
content = None
complete = False
response = handler(request)
if isinstance(response, Deferred):
content = yield response
complete = True
elif response is NOT_DONE_YET:
content = None
complete = False
else:
content = response
complete = True
# If this response is complete, but the request has not been
# finished yet, ensure finish is called.
if complete and not request.finished:
if content:
request.write(content)
request.finish()
def __execute_failure(self, failure, request):
# If the subclass overrode the deprecated _render_error code, execute
# it but log a deprecation warning.
if hasattr(self, '_render_error'):
self.__logger.warning('_render_error in txroutes.Dispatcher is deprecated, please override _render_failure instead')
handler = lambda request: self._render_error(request, failure=failure)
else:
handler = lambda request: self._render_failure(request, failure)
# Render the failure, falling back to the default failure renderer
# if an error occurs in _render_failure itself.
render = self.__execute_handler(request, handler)
render.addErrback(self.__execute_default_failure, request)
def __execute_default_failure(self, failure, request):
# Use default failure rendering when a subclass override of
# _render_failure itself raised an unhandled error.
try:
self.__logger.error(failure.getTraceback())
if not request.finished:
request.setResponseCode(500)
request.write(DEFAULT_500_HTML)
request.finish()
except Exception as e:
self.__logger.exception(e)
if __name__ == '__main__':
import logging
import twisted.python.log
from twisted.internet import defer, reactor, task
from twisted.web.server import Site
# Set up logging
log = logging.getLogger('txroutes')
log.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
log.addHandler(handler)
observer = twisted.python.log.PythonLoggingObserver(loggerName='txroutes')
observer.start()
# Create a Controller
class Controller(object):
def index(self, request):
return '<html><body>Hello World!</body></html>'
def docs(self, request, item):
return '<html><body>Docs for %s</body></html>' % item.encode('utf8')
def post_data(self, request):
return '<html><body>OK</body></html>'
@defer.inlineCallbacks
def deferred_example(self, request):
request.write('<html><body>Wait a tic...</body></html>')
yield task.deferLater(reactor, 5, lambda: request.finish())
c = Controller()
dispatcher = Dispatcher(log)
dispatcher.connect(name='index', route='/', controller=c, action='index')
dispatcher.connect(name='docs', route='/docs/{item}', controller=c,
action='docs')
dispatcher.connect(name='data', route='/data', controller=c,
action='post_data', conditions=dict(method=['POST']))
dispatcher.connect(name='deferred_example', route='/wait', controller=c,
action='deferred_example')
factory = Site(dispatcher)
reactor.listenTCP(8000, factory)
reactor.run()
| mit |
kedromelon/babel | packages/babel-polyfill/src/core-js/modules/es6.number.max-safe-integer.js | 56 | require("core-js/modules/es6.number.max-safe-integer");
| mit |
mllnd/Java-Paint | src/main/java/xyz/mllnd/javapaint/JavaPaint.java | 4704 | package main.java.xyz.mllnd.javapaint;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import java.util.Vector;
public class JavaPaint extends Applet implements MouseListener, MouseMotionListener {
/**
* Add listeners and buttons to the frame
*/
JavaPaint() {
addMouseListener(this);
addMouseMotionListener(this);
new PaintButton(this, "Black", "black");
new PaintButton(this, "White", "white");
new PaintButton(this, "Blue", "blue");
new PaintButton(this, "Red", "red");
new PaintButton(this, "Yellow", "yellow");
new PaintButton(this, "Green", "green");
new PaintButton(this, "Small", "small");
new PaintButton(this, "Medium", "medium");
new PaintButton(this, "Big", "big");
new PaintButton(this, "Huge", "huge");
}
/**
* The full "picture"
*/
Vector<PaintObject> v = new Vector<PaintObject>();
/**
* A separate object, created on mousePressed event and "ended" on mouseReleased event
*/
private PaintObject object;
/**
* Is user drawing currently?
*/
boolean drawing = false;
/**
* Default color
*/
Color color = Color.BLACK;
/**
* Default brush size
*/
int brushSize = 1;
/**
* Main method, invoked on program start
* @param args Arguments passed to method
*/
public static void main(String[] args) {
Frame frame = new Frame();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setVisible(true);
frame.setSize(dim.width, dim.height);
frame.add(new JavaPaint());
frame.setLocation(0, 0);
System.out.println("Starting JavaPaint...");
System.out.println("Created by Markkus Olaf Millend IVSB12, 2017");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.out.println("Thanks for trying out JavaPaint! Shutting down...");
System.out.println("Created by Markkus Olaf Millend IVSB12, 2017");
System.exit(0);
}
});
}
/**
* Mouse pressed event listener
* @param e MouseEvent
*/
public void mousePressed(MouseEvent e) {
switch (e.getButton()) {
case 1:
object = new PaintObject(brushSize, color);
drawing = true;
System.out.println("Starting painting!");
break;
case 3:
// Maybe deleting?
break;
}
}
/**
* Mouse released event listener
* @param e MouseEvent
*/
public void mouseReleased(MouseEvent e) {
if (drawing) {
drawing = false;
if (object.v.size() > 1) {
v.add(object);
repaint(); // Refresh
}
System.out.println("Stopping painting! There are "+object.v.size()+" points in the painted object.");
}
}
/**
* Mouse dragged event listener
* @param e MouseEvent
*/
public void mouseDragged(MouseEvent e) {
if (drawing) {
object.v.add(e.getPoint());
repaint(); // Refresh
}
}
/* Unused listeners */
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
/**
* "Paints" the points on the frame
* @param g Graphics
*/
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (int i=0; i<v.size(); i++) {
PaintObject m = v.get(i);
g2.setStroke(new BasicStroke(m.brushSize));
g2.setColor(m.color);
Point lastpoint = m.v.get(0); // Last point
for (int j=1; j<m.v.size(); j++) {
Point currentpoint = m.v.get(j);
g2.draw(new Line2D.Float(lastpoint.x, lastpoint.y, currentpoint.x, currentpoint.y));
lastpoint = currentpoint; // Set last point to current point
}
}
if (drawing && object.v.size() > 1) {
g2.setStroke(new BasicStroke(object.brushSize));
g2.setColor(object.color);
Point lastpoint = object.v.get(0);
for (int j=1; j<object.v.size(); j++) {
Point currentpoint = object.v.get(j);
g2.draw(new Line2D.Float(lastpoint.x, lastpoint.y, currentpoint.x, currentpoint.y));
lastpoint = currentpoint;
}
}
}
}
| mit |
vainyl/doctrine-orm-bridge | src/DoctrineEntityManager.php | 6124 | <?php
/**
* Vainyl
*
* PHP Version 7
*
* @package Doctrine-ORM-Bridge
* @license https://opensource.org/licenses/MIT MIT License
* @link https://vainyl.com
*/
declare(strict_types=1);
namespace Vainyl\Doctrine\ORM;
use Doctrine\Common\EventManager;
use Doctrine\Common\Persistence\Mapping\MappingException;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMException;
use Vainyl\Doctrine\ORM\Exception\LevelIntegrityDoctrineException;
use Vainyl\Doctrine\ORM\Factory\DoctrineEntityMetadataFactory;
use Vainyl\Domain\DomainInterface;
use Vainyl\Domain\Metadata\Factory\DomainMetadataFactoryInterface;
use Vainyl\Domain\Scenario\Storage\DomainScenarioStorageInterface;
use Vainyl\Domain\Storage\DomainStorageInterface;
use Vainyl\Time\Factory\TimeFactoryInterface;
/**
* Class DoctrineEntityManager
*
* @author Taras P. Girnyk <taras.p.gyrnik@gmail.com>
*
* @method DoctrineEntityMetadataFactory getMetadataFactory
*/
class DoctrineEntityManager extends EntityManager implements DomainStorageInterface, DomainScenarioStorageInterface
{
private $timeFactory;
private $domainMetadataFactory;
private $flushLevel = 0;
/**
* DoctrineEntityManager constructor.
*
* @param Connection $conn
* @param Configuration $config
* @param EventManager $eventManager
* @param TimeFactoryInterface $timeFactory
* @param DomainMetadataFactoryInterface $domainMetadataFactory
*/
protected function __construct(
Connection $conn,
Configuration $config,
EventManager $eventManager,
TimeFactoryInterface $timeFactory,
DomainMetadataFactoryInterface $domainMetadataFactory
) {
$this->timeFactory = $timeFactory;
$this->domainMetadataFactory = $domainMetadataFactory;
parent::__construct($conn, $config, $eventManager);
}
/**
* @param mixed $conn
* @param Configuration $config
* @param EventManager $eventManager
* @param TimeFactoryInterface $timeFactory
* @param DomainMetadataFactoryInterface $metadataFactory
*
* @return DoctrineEntityManager
* @throws ORMException
*/
public static function createExtended(
$conn,
Configuration $config,
EventManager $eventManager,
TimeFactoryInterface $timeFactory,
DomainMetadataFactoryInterface $metadataFactory
) {
if (!$config->getMetadataDriverImpl()) {
throw ORMException::missingMappingDriverImpl();
}
switch (true) {
case (is_array($conn)):
$conn = DriverManager::getConnection(
$conn,
$config,
($eventManager ?: new EventManager())
);
break;
case ($conn instanceof Connection):
if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
throw ORMException::mismatchedEventManager();
}
break;
default:
throw new \InvalidArgumentException("Invalid argument: " . $conn);
}
return new DoctrineEntityManager($conn, $config, $conn->getEventManager(), $timeFactory, $metadataFactory);
}
/**
* @param DoctrineEntityManager $obj
*
* @return bool
*/
public function equals($obj): bool
{
return $this->getId() === $obj->getId();
}
/**
* @inheritDoc
*/
public function findById(string $name, $id): ?DomainInterface
{
return $this->getRepository($name)->find($id);
}
/**
* @inheritDoc
*/
public function findMany(
string $name,
array $criteria = [],
array $orderBy = [],
int $limit = 0,
int $offset = 0
): array {
return $this->getRepository($name)->findBy($criteria, $orderBy, $limit ? $limit : null, $offset ? $offset : null);
}
/**
* @inheritDoc
*/
public function findOne(string $name, array $criteria = [], array $orderBy = []): ?DomainInterface
{
return $this->getRepository($name)->findOneBy($criteria, $orderBy);
}
/**
* @inheritDoc
*/
public function flush($entity = null)
{
$this->flushLevel--;
if (0 < $this->flushLevel) {
return $this;
}
if (0 > $this->flushLevel) {
throw new LevelIntegrityDoctrineException($this, $this->flushLevel);
}
parent::flush($entity);
return $this;
}
/**
* @return DomainMetadataFactoryInterface
*/
public function getDomainMetadataFactory(): DomainMetadataFactoryInterface
{
return $this->domainMetadataFactory;
}
/**
* @inheritDoc
*/
public function getId(): ?string
{
return spl_object_hash($this);
}
/**
* @inheritDoc
*/
public function getScenarios(string $name): array
{
return $this->getMetadataFactory()->getMetadataFor($name)->getDomainMetadata()->getScenarios();
}
/**
* @return TimeFactoryInterface
*/
public function getTimeFactory()
{
return $this->timeFactory;
}
/**
* @inheritDoc
*/
public function hash()
{
return $this->getId();
}
/**
* @inheritDoc
*/
public function init()
{
if (0 <= $this->flushLevel) {
$this->flushLevel++;
return $this;
}
throw new LevelIntegrityDoctrineException($this, $this->flushLevel);
}
/**
* @inheritDoc
*/
public function supports(string $name): bool
{
try {
return $this->getMetadataFactory()->getMetadataFor($name)->getDomainMetadata()->isPrimary();
} catch (MappingException $e) {
return false;
}
}
}
| mit |
freeuni-sdp/arkanoid-16 | src/main/java/ge/edu/freeuni/sdp/arkanoid/model/geometry/Size.java | 1192 | package ge.edu.freeuni.sdp.arkanoid.model.geometry;
public class Size {
private int _width;
private int _height;
public Size(int width, int height) {
if (width < 0) throw new IllegalArgumentException("width");
if (height < 0) throw new IllegalArgumentException("height");
_width = width;
_height = height;
}
public int getWidth() {
return _width;
}
public int getHeight() {
return _height;
}
public boolean isInRange(Point current) {
return current.X >= 0 &&
current.X < this.getWidth() &&
current.Y >= 0 &&
current.Y < this.getHeight();
}
public Point toPoint() {
return new Point(getWidth(), getHeight());
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Size other = (Size) obj;
//noinspection SimplifiableIfStatement
if (_width != other._width)
return false;
return _height == other._height;
}
}
| mit |
jordanams/lunchr | lunchr_extranet/app/view/menu/update_produit.php | 2419 | <?php include_once('../app/view/include/header.inc.php'); ?>
<div class="col-lg-12">
<h1> Administration des cartes / menus / produits</h1>
<br/>
<?php include_once('../app/view/include/header_carte_menu.inc.php'); ?>
<br/>
<?php echo 'Restaurant sélectionné : '; foreach ($select_resto_afficher as $key => $row) { echo '<span style="text-decoration:underline;">'.$row['lr_nom'].'</span>'; } ?>
<br/><br/><br/>
<form class="form-horizontal" id="formu_carte" name="formu_users" action="" method="POST" enctype="multipart/form-data">
<fieldset>
<!-- Form Name -->
<legend>Modifier votre produit</legend>
<br/><br/>
<div class="form-group">
<label class="col-md-3 control-label" for="selectbasic">Nom du produit</label>
<div class="col-md-5">
<input id="nom_produit" name="nom_produit" type="text" value="<?php echo $verif_produit[0]['lp_nom'];?>" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="selectbasic">Prix du produit</label>
<div class="col-md-5">
<input id="prix_produit" name="prix_produit" type="text" value="<?php echo $verif_produit[0]['lp_prix'];?>" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="selectbasic">Description du produit</label>
<div class="col-md-5">
<textarea id="desc_produit" name="desc_produit" class="form-control"><?php echo $verif_produit[0]['lp_description']; ?></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="selectbasic">Ajouter une image</label>
<div class="col-md-5">
<input value="test" id="ch_file1" name="ch_file1" class="input-file" type="file">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-3 control-label" for="singlebutton">Valider</label>
<div class="col-md-5">
<button id="singlebutton" name="singlebutton" class="btn btn-primary col-md-12" type="submit">Valider</button>
</div>
</div>
</fieldset>
</form>
</div>
<?php include_once('../app/view/include/footer.inc.php'); ?> | mit |
xzrunner/easyeditor | easydb/src/easydb/SearchList.cpp | 3127 | #include "SearchList.h"
#include "Database.h"
#include "MainList.h"
#include "LeafNode.h"
#include "IndexNode.h"
#include <easyimage.h>
#include <ee/SymbolFile.h>
#include <sprite2/SymType.h>
#include <gum/FilepathHelper.h>
namespace edb
{
BEGIN_EVENT_TABLE(SearchList, wxTreeCtrl)
EVT_TREE_ITEM_ACTIVATED(ID_CTRL, SearchList::OnItemActivated)
END_EVENT_TABLE()
SearchList::SearchList(wxWindow* parent, MainList* main_list, const Database& db)
: wxTreeCtrl(parent, ID_CTRL, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS | wxTR_LINES_AT_ROOT | wxTR_HIDE_ROOT)
, m_main_list(main_list)
, m_db(db)
{
SetBackgroundColour(wxColour(229, 229, 229));
}
void SearchList::OnSearch(const std::string& str)
{
DeleteAllItems();
m_root = AddRoot("search");
static const int MAX = 50;
std::vector<int> nodes;
m_db.QueryByStr(str, MAX, nodes);
for (int i = 0, n = nodes.size(); i < n; ++i)
{
const Node* node = m_db.Fetch(nodes[i]);
if (node->Type() != NODE_LEAF) {
continue;
}
const LeafNode* leaf = static_cast<const LeafNode*>(node);
AppendItem(m_root, leaf->GetPath());
}
}
void SearchList::OnSearchSameImages(float val)
{
DeleteAllItems();
m_root = AddRoot("search");
const std::vector<Node*>& nodes = m_db.GetNodes();
for (int i = 0, n = nodes.size(); i < n; ++i)
{
if (nodes[i]->Type() != NODE_INDEX) {
continue;
}
IndexNode* index = static_cast<IndexNode*>(nodes[i]);
const std::vector<int>& children = index->GetChildren();
std::vector<std::string> image_paths;
for (int j = 0, m = children.size(); j < m; ++j)
{
const Node* cnode = m_db.Fetch(children[j]);
if (cnode->Type() != NODE_LEAF) {
continue;
}
const LeafNode* cleaf = static_cast<const LeafNode*>(cnode);
std::string filepath = m_db.GetDirPath() + "\\" + cleaf->GetPath();
if (ee::SymbolFile::Instance()->Type(filepath) == s2::SYM_IMAGE) {
image_paths.push_back(filepath);
}
}
if (image_paths.empty()) {
continue;
}
std::vector<std::vector<int> > same;
GetSameImages(image_paths, val, same);
if (same.empty()) {
continue;
}
for (int i = 0, n = same.size(); i < n; ++i)
{
int num = same[i].size();
wxTreeItemId id = AppendItem(m_root, wxString::FromDouble(num));
for (int j = 0; j < num; ++j)
{
std::string relative = gum::FilepathHelper::Relative(m_db.GetDirPath(), image_paths[same[i][j]]);
AppendItem(id, relative);
}
}
}
}
void SearchList::OnItemActivated(wxTreeEvent& event)
{
wxTreeItemId id = event.GetItem();
wxString text = GetItemText(id);
int node_id = m_db.QueryByPath(m_db.GetDirPath() + "\\" + text.ToStdString());
m_main_list->OnSelected(node_id);
}
void SearchList::GetSameImages(const std::vector<std::string>& src, float val,
std::vector<std::vector<int> >& dst)
{
if (src.size() <= 1) {
return;
}
for (int i = 0; i < src.size() - 1; ++i) {
std::vector<int> same;
same.push_back(i);
for (int j = i + 1; j < src.size(); ++j) {
if (eimage::ImageCmp::IsSame(src[i], src[j], val)) {
same.push_back(j);
}
}
if (same.size() > 1) {
dst.push_back(same);
}
}
}
} | mit |
narekps/ZfbUser | src/Adapter/Factory/DbAdapterFactory.php | 1349 | <?php
namespace ZfbUser\Adapter\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use ZfbUser\Adapter\DbAdapter;
use ZfbUser\Mapper\UserMapperInterface;
use ZfbUser\Options\ModuleOptions;
use ZfbUser\Repository\UserRepositoryInterface;
/**
* Class DbAdapterFactory
*
* @package ZfbUser\Adapter\Factory
*/
class DbAdapterFactory implements FactoryInterface
{
/**
* @param \Interop\Container\ContainerInterface $container
* @param string $requestedName
* @param array|null $options
*
* @return object|\ZfbUser\Adapter\DbAdapter
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
/** @var ModuleOptions $moduleOptions */
$moduleOptions = $container->get(ModuleOptions::class);
/** @var UserMapperInterface $mapper */
$mapper = $container->get('zfbuser_user_mapper');
/** @var UserRepositoryInterface $repository */
$repository = $container->get('zfbuser_user_repository');
$adapter = new DbAdapter($moduleOptions, $mapper, $repository);
return $adapter;
}
}
| mit |
yyssc/ssc-grid | docs/examples/TreeBasic.js | 2247 | const treeData = [
{
'title': '0-0-label',
'key': '0-0-key',
'children': [
{
'title': '0-0-0-label',
'key': '0-0-0-key',
'children': [
{
'title': '0-0-0-0-label',
'key': '0-0-0-0-key'
},
{
'title': '0-0-0-1-label',
'key': '0-0-0-1-key'
},
{
'title': '0-0-0-2-label',
'key': '0-0-0-2-key'
}
]
},
{
'title': '0-0-1-label',
'key': '0-0-1-key',
'children': [
{
'title': '0-0-1-0-label',
'key': '0-0-1-0-key'
},
{
'title': '0-0-1-1-label',
'key': '0-0-1-1-key'
},
{
'title': '0-0-1-2-label',
'key': '0-0-1-2-key'
}
]
},
{
'title': '0-0-2-label',
'key': '0-0-2-key'
}
]
},
{
'title': '0-1-label',
'key': '0-1-key',
'children': [
{
'title': '0-1-0-label',
'key': '0-1-0-key',
'children': [
{
'title': '0-1-0-0-label',
'key': '0-1-0-0-key'
},
{
'title': '0-1-0-1-label',
'key': '0-1-0-1-key'
},
{
'title': '0-1-0-2-label',
'key': '0-1-0-2-key'
}
]
},
{
'title': '0-1-1-label',
'key': '0-1-1-key',
'children': [
{
'title': '0-1-1-0-label',
'key': '0-1-1-0-key'
},
{
'title': '0-1-1-1-label',
'key': '0-1-1-1-key'
},
{
'title': '0-1-1-2-label',
'key': '0-1-1-2-key'
}
]
},
{
'title': '0-1-2-label',
'key': '0-1-2-key'
}
]
},
{
'title': '0-2-label',
'key': '0-2-key'
}
];
const TreeBasicExample = React.createClass({
render() {
return (
<Tree
className="myCls"
showLine
checkable
defaultExpandAll
treeData={treeData}
/>
);
}
});
ReactDOM.render(<TreeBasicExample />, mountNode);
| mit |
fengnovo/webpack-react | zhihu/src/js/Reddit/reducers.js | 1331 | import { combineReducers } from 'redux'
import {
SELECT_SUBREDDIT, INVALIDATE_SUBREDDIT ,
REQUEST_POSTS, RECEIVE_POSTS
} from './actions'
function selectedSubreddit(state = 'reactjs', action) {
switch (action.type) {
case SELECT_SUBREDDIT:
return action.subreddit
default:
return state
}
}
function posts(state = {
isFetching: false,
didInvalidate: false,
items: []
}, action) {
switch (action.type) {
case INVALIDATE_SUBREDDIT :
return Object.assign({}, state, {
didInvalidate: true
})
case REQUEST_POSTS:
return Object.assign({}, state, {
isFetching: true,
didInvalidate: false
})
case RECEIVE_POSTS:
return Object.assign({}, state, {
isFetching: false,
didInvalidate: false,
items: action.posts,
lastUpdated: action.receivedAt
})
default:
return state
}
}
function postsBySubreddit(state = { }, action) {
switch (action.type) {
case INVALIDATE_SUBREDDIT :
case RECEIVE_POSTS:
case REQUEST_POSTS:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
})
default:
return state
}
}
const rootReducer = combineReducers({
postsBySubreddit,
selectedSubreddit
})
export default rootReducer | mit |
dokaptur/coreutils | src/fmt/parasplit.rs | 22192 | /*
* This file is part of `fmt` from the uutils coreutils package.
*
* (c) kwantam <kwantam@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use core::iter::Peekable;
use std::io::Lines;
use std::slice::Items;
use std::str::CharRange;
use FileOrStdReader;
use FmtOptions;
#[inline(always)]
fn char_width(c: char) -> uint {
if (c as uint) < 0xA0 {
// if it is ASCII, call it exactly 1 wide (including control chars)
// calling control chars' widths 1 is consistent with OpenBSD fmt
1
} else {
// otherwise, get the unicode width
// note that we shouldn't actually get None here because only c < 0xA0
// can return None, but for safety and future-proofing we do it this way
c.width(false).unwrap_or(1)
}
}
// lines with PSKIP, lacking PREFIX, or which are entirely blank are
// NoFormatLines; otherwise, they are FormatLines
#[deriving(Show)]
pub enum Line {
FormatLine(FileLine),
NoFormatLine(String, bool)
}
impl Line {
// when we know that it's a FormatLine, as in the ParagraphStream iterator
fn get_formatline(self) -> FileLine {
match self {
Line::FormatLine(fl) => fl,
Line::NoFormatLine(..) => panic!("Found NoFormatLine when expecting FormatLine")
}
}
// when we know that it's a NoFormatLine, as in the ParagraphStream iterator
fn get_noformatline(self) -> (String, bool) {
match self {
Line::NoFormatLine(s, b) => (s, b),
Line::FormatLine(..) => panic!("Found FormatLine when expecting NoFormatLine")
}
}
}
// each line's prefix has to be considered to know whether to merge it with
// the next line or not
#[deriving(Show)]
struct FileLine {
line : String,
indent_end : uint, // the end of the indent, always the start of the text
pfxind_end : uint, // the end of the PREFIX's indent, that is, the spaces before the prefix
indent_len : uint, // display length of indent taking into account tabs
prefix_len : uint, // PREFIX indent length taking into account tabs
}
// iterator that produces a stream of Lines from a file
pub struct FileLines<'a> {
opts : &'a FmtOptions,
lines : Lines<'a, FileOrStdReader>,
}
impl<'a> FileLines<'a> {
fn new<'a>(opts: &'a FmtOptions, lines: Lines<'a, FileOrStdReader>) -> FileLines<'a> {
FileLines { opts: opts, lines: lines }
}
// returns true if this line should be formatted
fn match_prefix(&self, line: &str) -> (bool, uint) {
if !self.opts.use_prefix { return (true, 0u); }
FileLines::match_prefix_generic(self.opts.prefix.as_slice(), line, self.opts.xprefix)
}
// returns true if this line should be formatted
fn match_anti_prefix(&self, line: &str) -> bool {
if !self.opts.use_anti_prefix { return true; }
match FileLines::match_prefix_generic(self.opts.anti_prefix.as_slice(), line, self.opts.xanti_prefix) {
(true, _) => false,
(_ , _) => true
}
}
fn match_prefix_generic(pfx: &str, line: &str, exact: bool) -> (bool, uint) {
if line.starts_with(pfx) {
return (true, 0);
}
if !exact {
// we do it this way rather than byte indexing to support unicode whitespace chars
let mut i = 0u;
while (i < line.len()) && line.char_at(i).is_whitespace() {
i = match line.char_range_at(i) { CharRange { ch: _ , next: nxi } => nxi };
if line.slice_from(i).starts_with(pfx) {
return (true, i);
}
}
}
(false, 0)
}
fn compute_indent(&self, string: &str, prefix_end: uint) -> (uint, uint, uint) {
let mut prefix_len = 0;
let mut indent_len = 0;
let mut indent_end = 0;
for (os, c) in string.char_indices() {
if os == prefix_end {
// we found the end of the prefix, so this is the printed length of the prefix here
prefix_len = indent_len;
}
if (os >= prefix_end) && !c.is_whitespace() {
// found first non-whitespace after prefix, this is indent_end
indent_end = os;
break;
} else if c == '\t' {
// compute tab length
indent_len = (indent_len / self.opts.tabwidth + 1) * self.opts.tabwidth;
} else {
// non-tab character
indent_len += char_width(c);
}
}
(indent_end, prefix_len, indent_len)
}
}
impl<'a> Iterator<Line> for FileLines<'a> {
fn next(&mut self) -> Option<Line> {
let n =
match self.lines.next() {
Some(t) => match t {
Ok(tt) => tt,
Err(_) => return None
},
None => return None
};
// if this line is entirely whitespace,
// emit a blank line
// Err(true) indicates that this was a linebreak,
// which is important to know when detecting mail headers
if n.as_slice().is_whitespace() {
return Some(Line::NoFormatLine("\n".to_string(), true));
}
// if this line does not match the prefix,
// emit the line unprocessed and iterate again
let (pmatch, poffset) = self.match_prefix(n.as_slice());
if !pmatch {
return Some(Line::NoFormatLine(n, false));
} else if n.as_slice().slice_from(poffset + self.opts.prefix.len()).is_whitespace() {
// if the line matches the prefix, but is blank after,
// don't allow lines to be combined through it (that is,
// treat it like a blank line, except that since it's
// not truly blank we will not allow mail headers on the
// following line)
return Some(Line::NoFormatLine(n, false));
}
// skip if this line matches the anti_prefix
// (NOTE definition of match_anti_prefix is TRUE if we should process)
if !self.match_anti_prefix(n.as_slice()) {
return Some(Line::NoFormatLine(n, false));
}
// figure out the indent, prefix, and prefixindent ending points
let prefix_end = poffset + self.opts.prefix.len();
let (indent_end, prefix_len, indent_len) = self.compute_indent(n.as_slice(), prefix_end);
Some(Line::FormatLine(FileLine {
line : n,
indent_end : indent_end,
pfxind_end : poffset,
indent_len : indent_len,
prefix_len : prefix_len
}))
}
}
// a paragraph : a collection of FileLines that are to be formatted
// plus info about the paragraph's indentation
// (but we only retain the String from the FileLine; the other info
// is only there to help us in deciding how to merge lines into Paragraphs
#[deriving(Show)]
pub struct Paragraph {
lines : Vec<String>, // the lines of the file
pub init_str : String, // string representing the init, that is, the first line's indent
pub init_len : uint, // printable length of the init string considering TABWIDTH
init_end : uint, // byte location of end of init in first line String
pub indent_str : String, // string representing indent
pub indent_len : uint, // length of above
indent_end : uint, // byte location of end of indent (in crown and tagged mode, only applies to 2nd line and onward)
pub mail_header : bool // we need to know if this is a mail header because we do word splitting differently in that case
}
// an iterator producing a stream of paragraphs from a stream of lines
// given a set of options.
pub struct ParagraphStream<'a> {
lines : Peekable<Line, FileLines<'a>>,
next_mail : bool,
opts : &'a FmtOptions,
}
impl<'a> ParagraphStream<'a> {
pub fn new<'a>(opts: &'a FmtOptions, reader: &'a mut FileOrStdReader) -> ParagraphStream<'a> {
let lines = FileLines::new(opts, reader.lines()).peekable();
// at the beginning of the file, we might find mail headers
ParagraphStream { lines: lines, next_mail: true, opts: opts }
}
// detect RFC822 mail header
fn is_mail_header(line: &FileLine) -> bool {
// a mail header begins with either "From " (envelope sender line)
// or with a sequence of printable ASCII chars (33 to 126, inclusive,
// except colon) followed by a colon.
if line.indent_end > 0 {
false
} else {
let l_slice = line.line.as_slice();
if l_slice.starts_with("From ") {
true
} else {
let colon_posn =
match l_slice.find(':') {
Some(n) => n,
None => return false
};
// header field must be nonzero length
if colon_posn == 0 { return false; }
return l_slice.slice_to(colon_posn).chars().all(|x| match x as uint {
y if y < 33 || y > 126 => false,
_ => true
});
}
}
}
}
impl<'a> Iterator<Result<Paragraph, String>> for ParagraphStream<'a> {
fn next(&mut self) -> Option<Result<Paragraph, String>> {
// return a NoFormatLine in an Err; it should immediately be output
let noformat =
match self.lines.peek() {
None => return None,
Some(l) => match l {
&Line::FormatLine(_) => false,
&Line::NoFormatLine(_, _) => true
}
};
// found a NoFormatLine, immediately dump it out
if noformat {
let (s, nm) = self.lines.next().unwrap().get_noformatline();
self.next_mail = nm;
return Some(Err(s));
}
// found a FormatLine, now build a paragraph
let mut init_str = String::new();
let mut init_end = 0;
let mut init_len = 0;
let mut indent_str = String::new();
let mut indent_end = 0;
let mut indent_len = 0;
let mut prefix_len = 0;
let mut pfxind_end = 0;
let mut p_lines = Vec::new();
let mut in_mail = false;
let mut second_done = false; // for when we use crown or tagged mode
loop {
{ // peek ahead
// need to explicitly force fl out of scope before we can call self.lines.next()
let fl =
match self.lines.peek() {
None => break,
Some(l) => {
match l {
&Line::FormatLine(ref x) => x,
&Line::NoFormatLine(..) => break
}
}
};
if p_lines.len() == 0 {
// first time through the loop, get things set up
// detect mail header
if self.opts.mail && self.next_mail && ParagraphStream::is_mail_header(fl) {
in_mail = true;
// there can't be any indent or pfxind because otherwise is_mail_header would fail
// since there cannot be any whitespace before the colon in a valid header field
indent_str.push_str(" ");
indent_len = 2;
} else {
if self.opts.crown || self.opts.tagged {
init_str.push_str(fl.line.as_slice().slice_to(fl.indent_end));
init_len = fl.indent_len;
init_end = fl.indent_end;
} else {
second_done = true;
}
// these will be overwritten in the 2nd line of crown or tagged mode, but
// we are not guaranteed to get to the 2nd line, e.g., if the next line
// is a NoFormatLine or None. Thus, we set sane defaults the 1st time around
indent_str.push_str(fl.line.as_slice().slice_to(fl.indent_end));
indent_len = fl.indent_len;
indent_end = fl.indent_end;
// save these to check for matching lines
prefix_len = fl.prefix_len;
pfxind_end = fl.pfxind_end;
// in tagged mode, add 4 spaces of additional indenting by default
// (gnu fmt's behavior is different: it seems to find the closest column to
// indent_end that is divisible by 3. But honesly that behavior seems
// pretty arbitrary.
// Perhaps a better default would be 1 TABWIDTH? But ugh that's so big.
if self.opts.tagged {
indent_str.push_str(" ");
indent_len += 4;
}
}
} else if in_mail {
// lines following mail headers must begin with spaces
if fl.indent_end == 0 || (self.opts.use_prefix && fl.pfxind_end == 0) {
break; // this line does not begin with spaces
}
} else if !second_done {
// now we have enough info to handle crown margin and tagged mode
if prefix_len != fl.prefix_len || pfxind_end != fl.pfxind_end {
// in both crown and tagged modes we require that prefix_len is the same
break;
} else if self.opts.tagged && indent_len - 4 == fl.indent_len && indent_end == fl.indent_end {
// in tagged mode, indent has to be *different* on following lines
break;
} else {
// this is part of the same paragraph, get the indent info from this line
indent_str.clear();
indent_str.push_str(fl.line.as_slice().slice_to(fl.indent_end));
indent_len = fl.indent_len;
indent_end = fl.indent_end;
}
second_done = true;
} else {
// detect mismatch
if indent_end != fl.indent_end || pfxind_end != fl.pfxind_end || indent_len != fl.indent_len || prefix_len != fl.prefix_len {
break;
}
}
}
p_lines.push(self.lines.next().unwrap().get_formatline().line);
// when we're in split-only mode, we never join lines, so stop here
if self.opts.split_only {
break;
}
}
// if this was a mail header, then the next line can be detected as one. Otherwise, it cannot.
// NOTE next_mail is true at ParagraphStream instantiation, and is set to true after a blank
// NoFormatLine.
self.next_mail = in_mail;
Some(Ok(Paragraph {
lines : p_lines,
init_str : init_str,
init_len : init_len,
init_end : init_end,
indent_str : indent_str,
indent_len : indent_len,
indent_end : indent_end,
mail_header : in_mail
}))
}
}
pub struct ParaWords<'a> {
opts : &'a FmtOptions,
para : &'a Paragraph,
words : Vec<WordInfo<'a>>
}
impl<'a> ParaWords<'a> {
pub fn new<'a>(opts: &'a FmtOptions, para: &'a Paragraph) -> ParaWords<'a> {
let mut pw = ParaWords { opts: opts, para: para, words: Vec::new() };
pw.create_words();
pw
}
fn create_words<'r>(&'r mut self) {
if self.para.mail_header {
// no extra spacing for mail headers; always exactly 1 space
// safe to trim_left on every line of a mail header, since the
// first line is guaranteed not to have any spaces
self.words.extend(self.para.lines.iter().flat_map(|x| x.as_slice().words()).map(|x| WordInfo {
word : x,
word_start : 0,
word_nchars : x.len(), // OK for mail headers; only ASCII allowed (unicode is escaped)
before_tab : None,
after_tab : 0,
sentence_start : false,
ends_punct : false,
new_line : false
}));
} else {
// first line
self.words.extend(
if self.opts.crown || self.opts.tagged {
// crown and tagged mode has the "init" in the first line, so slice from there
WordSplit::new(self.opts, self.para.lines[0].as_slice().slice_from(self.para.init_end))
} else {
// otherwise we slice from the indent
WordSplit::new(self.opts, self.para.lines[0].as_slice().slice_from(self.para.indent_end))
});
if self.para.lines.len() > 1 {
let indent_end = self.para.indent_end;
let opts = self.opts;
self.words.extend(
self.para.lines.iter().skip(1).flat_map(|x| WordSplit::new(opts, x.as_slice().slice_from(indent_end))));
}
}
}
pub fn words(&'a self) -> Items<'a, WordInfo<'a>> { return self.words.iter() }
}
struct WordSplit<'a> {
opts : &'a FmtOptions,
string : &'a str,
length : uint,
position : uint,
prev_punct : bool
}
impl<'a> WordSplit<'a> {
fn analyze_tabs(&self, string: &str) -> (Option<uint>, uint, Option<uint>) {
// given a string, determine (length before tab) and (printed length after first tab)
// if there are no tabs, beforetab = -1 and aftertab is the printed length
let mut beforetab = None;
let mut aftertab = 0;
let mut word_start = None;
for (os, c) in string.char_indices() {
if !c.is_whitespace() {
word_start = Some(os);
break;
} else if c == '\t' {
if beforetab == None {
beforetab = Some(aftertab);
aftertab = 0;
} else {
aftertab = (aftertab / self.opts.tabwidth + 1) * self.opts.tabwidth;
}
} else {
aftertab += 1;
}
}
(beforetab, aftertab, word_start)
}
}
impl<'a> WordSplit<'a> {
fn new<'a>(opts: &'a FmtOptions, string: &'a str) -> WordSplit<'a> {
// wordsplits *must* start at a non-whitespace character
let trim_string = string.trim_left();
WordSplit { opts: opts, string: trim_string, length: string.len(), position: 0, prev_punct: false }
}
fn is_punctuation(c: char) -> bool {
match c {
'!' | '.' | '?' => true,
_ => false
}
}
}
pub struct WordInfo<'a> {
pub word : &'a str,
pub word_start : uint,
pub word_nchars : uint,
pub before_tab : Option<uint>,
pub after_tab : uint,
pub sentence_start : bool,
pub ends_punct : bool,
pub new_line : bool
}
// returns (&str, is_start_of_sentence)
impl<'a> Iterator<WordInfo<'a>> for WordSplit<'a> {
fn next(&mut self) -> Option<WordInfo<'a>> {
if self.position >= self.length {
return None
}
let old_position = self.position;
let new_line = old_position == 0;
// find the start of the next word, and record if we find a tab character
let (before_tab, after_tab, word_start) = match self.analyze_tabs(self.string.slice_from(old_position)) {
(b, a, Some(s)) => (b, a, s + old_position),
(_, _, None) => {
self.position = self.length;
return None;
}
};
// find the beginning of the next whitespace
// note that this preserves the invariant that self.position
// points to whitespace character OR end of string
let mut word_nchars = 0;
self.position =
match self.string.slice_from(word_start)
.find(|x: char| if !x.is_whitespace() { word_nchars += char_width(x); false } else { true }) {
None => self.length,
Some(s) => s + word_start
};
let word_start_relative = word_start - old_position;
// if the previous sentence was punctuation and this sentence has >2 whitespace or one tab, is a new sentence.
let is_start_of_sentence = self.prev_punct && (before_tab.is_some() || word_start_relative > 1);
// now record whether this word ends in punctuation
self.prev_punct = match self.string.char_range_at_reverse(self.position) {
CharRange { ch, next: _ } => WordSplit::is_punctuation(ch)
};
let (word, word_start_relative, before_tab, after_tab) =
if self.opts.uniform {
(self.string.slice(word_start, self.position), 0, None, 0)
} else {
(self.string.slice(old_position, self.position), word_start_relative, before_tab, after_tab)
};
Some(WordInfo {
word : word,
word_start : word_start_relative,
word_nchars : word_nchars,
before_tab : before_tab,
after_tab : after_tab,
sentence_start : is_start_of_sentence,
ends_punct : self.prev_punct,
new_line : new_line
})
}
}
| mit |
zfang399/LeetCode-Problems | 69.cpp | 268 | class Solution {
public:
int mySqrt(int x) {
long long f=0,r=x,mid;
while(f<=r){
mid=(f+r)/2;
if(mid*mid==x) return mid;
else if(mid*mid>x) r=mid-1;
else f=mid+1;
}
return r;
}
};
| mit |
senthilnayagam/training-ruby | nithya/13sep/hello.rb | 1561 | require 'rubygems'
require 'bundler/setup'
require 'sinatra'
require 'mysql'
require '/home/nithya/training-ruby/nithya/13sep/dbclass'
get '/hi' do
"Hello World!"
end
get '/time' do
Time.now.to_s
end
get '/hello' do
name = params[:name]
"hello "+name.to_s
end
get '/your_result' do
#~ db_conn = Mysql.new('localhost', 'root', 'root', 'Training')
"<html><head>
<link rel=\"stylesheet\" type=\"text/css\" href=\"mystyle.css\">
<title> your result </title></head>"
result = "" + "<body><h3><center>Your Result</h3><br><table border=\"1\" align=\"center\">
<tr>
<th>rollno</th>
<th>name</th>
<th>marks1</th>
<th>marks2</th>
<th>marks3</th>
<th>marks4</th>
<th>marks5</th>
<th>average</th>
<th>result</th>
</tr>"
params[:roll_no]
#~ a = db_conn.query("select * from student where roll_no = #{params[:roll_no]}")
conn= Dbclass.new
rs=conn.db(:roll_no)
rs.each do |row|
result += "<tr><td>"+row.join("</td><td>") + "</td></tr>"
end
result
#~ +a.each_hash do |key, value|
#~ +result += key.to_s
#~ +result += value.to_s
#~ "<p>Invalid roll number</p><a href= /result>Back</a></body></html>"
#~ end
end
get '/result' do
"<html>
<head>
<title>result</title>
<body>
</head>
<center><h3>Submit ur roll number to know ur result</h3>
<form action=\"/your_result\" method= \"get\">
<center>
Roll_no:<input type= \"text\" name= \"roll_no\">
<input type=\"submit\" value= \"submit\">
</form>
</body>
</html>"
end
| mit |
YaniLozanov/Software-University | C#/04. Database Module/02. Databases Advanced - Entity Framework/07. Best Practices and Architecture/Photo Share System/PhotoShare.Client/Core/Commands/LogoutCommand.cs | 1076 | using PhotoShare.Client.Core.Commands.Contracts;
using PhotoShare.Services.Contracts;
using System;
namespace PhotoShare.Client.Core.Commands
{
public class LogoutCommand : ICommand
{
private IUserSessionService userSessionService;
private IUserService userService;
public LogoutCommand(IUserService userService, IUserSessionService userSessionService)
{
this.userService = userService;
this.userSessionService = userSessionService;
}
public string Execute(string command, params string[] data)
{
if(data.Length != 0)
{
throw new InvalidOperationException($"Command {command} not valid!");
}
if (!userSessionService.IsLoggedIn())
{
throw new InvalidOperationException("You should log in first in order to logout.");
}
string loggedOutUsername = this.userService.Logout();
return $"User {loggedOutUsername} successfully logged out!";
}
}
}
| mit |
anothergbr/a-cat-named-nyan | src/test/java/com/gbr/nyan/appdirect/SubscriptionEventServiceChangeTest.java | 2330 | package com.gbr.nyan.appdirect;
import com.gbr.nyan.appdirect.entity.SubscriptionEvent;
import com.gbr.nyan.appdirect.entity.SubscriptionResponse;
import com.gbr.nyan.domain.Account;
import com.gbr.nyan.domain.AccountRepository;
import com.gbr.nyan.domain.UserRepository;
import org.junit.Before;
import org.junit.Test;
import static com.gbr.nyan.support.builder.SubscriptionEventBuilder.someEvent;
import static com.gbr.nyan.support.builder.SubscriptionEventBuilder.someStatelessEvent;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
public class SubscriptionEventServiceChangeTest {
private AccountExtractor accountExtractor;
private AccountRepository accountRepository;
private SubscriptionEventService service;
@Before
public void thisService() {
accountExtractor = mock(AccountExtractor.class);
accountRepository = mock(AccountRepository.class);
service = new SubscriptionEventService(accountExtractor, accountRepository, mock(EventUserExtractor.class), mock(UserRepository.class));
}
@Test
public void returnsUnknownErrorWhenStatelessChangeEventOccurs() {
SubscriptionEvent statelessEvent = someStatelessEvent().build();
SubscriptionResponse response = service.change(statelessEvent);
assertThat(response.getSuccess(), is("false"));
assertThat(response.getErrorCode(), is("UNKNOWN_ERROR"));
}
@Test
public void sendsEventToExtractorThenUpdatesExistingAccount() {
Account existingAccountWithNewEdition = someAccount("this-is-an-existing-account-id");
SubscriptionEvent someEvent = someEvent().build();
when(accountExtractor.whenAccountExists(someEvent)).thenReturn(existingAccountWithNewEdition);
when(accountRepository.save(existingAccountWithNewEdition)).thenReturn(existingAccountWithNewEdition);
SubscriptionResponse response = service.change(someEvent);
assertThat(response.getSuccess(), is("true"));
verify(accountExtractor).whenAccountExists(someEvent);
verify(accountRepository).save(existingAccountWithNewEdition);
}
private Account someAccount(String id) {
Account account = new Account();
account.setId(id);
return account;
}
}
| mit |
kevinali1/Pdf-Scraper | pdfscraper/toolkit/management/commands/scrape.py | 4213 | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Avg, Max, Min, Count, Sum, StdDev
import subprocess
import os
import calendar as cal
import copy
from django.conf import settings
from django.template.defaultfilters import slugify
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.utils import timezone
# Import Project models
from spiders.models import Spider, SpiderUrl, SpiderRule
from dataitems.models import DataItem
from toolkit.toolkit.spiders.spiders import CustomSpider
from scrapesessions.models import SpiderSession
# Import Python libraries
from datetime import date, datetime
import time as sleeper
# Import Scrapy Requirements
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
def bash_command(cmd):
subprocess.Popen(['/bin/bash', '-c', cmd], shell=True)
def scrape_spider(myspider):
from django.conf import settings
start_time = timezone.now()
# Save spider session
new_spider_session = SpiderSession(time_started=start_time)
new_spider_session.save()
print "Fetch Spider details"
input_required_filetype = "pdf"
print "Create spider for %s" % myspider.title
spider1 = CustomSpider(spidermodel = myspider,
spidersession = new_spider_session,
input_required_filetype=input_required_filetype,
input_allowed_domains=list(SpiderUrl.objects.filter(spider=myspider, url_type="ALLOWED_DOMAINS").values_list('url', flat=True)),
input_start_urls=list(SpiderUrl.objects.filter(spider=myspider, url_type="START_URL").values_list('url', flat=True)),
input_spider_name=myspider.title,
input_denied_files=settings.DENY_FILE_TYPES,
input_allow_rules=list(SpiderRule.objects.filter(spider=myspider, rule_type="ALLOW").values_list('regexp', flat=True)),
input_deny_rules=list(SpiderRule.objects.filter(spider=myspider, rule_type="DENY").values_list('regexp', flat=True)))
print "\n\n\n\n**********"
print "Spider Rules"
print spider1.rules
print "Spider Allowed Domains"
print spider1.allowed_domains
print "Spider Start Urls"
print spider1.start_urls
print "Spider Required Filetypes"
print spider1.required_filetypes
print "Spider Name"
print spider1.name
print "**********\n\n\n\n"
print "Get settings"
settings = get_project_settings()
print "Create crawlser"
crawler = Crawler(settings)
print "Connect crawler to reactor"
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
print "Configure crawler"
crawler.configure()
print "Crawl spider"
crawler.crawl(spider1)
print "Start crawler"
crawler.start()
print "Make logs"
#log.start()
print "Run reactor"
reactor.run() # the script will block here until the spider_closed signal was sent
end_time = timezone.now()
time_taken = round((end_time - start_time).total_seconds() / 60, 4)
print "Completed scrape"
print "Total time: %s minutes " % str(time_taken)
num_data = DataItem.objects.filter(session=new_spider_session).count()
print "Number of new pdfs found: " + str(num_data)
# Save spider session
new_spider_session.time_ended = end_time
new_spider_session.save()
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--long', '-l', dest='long',
help='Help for the long options'),
)
help = 'Help text goes here'
def handle(self, **options):
"""
"""
print "START"
#sleeper.sleep(3)
for spider in Spider.objects.filter(is_enabled=True):
print spider
scrape_spider(spider)
sleeper.sleep(2)
print "END" | mit |
eemece2/angular-bpmn | karma.conf.js | 2184 | // Karma configuration
// Generated on Fri May 01 2015 21:34:16 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/js/**/*.js',
'src/js/**/*.html',
'test/**/*.js'
],
// list of files to exclude
exclude: [
],
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"src/js/**/*.html": ["ng-html2js"]
},
ngHtml2JsPreprocessor: {
// If your build process changes the path to your templates,
// use stripPrefix and prependPrefix to adjust it.
stripPrefix: "src/",
//prependPrefix: "web/path/to/templates/",
// the name of the Angular module to create
moduleName: "bpmn.templates"
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| mit |
ptownsend1984/SampleApplications | GMailLabelCleanup/GMailLabelCleanup/App_Start/BundleConfig.cs | 1669 | using System.Web;
using System.Web.Optimization;
namespace GMailLabelCleanup
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/insights").Include(
"~/Scripts/insights.js"));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jquery-ui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/jquery-ui/css").Include(
"~/Content/themes/ui-darkness/jquery-ui.css"
));
}
}
}
| mit |
Rohitbels/KolheshwariIndustries | app/routes.js | 2979 | // These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from './utils/asyncInjectors';
const errorLoading = (err) => {
console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};
const loadModule = (cb) => (componentModule) => {
cb(null, componentModule.default);
};
export default function createRoutes(store) {
// create reusable async injectors using getAsyncInjectors factory
const { injectReducer, injectSagas } = getAsyncInjectors(store);
return [
/*{
path: '/',
name: 'home',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/HomePage/reducer'),
System.import('containers/HomePage/sagas'),
System.import('containers/HomePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('home', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
},*/ {
path: '/features',
name: 'features',
getComponent(nextState, cb) {
System.import('containers/FeaturePage')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/',
name: 'home',
getComponent(location, cb) {
System.import('components/Home')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/about',
name: 'aboutUs',
getComponent(location, cb) {
System.import('components/AboutUs')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/product',
name: 'product',
getComponent(location, cb) {
System.import('components/Product')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/contact',
name: 'contact',
getComponent(location, cb) {
System.import('components/Contact')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/counter',
name: 'counter',
getComponent(location, cb) {
System.import('components/Counter')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/navbar',
name: 'navscrollspy',
getComponent(location, cb) {
System.import('components/Navscrollspy')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '*',
name: 'notfound',
getComponent(nextState, cb) {
System.import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
];
}
| mit |
ctufo/angular2 | app/service/mock.jumbo.js | 343 | "use strict";
exports.JUMBODATA = [
{
id: 0,
item: 'home',
link: 'home',
red: false
}, {
id: 0,
item: 'Photo',
link: 'Photo',
red: false
}, {
id: 0,
item: 'Work',
link: 'Work',
red: false
}
];
//# sourceMappingURL=mock.jumbo.js.map | mit |
iiED-csumb/hackmb-partyon | backend/html/createNotification.php | 758 | <?php
include_once 'db_connect.php';
include_once 'notification.php';
$FBID = '';
$inviteId = '';
$type = '';
$startDate = '';
$data = '';
if (array_key_exists ('FBID' , $_GET )) {
$FBID = $_GET['FBID'];
}
if (array_key_exists ('inviteId' , $_GET )) {
$inviteId = $_GET['inviteId'];
}
if (array_key_exists ('type' , $_GET )) {
$type = $_GET['type'];
}
if (array_key_exists ('startDate' , $_GET )) {
$startDate = $_GET['startDate'];
}
if (array_key_exists ('data' , $_GET )) {
$data = $_GET['data'];
}
$new_notification_id = create_notification($mysqli, $FBID, $inviteId, $type, $startDate, $data);
if (null != $new_notification_id) {
echo $new_notification_id;
} else {
echo 'create notification failed';
echo $mysqli->error;
}
?> | mit |
BankOfGiving/Bog.net | Bog.Data.EntityFramework/Properties/AssemblyInfo.cs | 1378 | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Bog.Data.EntityFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Bog.Data.EntityFramework")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("193f75cc-a259-4ff3-852d-c236e7436d88")]
// Version information for an assembly consists of the following four values:
// Major Version
// Minor Version
// Build Number
// Revision
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | mit |
brakmic/BiB | src/app/reducers/stats/index.ts | 71 | export {
statsReducer,
STATS_CHANGED
} from './stats.reducer';
| mit |
christianmemije/kolibri | kolibri/content/utils/paths.py | 3735 | import os
import re
from django.conf import settings
from django.core.urlresolvers import reverse
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
# valid storage filenames consist of 32-char hex plus a file extension
VALID_STORAGE_FILENAME = re.compile("[0-9a-f]{32}(-data)?\.[0-9a-z]+")
# set of file extensions that should be considered zip files and allow access to internal files
POSSIBLE_ZIPPED_FILE_EXTENSIONS = set([".perseus", ".zip"])
# TODO: add ".epub" and ".epub3" if epub-equivalent of ZipContentView implemented
def get_content_file_name(obj):
return '{checksum}.{extension}'.format(checksum=obj.id, extension=obj.extension)
# DISK PATHS
def get_content_folder_path(datafolder):
return os.path.join(
datafolder,
"content",
)
def get_content_database_folder_path(datafolder=None):
"""
Returns the path to the content sqlite databases
($HOME/.kolibri/content/databases on POSIX systems, by default)
"""
return os.path.join(
get_content_folder_path(datafolder),
"databases",
) if datafolder else settings.CONTENT_DATABASE_DIR
def get_content_database_file_path(channel_id, datafolder=None):
"""
Given a channel_id, returns the path to the sqlite3 file
($HOME/.kolibri/content/databases/<channel_id>.sqlite3 on POSIX systems, by default)
"""
return os.path.join(
get_content_database_folder_path(datafolder),
"{}.sqlite3".format(channel_id),
)
def get_content_storage_folder_path(datafolder=None):
return os.path.join(
get_content_folder_path(datafolder),
"storage",
) if datafolder else settings.CONTENT_STORAGE_DIR
def get_content_storage_file_path(filename, datafolder=None):
assert VALID_STORAGE_FILENAME.match(filename), "'{}' is not a valid content storage filename".format(filename)
return os.path.join(
get_content_storage_folder_path(datafolder),
filename[0],
filename[1],
filename,
)
# URL PATHS
def get_content_url(baseurl=None):
return urljoin(
baseurl or settings.CENTRAL_CONTENT_DOWNLOAD_BASE_URL,
"content/",
)
def get_content_database_url(baseurl=None):
return urljoin(
get_content_url(baseurl),
"databases/",
)
def get_content_database_file_url(channel_id, baseurl=None):
return urljoin(
get_content_database_url(baseurl),
"{}.sqlite3".format(channel_id),
)
def get_content_storage_url(baseurl=None):
return urljoin(
get_content_url(baseurl),
"storage/",
)
def get_content_storage_remote_url(filename, baseurl=None):
return "{}{}/{}/{}".format(get_content_storage_url(baseurl), filename[0], filename[1], filename)
def get_channel_lookup_url(identifier=None, base_url=None):
studio_url = "/api/public/v1/channels"
if identifier:
studio_url += "/lookup/{}".format(identifier)
return urljoin(
base_url or settings.CENTRAL_CONTENT_DOWNLOAD_BASE_URL,
studio_url
)
def get_content_storage_file_url(filename, baseurl=None):
"""
Return the URL at which the specified file can be accessed. For regular files, this is a link to the static
file itself, under "/content/storage/". For "zip" files, this points to a dynamically generated view that
allows the client-side to index into the files within the zip.
"""
ext = os.path.splitext(filename)[1]
if ext in POSSIBLE_ZIPPED_FILE_EXTENSIONS:
return reverse("zipcontent", kwargs={"zipped_filename": filename, "embedded_filepath": ""})
else:
return "{}{}/{}/{}".format(get_content_storage_url(baseurl), filename[0], filename[1], filename)
| mit |
concord-consortium/codap | apps/dg/controllers/app_controller.js | 42429 | // ==========================================================================
// DG.appController
//
// Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ==========================================================================
sc_require('controllers/document_helper');
sc_require('controllers/document_controller');
sc_require('utilities/menu_pane');
sc_require('utilities/clipboard_utilities');
/** @class
Top-level coordinating controller for the DG application.
@extends SC.Object
*/
DG.appController = SC.Object.create((function () // closure
/** @scope DG.appController.prototype */ {
return { // return from closure
/**
* Options menu.
* @property {DG.MenuPane}
*/
optionMenuPane: null,
/**
* Guide menu.
* @property {SC.MenuPane}
*/
guideMenuPane: null,
/**
* Help menu.
* @property {DG.MenuPane}
*/
helpMenuPane: null,
documentArchiver: DG.DocumentHelper.create({}),
/**
* Show the case table or case card for a data context.
* @param iDataContext
*/
showCaseDisplayFor: function(iMenuItem) {
function removeCaseDisplay(componentID) {
var controller = documentController.componentControllersMap[componentID];
var view = controller.get('view');
var containerView = view.parentView;
containerView.removeComponentView(view);
}
function selectView (componentView) {
if (componentView) {
componentView.invokeLater(function () { componentView.showAndSelect(); });
}
}
// is there a data context? if so, is there a case table for it? If so,
// select it. If not create it. If there is no data context, create a
// new one.
var dataContext = iMenuItem.dataContext;
var action = iMenuItem.dgAction;
var documentController = DG.currDocumentController();
var foundView;
var caseTable;
// If no data context, we create a new one.
if (SC.none(dataContext) && action === 'openCaseTableForNewContext') {
DG.UndoHistory.execute(DG.Command.create({
name: 'dataContext.create',
undoString: 'DG.Undo.dataContext.create',
redoString: 'DG.Redo.dataContext.create',
log: 'createNewEmptyDataSet',
isUndoable: false,
execute: function () {
dataContext = DG.appController.createMinimalDataContext(
'DG.AppController.createDataSet.initialAttribute'.loc(), /*'AttributeName'*/
'DG.AppController.createDataSet.name'.loc() /* 'New Dataset' */);
caseTable = documentController.addCaseTable(
DG.mainPage.get('docView'), null,
{position: 'top', dataContext: dataContext});
this.invokeLater(function () {
caseTable.setFocusToComponentTitle();
}, 1000);
},
undo: function () {
documentController.destroyDataContext(dataContext.get('id'));
},
redo: function () {
this.execute();
}
}));
} else if (SC.none(dataContext) && action === 'openNewDataSetFromClipboard') {
this.openNewDataSetFromClipboard();
} else {
foundView = documentController.tableCardRegistry.getViewForContext(dataContext);
if (foundView) {
// find its view and make it selected
selectView(foundView);
} else {
DG.UndoHistory.execute(DG.Command.create({
name: 'caseTable.open',
undoString: 'DG.Undo.caseTable.open',
redoString: 'DG.Redo.caseTable.open',
log: 'openCaseTable: {name: "%@"}'.fmt(dataContext.get('name')),
executeNotification: DG.UndoHistory.makeComponentNotification( 'create', 'table'),
undoNotification: DG.UndoHistory.makeComponentNotification( 'delete', 'table'),
execute: function () {
caseTable = documentController.addCaseTable(
DG.mainPage.get('docView'), null,
{position: 'top', dataContext: dataContext});
selectView(caseTable);
},
undo: function () {
removeCaseDisplay(caseTable.getPath('model.id'));
},
redo: function () {
this.execute();
}
}));
}
}
return caseTable && caseTable.controller;
},
/**
* Initialization function.
*/
init: function () {
sc_super();
// Without the SC.run() we get warnings about invokeOnce() being called
// outside the run loop in SC 1.10. A better solution would probably be
// to create these menus somewhere else, but for now we just wrap them
// in a run loop to quiet the warnings.
SC.run(function() {
this.tileMenuPane = DG.MenuPane.create({
showTileList: function (iAnchor) {
this.set('items', DG.mainPage.mainPane.scrollView.contentView.get('tileMenuItems'));
this.popup(iAnchor);
},
layout: {width: 150},
menuItemDidChange: function () {
var tItemView = this.getPath('currentMenuItem.content.target'),
tPrevItemView = this.getPath('previousMenuItem.content.target');
if (tItemView) {
tItemView.get('parentView').bringToFront(tItemView);
tItemView.$().addClass('dg-component-view-staging');
tItemView.scrollToVisible();
}
if (tPrevItemView && tPrevItemView !== tItemView)
tPrevItemView.$().removeClass('dg-component-view-staging');
}.observes('currentMenuItem', 'previousMenuItem'),
willRemoveFromDocument: function () {
var tItem = this.get('currentMenuItem'),
tPrevItem = this.get('previousMenuItem');
if (tItem)
tItem.getPath('content.target').$().removeClass('dg-component-view-staging');
if (tPrevItem)
tPrevItem.getPath('content.target').$().removeClass('dg-component-view-staging');
}
});
this.caseTableMenuPane = DG.MenuPane.create({
showMenu: function (iAnchor) {
this.set('items', DG.appController.get('caseTableMenuItems'));
this.popup(iAnchor);
},
selectedItemDidChange: function () {
DG.appController.showCaseDisplayFor(this.get('selectedItem'));
}.observes('selectedItem'),
itemLayerIdKey: 'id',
layout: {width: 150}
});
this.pluginMenuPane = DG.MenuPane.create({
init: function () {
sc_super();
var pluginMetadataURL = DG.get('pluginMetadataURL');
if (!pluginMetadataURL) {
DG.logWarn('Plugin metadata URL absent.');
}
// Retrieve plugin metadata for later reference
$.ajax(pluginMetadataURL, {
success: function (data) {
SC.run(function () {
DG.set('pluginMetadata', data);
this.set('items', DG.appController.get('pluginMenuItems'));
}.bind(this));
}.bind(this),
error: function () {
DG.logError('Plugin Metadata Get failed: ' + pluginMetadataURL);
}
});
},
showMenu: function (iAnchor) {
this.popup(iAnchor);
},
openStandardPlugin: function (pluginDef) {
var doc = DG.currDocumentController();
var tComponent = DG.Component.createComponent({
type: "DG.GameView",
document: doc.get('content') ,
layout: pluginDef.dimensions,
componentStorage: {
currentGameName: pluginDef.title,
currentGameUrl: pluginDef.url,
allowInitGameOverride: true
}
});
doc.createComponentAndView( tComponent);
},
selectedItemDidChange: function () {
var selectedItem = this.get('selectedItem');
if (selectedItem) {
this.openStandardPlugin(selectedItem);
this.set('selectedItem', null);
}
}.observes('selectedItem'),
itemLayerIdKey: 'id',
layout: {width: 150}
});
this.optionMenuPane = DG.MenuPane.create({
items: this.get('optionMenuItems'),
itemLayerIdKey: 'id',
layout: {width: 150}
});
this.guideMenuPane = SC.MenuPane.create({
layout: {width: 250}
});
this.helpMenuPane = DG.MenuPane.create({
items: this.get('helpMenuItems'),
itemLayerIdKey: 'id',
layout: {width: 150}
});
}.bind(this));
// Give the user a chance to confirm/cancel before closing, reloading,
// or navigating away from the page. The sites listed below provide some
// information on the 'beforeunload' event and its handling, but the upshot
// is that if you return a string, then the browser will provide a dialog
// that should include the returned string (Firefox >= 4 chooses not to on
// the grounds that there are security concerns).
// https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
// http://bytes.com/topic/javascript/insights/825556-using-onbeforeunload-javascript-event
// https://bugzilla.mozilla.org/show_bug.cgi?id=588292 for discussion of Firefox functionality.
// TODO: This confirmation message can cause an unescapable loop if
// TODO: saving fails. Need a way out in these circumstances.
window.onbeforeunload = function (iEvent) {
if (DG.currDocumentController().get('hasUnsavedChanges') &&
(DG.get('embeddedMode') === 'no') &&
(DG.get('componentMode') === 'no')) {
return 'DG.AppController.beforeUnload.confirmationMessage'.loc();
}
};
},
dataSetDeleteAgent: SC.Object.extend({
deleteWithAlert: function (menu) {
DG.AlertPane.warn({
dataContext: this.dataContext,
doDelete: function () {
DG.currDocumentController().destroyDataContext(this.get('dataContext').get('id'));
},
message: 'DG.TableController.deleteDataSet.confirmMessage'.loc(
this.get('dataContext').get('title')),
description: 'DG.TableController.deleteDataSet.confirmDescription'.loc(),
buttons: [{
title: 'DG.TableController.deleteDataSet.okButtonTitle',
action: 'doDelete',
localize: YES
}, {
title: 'DG.TableController.deleteDataSet.cancelButtonTitle',
localize: YES
}],
localize: false
});
}
}),
caseTableMenuItems: function () {
var documentController = DG.currDocumentController();
var dataContexts = documentController.get('contexts');
var menuItems = dataContexts.map(function (dataContext) {
var viewType = documentController.tableCardRegistry.getActiveViewTypeForContext(dataContext.get('id'));//'DG.CaseTable' || 'DG.CaseCard'
return {
localize: false,
title: dataContext.get('title'),
toolTip: 'DG.AppController.caseTableMenu.openCaseTableToolTip',
target: DG.appController,
icon: viewType==='DG.CaseCard'? 'tile-icon-card': 'tile-icon-table',
dataContext: dataContext,
rightIcon: 'dg-trash-icon',
rightTarget: this.dataSetDeleteAgent.create({dataContext: dataContext}),
rightAction: 'deleteWithAlert',
rightToolTip: 'DG.AppController.caseTableMenu.deleteDataSetToolTip'
};
}.bind(this));
menuItems.push({
localize: true,
title: 'DG.AppController.caseTableMenu.clipboardDataset',
toolTip: 'DG.AppController.caseTableMenu.clipboardDatasetToolTip',
target: DG.appController,
isEnabled: DG.ClipboardUtilities.canPaste(),
dgAction: 'openNewDataSetFromClipboard',
icon: 'tile-icon-table'
});
menuItems.push({
localize: true,
title: 'DG.AppController.caseTableMenu.newDataSet',
toolTip: 'DG.AppController.caseTableMenu.newDataSetToolTip',
target: DG.mainPage,
dgAction: 'openCaseTableForNewContext',
icon: 'tile-icon-table'
});
return menuItems;
}.property(),
pluginMenuItems: function () {
// DG.log('Making plugin menu items');
var baseURL = DG.get('pluginURL');
var pluginMetadata = DG.get('pluginMetadata');
var items = pluginMetadata? pluginMetadata.map(function (pluginData) {
return {
localize: true,
title: pluginData.title,
url: baseURL + pluginData.path,
target: this,
toolTip: pluginData.description,
dgAction: 'openPlugin',
dimensions: {
width: pluginData.width || 400,
height: pluginData.height || 300
},
icon: pluginData.icon? baseURL + pluginData.icon: 'tile-icon-mediaTool',
// replace spaces with hyphens when creating the id
id: 'dg-pluginMenuItem-' + pluginData.title.replace(/ /g, '-')
};
}): [];
return items;
}.property(),
optionMenuItems: function () {
return [
{ localize: true, title: 'DG.AppController.optionMenuItems.viewWebPage', // "View Web Page..."
target: this, dgAction: 'viewWebPage', id: 'dg-optionMenuItem-view_webpage' },
{ localize: true, title: 'DG.AppController.optionMenuItems.configureGuide', // "Configure Guide..."
target: this, dgAction: 'configureGuide', id: 'dg-optionMenuItem-configure-guide' }
];
}.property(),
helpMenuItems: function () {
return [
{ localize: true, title: 'DG.AppController.optionMenuItems.help', // "Help...",
target: this, dgAction: 'showHelpSite', id: 'dg-optionMenuItem-help-website' },
{ localize: true, title: 'DG.AppController.optionMenuItems.help-forum', // "Help...",
target: this, dgAction: 'showHelpForum', id: 'dg-optionMenuItem-help-forum' },
{ localize: true, title: 'DG.AppController.optionMenuItems.toWebSite', // "CODAP website...",
target: this, dgAction: 'showWebSite', id: 'dg-optionMenuItem-codap-website' },
{ localize: true, title: 'DG.AppController.optionMenuItems.toPrivacyPage', // "CODAP privacy...",
target: this, dgAction: 'showPrivacyPage', id: 'dg-optionMenuItem-privacy-page' }
// { localize: true, title: 'DG.AppController.optionMenuItems.reportProblem', // "Report Problem..."
// target: this, dgAction: 'reportProblem', id: 'dg-optionMenuItems-report-problem' }
];
}.property(),
openNewDataSetFromClipboard: function() {
var _this = this;
window.focus();
if (document.activeElement) {
document.activeElement.blur();
}
window.navigator.clipboard.readText().then(
function(data) {
SC.run(function () {
if (/^https?:\/\/[^\n]*$/.test(data)) {
_this.importURL(data);
} else {
_this.openCSVImporter({
contentType: 'text/csv',
text: data,
datasetName: 'clipboard data',
showCaseTable: true
});
}
});
},
function (err) {
// maybe user didn't grant access to read from clipboard
console.log('Error importing from clipboard: ', err);
}
);
},
extractNameFromURLPath: function (iURL) {
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return a;
}
var parsedURL = parseURL(iURL);
if (parsedURL.protocol === 'data:') {
return 'data';
}
var fullPathname = parsedURL.pathname;
var path = fullPathname?fullPathname
.replace(/\/$/, '')
.replace(/.*\//, '')
.replace(/\.[^.]*$/, '')||iURL:iURL;
return path;
},
/**
* Imports text (e.g. from a CSV file) to the document from a URL.
*
* @param {string} iURL The url of a text (e.g. CSV) file
* @param {Boolean} iShowCaseTable
* @return {Deferred|undefined}
*/
importTextFromUrl: function (iURL, iShowCaseTable, iName) {
var name = iName || this.extractNameFromURLPath(iURL);
this.openCSVImporter({
contentType: 'text/csv',
url: iURL,
datasetName: name,
showCaseTable: iShowCaseTable
});
},
importGeoJSONFromURL: function (iURL) {
var name = this.extractNameFromURLPath(iURL);
this.openGeoJSONImporter({
contentType: 'application/geo+json',
url: iURL,
datasetName: name,
showCaseTable: false
});
},
openImporterPlugin: function(iName, iPath, iGameState) {
var tComponent = DG.Component.createComponent({
type: 'DG.GameView',
layout: {
isVisible: false
},
componentStorage: {
currentGameName: iName,
currentGameUrl: DG.get('pluginURL') + iPath,
savedGameState: iGameState,
title: iName,
}
});
DG.currDocumentController().createComponentAndView(tComponent);
},
/**
* Opens the CSV Importer plugin, preconfigured with the information
* it needs to perform the import.
* @param iConfig {Object} Configuration, as follows (iConfig must have
* one of url or data, but not both)
*
* url: url refering to a CSV or tab delimited file
* data: an array of arrays
* datasetName: the name of the dataset
* showCaseTable: whether to display the case
* table for the new context
*/
openCSVImporter: function (iConfig) {
this.openImporterPlugin('Importer', '/Importer/', iConfig);
},
openGeoJSONImporter: function (iConfig) {
this.openImporterPlugin('Importer', '/Importer/', iConfig);
},
openHTMLImporter: function (iConfig) {
this.openImporterPlugin('Importer', '/Importer/', iConfig);
},
openGoogleSheetsImporter: function (iConfig) {
this.openImporterPlugin('Importer', '/Importer/', iConfig);
},
/**
* Imports a csv to the document from a data uri.
*
* @param {string} iURL The url of a text (e.g. CSV) file as a data uri
* @return {Deferred|undefined}
*/
importCSVFromDataUri: function (iURL) {
if (iURL) {
var urlParts = iURL.match(/^data:text\/csv;((base64),|(charset)=([^,]+),)?(.*)$/);
if (urlParts) {
var doc = urlParts[5];
if (urlParts[2] === "base64") {
try {
doc = atob(doc);
}
catch (e) {
doc = null;
DG.logWarn(e);
}
}
else {
// keep decoding until there are no encoded characters (to ensure against double encoding)
while (doc.match(/%[0-9a-f]{2}/i)) {
doc = decodeURIComponent(doc);
}
}
if (doc !== null) {
SC.run(function() {
return this.importText(doc, "Imported CSV");
}.bind(this));
}
}
}
},
/**
* Create a data context from a string formatted as a CSV file.
* @param iColumnName {string}
* @param iContextName {string}
* @return {DG.DataContext}
*/
createMinimalDataContext: function (iColumnName, iContextName) {
// Create document-specific store.
var context, contextRecord,
documentController = DG.currDocumentController(),
baseContextName = iContextName.replace(/.*[\\\/]/g, '').replace(/\.[^.]*/, ''),
contextName = baseContextName,
collectionName = 'DG.AppController.createDataSet.collectionName'.loc(),
i = 1;
// guarantee uniqueness of data context name/title
while (documentController.getContextByName(contextName) ||
documentController.getContextByTitle(contextName)) {
contextName = baseContextName + " " + (++i);
}
// Create the context record.
contextRecord = DG.DataContextRecord.createContext({
title: contextName,
name: contextName,
collections: [{
name: collectionName,
attrs: [{
name: iColumnName
}]
}],
contextStorage: {}
});
// create the context
context = documentController.createDataContextForModel(contextRecord);
context.restoreFromStorage(contextRecord.contextStorage);
return context;
},
/**
* Create a data context from a CSV string and expose it as a case table.
* @param iText String either CSV or tab-delimited
* @param iName String document name
* @param { Boolean } iShowCaseTable Defaults to true
* @returns {Boolean}
*/
importText: function( iText, iName, iFilename, iShowCaseTable) {
this.openCSVImporter({
contentType: 'text/csv',
text: iText,
datasetName: iName,
filename: iFilename,
showCaseTable: iShowCaseTable
});
return true;
},
importHTMLTable: function (iText) {
this.openHTMLImporter({
contentType: 'text/html',
text: iText
});
return true;
},
importGoogleSheets: function (iURL) {
var config = {
contentType: 'application/vnd.google-apps.spreadsheet',
url: iURL,
showCaseTable: true
};
this.openGoogleSheetsImporter(config);
},
importImage: function(iURL, iName) {
function determineImageSize(imgSrc, callback) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
newImg = undefined;
callback(width, height);
};
newImg.src = imgSrc; // this must be done AFTER setting onload
}
var documentController = DG.currDocumentController();
var tName = iName? iName.slice(0,30): '';
determineImageSize(iURL, function (iWidth, iHeight) {
SC.run(function () {
documentController.addImageView( DG.mainPage.get('docView'), null,
iURL, tName, {width: Math.min(iWidth, 480),
height: Math.min(iHeight + 25, 385) });
});
});
},
/**
*
* @param iURL - the URL of a webpage, data interactive, csv or json document based on
* file extension in pathname.
* @param iComponentType - (optional) the type of the component, defaults to DG.GameView
* @returns {Boolean}
*/
importURL: function (iURL, iComponentType, iName) {
var addInteractive = function () {
var tDoc = DG.currDocumentController(),
tComponent;
switch (iComponentType || "DG.GameView") {
case "DG.GameView":
tComponent = DG.Component.createComponent({
"type": "DG.GameView",
"document": tDoc.get('content') ,
"componentStorage": {
"currentGameName": "",
"currentGameUrl": iURL,
allowInitGameOverride: true
}
});
tDoc.createComponentAndView( tComponent);
break;
case "DG.WebView":
tDoc.addWebView(DG.mainPage.get('docView'), null, iURL, 'Web Page', {width: 600, height: 400});
break;
}
}.bind(this);
// from: http://www.abeautifulsite.net/parsing-urls-in-javascript/
var urlParser = document.createElement('a');
urlParser.href = iURL;
var baseURL = urlParser.protocol + urlParser.host + urlParser.pathname;
var mimeSpec = this.matchMimeSpec(baseURL, iComponentType);
if (!mimeSpec) { mimeSpec = {group:'UNKOWN',mime: ['unkown']}; }
DG.log('Opening url "%@" of type %@'.loc(iURL, mimeSpec.mime[0]));
if (mimeSpec) {
switch (mimeSpec.group) {
case 'TEXT':
this.importTextFromUrl(iURL, false, iName);
break;
case 'GEOJSON':
this.importGeoJSONFromURL(iURL);
break;
case 'JSON':
DG.cfmClient.openUrlFile(iURL);
break;
case 'IMAGE':
this.importImage(iURL, iName);
break;
case 'SHEETS':
this.importGoogleSheets(iURL);
break;
default:
addInteractive();
}
}
return true;
},
importDrawToolWithDataURL: function(iDataURL, iTitle) {
var kWidth = 600, kHeight = 400,
kComponentType = 'DG.GameView',
layout = { width : kWidth, height: kHeight },
drawToolUrl = DG.get('drawToolPluginURL'),
title = "DG.DataDisplayMenu.imageOfTitle".loc(iTitle),
tDoc = DG.currDocumentController(),
tComponent = DG.Component.createComponent({
type: kComponentType,
document: tDoc.get('content'),
layout: layout,
componentStorage: {
currentGameName: title,
currentGameUrl: drawToolUrl,
allowInitGameOverride: true
}
}),
tComponentArgs = { initiatedViaCommand: true },
tView = tDoc.createComponentAndView(tComponent, kComponentType, tComponentArgs),
tSuperView = tView && tView.get('parentView'),
tController = tView && tView.get('controller');
if (tSuperView && tSuperView.positionNewComponent)
tSuperView.positionNewComponent(tView, 'top', true);
if (tController && tController.sendCommand)
tController.sendCommand({ action: 'update', resource: 'backgroundImage', values: { image: iDataURL }});
},
/**
Close the current document and all its components.
*/
closeDocument: function () {
// Destroy the document and its contents
DG.currDocumentController().closeDocument();
DG.store = null;
},
/**
* Closes the current document with confirmation.
*
* We interpose this between the menu item and closeDocumentWithConfirmation
* to correct the argument.
*
* @param {object} sender: unused by the function.
*/
closeCurrentDocument: function (sender) {
this.closeDocumentWithConfirmation(null);
},
/**
Closes the document after confirming with the user that that is desired.
*/
closeDocumentWithConfirmation: function (iDefaultGameName) {
var docName = DG.currDocumentController().get('documentName');
var closeDocumentAfterConfirmation = function () {
this.closeAndNewDocument(iDefaultGameName);
DG.logUser("closeDocument: '%@'", docName);
}.bind(this);
var cancelCloseDocument = function () {
DG.logUser("cancelCloseDocument: '%@'", docName);
};
if (DG.currDocumentController().get('hasUnsavedChanges')) {
DG.logUser("confirmCloseDocument?: '%@'", docName);
DG.AlertPane.warn({
message: 'DG.AppController.closeDocument.warnMessage',
description: 'DG.AppController.closeDocument.warnDescription',
buttons: [
{ title: 'DG.AppController.closeDocument.okButtonTitle',
action: closeDocumentAfterConfirmation,
localize: YES
},
{ title: 'DG.AppController.closeDocument.cancelButtonTitle',
action: cancelCloseDocument,
localize: YES
}
],
localize: YES
});
}
else {
closeDocumentAfterConfirmation();
}
},
/**
Close the current document and open up a new empty document.
*/
closeAndNewDocument: function (iDefaultGameName) {
// Close the current document
this.closeDocument();
// Create a new empty document
DG.currDocumentController().setDocument(DG.currDocumentController().createDocument());
},
mimeTypesAndExtensions: [
{
group: 'TEXT',
mime: ['text/csv', 'application/csv'],
extensions: ['csv']
},
{
group: 'TEXT',
mime: ['text/plain'],
extensions: ['txt']
},
{
group: 'TEXT',
mime: ['text/tab-separated-values'],
extensions: ['tsv', 'tab']
},
{
group: 'JSON',
mime: ['application/json', 'application/x-javascript', 'text/x-json'],
extensions: ['json', 'codap']
},
{
group: 'GEOJSON',
mime: ['application/geo+json','application/vnd.geo+json'],
extensions: ['geojson']
},
{
group: 'IMAGE',
mime: ['image/gif'],
extensions: ['gif']
},
{
group: 'IMAGE',
mime: ['image/jpeg'],
extensions: ['jpeg','jpg']
},
{
group: 'IMAGE',
mime: ['image/png'],
extensions: ['png']
},
{
group: 'IMAGE',
mime: ['image/svg+xml'],
extensions: ['svg', 'svgz']
}/*,
{
group: 'IMAGE',
mime: 'application/pdf',
xtensions: 'pdf'
}*/,
{
group: 'SHEETS',
mime: ['application/vnd.google-apps.spreadsheet'],
extensions: []
}
],
/**
* Attempts to match a filename or URL or a type to an entry in the above
* spec list.
* @param name: a filename or URL
* @param type: a type string. May be missing.
*/
matchMimeSpec: function (name, type) {
var isSheetsURL = /docs.google.com\/spreadsheets/.test(name);
var isDataURIMatch = /^data:([^;]+);.+$/.exec(name);
var match = name && name.match(/\.([^.\/]+)$/);
var mySuffix = match && match[1].toLowerCase();
var typeDesc;
// if we haven't a type and its a data URI, use its mime type
if (type == null && isDataURIMatch) {
type = isDataURIMatch[1];
}
if (isSheetsURL) {
type = 'application/vnd.google-apps.spreadsheet';
}
typeDesc = typeDesc || type && this.mimeTypesAndExtensions.find(function (mimeDef) {
return (type != null) && mimeDef.mime.find(function (str) {
return str === type;
});
});
typeDesc = typeDesc || this.mimeTypesAndExtensions.find(function (mimeDef) {
return mySuffix && mimeDef.extensions.find(function (ext) {
return mySuffix === ext;
});
});
return typeDesc;
},
/**
Imports a dragged or selected file
*/
importFile: function ( iFile) {
var typeDesc = this.matchMimeSpec(iFile.name, iFile.type);
var handlingGroup = typeDesc? typeDesc.group: 'JSON';
var tAlertDialog = {
showAlert: function( iError) {
var message = 'DG.AppController.dropFile.error'.loc(iError.message);
if (DG.cfmClient) {
DG.cfmClient.alert(message);
}
else {
DG.AlertPane.show( {
message: message
});
}
},
close: function() {
// Do nothing
}
};
DG.log('Opening file "%@" of type %@'.loc(iFile && iFile.name, typeDesc? typeDesc.mime[0]: 'unknown'));
this.importFileWithConfirmation(iFile, handlingGroup, tAlertDialog);
},
/**
* Read a file from the file system.
*
* Handles CODAP documents and 'TEXT' files
* (TEXT files here means comma or tab delimited data files.)
* Will present a confirmation dialog if the type indicates a CODAP document
* and the document is managed by the document server and has unsaved
* changes.
*
* The file parameter may have come from a drop or a dialog box.
* @param {File} iFile
* @param {String} iType 'JSON' or 'TEXT'
* @param {{showAlert:function,close:function}} iDialog optional error alert.
*/
importFileWithConfirmation: function( iFile, iType, iDialog) {
var finishImport = function() {
function handleAbnormal() {
console.log("Abort or error on file read.");
}
var handleRead = function () {
SC.run(function() {
try {
if (iType === 'JSON') {
DG.cfmClient.openLocalFile(iFile);
window.location.hash = '';
DG.log('Opened: ' + iFile.name);
}
else if (iType === 'GEOJSON') {
that.openGeoJSONImporter({
contentType: 'application/geo+json',
text: this.result,
datasetName: iFile.name.replace(/\.[^.]*$/, ''),
filename: iFile.name,
showCaseTable: true
});
}
else if (iType === 'TEXT') {
that.importText(this.result,
iFile.name.replace(/\.[^.]*$/, ''), iFile.name);
}
else if (iType === 'IMAGE') {
that.importImage(this.result, iFile.name);
}
if (iDialog)
iDialog.close();
}
catch (er) {
console.log(er);
if (iDialog) {
iDialog.showAlert(er);
}
}
}.bind(this));
};
var that = this;
DG.busyCursor.show( function() {
var reader = new FileReader();
if (iFile) {
reader.onabort = handleAbnormal;
reader.onerror = handleAbnormal;
reader.onload = handleRead;
if (iType === 'IMAGE') {
reader.readAsDataURL(iFile);
} else {
reader.readAsText(iFile);
}
}
});
}.bind( this);
var docName;
var cancelCloseDocument = function () {
DG.logUser("cancelCloseDocument: '%@'", docName);
};
if ((iType === 'JSON') && DG.currDocumentController().get('hasUnsavedChanges')) {
docName = DG.currDocumentController().get('documentName');
DG.logUser("confirmCloseDocument?: '%@'", docName);
DG.AlertPane.warn({
message: 'DG.AppController.closeDocument.warnMessage',
description: 'DG.AppController.closeDocument.warnDescription',
buttons: [
{ title: 'DG.AppController.closeDocument.okButtonTitle',
action: finishImport,
localize: YES
},
{ title: 'DG.AppController.closeDocument.cancelButtonTitle',
action: cancelCloseDocument,
localize: YES
}
],
localize: YES
});
}
else {
DG.busyCursor.show(function() {
finishImport();
});
}
if( iDialog)
iDialog.close();
},
/**
Bring up the bug report page.
*/
reportProblem: function () {
var submitFeedback= function() {
console.log(feedbackPane.contentView.subjectText.value);
console.log(feedbackPane.contentView.feedbackText.value);
console.log("Build #"+DG.BUILD_NUM);
console.log("Browser: "+SC.browser.name+" v."+SC.browser.version);
console.log("Device: "+SC.browser.device);
console.log("OS: "+SC.browser.os+ " v."+SC.browser.osVersion);
//SC.Request.postUrl('http://app.codap.concord.org/DataGames/WebPages/scripts/datagames.php?'+
SC.Request.postUrl('https://codap.concord.org/help/contact?'+
'device='+ SC.browser.device +
'&os='+SC.browser.os+
'&os_version='+SC.browser.osVersion+
'&cf_browser='+SC.browser.name+
'&cf_browser_version='+SC.browser.version+
'&version='+DG.BUILD_NUM+
// '&name='+iUser+
'&description='+feedbackPane.contentView.subjectText.value+
'&comments='+feedbackPane.contentView.feedbackText.value)
// .notify()
.send();
feedbackPane.remove();
feedbackPane=null;
};
var cancelFeedback= function() {
feedbackPane.remove();
feedbackPane=null;
};
//Begin feedback form
var feedbackPane=SC.PanelPane.create({
layout: { top: 175, centerX: 0, width: 405, height: 350 },
contentView: SC.View.extend({
backgroundColor: '#dde2e8',
childViews: 'feedbackHeader codapLogo feedbackImage subHeaderText messageText subjectText feedbackText submitFeedbackButton cancelFeedbackButton'.w(),
feedbackHeader: SC.LabelView.design({
layout: { top: 27, height: 20 },
controlSize: SC.LARGE_CONTROL_SIZE,
fontWeight: SC.BOLD_WEIGHT,
textAlign: SC.ALIGN_CENTER,
value: 'DG.AppController.feedbackDialog.dialogTitle',
localize: YES
}),
codapLogo: SC.ImageView.design({
layout: {top:10, left:10, height:35, width:35},
value: static_url('images/codap_logo.png')
}),
subHeaderText: SC.LabelView.design({
layout: { top: 55, left: 10},
fontWeight: SC.BOLD_WEIGHT,
value: 'DG.AppController.feedbackDialog.subHeaderText',
localize: YES
}),
messageText: SC.LabelView.design({
layout: { top: 70, left: 10, right: 0, width: 395},
textAlign: SC.ALIGN_LEFT,
value: 'DG.AppController.feedbackDialog.messageText',
localize: YES
}),
subjectText: SC.TextFieldView.design({
layout: { top: 110, left: 10, width: 385, height: 20 },
autoCorrect: false,
autoCapitalize: false,
hint: 'DG.AppController.feedbackDialog.subjectHint'
}),
feedbackText: SC.TextFieldView.design({
layout: { top: 140, left: 10, height: 170, width: 385 },
isTextArea: true,
autoCorrect: false,
autoCapitalize: false,
hint:'DG.AppController.feedbackDialog.feedbackHint'
}),
submitFeedbackButton: SC.ButtonView.design({
layout: { bottom: 10, height: 24, right: 10, width: 113 },
title: 'DG.AppController.feedbackDialog.submitFeedbackButton',
localize: YES,
action: submitFeedback,
isDefault: NO
}),
cancelFeedbackButton: SC.ButtonView.design({
layout: { bottom: 10, height: 24, right: 135, width: 113 },
title: 'DG.AppController.feedbackDialog.cancelFeedbackButton',
localize: YES,
action: cancelFeedback,
isDefault: NO
})
})
});
feedbackPane.append();
feedbackPane.contentView.subjectText.becomeFirstResponder();
},
/**
Pass responsibility to document controller
*/
viewWebPage: function () {
DG.currDocumentController().viewWebPage();
},
/**
Pass responsibility to document controller
*/
configureGuide: function () {
DG.currDocumentController().configureGuide();
},
/**
Show the help window.
*/
showHelp: function () {
var kWidth = 600, kHeight = 400,
tLayout = { width : kWidth, height: kHeight };
DG.currDocumentController().addWebView(DG.mainPage.get('docView'), null,
(DG.showHelpURL),
'DG.AppController.showHelpTitle'.loc(), //'Help with CODAP'
tLayout);
},
openWebView: function( iURL, iTitle, iWidth, iHeight) {
var tDocFrame = DG.mainPage.mainPane.scrollView.frame(),
tLayout = { left: (tDocFrame.width - iWidth) / 2, top: (tDocFrame.height - iHeight) / 2,
width: iWidth, height: iHeight };
//var windowFeatures = "location=yes,scrollbars=yes,status=yes,titlebar=yes";
DG.currDocumentController().addWebView(DG.mainPage.get('docView'), null,
iURL, iTitle, tLayout);
},
/**
Open a new tab with the CODAP website.
*/
showWebSite: function () {
var kWebsiteURL = DG.get('showWebSiteURL');
window.open(kWebsiteURL); //If tab with site is already open, no new tabs are generated, but tab with page does not come forward
},
showPrivacyPage: function () {
var kWebsiteURL = DG.get('showPrivacyURL');
window.open(kWebsiteURL);
},
/**
Open a new tab with the CODAP help pages.
*/
showHelpSite: function () {
var tLang = DG.get('currentLanguage');
var tHelpURL = DG.get('showHelpURL_' + tLang) || DG.get('showHelpURL'),
tWidth = 400, tHeight = 400;
this.openWebView( tHelpURL, 'DG.AppController.showHelpTitle'.loc(), tWidth, tHeight);
},
/**
Open a new tab with the CODAP help forum.
*/
showHelpForum: function () {
var tHelpForumURL = DG.get('showHelpForumURL'),
tWidth = 400, tHeight = 400,
tBrowser = SC.browser;
if(tBrowser.name === SC.BROWSER.safari && tBrowser.os === SC.OS.ios) {
this.openWebView( tHelpForumURL, 'DG.AppController.showHelpForumTitle'.loc(), tWidth, tHeight);
}
else {
window.open(tHelpForumURL);
}
},
openPlugin: function (iURL) {
this.importURL(iURL);
}
}; // end return from closure
}())); // end closure
| mit |
WonbaeLee/cmoa | cmoa/src/main/java/com/itwill/cmoa/model/dao/TheBlogDao.java | 3863 | package com.itwill.cmoa.model.dao;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.itwill.cmoa.model.dto.Blog;
import com.itwill.cmoa.model.dto.Friend;
import com.itwill.cmoa.model.dto.Good;
import com.itwill.cmoa.model.dto.Member;
import com.itwill.cmoa.model.dto.Rply;
import com.itwill.cmoa.model.mapper.BlogMapper;
import oracle.net.aso.s;
@Repository("blogDao")
public class TheBlogDao implements BlogDao {
@Autowired
@Qualifier("sqlSession")
private SqlSessionTemplate sqlSessionTemplate;
@Autowired
@Qualifier("blogMapper")
private BlogMapper blogMapper;
@Override
public List<Blog> getCtgy(String mEmail) {
List<Blog> blogCtgys = blogMapper.selectCtgy(mEmail);
return blogCtgys;
}
@Override
public List<Blog> getNews(String mEmail) {
List<Blog> blogNews = blogMapper.selectNews(mEmail);
return blogNews;
}
@Override
public Member getPro(String mEmail) {
Member blogPro = blogMapper.selectPro(mEmail);
return blogPro;
}
@Override
public int updateHeoseo(String mInfo, String mEmail) {
int blogHeo = blogMapper.updateHeoseo(mInfo, mEmail);
return blogHeo;
}
@Override
public void getBlogDel(int sSeq) {
blogMapper.deletePost(sSeq);
}
@Override
public Member getconMem(String mEmail) {
Member conMem = blogMapper.conMem(mEmail);
return conMem;
}
@Override
public void setReply(String rCmt, int sSeq, String mEmail) {
blogMapper.insertReply(rCmt, sSeq, mEmail);
}
@Override
public List<Rply> getBlogReply(int sSeq) {
List<Rply> blogReply = blogMapper.selectReply(sSeq);
return blogReply;
}
public List<Good> getGoodList(int sSeq, String mEmail) {
List<Good> goodList = blogMapper.selectGoodList(sSeq, mEmail);
return goodList;
}
@Override
public List<Blog> getSelectCategory(String mEmail, String cName) {
List<Blog> selectCategory = blogMapper.selectCategory(mEmail, cName);
return selectCategory;
}
@Override
public int updateBlogContentEdit(String sCmt, int sSeq) {
int blogContent = blogMapper.updateBlogContentEdit(sCmt, sSeq);
return blogContent;
}
// 카테고리 수정 기능
@Override
public int updateBlogUpdCtgy(int cSeq, int sSeq) {
int categoryUpdate = blogMapper.updateBlogUpdCtgy(cSeq, sSeq);
return categoryUpdate;
}
@Override
public void goodInsert(String mEmail, int sSeq) {
blogMapper.goodInsert(mEmail, sSeq);
}
@Override
public void goodDelete(int sSeq) {
blogMapper.goodDelete(sSeq);
}
@Override
public int insertBlog(Blog blog) {
return blogMapper.insertBlog(blog);
}
@Override
public List<Blog> getBlogCtgys2(String mEmail) {
List<Blog> blogCtgys2 = blogMapper.selectBlogCtgys2(mEmail);
return blogCtgys2;
}
@Override
public Friend getFollow(String memail, String inmember) {
Friend followName = blogMapper.selectFollow(memail, inmember);
return followName;
}
@Override
public void followDelete(String mEmail, String mFrdMail) {
blogMapper.followDelete(mEmail, mFrdMail);
}
@Override
public void followInsert(String mEmail, String mFrdMail) {
blogMapper.followInsert(mEmail, mFrdMail);
}
@Override
public List<Friend> getSelectFollow(String inmember) {
List<Friend> selectFollowList = blogMapper.selectFollowList(inmember);
return selectFollowList;
}
@Override
public void insertCate(String mEmail, String cName) {
blogMapper.insertCate(mEmail, cName);
}
@Override
public void delectCate(String mEmail, String cName) {
blogMapper.delectCate(mEmail, cName);
}
} | mit |
GreenfieldTech/irked | src/test/java/tech/greenfield/vertx/irked/TestFieldController.java | 3113 | package tech.greenfield.vertx.irked;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static tech.greenfield.vertx.irked.Matchers.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.junit5.Checkpoint;
import io.vertx.junit5.VertxTestContext;
import tech.greenfield.vertx.irked.annotations.Delete;
import tech.greenfield.vertx.irked.annotations.Get;
import tech.greenfield.vertx.irked.annotations.Post;
import tech.greenfield.vertx.irked.annotations.Put;
import tech.greenfield.vertx.irked.base.TestBase;
import tech.greenfield.vertx.irked.status.BadRequest;
import tech.greenfield.vertx.irked.status.NoContent;
public class TestFieldController extends TestBase {
public class TestController extends Controller {
@Get("/get")
WebHandler index = r -> {
r.sendJSON(new JsonObject().put("success", true));
};
@Post("/post")
WebHandler create = r -> {
r.sendError(new BadRequest());
};
@Put("/put")
WebHandler update = r -> {
r.response().putHeader("Content-Length", "7").write("success");
};
@Delete("/delete")
WebHandler delete = r -> {
r.response(new NoContent()).end();
};
}
@BeforeEach
public void deployServer(VertxTestContext context, Vertx vertx) {
deployController(new TestController(), vertx, context.succeedingThenComplete());
}
@Test
public void testGet(VertxTestContext context, Vertx vertx) {
Checkpoint async = context.checkpoint();
getClient(vertx).get(port, "localhost", "/get").sendP().thenAccept(res -> {
assertThat(res, isOK());
JsonObject o = res.bodyAsJsonObject();
assertThat(o.getValue("success"), equalTo(Boolean.TRUE));
})
.exceptionally(failureHandler(context))
.thenRun(async::flag);
}
@Test
public void testPost(VertxTestContext context, Vertx vertx) {
Checkpoint async = context.checkpoint();
getClient(vertx).post(port, "localhost", "/post").sendP("{}").thenAccept(res -> {
assertThat(res, is(status(new BadRequest())));
JsonObject o = res.bodyAsJsonObject();
assertThat(o.getValue("message"), equalTo(new BadRequest().getMessage()));
})
.exceptionally(failureHandler(context))
.thenRun(async::flag);
}
@Test
public void testPut(VertxTestContext context, Vertx vertx) {
Checkpoint async = context.checkpoint();
getClient(vertx).put(port, "localhost", "/put").sendP("{}").thenAccept(res -> {
assertThat(res, isOK());
assertThat(res.bodyAsString(), equalTo("success"));
})
.exceptionally(failureHandler(context))
.thenRun(async::flag);
}
@Test
public void testDelete(VertxTestContext context, Vertx vertx) {
Checkpoint async = context.checkpoint();
getClient(vertx).delete(port, "localhost", "/delete").sendP("{}").thenAccept(res -> {
assertThat(res, is(status(new NoContent())));
assertThat(res.body(), is(nullValue()));
})
.exceptionally(failureHandler(context))
.thenRun(async::flag);
}
}
| mit |
ginach/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/BaseItemRequest.cs | 8486 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type BaseItemRequest.
/// </summary>
public partial class BaseItemRequest : BaseRequest, IBaseItemRequest
{
/// <summary>
/// Constructs a new BaseItemRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public BaseItemRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified BaseItem using POST.
/// </summary>
/// <param name="baseItemToCreate">The BaseItem to create.</param>
/// <returns>The created BaseItem.</returns>
public System.Threading.Tasks.Task<BaseItem> CreateAsync(BaseItem baseItemToCreate)
{
return this.CreateAsync(baseItemToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified BaseItem using POST.
/// </summary>
/// <param name="baseItemToCreate">The BaseItem to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created BaseItem.</returns>
public async System.Threading.Tasks.Task<BaseItem> CreateAsync(BaseItem baseItemToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<BaseItem>(baseItemToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified BaseItem.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified BaseItem.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<BaseItem>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified BaseItem.
/// </summary>
/// <returns>The BaseItem.</returns>
public System.Threading.Tasks.Task<BaseItem> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified BaseItem.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The BaseItem.</returns>
public async System.Threading.Tasks.Task<BaseItem> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<BaseItem>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified BaseItem using PATCH.
/// </summary>
/// <param name="baseItemToUpdate">The BaseItem to update.</param>
/// <returns>The updated BaseItem.</returns>
public System.Threading.Tasks.Task<BaseItem> UpdateAsync(BaseItem baseItemToUpdate)
{
return this.UpdateAsync(baseItemToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified BaseItem using PATCH.
/// </summary>
/// <param name="baseItemToUpdate">The BaseItem to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated BaseItem.</returns>
public async System.Threading.Tasks.Task<BaseItem> UpdateAsync(BaseItem baseItemToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<BaseItem>(baseItemToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IBaseItemRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IBaseItemRequest Expand(Expression<Func<BaseItem, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IBaseItemRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IBaseItemRequest Select(Expression<Func<BaseItem, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="baseItemToInitialize">The <see cref="BaseItem"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(BaseItem baseItemToInitialize)
{
}
}
}
| mit |
ifanjuang/themes | TLDR/sidebar.php | 1668 |
<?php
$PTs= get_post_types(array('_builtin'=>false));
foreach ($PTs as $post_type) {
if( is_post_type_hierarchical($post_type) ) $HPTs[]=$post_type;
else $IPTs[] = $post_type;
}
$output = '<nav id="nav-container" class="nav-container">';
$output .= '<div class="navDiv">';
$output.= '<ul class="navlist toPages">';
foreach ($HPTs as $HPT) {
$HPTo = get_post_type_object( $HPT );
$output .= '<li class="navlist-item toPage">';
$output .= '<a class="button-prinav mainnav-link" ajaxtype="page" href="'.get_post_type_archive_link($HPT).'">';
$output .= $HPTo->label;
$output .= '</a></li>';
}
$output .= '<li class="navlist-item toContact"><a class="button-prinav mainnav-link" ajaxtype="contact">contact</a></li>';
$output.='</ul>';
$output.='<ul id="subNavlist" class="subNavlist navlist"><li class="subNavlist-close subNavlist-toindex"><a id="subNav-index" class="subNavClose"> / CLOSE</a></li></ul>';
$output .='<ul class="navlist toFilters">';
$output .= '<li class="navlist-item toHome">';
$output .= '<a class="button-prinav mainnav-link toTLDR" ajaxtype="home" href="'.get_post_type_archive_link( get_post_type() ).'">TLDR'. /*get_post($post)->post_type.*/'</a></li>';
foreach ($IPTs as $post_type) {
$PT = get_post_type_object( $post_type );
$output .= '<li class="navlist-item toFilter">';
$output .= '<a class="button-prinav mainnav-link" ajaxtype="cpt" cpt="'.sanitize_title($PT->labels->name).'" href="' . get_post_type_archive_link( $post_type ) . '" child_data="' . CPT_getarticles($post_type) . '">';
$output .= $PT->label;
$output .= '</a></li>';
}
$output .= '</ul></div></nav>';
echo $output;
?>
| mit |
Julien35/dev-courses | 3wacademyCourses/DéveloppementJS/Movies (départ) full JS/data.js | 1020 | var movies = {
'movie-1': {
'title': 'X-Men: Days of Future Past',
'duration': 124,
'cover': 'xmen.jpg'
},
'movie-2': {
'title': 'Grace de Monaco',
'duration': 96,
'cover': 'grace.jpg'
},
'movie-3': {
'title': 'Captain America 2',
'duration': 136,
'cover': 'captain-america-2.jpg'
},
'movie-4': {
'title': 'Les yeux jaunes des crocodiles',
'duration': 121,
'cover': 'yeux-jaunes.jpg'
},
'movie-5': {
'title': 'Rio 2',
'duration': 88,
'cover': 'rio-2.jpg'
},
'movie-6': {
'title': 'Spiderman',
'duration': 145,
'cover': 'spiderman.jpg'
},
'movie-7': {
'title': "Qu'est ce qu'on a fait au bon Dieu ?",
'duration': 114,
'cover': 'bon-dieu.jpg'
},
'movie-8': {
'title': 'Grand Budapest Hotel',
'duration': 128,
'cover': 'budapest-hotel.jpg'
}
};
console.log(movies);
| mit |
Bedrock02/rainy_buckets | rainy_home/models.py | 2362 | from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, timedelta
from django.core.exceptions import ObjectDoesNotExist
import uuid
class CollectorManager(models.Manager):
@staticmethod
def collector_from_user(user_id):
try:
return Collector.objects.get(user_id=user_id)
except ObjectDoesNotExist:
return None
class Collector(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
created = models.DateField(auto_now_add=True, editable=False)
modified = models.DateTimeField(auto_now=True, editable=False)
objects = CollectorManager()
@property
def buckets(self):
return BucketManager.buckets_from_collector(self.id)
class BucketManager(models.Manager):
def create_bucket(self, collector_id, title):
new_hash = Bucket.get_bucket_hash()
return self.create(
collector_id=collector_id,
bucket_hash=new_hash,
title=title,
)
@staticmethod
def buckets_from_collector(collector_id):
return Bucket.objects.filter(collector_id=collector_id)
class Bucket(models.Model):
collector = models.ForeignKey(Collector, on_delete=models.CASCADE)
bucket_hash = models.CharField(
blank=False, max_length=255, default='')
expiration_date = models.DateField(
editable=True, default=datetime.now() + timedelta(hours=48))
title = models.CharField(
blank=False, max_length=255, default='My New Bucket')
created = models.DateField(auto_now_add=True, editable=False)
modified = models.DateTimeField(auto_now=True, editable=False)
objects = BucketManager()
@staticmethod
def get_bucket_hash():
return uuid.uuid4().hex
@property
def notes(self):
return NoteManager.notes_from_bucket(self.id)
class NoteManager(models.Manager):
@staticmethod
def notes_from_bucket(bucket_id):
# Verify that bucker_id is an int
return Note.objects.filter(bucket_id=bucket_id)
class Note(models.Model):
message = models.TextField(blank=False, default='You are enough!')
author = models.CharField(max_length=255, blank=True, default='')
bucket = models.ForeignKey(Bucket)
flagged = models.BooleanField(default=False)
created = models.DateField(auto_now_add=True, editable=False)
modified = models.DateTimeField(auto_now=True, editable=False)
objects = NoteManager()
| mit |
almadaocta/lordbike-production | app/code/core/Mage/AdminNotification/sql/adminnotification_setup/mysql4-install-1.0.0.php | 1850 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_AdminNotification
* @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer->startSetup();
$installer->run("
-- DROP TABLE IF EXISTS `{$installer->getTable('adminnotification_inbox')}`;
CREATE TABLE IF NOT EXISTS `{$installer->getTable('adminnotification_inbox')}` (
`notification_id` int(10) unsigned NOT NULL auto_increment,
`severity` tinyint(3) unsigned NOT NULL default '0',
`date_added` datetime NOT NULL,
`title` varchar(255) NOT NULL,
`description` text,
`url` varchar(255) NOT NULL,
`is_read` tinyint(1) unsigned NOT NULL default '0',
`is_remove` tinyint(1) unsigned NOT NULL default '0',
PRIMARY KEY (`notification_id`),
KEY `IDX_SEVERITY` (`severity`),
KEY `IDX_IS_READ` (`is_read`),
KEY `IDX_IS_REMOVE` (`is_remove`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");
$installer->endSetup();
| mit |
williamccondori/UPT.BOT | UPT.BOT.Presentacion.Web.Administracion/Angular/Factories/Configuracion/UsuarioFactory.js | 842 | (function (module) {
UsuarioFactory.$inject = ["$resource"];
function UsuarioFactory($resource) {
var GestionController = [];
GestionController.ObtenerUsuario = function () {
return $resource('/Configuracion/ObtenerUsuario', {}, {
Get: {
method: 'GET',
isArray: false
}
}).Get();
};
GestionController.GuardarUsuario = function (Usuario) {
return $resource('/Configuracion/GuardarUsuario', {}, {
Post: {
method: 'POST',
isArray: false
}
}).Post(Usuario);
};
return GestionController;
}
module.factory("UsuarioFactory", UsuarioFactory);
})(angular.module("uptAdministracion")); | mit |
roseweixel/blogger | db/migrate/20150512172518_create_memberships.rb | 201 | class CreateMemberships < ActiveRecord::Migration
def change
create_table :memberships do |t|
t.integer :user_id
t.integer :cohort_id
t.timestamps null: false
end
end
end
| mit |
oleander/show-time | app/lib/languages.js | 536 | export default {
keys: function(){
var keys = [];
for(var language in this.content) {
keys.push(language);
}
return keys;
},
values: function(){
var values = [];
for(var language in this.content) {
values.push(this.content[language]);
}
return values;
},
content: {
"English": "eng",
"Swedish": "swe",
"None": null
},
byKey: function(key) {
for(var k in this.content){
if(this.content[k] === key) { return k; }
}
throw key + " not found";
}
}; | mit |
patatoid/notify | app/models/notify/notification.rb | 106 | module Notify
class Notification < ActiveRecord::Base
serialize :user
serialize :result
end
end
| mit |
kottenator/my-little-blog | src/project/core/apps.py | 124 | from django.apps.config import AppConfig
class CoreConfig(AppConfig):
name = 'project.core'
verbose_name = 'Core'
| mit |
rpeev/apivis | src/index.universal.js | 65 | import apivis from './universal/apivis';
export default apivis;
| mit |
fvcproductions/BITS | Python/RSAPublicKeyAlgorithm_Program4.py | 1452 | '''
FVCproductions
RSAPublicKeyAlgorithm_Program4.py
Discrete Structures
November 2014
Written in Python 2.7
'''
# simplified values for RSA Public Key Algorithm
# published in 5.4.2
p = 23
q = 31
n = 29
z = p*q
h = (p-1)*(q-1) # phi symbol
s = 569
# encryption method
def encrypt(aString):
chars = []
for x in range(len(aString)):
chars.append(ord(aString[x]))
encrypted = []
for y in chars:
encrypted.append((y**n) % z )
return encrypted
# decryption method
def decrypt(integers):
decrypted = ""
for i in integers:
decrypted += chr((i**s) % z)
return decrypted
def printEncrypted(encryptedMessage):
toPrint = ""
for char in encryptedMessage:
toPrint += str(char) + " "
print toPrint
# main method
# asking for message from user
message = raw_input("Enter Message\n")
print "\nClear Text Message"
print message
# encrypting given message
encryptedMessage = encrypt(message)
print "\nEncrypted Message"
printEncrypted(encryptedMessage)
# decrypting the encrypted message
decryptedMessage = decrypt(encryptedMessage)
print "\nDecrypted Message"
print decryptedMessage
raw_input("\nEnter Message\n")
''' --- SAMPLE OUTPUT ---
Enter Message
This is a test message.
Clear Text Message
This is a test message.
Encrypted Message
241 637 354 644 280 354 644 280 132 280 461 4 644 461 280 250 4 644 644 132 214 4 184
Decrypted Message
This is a test message.
Enter Message
''' | mit |
mjmarianetti/computer-science | examples/algorithms/kmp.js | 172 | const KMP = require('../../index').KMP;
let str = "ABCABCABCABCABC",
pat = "ABC";
console.log("String: " + str);
console.log("Pattern: " + pat);
KMP.resolve(str, pat);
| mit |
nbwsc/leetcode | adventofcode/1206.js | 1977 | const fs = require('fs');
const input = fs
.readFileSync('input/1206')
.toString()
.trim();
// const input = `1, 1
// 1, 6
// 8, 3
// 3, 4
// 5, 5
// 8, 9`;
function getDist(x, y, point) {
return Math.abs(x - point[0]) + Math.abs(y - point[1]);
}
const points = input.split('\n').map(row => row.split(', ').map(s => +s));
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const p of points) {
if (p[0] < minX) {
minX = p[0];
}
if (p[0] > maxX) {
maxX = p[0];
}
if (p[1] < minY) {
minY = p[1];
}
if (p[1] > maxY) {
maxY = p[1];
}
}
const map = [];
const limit = 10000;
let part2count = 0;
for (let i = minX - 10; i < maxX + 10; i++) {
map[i] = [];
for (let j = minY - 10; j < maxY + 10; j++) {
// getDist();
let minDist = Infinity;
let secondDist = Infinity;
let tag;
let distSum = 0;
for (const p of points) {
const dist = getDist(i, j, p);
distSum += dist;
if (dist < minDist) {
tag = p.join();
secondDist = minDist;
minDist = dist;
} else if (dist < secondDist) {
secondDist = dist;
}
}
if (distSum < limit) {
part2count++;
}
map[i][j] = minDist === secondDist ? '.' : tag;
}
}
fs.writeFileSync('output1206.2', JSON.stringify(map));
const borderPoints = new Set();
map[minX - 10].forEach(t => borderPoints.add(t));
map[maxX + 9].forEach(t => borderPoints.add(t));
map.forEach(col => {
borderPoints.add(col[minY]);
borderPoints.add(col[maxY + 9]);
});
const areaMap = {};
for (let i = minX - 10; i < maxX + 10; i++) {
for (let j = minY - 10; j < maxY + 10; j++) {
t = map[i][j];
if (!borderPoints.has(t)) {
areaMap[t] = areaMap[t] ? areaMap[t] + 1 : 1;
}
}
}
console.log(
Object.keys(areaMap)
.sort((a, b) => {
return areaMap[a] - areaMap[b];
})
.map(m => areaMap[m])
);
// console.log(map);
console.log('part 2 ', part2count);
| mit |
boggad/jdk9-sample | sample-catalog/spring-jdk9/src/spring.messaging/org/springframework/messaging/core/DestinationResolver.java | 1244 | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.core;
/**
* Strategy for resolving a String destination name to an actual destination
* of type {@code <D>}.
*
* @author Mark Fisher
* @since 4.0
*/
@FunctionalInterface
public interface DestinationResolver<D> {
/**
* Resolve the given destination name.
* @param name the destination name to resolve
* @return the resolved destination (never {@code null})
* @throws DestinationResolutionException if the specified destination
* wasn't found or wasn't resolvable for any other reason
*/
D resolveDestination(String name) throws DestinationResolutionException;
}
| mit |
Granary/granary2 | granary/cfg/block.cc | 11332 | /* Copyright 2014 Peter Goodman, all rights reserved. */
#define GRANARY_INTERNAL
#include "granary/base/option.h"
#include "granary/cfg/block.h"
#include "granary/cfg/trace.h"
#include "granary/cfg/factory.h"
#include "granary/cfg/instruction.h"
#include "granary/app.h" // For `AppMetaData`.
#include "granary/cache.h" // For `CacheMetaData`.
#include "granary/util.h" // For `GetMetaData`.
GRANARY_DECLARE_bool(transparent_returns);
namespace granary {
GRANARY_IMPLEMENT_NEW_ALLOCATOR(NativeBlock)
GRANARY_IMPLEMENT_NEW_ALLOCATOR(CachedBlock)
GRANARY_IMPLEMENT_NEW_ALLOCATOR(DecodedBlock)
GRANARY_IMPLEMENT_NEW_ALLOCATOR(CompensationBlock)
GRANARY_IMPLEMENT_NEW_ALLOCATOR(DirectBlock)
GRANARY_IMPLEMENT_NEW_ALLOCATOR(IndirectBlock)
GRANARY_IMPLEMENT_NEW_ALLOCATOR(ReturnBlock)
GRANARY_DECLARE_CLASS_HEIRARCHY(
(Block, 2),
(NativeBlock, 2 * 3),
(InstrumentedBlock, 2 * 5),
(CachedBlock, 2 * 5 * 7),
(DecodedBlock, 2 * 5 * 11),
(CompensationBlock, 2 * 5 * 11 * 13),
(DirectBlock, 2 * 5 * 17),
(IndirectBlock, 2 * 5 * 19),
(ReturnBlock, 2 * 5 * 23))
GRANARY_DEFINE_BASE_CLASS(Block)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, NativeBlock)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, InstrumentedBlock)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, CachedBlock)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, DecodedBlock)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, CompensationBlock)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, DirectBlock)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, IndirectBlock)
GRANARY_DEFINE_DERIVED_CLASS_OF(Block, ReturnBlock)
namespace internal {
// Return the next successor by iterating through the instructions in the
// basic block.
namespace {
static Instruction *FindNextSuccessorInstruction(Instruction *instr) {
for (Instruction *curr(instr->Next()); curr; curr = curr->Next()) {
if (IsA<ControlFlowInstruction *>(curr)) {
return curr;
}
}
return nullptr;
}
} // namespace
} // namespace internal
namespace detail {
SuccessorBlockIterator::SuccessorBlockIterator(Instruction *instr_)
: cursor(instr_),
next_cursor(nullptr) {
if (cursor) {
next_cursor = cursor->Next();
}
}
BlockSuccessor SuccessorBlockIterator::operator*(void) const {
auto cti(DynamicCast<ControlFlowInstruction *>(cursor));
return BlockSuccessor(cti, cti->TargetBlock());
}
void SuccessorBlockIterator::operator++(void) {
if (next_cursor && next_cursor->Previous() != cursor) {
cursor = next_cursor;
}
next_cursor = nullptr;
if ((cursor = internal::FindNextSuccessorInstruction(cursor))) {
next_cursor = cursor->Next();
}
}
} // namespace detail
Block::Block(void)
: list(),
id(-1),
generation(0),
is_reachable(false),
successors{nullptr, nullptr},
fragment(nullptr) {}
detail::SuccessorBlockIterator Block::Successors(void) const {
return detail::SuccessorBlockIterator();
}
// Returns a unique ID for this basic block within the trace. This can be
// useful for client tools to implement data flow passes.
int Block::Id(void) const {
return id;
}
// Get this basic block's meta-data.
BlockMetaData *InstrumentedBlock::MetaData(void) {
return meta;
}
// Get this basic block's meta-data.
BlockMetaData *InstrumentedBlock::UnsafeMetaData(void) {
return meta;
}
InstrumentedBlock::InstrumentedBlock(Trace *cfg_,
BlockMetaData *meta_)
: Block(),
cfg(cfg_),
meta(meta_),
native_pc(meta ? MetaDataCast<AppMetaData *>(meta)->start_pc
: nullptr) {}
// Returns the starting PC of this basic block.
AppPC InstrumentedBlock::StartAppPC(void) const {
return native_pc;
}
// Returns the starting PC of this basic block in the code cache.
CachePC InstrumentedBlock::StartCachePC(void) const {
const auto cache_meta = MetaDataCast<CacheMetaData *>(meta);
return cache_meta->start_pc;
}
CachedBlock::CachedBlock(Trace *cfg_, const BlockMetaData *meta_)
: InstrumentedBlock(cfg_, const_cast<BlockMetaData *>(meta_)) {}
DecodedBlock::~DecodedBlock(void) {
for (Instruction *instr(first), *next_instr(nullptr); instr;) {
next_instr = instr->Next();
delete instr;
instr = next_instr;
}
first = nullptr;
last = nullptr;
}
// Initialize a decoded basic block.
DecodedBlock::DecodedBlock(Trace *cfg_, BlockMetaData *meta_)
: InstrumentedBlock(cfg_, meta_),
first(new AnnotationInstruction(kAnnotBeginBlock,
reinterpret_cast<void *>(&first))),
last(new AnnotationInstruction(kAnnotEndBlock,
reinterpret_cast<void *>(&last))),
is_cold_code(false) {
first->InsertAfter(last);
for (auto ® : arg_regs) {
reg = cfg->AllocateVirtualRegister();
}
}
InstrumentedBlock::~InstrumentedBlock(void) {
meta = nullptr;
}
// Return an iterator of the successor blocks of this basic block.
detail::SuccessorBlockIterator DecodedBlock::Successors(void) const {
return detail::SuccessorBlockIterator(
internal::FindNextSuccessorInstruction(first));
}
// Allocates a new temporary virtual register for use by instructions within
// this basic block.
VirtualRegister DecodedBlock::AllocateVirtualRegister(size_t num_bytes) {
return cfg->AllocateVirtualRegister(num_bytes);
}
// Allocates a new temporary virtual register for use by instructions within
// this basic block.
VirtualRegister DecodedBlock::AllocateTemporaryRegister(
size_t num_bytes) {
return cfg->AllocateTemporaryRegister(num_bytes);
}
// Return the first instruction in the basic block.
Instruction *DecodedBlock::FirstInstruction(void) const {
return first;
}
// Return the last instruction in the basic block.
Instruction *DecodedBlock::LastInstruction(void) const {
return last;
}
// Return an iterator for the instructions of the block.
InstructionIterator DecodedBlock::Instructions(void) const {
return InstructionIterator(first);
}
// Return a reverse iterator for the instructions of the block.
ReverseInstructionIterator
DecodedBlock::ReversedInstructions(void) const {
return ReverseInstructionIterator(last);
}
// Return an iterator for the application instructions of a basic block.
AppInstructionIterator DecodedBlock::AppInstructions(void) const {
return AppInstructionIterator(first);
}
// Return a reverse iterator for the application instructions of the block.
ReverseAppInstructionIterator
DecodedBlock::ReversedAppInstructions(void) const {
return ReverseAppInstructionIterator(last);
}
// Add a new instruction to the beginning of the instruction list.
void DecodedBlock::PrependInstruction(std::unique_ptr<Instruction> instr) {
FirstInstruction()->InsertAfter(instr.release());
}
// Add a new instruction to the end of the instruction list.
void DecodedBlock::AppendInstruction(std::unique_ptr<Instruction> instr) {
LastInstruction()->InsertBefore(instr.release());
}
// Add a new instruction to the beginning of the instruction list.
void DecodedBlock::PrependInstruction(Instruction *instr) {
FirstInstruction()->InsertAfter(instr);
}
// Add a new instruction to the end of the instruction list.
void DecodedBlock::AppendInstruction(Instruction *instr) {
LastInstruction()->InsertBefore(instr);
}
// Mark the code of this block as being cold.
void DecodedBlock::MarkAsColdCode(void) {
is_cold_code = true;
}
// Is this cold code?
bool DecodedBlock::IsColdCode(void) const {
return is_cold_code;
}
// Remove and return single instruction. Some special kinds of instructions
// can't be removed.
std::unique_ptr<Instruction> DecodedBlock::Unlink(Instruction *instr) {
if (auto annot_instr = DynamicCast<AnnotationInstruction *>(instr)) {
// Don't allow removal of these instructions.
switch (annot_instr->annotation) {
case kAnnotBeginBlock:
case kAnnotEndBlock:
case kAnnotationLabel:
case kAnnotInvalidStack:
return std::unique_ptr<Instruction>(nullptr);
default:
break;
}
// If we're unlinking a branch then make sure that the target itself does
// not continue to reference the branch.
} else if (auto branch = DynamicCast<BranchInstruction *>(instr)) {
GRANARY_ASSERT(1 <= branch->TargetLabel()->Data<uintptr_t>());
branch->TargetLabel()->DataRef<uintptr_t>() -= 1;
}
return Instruction::Unlink(instr);
}
// Truncate a decoded basic block. This removes `instr` up until the end of
// the instruction list. In some cases, certain special instructions are not
// allowed to be truncated. This will not remove such special cases.
void DecodedBlock::Truncate(Instruction *instr) {
for (Instruction *next_instr(nullptr); instr; instr = next_instr) {
next_instr = instr->Next();
Unlink(instr);
}
}
// Returns the Nth argument register for use by a lir function call.
VirtualRegister DecodedBlock::NthArgumentRegister(size_t arg_num) const {
return arg_regs[arg_num];
}
CompensationBlock::CompensationBlock(Trace *cfg_,
BlockMetaData *meta_)
: DecodedBlock(cfg_, meta_),
is_comparable(true) {}
DirectBlock::~DirectBlock(void) {
materialized_block = nullptr;
}
// Initialize a future basic block.
DirectBlock::DirectBlock(Trace *cfg_,
BlockMetaData *meta_)
: InstrumentedBlock(cfg_, meta_),
materialized_block(nullptr),
materialize_strategy(kRequestBlockLater) {}
// Returns the starting PC of this basic block.
AppPC IndirectBlock::StartAppPC(void) const {
GRANARY_ASSERT(false);
return nullptr;
}
// Returns the starting PC of this basic block in the code cache.
CachePC IndirectBlock::StartCachePC(void) const {
GRANARY_ASSERT(false);
return nullptr;
}
// Initialize a return basic block.
ReturnBlock::ReturnBlock(Trace *cfg_,
BlockMetaData *meta_)
: InstrumentedBlock(cfg_, FLAG_transparent_returns ? meta_ : nullptr),
lazy_meta(FLAG_transparent_returns ? nullptr : meta_) {}
ReturnBlock::~ReturnBlock(void) {
if (!meta && lazy_meta) {
delete lazy_meta;
}
lazy_meta = nullptr;
}
// Returns true if this return basic block has meta-data. If it has meta-data
// then the way that the branch is resolved is slightly more complicated.
bool ReturnBlock::UsesMetaData(void) const {
return nullptr != meta;
}
// Return this basic block's meta-data. Accessing a return basic block's meta-
// data will "create" it for the block.
BlockMetaData *ReturnBlock::MetaData(void) {
if (GRANARY_UNLIKELY(!UsesMetaData())) {
std::swap(lazy_meta, meta);
}
return meta;
}
// Returns the starting PC of this basic block.
AppPC ReturnBlock::StartAppPC(void) const {
GRANARY_ASSERT(false);
return nullptr;
}
// Returns the starting PC of this basic block in the code cache.
CachePC ReturnBlock::StartCachePC(void) const {
GRANARY_ASSERT(false);
return nullptr;
}
NativeBlock::NativeBlock(AppPC native_pc_)
: Block(),
native_pc(native_pc_) {}
// Returns the starting PC of this basic block.
AppPC NativeBlock::StartAppPC(void) const {
return native_pc;
}
// Returns the starting PC of this basic block in the code cache.
CachePC NativeBlock::StartCachePC(void) const {
GRANARY_ASSERT(false);
return nullptr;
}
} // namespace granary
| mit |
ringcentral/ringcentral-js-widget | packages/babel-settings/lib/register.js | 137 | require('@babel/register')({
extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs'],
ignore: [/node_modules/],
rootMode: 'upward',
});
| mit |
sanborino/clinica | src/Asi/ClinicaBundle/Controller/ReporteController.php | 1032 | <?php
namespace Asi\ClinicaBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Asi\ClinicaBundle\Entity\Cita;
use Symfony\Component\HttpFoundation\Response;
use Knp\SnappyBundle;
/**
* Reporte controller.
*
*/
class ReporteController extends Controller
{
/**
* Lists all Cita entities.
*
*/
public function viewAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AsiClinicaBundle:Cita')->findAll();
$html = $this->renderView('AsiClinicaBundle:Reporte:view.html.twig', array(
'entities' => $entities,
));
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
}
} | mit |
xy2041/GmailNotifierClone | Classes/Settings.cs | 1502 | using System;
using System.Collections.Generic;
using System.Linq;
namespace GmailNotifierClone
{
public class Settings
{
public String Login { get; set; }
public String Password { get; set; }
public bool IsNeedToSaveAuth { get; set; }
private static Settings m_instance;
public static Settings Instance
{
get { return m_instance ?? (m_instance = new Settings()); }
}
private Settings()
{
LoadSettings();
}
private void LoadSettings()
{
try
{
IsNeedToSaveAuth = Properties.Settings.Default.IsNeedToSaveAuth;
Login = Properties.Settings.Default.Login;
Password = StringCipher.Decrypt(Properties.Settings.Default.Password, Environment.MachineName + Environment.UserName);
}
catch (Exception)
{
IsNeedToSaveAuth = false;
Login = "";
Password = "";
}
}
public void Save()
{
Properties.Settings.Default.IsNeedToSaveAuth = IsNeedToSaveAuth;
Properties.Settings.Default.Login = Login;
Properties.Settings.Default.Password = StringCipher.Encrypt(Password, Environment.MachineName + Environment.UserName);
Properties.Settings.Default.Save();
}
}
}
| mit |
krayush/angularjs-cdn | src/app/app.module.ts | 1267 | // Core Modules Section
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import 'rxjs/Rx';
// Routing Section
import { AppRoutingModule } from './app-routing.module';
// Component Section
import { AppComponent } from './app.component';
import { SidebarComponent } from './components/sidebar/sidebar.component';
import { Module404Component } from './components/module-404/module-404-component';
import { DashboardModule } from './components/dashboard/dashboard.module';
// Loading Strategies
import { CustomPreloadStrategy } from './preload-strategy/custom-preload-strategy';
// Additional Providers
import { RoutesInfo } from "./resources/routes";
@NgModule({
imports: [
BrowserModule,
CommonModule,
FormsModule,
HttpModule,
DashboardModule,
AppRoutingModule
],
declarations: [
AppComponent,
SidebarComponent,
Module404Component
],
bootstrap: [
AppComponent
],
providers: [
CustomPreloadStrategy,
RoutesInfo
]
})
export class AppModule { }
| mit |
tehoko/lane | public_html/js/jquery.focuslost.js | 1029 | $(function()
{
// will store the last focus chain
var currentFocusChain = $();
// stores a reference to any DOM objects we want to watch focus for
var focusWatch = [];
function checkFocus()
{
var newFocusChain = $(':focus').parents().andSelf();
// elements in the old focus chain that aren't in the new focus chain...
var lostFocus = currentFocusChain.not(newFocusChain.get());
lostFocus.each(function()
{
if ($.inArray(this, focusWatch) != -1)
{
$(this).trigger('focuslost');
}
});
currentFocusChain = newFocusChain;
}
// bind to the focus/blur event on all elements:
$('*').on('focus blur', function(e)
{
// wait until the next free loop to process focus change
// when 'blur' is fired, focus will be unset
setTimeout(checkFocus, 0);
});
$.fn.focuslost = function(fn)
{
return this.each(function()
{
// tell the live handler we are watching this event
if ($.inArray(this, focusWatch) == -1)
focusWatch.push(this);
$(this).bind('focuslost', fn);
});
};
});
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/mediaelement/2.4.0/mediaelement-and-player.min.js | 130 | version https://git-lfs.github.com/spec/v1
oid sha256:05d6bd0c63b3b5b2e12375741bf9e0fdacc901d1df6a72fa50ac73db27fa8442
size 55080
| mit |
microlv/vscode | src/vs/workbench/parts/extensions/common/extensions.ts | 4247 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IViewlet } from 'vs/workbench/common/viewlet';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Event } from 'vs/base/common/event';
import { IPager } from 'vs/base/common/paging';
import { IQueryOptions, IExtensionManifest, LocalExtensionType, EnablementState, ILocalExtension, IGalleryExtension } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IViewContainersRegistry, ViewContainer, Extensions as ViewContainerExtensions } from 'vs/workbench/common/views';
import { Registry } from 'vs/platform/registry/common/platform';
import { CancellationToken } from 'vs/base/common/cancellation';
export const VIEWLET_ID = 'workbench.view.extensions';
export const VIEW_CONTAINER: ViewContainer = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer(VIEWLET_ID);
export interface IExtensionsViewlet extends IViewlet {
search(text: string): void;
}
export const enum ExtensionState {
Installing,
Installed,
Uninstalling,
Uninstalled
}
export interface IExtension {
type?: LocalExtensionType;
state: ExtensionState;
name: string;
displayName: string;
id: string;
uuid?: string;
publisher: string;
publisherDisplayName: string;
version: string;
latestVersion: string;
description: string;
url?: string;
repository?: string;
iconUrl: string;
iconUrlFallback: string;
licenseUrl?: string;
installCount?: number;
rating?: number;
ratingCount?: number;
outdated: boolean;
enablementState: EnablementState;
dependencies: string[];
extensionPack: string[];
telemetryData: any;
preview: boolean;
getManifest(token: CancellationToken): Promise<IExtensionManifest | null>;
getReadme(token: CancellationToken): Promise<string>;
hasReadme(): boolean;
getChangelog(token: CancellationToken): Promise<string>;
hasChangelog(): boolean;
local?: ILocalExtension;
locals?: ILocalExtension[];
gallery?: IGalleryExtension;
isMalicious: boolean;
}
export interface IExtensionDependencies {
dependencies: IExtensionDependencies[];
hasDependencies: boolean;
identifier: string;
extension: IExtension;
dependent: IExtensionDependencies | null;
}
export const SERVICE_ID = 'extensionsWorkbenchService';
export const IExtensionsWorkbenchService = createDecorator<IExtensionsWorkbenchService>(SERVICE_ID);
export interface IExtensionsWorkbenchService {
_serviceBrand: any;
onChange: Event<IExtension | undefined>;
local: IExtension[];
queryLocal(): Promise<IExtension[]>;
queryGallery(options?: IQueryOptions): Promise<IPager<IExtension>>;
canInstall(extension: IExtension): boolean;
install(vsix: string): Promise<void>;
install(extension: IExtension, promptToInstallDependencies?: boolean): Promise<void>;
uninstall(extension: IExtension): Promise<void>;
installVersion(extension: IExtension, version: string): Promise<void>;
reinstall(extension: IExtension): Promise<void>;
setEnablement(extensions: IExtension | IExtension[], enablementState: EnablementState): Promise<void>;
loadDependencies(extension: IExtension, token: CancellationToken): Promise<IExtensionDependencies | null>;
open(extension: IExtension, sideByside?: boolean): Promise<any>;
checkForUpdates(): Promise<void>;
allowedBadgeProviders: string[];
}
export const ConfigurationKey = 'extensions';
export const AutoUpdateConfigurationKey = 'extensions.autoUpdate';
export const AutoCheckUpdatesConfigurationKey = 'extensions.autoCheckUpdates';
export const ShowRecommendationsOnlyOnDemandKey = 'extensions.showRecommendationsOnlyOnDemand';
export const CloseExtensionDetailsOnViewChangeKey = 'extensions.closeExtensionDetailsOnViewChange';
export interface IExtensionsConfiguration {
autoUpdate: boolean;
autoCheckUpdates: boolean;
ignoreRecommendations: boolean;
showRecommendationsOnlyOnDemand: boolean;
closeExtensionDetailsOnViewChange: boolean;
}
| mit |
kencookco/spring-sharpspring-api | src/test/java/com/kencook/sharpspring/SharpspringOperationsTest.java | 1427 | package com.kencook.sharpspring;
import com.kencook.sharpspring.responses.GetEventsResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static com.kencook.sharpspring.SharpspringRequestBuilder.request;
import static org.assertj.core.api.Assertions.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SharpspringOperationsTest {
@Autowired
private SharpspringOperations operations;
@Autowired
private SharpspringProperties properties;
@Test
public void urlIsConfiguredCorrectly() {
assertThat(operations.getURL()).isEqualTo(properties.getUrl()+"?accountID="+
properties.getAccountId()+"&secretKey="+properties.getSecretKey());
}
/**
* This test performs no assertions because we cannot know what content the server might have. and exists to test a query and ensure connection and that the response
* is parsed correctly.
*/
@Test
public void queryIsSuccessful() {
SharpspringRequest request = request(1, SharpspringMethod.GET_EVENTS)
.where("createTimestamp").is("2017-05-23")
.build();
GetEventsResponse result = operations.query(request, GetEventsResponse.class);
}
}
| mit |
tbetbetbe/reel | lib/reel/version.rb | 60 | module Reel
VERSION = "0.6.0"
CODENAME = "Garland"
end
| mit |
la-haute-societe/yii2-save-relations-behavior | tests/models/User.php | 1441 | <?php
namespace tests\models;
use lhs\Yii2SaveRelationsBehavior\SaveRelationsBehavior;
use lhs\Yii2SaveRelationsBehavior\SaveRelationsTrait;
class User extends \yii\db\ActiveRecord
{
use SaveRelationsTrait;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'saveRelations' => [
'class' => SaveRelationsBehavior::className(),
'relations' => ['userProfile' => ['cascadeDelete' => true], 'company']
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['company_id', 'integer'],
[['username'], 'required'],
['username', 'unique', 'targetClass' => '\tests\models\User'],
[['company_id'], 'exist', 'skipOnError' => true, 'targetClass' => Company::className(), 'targetAttribute' => ['company_id' => 'id']],
[['userProfile', 'company'], 'safe']
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUserProfile()
{
return $this->hasOne(UserProfile::className(), ['user_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompany()
{
return $this->hasOne(Company::className(), ['id' => 'company_id']);
}
}
| mit |
lingtalfi/bee | bee/modules/BeeSandBox/Language/Parser/ParseTree/ParseTree.php | 1172 | <?php
/*
* This file is part of the Bee package.
*
* (c) Ling Talfi <lingtalfi@bee-framework.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BeeSandBox\Language\Parser\ParseTree;
use BeeSandBox\Language\Parser\Exception\ParserException;
use BeeSandBox\Language\Parser\Lexer\Token;
/**
* ParseTree
* @author Lingtalfi
* 2015-06-29
*
*/
abstract class ParseTree
{
public $children;
public function addChild($value)
{
if (is_string($value)) {
$r = new RuleNode($value);
$this->addChild($r);
return $r;
}
elseif ($value instanceof Token) {
$r = new TokenNode($value);
$this->addChild($r);
return $r;
}
elseif ($value instanceof ParseTree) {
if (null === $this->children) {
$this->children = [];
}
$this->children[] = $value;
}
else {
throw new ParserException(sprintf("expected string, Token or ParserTree, %s given", gettype($value)));
}
}
}
| mit |
ministryofjustice/defence-request-service-rota | spec/controllers/organisations_controller_spec.rb | 1646 | require "rails_helper"
RSpec.describe OrganisationsController do
before do
sign_in(create(:admin_user))
end
describe "POST create" do
it "saves the organisation and redirects to index" do
stub_organisation method: :save, return_value: true
post :create, organisation: organisation_params
expect(response).to redirect_to organisations_path
end
it "redirects to new if the organisation could not be created" do
stub_organisation method: :save, return_value: false
post :create, organisation: { name: "" }
expect(response).to render_template :new
end
end
describe "PATCH update" do
it "updates the organisation and redirects to index" do
stub_organisation_lookup
stub_organisation method: :update_attributes, return_value: true
patch :update, { id: "1", organisation: organisation_params }
expect(response).to redirect_to organisations_path
end
it "redirects to edit if the organisation could not be updated" do
stub_organisation_lookup
stub_organisation method: :update_attributes, return_value: false
patch :update, { id: "1", organisation: organisation_params }
expect(response).to render_template :edit
end
end
def stub_organisation(method:, return_value:)
allow(mock_organisation).to receive(method).and_return(return_value)
end
def mock_organisation
@_mock ||= double(:mock_organisation)
end
def stub_organisation_lookup
allow(Organisation).to receive(:find).
and_return(mock_organisation)
end
def organisation_params
attributes_for(:organisation)
end
end
| mit |
caesarius1187/contasynfotech | app/Model/Conveniocolectivotrabajo.php | 1271 | <?php
App::uses('AppModel', 'Model');
/**
* Conveniocolectivotrabajo Model
*
* @property Impcli $Impcli
* @property Cctxconcepto $Cctxconcepto
*/
class Conveniocolectivotrabajo extends AppModel {
//The Associations below have been created with all possible keys, those that are not needed can be removed
public $displayField = 'nombre';
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Impuesto' => array(
'className' => 'Impuesto',
'foreignKey' => 'impuesto_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
'Cctxconcepto' => array(
'className' => 'Cctxconcepto',
'foreignKey' => 'conveniocolectivotrabajo_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'Empleado' => array(
'className' => 'Empleado',
'foreignKey' => 'conveniocolectivotrabajo_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
| mit |
tristan-reeves/SharpConfig | SharpConfig/Properties/AssemblyInfo.cs | 1295 | // The MIT License (MIT)
//
// Copyright (c) 2014 Tristan Reeves
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System.Reflection;
[assembly: AssemblyTitle("SharpConfig")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] | mit |
kodmunki/ku4js-webApp | src/factories/valiatorFactory.js | 271 | function validatorFactory(config) {
this._config = config;
}
validatorFactory.prototype = {
create: function(key) { return $.ku4webApp.validator(this._config[key]); }
};
$.ku4webApp.validatorFactory = function(config) {
return new validatorFactory(config);
}; | mit |
weew/validator | tests/Weew/Validator/Constraints/ForbiddenSubsetConstraintTest.php | 1283 | <?php
namespace Tests\Weew\Validator\Constraints;
use PHPUnit_Framework_TestCase;
use Weew\Validator\Constraints\ForbiddenSubsetConstraint;
class ForbiddenSubsetConstraintTest extends PHPUnit_Framework_TestCase {
public function test_check() {
$c = new ForbiddenSubsetConstraint([true, '1']);
$this->assertFalse($c->check(true));
$this->assertFalse($c->check('true'));
$this->assertFalse($c->check('1'));
$this->assertFalse($c->check(1));
$this->assertFalse($c->check([true, '1']));
$this->assertTrue($c->check(['true']));
$this->assertTrue($c->check([1]));
$this->assertTrue($c->check(['true', 1]));
}
public function test_get_options() {
$c = new ForbiddenSubsetConstraint(['foo', 'bar']);
$this->assertEquals(['forbidden' => ['foo', 'bar']], $c->getOptions());
$c = new ForbiddenSubsetConstraint(['foo', 'bar']);
$this->assertEquals(['forbidden' => ['foo', 'bar']], $c->getOptions());
}
public function test_get_message() {
$c = new ForbiddenSubsetConstraint(['yolo'], 'foo');
$this->assertEquals('foo', $c->getMessage());
$c = new ForbiddenSubsetConstraint(['yolo']);
$this->assertNotNull($c->getMessage());
}
}
| mit |
arrow-/phoenix | api/python2/src/botapi.py | 2732 | from json import loads, dumps
import sys
class game:
def __init__(self, name):
self.game_state = loads(raw_input())
self.name = name
self.move_obj = {}
for bot in self.game_state['bots']:
if bot['botname'] == self.name:
self.move_obj[bot['childno']] = {
'childno': bot['childno'],
'relativeangle':0,
'ejectmass':False,
'split':False,
'pause':False}
def change_direction(self, child_no, relative_angle):
'''
set new relative direction
'''
self.move_obj[child_no]['relativeangle'] = relative_angle
def eject_mass(self, child_no):
'''
set if eject mass is true or not
'''
self.move_obj[child_no]['ejectmass'] = True
def split(self, child_no):
'''
set if split in current direction is true or not. If the mass is not
enough to split, then this command is ignored.
'''
self.move_obj[child_no]['split'] = True
def pause(self, child_no):
'''
set if the bot has to be brought to a stand still
'''
self.move_obj[child_no]['pause'] = True
def send_move(self):
'''
returns a move object in json format for all the children together
'''
print dumps(self.move_obj.values())
sys.stdout.flush()
@staticmethod
def send_acknowledgement():
'''
prints `I'm Poppy!` to STDOUT so that the engine can acknowledge the bot
'''
print "I'm Poppy!"
sys.stdout.flush()
def get_children(self):
'''
returns the list dicts with the details of children
{
'botname':'kevin',
'childno':0,
'center':[x, y],
'mass':20,
'angle':0,
'radius':10
}
'''
return filter(lambda x: x['botname'] == self.name, self.game_state['bots'])
def get_blobs(self):
'''
returns a list of dicts of all the blobs other than your bot
{
'botname':'kevin',
'childno':0,
'center':[x, y],
'mass':20,
'angle':0,
'radius':10
}
'''
return filter(lambda x: x['botname'] != self.name, self.game_state['bots'])
def get_foods(self):
'''
return a list of tuples as x and y coordinates
'''
return list(map(lambda x: tuple(x), self.game_state['food']))
def get_viruses(self):
'''
return a list of tuples as x and y coordinates
'''
return list(map(lambda x: tuple(x), self.game_state['virus']))
| mit |
ChillyFlashER/OpenInput | src/OpenInput/Mechanics/InputSystem.cs | 4465 | namespace OpenInput.Mechanics
{
using OpenInput.Trackers;
using System;
using System.Collections.Generic;
public struct InputAction
{
public readonly string Name;
public readonly InputKey Key;
/// <summary>
/// Initialize a new <see cref="InputAction"/> structure.
/// </summary>
public InputAction(string name, InputKey key)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
this.Name = name;
this.Key = key;
}
}
public struct InputAxis
{
public readonly string Name;
public readonly InputKey Key;
public readonly float Value;
/// <summary>
/// Initialize a new <see cref="InputAxis"/> structure.
/// </summary>
public InputAxis(string name, InputKey key, float value)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
if (float.IsInfinity(value) || float.IsNaN(value)) throw new ArgumentOutOfRangeException(nameof(value));
this.Name = name;
this.Key = key;
this.Value = value;
}
}
public class InputSystem : ITracker
{
public readonly IKeyboard Keyboard;
public readonly IMouse Mouse;
public readonly List<InputAction> Actions = new List<InputAction>();
public readonly List<InputAxis> Axis = new List<InputAxis>();
private readonly Dictionary<string, bool> inputActions = new Dictionary<string, bool>();
private readonly Dictionary<string, float> inputAxis = new Dictionary<string, float>();
public InputSystem(IKeyboard keyboard, IMouse mouse)
{
this.Keyboard = keyboard ?? throw new ArgumentNullException(nameof(keyboard));
this.Mouse = mouse ?? throw new ArgumentNullException(nameof(mouse));
}
public IEnumerable<KeyValuePair<string, bool>> GetActionsValues()
{
return inputActions;
}
public IEnumerable<KeyValuePair<string, float>> GetAxisValues()
{
return inputAxis;
}
public void Update(float elapsedTime)
{
inputActions.Clear();
inputAxis.Clear();
var keyboardState = Keyboard.GetCurrentState();
//var mouseState = Mouse.GetCurrentState();
foreach (var action in Actions)
{
switch (action.Key.Type)
{
case InputKeyType.Keyboard:
if (keyboardState.IsKeyDown(action.Key.Key))
{
if (inputActions.ContainsKey(action.Name))
{
inputActions[action.Name] = true;
}
else
{
inputActions.Add(action.Name, true);
}
}
break;
case InputKeyType.Mouse:
break;
case InputKeyType.GamePad:
break;
}
}
foreach (var axis in Axis)
{
switch (axis.Key.Type)
{
case InputKeyType.Keyboard:
if (keyboardState.IsKeyDown(axis.Key.Key))
{
if (inputAxis.ContainsKey(axis.Name))
{
inputAxis[axis.Name] += axis.Value;
}
else
{
inputAxis.Add(axis.Name, axis.Value);
}
}
break;
case InputKeyType.Mouse:
break;
case InputKeyType.GamePad:
break;
}
}
}
public bool GetAction(string name)
{
return inputActions.ContainsKey(name) ? inputActions[name] : false;
}
public float GetAxis(string name)
{
return inputAxis.ContainsKey(name) ? inputAxis[name] : 0.0f;
}
}
}
| mit |
CCU-CSIE-SmartCafe/Backend | app/Http/Controllers/Auth/RegisterController.php | 3460 | <?php
namespace SmartCafe\Http\Controllers\Auth;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use SmartCafe\Exceptions\ValidateFail;
use SmartCafe\Http\Requests;
use SmartCafe\Http\Controllers\Controller;
use SmartCafe\User;
use Validator;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('throttle:10,1', ['only' => ['store']]);
}
/**
* Options for api document.
*
* @return JsonResponse
*/
public function options(): JsonResponse
{
$description = 'Register a new user.';
$allow = ['POST'];
$methods = [
'POST' => [
'email' => [
'description' => "User's email.",
'required' => true,
'type' => 'string',
],
'name' => [
'description' => "User's name.",
'required' => true,
'type' => 'string',
],
'password' => [
'description' => "User's password.",
'required' => true,
'type' => 'string',
],
],
];
$returns = [
'status' => [
'description' => 'Is this request successfully?',
'type' => 'boolean',
],
'message' => [
'description' => 'Request message.',
'type' => 'array/string',
],
];
return response()
->json([
'description' => $description,
'allow' => $allow,
'methods' => $methods,
'returns' => $returns,
], 200, [
'Allow' => 'OPTIONS, POST',
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return JsonResponse
*/
public function store(Request $request): JsonResponse
{
try {
$this->validator($request);
$this->createUser($request);
return response()
->json([
'status' => true,
'message' => 'Register successfully.',
]);
} catch (ValidateFail $e) {
return response()
->json([
'status' => false,
'message' => $e->getErrors(),
]);
}
}
/**
* Validate the request data is valid.
*
* @param Request $request
* @throws ValidateFail
*/
protected function validator(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|max:255|unique:users',
'name' => 'required|max:255',
'password' => 'required|min:6',
]);
if ($validator->fails()) {
throw new ValidateFail($validator->errors());
}
}
/**
* Crate user data in database.
*
* @param Request $request
*/
protected function createUser(Request $request)
{
User::create([
'email' => $request->email,
'name' => $request->name,
'password' => bcrypt($request->password),
]);
}
}
| mit |