repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
NotARealTree/tyche | scala/src/main/scala/xyz/notarealtree/items/ProcessingThread.scala | 320 | package xyz.notarealtree.items
/**
* Created by Francis on 21/07/2016.
*/
class ProcessingThread(val interval: Long, val processor: Processor) extends Runnable{
override def run(): Unit = {
while(!Thread.currentThread().isInterrupted){
Thread.sleep(interval)
}
}
}
| mit |
bryant-pham/brograder | webapp/src/app/guard/auth.guard.spec.ts | 1403 | import {
describe,
it,
expect,
beforeEachProviders,
beforeEach,
inject
} from '@angular/core/testing';
import { provide } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/Subject';
import { AuthGuard } from './auth.guard';
import { AuthenticationService } from '../shared/services/authentication.service';
class MockRouter {
navigate(): void {
// no op
}
}
class MockAuthService {
authenticationStream(): void {
// use spyOn to mock
}
}
describe('AuthGuard', () => {
beforeEachProviders(() => [
AuthGuard,
provide(AuthenticationService, {useClass: MockAuthService}),
provide(Router, {useClass: MockRouter})
]);
let guard: AuthGuard;
let authService: AuthenticationService;
let authObs = Subject.create();
beforeEach(inject([AuthenticationService], (_authService) => {
authService = _authService;
spyOn(authService, 'authenticationStream').and.returnValue(authObs);
}));
beforeEach(inject([AuthGuard, AuthenticationService], (_guard) => {
guard = _guard;
}));
it('should return true if authenticated', () => {
authObs.next(true);
let result = guard.canActivate();
expect(result).toBeTruthy();
});
it('should return false if not authenticated', () => {
authObs.next(false);
let result = guard.canActivate();
expect(result).toBeFalsy();
});
});
| mit |
liufeiit/itmarry | source/Apollo/Apollo/src/com/andrew/apolloMod/ui/fragments/grid/ArtistsFragment.java | 8855 | /**
*
*/
package com.andrew.apolloMod.ui.fragments.grid;
import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Audio.ArtistColumns;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.andrew.apolloMod.R;
import com.andrew.apolloMod.activities.TracksBrowser;
import com.andrew.apolloMod.cache.ImageInfo;
import com.andrew.apolloMod.cache.ImageProvider;
import com.andrew.apolloMod.helpers.utils.ApolloUtils;
import com.andrew.apolloMod.helpers.utils.MusicUtils;
import com.andrew.apolloMod.service.ApolloService;
import com.andrew.apolloMod.ui.adapters.ArtistAdapter;
import static com.andrew.apolloMod.Constants.*;
/**
* @author Andrew Neal
* @Note This is the first tab
*/
public class ArtistsFragment extends Fragment implements LoaderCallbacks<Cursor>,
OnItemClickListener {
// Adapter
private ArtistAdapter mArtistAdapter;
// GridView
private GridView mGridView;
// Cursor
private Cursor mCursor;
// Options
private final int PLAY_SELECTION = 0;
private final int ADD_TO_PLAYLIST = 1;
private final int SEARCH = 2;
// Artist ID
private String mCurrentArtistId;
// Album ID
private String mCurrentAlbumId;
// Audio columns
public static int mArtistIdIndex, mArtistNameIndex, mArtistNumAlbumsIndex;
public ArtistsFragment() {
}
public ArtistsFragment(Bundle bundle) {
setArguments(bundle);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// ArtistAdapter
mArtistAdapter = new ArtistAdapter(getActivity(), R.layout.gridview_items, null,
new String[] {}, new int[] {}, 0);
mGridView.setOnCreateContextMenuListener(this);
mGridView.setOnItemClickListener(this);
mGridView.setAdapter(mArtistAdapter);
mGridView.setTextFilterEnabled(true);
// Important!
getLoaderManager().initLoader(0, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.gridview, container, false);
mGridView = ((GridView)root.findViewById(R.id.gridview));
return root;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
BaseColumns._ID, ArtistColumns.ARTIST, ArtistColumns.NUMBER_OF_ALBUMS
};
Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI;
String sortOrder = Audio.Artists.DEFAULT_SORT_ORDER;
return new CursorLoader(getActivity(), uri, projection, null, null, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Check for database errors
if (data == null) {
return;
}
mArtistIdIndex = data.getColumnIndexOrThrow(BaseColumns._ID);
mArtistNameIndex = data.getColumnIndexOrThrow(ArtistColumns.ARTIST);
mArtistNumAlbumsIndex = data.getColumnIndexOrThrow(ArtistColumns.NUMBER_OF_ALBUMS);
mArtistAdapter.changeCursor(data);
mCursor = data;
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
if (mArtistAdapter != null)
mArtistAdapter.changeCursor(null);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putAll(getArguments() != null ? getArguments() : new Bundle());
super.onSaveInstanceState(outState);
}
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
tracksBrowser(id);
}
/**
* @param id
*/
private void tracksBrowser(long id) {
String artistName = mCursor.getString(mArtistNameIndex);
String artistNulAlbums = mCursor.getString(mArtistNumAlbumsIndex);
Bundle bundle = new Bundle();
bundle.putString(MIME_TYPE, Audio.Artists.CONTENT_TYPE);
bundle.putString(ARTIST_KEY, artistName);
bundle.putString(NUMALBUMS, artistNulAlbums);
bundle.putLong(BaseColumns._ID, id);
ApolloUtils.setArtistId(artistName, id, ARTIST_ID, getActivity());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClass(getActivity(), TracksBrowser.class);
intent.putExtras(bundle);
getActivity().startActivity(intent);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.add(0, PLAY_SELECTION, 0, getResources().getString(R.string.play_all));
menu.add(0, ADD_TO_PLAYLIST, 0, getResources().getString(R.string.add_to_playlist));
menu.add(0, SEARCH, 0, getResources().getString(R.string.search));
mCurrentArtistId = mCursor.getString(mArtistIdIndex);
mCurrentAlbumId = mCursor.getString(mCursor.getColumnIndexOrThrow(BaseColumns._ID));
menu.setHeaderView(setHeaderLayout());
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case PLAY_SELECTION: {
long[] list = mCurrentArtistId != null ? MusicUtils.getSongListForArtist(
getActivity(), Long.parseLong(mCurrentArtistId)) : MusicUtils
.getSongListForAlbum(getActivity(), Long.parseLong(mCurrentAlbumId));
MusicUtils.playAll(getActivity(), list, 0);
break;
}
case ADD_TO_PLAYLIST: {
Intent intent = new Intent(INTENT_ADD_TO_PLAYLIST);
long[] list = mCurrentArtistId != null ? MusicUtils.getSongListForArtist(
getActivity(), Long.parseLong(mCurrentArtistId)) : MusicUtils
.getSongListForAlbum(getActivity(), Long.parseLong(mCurrentAlbumId));
intent.putExtra(INTENT_PLAYLIST_LIST, list);
getActivity().startActivity(intent);
break;
}
case SEARCH: {
MusicUtils.doSearch(getActivity(), mCursor, mArtistNameIndex);
break;
}
default:
break;
}
return super.onContextItemSelected(item);
}
/**
* Update the list as needed
*/
private final BroadcastReceiver mMediaStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (mGridView != null) {
mArtistAdapter.notifyDataSetChanged();
}
}
};
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction(ApolloService.META_CHANGED);
filter.addAction(ApolloService.PLAYSTATE_CHANGED);
getActivity().registerReceiver(mMediaStatusReceiver, filter);
}
@Override
public void onStop() {
getActivity().unregisterReceiver(mMediaStatusReceiver);
super.onStop();
}
/**
* @return A custom ContextMenu header
*/
public View setHeaderLayout() {
// Get artist name
final String artistName = mCursor.getString(mArtistNameIndex);
// Inflate the header View
LayoutInflater inflater = getActivity().getLayoutInflater();
View header = inflater.inflate(R.layout.context_menu_header, null, false);
// Artist image
final ImageView mHanderImage = (ImageView)header.findViewById(R.id.header_image);
ImageInfo mInfo = new ImageInfo();
mInfo.type = TYPE_ARTIST;
mInfo.size = SIZE_THUMB;
mInfo.source = SRC_FIRST_AVAILABLE;
mInfo.data = new String[]{ artistName};
ImageProvider.getInstance(getActivity()).loadImage( mHanderImage, mInfo );
// Set artist name
TextView headerText = (TextView)header.findViewById(R.id.header_text);
headerText.setText(artistName);
headerText.setBackgroundColor(getResources().getColor(R.color.transparent_black));
return header;
}
}
| mit |
Sigurdurhelga/Sigurdurhelga.github.io | drawio/js/init.js | 1504 | $(function () {
$('#colorpicker').farbtastic('#color');
/*
get all available fonts from google webfonts and include them into the project
*/
$.ajax({
type: "GET",
headers: {
Accept: "application/json",
},
url: "https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyCXm6o1hpeorzN_rutxXdbt03jMreNMgG0&sort=popularity",
success: (response) => {
let select = $("#textToolFont")[0];
for (let index = 0; index < 50; index++) {
if (response.items[index].variants.includes("regular") && response.items[index].family.match(/\d+/g) == null) {
var newFontFace = new FontFace(response.items[index].family, 'url(' + response.items[index].files.regular + ')');
document.fonts.add(newFontFace);
let option = document.createElement('option');
option.text = response.items[index].family;
option.value = response.items[index].family;
option.style.fontFamily = response.items[index].family;
select.add(option);
}
}
},
error: (err) => {
console.log(err);
}
});
function resizeCanvas() {
drawio.canvas.width = $(window).width();
drawio.canvas.height = $(window).height();
drawio.redraw();
}
resizeCanvas();
$(window).bind("resize", resizeCanvas);
});
| mit |
tompo-andri/IUT | Second Year (2013-2014)/OMGL6/TP4/Exercice 1/src/USAddressFactory.java | 229 | public class USAddressFactory implements AddressFactory{
public Address createAddress(){
return new USAddress();
}
public PhoneNumber createPhoneNumber(){
return new USPhoneNumber();
}
}
| mit |
cknow/checker | src/Console/Command/Git/InstallCommand.php | 7346 | <?php
namespace ClickNow\Checker\Console\Command\Git;
use ClickNow\Checker\Config\Checker;
use ClickNow\Checker\Exception\FileNotFoundException;
use ClickNow\Checker\IO\IOInterface;
use ClickNow\Checker\Repository\Filesystem;
use SplFileInfo;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\ProcessBuilder;
class InstallCommand extends Command
{
const GENERATED_MESSAGE = 'Checker generated this file, do not edit!';
/**
* @var \ClickNow\Checker\Config\Checker
*/
private $checker;
/**
* @var \ClickNow\Checker\Repository\Filesystem
*/
private $filesystem;
/**
* @var \ClickNow\Checker\IO\IOInterface
*/
private $io;
/**
* @var \Symfony\Component\Process\ProcessBuilder
*/
private $processBuilder;
/**
* @var array
*/
private $gitHooks;
/**
* @var \Symfony\Component\Console\Input\InputInterface
*/
private $input;
/**
* Install command.
*
* @param \ClickNow\Checker\Config\Checker $checker
* @param \ClickNow\Checker\Repository\Filesystem $filesystem
* @param \ClickNow\Checker\IO\IOInterface $io
* @param \Symfony\Component\Process\ProcessBuilder $processBuilder
* @param array $gitHooks
*/
public function __construct(
Checker $checker,
Filesystem $filesystem,
IOInterface $io,
ProcessBuilder $processBuilder,
array $gitHooks
) {
$this->checker = $checker;
$this->filesystem = $filesystem;
$this->io = $io;
$this->processBuilder = $processBuilder;
$this->gitHooks = array_keys($gitHooks);
parent::__construct('git:install');
$this->setDescription('Install git hooks');
}
/**
* Execute.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return int|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->io->title('Checker are installing in git hooks!');
$gitHooksDir = $this->getGitHooksDir();
foreach ($this->gitHooks as $gitHook) {
$gitHookPath = $gitHooksDir.$gitHook;
$hookTemplate = $this->getHookTemplate($gitHook);
$this->backupGitHook($gitHookPath);
$this->createGitHook($gitHook, $gitHookPath, $hookTemplate);
}
$this->io->success('Checker was installed in git hooks successfully! Very nice...');
}
/**
* Get git hooks directory.
*
* @return string
*/
private function getGitHooksDir()
{
$gitHooksDir = $this->getPathsHelper()->getGitHooksDir();
if (!$this->filesystem->exists($gitHooksDir)) {
$this->filesystem->mkdir($gitHooksDir);
$this->io->note(sprintf('Created git hooks folder at: `%s`.', $gitHooksDir));
}
return $gitHooksDir;
}
/**
* Get hook template.
*
* @param string $name
*
* @throws \ClickNow\Checker\Exception\FileNotFoundException
*
* @return SplFileInfo
*/
private function getHookTemplate($name)
{
$resourcePath = $this->getPathsHelper()->getGitHookTemplatesDir().$this->checker->getHooksPreset();
$customPath = $this->getPathsHelper()->getPathWithTrailingSlash($this->checker->getHooksDir());
$template = $this->getPathsHelper()->getPathWithTrailingSlash($resourcePath).$name;
if ($customPath && $this->filesystem->exists($customPath.$name)) {
$template = $customPath.$name;
}
if (!$this->filesystem->exists($template)) {
throw new FileNotFoundException(sprintf('Could not find template for `%s` at `%s`.', $name, $template));
}
return new SplFileInfo($template);
}
/**
* Backup git hook.
*
* @param string $path
*
* @return void
*/
private function backupGitHook($path)
{
if (!$this->filesystem->exists($path)) {
return;
}
$content = $this->filesystem->readFromFileInfo(new SplFileInfo($path));
if (strpos($content, self::GENERATED_MESSAGE) !== false) {
return;
}
$this->io->log(sprintf('Checker backup git hook `%s` to `%s`.', $path, $path.'.checker'));
$this->filesystem->rename($path, $path.'.checker', true);
}
/**
* Create git hook.
*
* @param string $name
* @param string $path
* @param SplFileInfo $template
*
* @return void
*/
private function createGitHook($name, $path, SplFileInfo $template)
{
$this->io->log(sprintf('Checker create git hook `%s`.', $path));
$content = $this->filesystem->readFromFileInfo($template);
$replacements = [
'$(GENERATED_MESSAGE)' => self::GENERATED_MESSAGE,
'${HOOK_EXEC_PATH}' => $this->getPathsHelper()->getGitHookExecutionPath(),
'$(HOOK_COMMAND)' => $this->generateHookCommand('git:'.$name),
];
$content = str_replace(array_keys($replacements), array_values($replacements), $content);
$this->filesystem->dumpFile($path, $content);
$this->filesystem->chmod($path, 0775);
}
/**
* Generate hook command.
*
* @param string $command
*
* @return string
*/
private function generateHookCommand($command)
{
$executable = $this->getPharCommand() ?: $this->getPathsHelper()->getBinCommand('checker', true);
$this->processBuilder->setArguments([
$this->getPathsHelper()->getRelativeProjectPath($executable),
$command,
]);
$configPath = $this->useExoticConfigPath();
if ($configPath !== null) {
$this->processBuilder->add(sprintf('--config=%s', $configPath));
}
return $this->processBuilder->getProcess()->getCommandLine();
}
/**
* Get phar command.
*
* @return string
*
* @SuppressWarnings(PHPMD.Superglobals)
* @codeCoverageIgnore
*/
private function getPharCommand()
{
$token = $_SERVER['argv'][0];
if (pathinfo($token, PATHINFO_EXTENSION) == 'phar') {
return $token;
}
return '';
}
/**
* Use exotic config path.
*
* @return null|string
*/
private function useExoticConfigPath()
{
try {
$configPath = $this->getPathsHelper()->getAbsolutePath($this->input->getOption('config'));
if ($configPath != $this->getPathsHelper()->getDefaultConfigPath()) {
return $this->getPathsHelper()->getRelativeProjectPath($configPath);
}
} catch (FileNotFoundException $e) {
// no config path
}
return null;
}
/**
* Get paths helper.
*
* @return \ClickNow\Checker\Helper\PathsHelper
*/
private function getPathsHelper()
{
return $this->getHelperSet()->get('paths');
}
}
| mit |
Jam3/glsl-version-regex | index.js | 62 | module.exports = /^\s*\#version\s+([0-9]+(\s+[a-zA-Z]+)?)\s*/
| mit |
jbasdf/cms-lite | test/rails_test/test/functional/cms_lite_controller_test.rb | 1109 | require File.dirname(__FILE__) + '/../test_helper'
class CmsLiteControllerTest < ActionController::TestCase
tests CmsLiteController
context "cms lite controller" do
context "unprotected pages" do
setup do
get :show_page, :content_key => 'open', :content_page => ['hello']
end
should respond_with :success
end
context "unprotected root pages" do
setup do
get :show_page, :content_key => '/default', :content_page => 'root'
end
should respond_with :success
end
context "protected pages"do
context "not logged in" do
setup do
get :show_protected_page, :content_key => 'protected', :content_page => ['safe-hello']
end
should redirect_to("login") { login_path }
end
context "logged in" do
setup do
activate_authlogic
@user = Factory(:user)
login_as @user
get :show_protected_page, :content_key => 'protected', :content_page => ['safe-hello']
end
should respond_with :success
end
end
end
end
| mit |
Opifer/CmsBundle | Controller/Backend/DashboardController.php | 989 | <?php
namespace Opifer\CmsBundle\Controller\Backend;
use Opifer\CmsBundle\Manager\ContentManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class DashboardController extends Controller
{
/**
* @return Response
*/
public function viewAction()
{
/** @var ContentManager $contentManager */
$contentManager = $this->get('opifer.cms.content_manager');
$latestContent = $contentManager->getRepository()
->findLastUpdated(6);
$newContent = $contentManager->getRepository()
->findLastCreated(6);
$unpublishedContent = $contentManager->getRepository()
->findUnpublished(6);
return $this->render('OpiferCmsBundle:Backend/Dashboard:dashboard.html.twig', [
'latest_content' => $latestContent,
'new_content' => $newContent,
'unpublished_content' => $unpublishedContent,
]);
}
}
| mit |
Blackrush/Rocket | network/src/main/java/org/rocket/network/guice/ControllerFactoryModule.java | 1622 | package org.rocket.network.guice;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import org.rocket.network.Controller;
import org.rocket.network.ControllerFactory;
import org.rocket.network.NetworkClient;
import java.lang.annotation.Annotation;
import java.util.Set;
public final class ControllerFactoryModule extends AbstractModule {
private final Class<? extends Annotation> controllerAnnotation;
public ControllerFactoryModule(Class<? extends Annotation> controllerAnnotation) {
this.controllerAnnotation = controllerAnnotation;
}
public ControllerFactoryModule() {
this(Controller.class);
}
@Override
protected void configure() {
Hook hook = new Hook(getProvider(RocketGuiceUtil.controllersKeyFor(controllerAnnotation)));
bind(NetworkClient.class).toProvider(hook);
bind(ControllerFactory.class).toInstance(hook);
}
private static class Hook implements Provider<NetworkClient>, ControllerFactory {
private final ThreadLocal<NetworkClient> client = new ThreadLocal<>();
private final Provider<Set<Object>> controllers;
Hook(Provider<Set<Object>> controllers) {
this.controllers = controllers;
}
@Override
public NetworkClient get() {
return client.get();
}
@Override
public Set<Object> create(NetworkClient client) {
this.client.set(client);
try {
return controllers.get();
} finally {
this.client.remove();
}
}
}
}
| mit |
istrwei/pocent | admin/Document/my.php | 2941 | <?php
/**
* @param Protty
* @url www.pder.org
**/
if ($_GET['c']=='my'){
require_once EXE . 'PerClass' . EXP . 'State.admin.php';
$ver = LoginStaFun($_SESSION['id'], $config);
require_once EXE . 'Delivery' . EXP . 'my.html';
if (!empty($_POST['update_set'])){
require_once EXE . 'PerClass' . EXP . 'Updata.admin.php';
$img = $_FILES['touxiang'];
$images = uploadFile($img,'img');
$u = FileTer($_POST['u']);
$p = md5($_POST['p'].LOGIN_PROTTY);
$n = FileTer($_POST['n']);
$q = FileTer($_POST['q']);
$sex = FileTer($_POST['sex']);
//开始额外数据
$qq = FileTer($_POST['qq_num']);
$email = FileTer($_POST['user_mail']);
$bri = FileTer($_POST['user_bri']);
$weibo = FileTer($_POST['user_weibo']);
$image = FileTer($_POST['user_image_new']);
$qzone = FileTer($_POST['user_qzone']);
if (is_array($images)){
$img = true;
}else {
$img = false;
}
require_once EXE . 'PerClass' . EXP . 'root.admin.php';
if (!empty($img) && !empty($_POST['u']) && !empty($_POST['p']) && !empty($_POST['n']) && !empty($_POST['q']) && !empty($_POST['sex'])){
$set="username='$u',password='$p',nickname='$n',sig='$q',sex='$sex',img='$images[url]',qq_num='$qq',user_mail='$email',user_bri='$bri',user_weibo='$weibo',user_image_new='$image',user_qzone='$qzone'";
session_destroy();
}
if (empty($img) && !empty($_POST['u']) && empty($_POST['p']) && !empty($_POST['n']) && !empty($_POST['q']) && !empty($_POST['sex'])){
$set="username='$u',nickname='$n',sig='$q',sex='$sex',qq_num='$qq',user_mail='$email',user_bri='$bri',user_weibo='$weibo',user_image_new='$image',user_qzone='$qzone'";
}
if (!empty($img) && !empty($_POST['u']) && empty($_POST['p']) && !empty($_POST['n']) && !empty($_POST['q']) && !empty($_POST['sex'])){
$set="username='$u',nickname='$n',sig='$q',sex='$sex',img='$images[url]',qq_num='$qq',user_mail='$email',user_bri='$bri',user_weibo='$weibo',user_image_new='$image',user_qzone='$qzone'";
}
if (empty($img) && !empty($_POST['u']) && !empty($_POST['p']) && !empty($_POST['n']) && !empty($_POST['q']) && !empty($_POST['sex'])){
$set="username='$u',password='$p',nickname='$n',sig='$q',sex='$sex',qq_num='$qq',user_mail='$email',user_bri='$bri',user_weibo='$weibo',user_image_new='$image',user_qzone='$qzone'";
session_destroy();
}
$up = MySet($set, "where id=$ver[id]", $config);
if ($up){
echo "<script>alert('修改成功!');location.href='';</script>";
if ($ver['username'] !== $u){
session_destroy();
}
}else {
echo "<script>alert('修改失败!');location.href='';</script>";
}
}
}
?> | mit |
xAleXXX007x/Witcher-RolePlay | witcherrp/plugins/hunger/items/alcohol/sh_nastoy.lua | 158 | ITEM.name = "Самогон из мандрагоры"
ITEM.desc = "Уникальный алкоголь."
ITEM.force = 90
ITEM.thirst = 15
ITEM.quantity = 3 | mit |
gricelsepulveda/arbifup | application/views/estaticos/navegacion.php | 5999 | <!DOCTYPE html>
<html lang="en" ng-app="app2">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!--AUX RESPONSIVO-->
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>ARBIFUP Asocación de Árbitros Profesionales</title>
<link rel="shortcut icon" type="image/x-icon" href="<?php echo base_url(); ?>img/favicon.ico"/><!--FAVICON-->
<link rel="stylesheet" href="<?php echo base_url(); ?>css/uikit.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>css/font-awesome.min.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>css/bootstrap.min.css"><!--BOOTSTRAP CSS-->
<link rel="stylesheet" href="<?php echo base_url(); ?>css/estilos.css">
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/angular.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/angular-route.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/login.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/uikit.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/app/app2.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/bootstrap.min.js"></script><!--BOOTSTRAP JS-->
<script type="text/javascript" src="<?php echo base_url(); ?>js/scripts.js"></script><!--SCRIPT PERSONALIZADO-->
<script type="text/javascript" src="<?php echo base_url(); ?>js/twitter.js"></script><!--SCRIPT PERSONALIZADO-->
<link rel="stylesheet" href="<?php echo base_url(); ?>fonts/glyphicons-halflings-regular.eot"><!--FUENTES BOOTSTRAP-->
<link rel="stylesheet" href="<?php echo base_url(); ?>fonts/glyphicons-halflings-regular.svg">
<link rel="stylesheet" href="<?php echo base_url(); ?>fonts/glyphicons-halflings-regular.ttf">
<link rel="stylesheet" href="<?php echo base_url(); ?>fonts/glyphicons-halflings-regular.woff">
<link rel="stylesheet" href="<?php echo base_url(); ?>fonts/glyphicons-halflings-regular.woff2">
</head>
<body>
<div class="titulo">
<a href="#"><h1>Arbifup </h1></a><img src="img/insignia_arbifup.png">
<h4>Comité de árbitros profesionales A.N.F.P.</h4>
</div>
<div class="btn_menu">
<img src="img/football.svg">
</div>
<nav class="navegacion navi">
<ul>
<li id="navegacion_menu" class="hidden-lg hidden-md">Menú</li>
<a href="<?php echo base_url(); ?>"><li class="navegacion_activo" id="inicio">Inicio</li></a>
<a href="<?php echo base_url(); ?>Quienes"><li id="quienessomos">Quiénes somos</li></a>
<a href="<?php echo base_url(); ?>Noticias"><li id="noticias">Noticias</li></a>
<a href="<?php echo base_url(); ?>Media"><li id="media">Media</li></a>
<a href="<?php echo base_url(); ?>Servicios"><li id="servicios">Servicios</li></a>
<a href="<?php echo base_url(); ?>Designaciones"><li id="designaciones">Designaciones</li></a>
</ul>
</nav>
<!--FIN PERMANENTE-->
<!--INICIO-->
<!--Botonera-->
<nav class="botonera">
<span data-toggle="modal" data-target="#contacto">contacto</span>
<a href=""><img src="img/facebook_botonera.svg" title="Nuestro fanpage"></a>
<a href=""><img src="img/twitter_botonera.svg" title="Síguenos en twitter"></a>
<img src="img/admin_botonera.svg" title="Panel de autoadminstración" data-toggle="modal" data-target="#login">
</nav>
<!--Login administracion-->
<div class="modal fade" tabindex="-1" role="dialog" id="login">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="text-center">Acceso a panel de administración</h3>
</div>
<div class="modal-body">
<form class="text-center" id="login_admin">
<input type="text" id="user" name="user" placeholder="Escriba usuario"><br/>
<input type="password" id="pass" name="pass" placeholder="Proporcione contraseña"><br/>
<button id="login_admin"class="ambos_abajo">I ngresar</button>
</form>
</div>
</div>
</div>
</div>
<!--Formulario contacto-->
<div class="modal fade" tabindex="-1" role="dialog" id="contacto">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="text-center">Escríbanos</h3>
</div>
<div class="modal-body">
<form class="text-center">
<input type="text" name="user" placeholder="Su nombre"><br/>
<input type="email" name="email" placeholder="Su correo"><br/>
<textarea rows="5" name="message" placeholder="Escriba su mensaje"></textarea>
<br/>
<button class="ambos_abajo">Enviar</button>
</form>
<p>
<span>Nota:</span>
Los mensajes no son contestados de manera inmediata, no obstante son leídos por la administración.Mensajes ofensivos serán considerados spam.
</p>
</div>
</div>
</div>
</div> | mit |
Ohjel/wood-process | test/clock.py | 120 | import pygame
pygame.init()
clk = pygame.time.Clock()
for i in range(0, 20):
print(clk.tick(60))
pygame.quit()
| mit |
haboustak/XdsKit | Source/XdsKit/XdsKit/Properties/AssemblyInfo.cs | 125 | using System.Reflection;
[assembly: AssemblyTitle("XdsKit")]
[assembly: AssemblyDescription("IHE XDS.b implementation")]
| mit |
skeetr/skeetr | tests/Skeetr/Tests/Debugger/Watchers/RecursiveIteratorWatcherTest.php | 660 | <?php
namespace Skeetr\Tests\Gearman;
use Skeetr\Tests\TestCase;
use Skeetr\Debugger\Watchers\RecursiveIteratorWatcher;
class RecursiveIteratorWatcherTest extends TestCase
{
public function testWatch()
{
$watcher = new RecursiveIteratorWatcher();
$watcher->addPattern(sys_get_temp_dir() . '/*.php');
$file = sys_get_temp_dir() . '/test.php';
shell_exec(sprintf('echo "1" > %s', $file));
$watcher->track();
$this->assertFalse($watcher->watch());
sleep(1);
shell_exec(sprintf('echo "2" >> %s', $file));
clearstatcache();
//$this->assertTrue($watcher->watch());
}
}
| mit |
akira-baruah/nes-pacs | src/tests/cpu_tb.cpp | 1694 | #include <cstdio>
#include <iostream>
#include "Vcpu.h"
using namespace std;
#define MEMSIZE 65536
void tick(Vcpu *cpu);
void print_stats(Vcpu *cpu, int time);
int main(int argc, char **argv) {
Verilated::commandArgs(argc, argv);
if (argc < 2) {
cerr << "usage: " << argv[0] << " <6502 executable>" << endl;
return 1;
}
Vcpu *cpu = new Vcpu;
char memory[MEMSIZE];
memset((char *)memory, 9, sizeof(memory));
int time = 0;
uint16_t addr = 0;
uint8_t input;
/* Read assembled binary into simulated memory */
char *filename = argv[1];
FILE *binary = fopen(filename, "r");
if (binary == NULL) {
perror(filename);
return 2;
}
size_t len = fread(memory, 1, MEMSIZE, binary);
while (1) {
if (Verilated::gotFinish()) { break; }
cpu->ready = 1;
addr = cpu->addr;
if (addr == (len+1)) { break; }
if (cpu->write) { memory[cpu->addr] = cpu->d_out; }
tick(cpu);
input = memory[addr];
cpu->d_in = input;
cpu->eval();
print_stats(cpu, time);
time++;
}
cpu->final();
delete cpu;
return 0;
}
void tick(Vcpu *cpu) {
cpu->clk = 0;
cpu->eval();
cpu->clk = 1;
cpu->eval();
}
void print_stats(Vcpu *cpu, int time) {
static int first = 1;
if (first) {
printf("Cycle Op A X Y P\n");
first = 0;
}
if (cpu->sync) {
printf("%5d %.2x %.2x %.2x %.2x %.2x\n",
time,
cpu->v__DOT__IR,
cpu->v__DOT__A,
cpu->v__DOT__X,
cpu->v__DOT__Y,
cpu->v__DOT__P);
}
}
| mit |
jwg2s/bond-ruby | lib/bond/account.rb | 423 | require 'faraday'
require 'json'
module Bond
class Account
attr_accessor :first_name, :last_name, :email, :credits, :links
def initialize
response = Bond::Connection.connection.get('/account')
json = JSON.parse(response.body)
Bond::BondError.handle_errors(json)
json['data'].each { |name, value| instance_variable_set("@#{name}", value) }
@links = json['links']
end
end
end | mit |
choodur/aviator | test/aviator/openstack/identity/v3/public/create_token_test.rb | 1560 | require 'test_helper'
class Aviator::Test
describe 'aviator/openstack/identity/v3/public/create_token' do
validate_response 'parameters are valid' do
#puts V3::Environment.openstack_admin[:auth_service].inspect
#puts RequestHelper.admin_bootstrap_session_data
service = Aviator::Service.new(
provider: 'openstack',
log_file: V3::Environment.log_file_path,
service: 'identity',
default_session_data: RequestHelper.admin_bootstrap_v3_session_data
)
response = service.request :create_token do |params|
params[:username] = V3::Environment.openstack_admin[:auth_credentials][:username]
params[:password] = V3::Environment.openstack_admin[:auth_credentials][:password]
params[:domainId] = V3::Environment.openstack_admin[:auth_credentials][:domainId]
end
[200, 201].include?(response.status).must_equal true
response.body.wont_be_nil
response.headers.wont_be_nil
end
validate_response "session is valid" do
@session = Aviator::Session.new(
config_file: V3::Environment.path,
environment: 'openstack_admin'
)
@session.authenticate
@session.authenticated?.must_equal true
end
validate_response "session is validated" do
@session = Aviator::Session.new(
config_file: V3::Environment.path,
environment: 'openstack_admin',
log_file: V3::Environment.log_file_path
)
@session.authenticate
@session.validate.must_equal true
end
end
end | mit |
plankt/Photo-Editor | Photo Editor/App.xaml.cs | 1199 | using System;
using System.Diagnostics;
using System.Windows;
using PhotoEditor.Data.Database;
using PhotoEditor.Views;
using PhotoEditor.Views.UserControls;
namespace PhotoEditor
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
public App()
{
ShutdownMode = ShutdownMode.OnLastWindowClose;
Startup += OnStartup;
}
private void OnStartup(object sender, StartupEventArgs startupEventArgs)
{
if (Debugger.IsAttached)
{
PhotoEditor.Properties.Settings.Default.Reset();
}
SQLiteDB.Init();
var mainControl = new MainPage();
var mainControlTabContent = new TabContent("Main", mainControl);
mainControl.MainControlTabContent = mainControlTabContent;
var mainWindowViewModel = new MainWindowViewModel();
mainWindowViewModel.TabContents.Add(mainControlTabContent);
var mainWindow = new MainWindow
{
DataContext = mainWindowViewModel
};
mainWindow.Show();
}
}
}
| mit |
paintsnow/paintsnow | Source/Driver/Script/TCC/ZScriptTCC.cpp | 7363 | #include "ZScriptTCC.h"
using namespace PaintsNow;
// only one script tcc is allowed to present at the same time within one module.
bool ZScriptTCC::instanceMutex = false;
ZScriptTCC::ZScriptTCC(IThread& threadApi) : IScript(threadApi) {
assert(!instanceMutex);
instanceMutex = true;
defaultRequest = NewRequest("");
}
ZScriptTCC::~ZScriptTCC() {
assert(instanceMutex);
delete defaultRequest;
instanceMutex = false;
}
void ZScriptTCC::Reset() {}
IScript::Request& ZScriptTCC::Request::CleanupIndex() {
return *this;
}
IScript::Request& ZScriptTCC::GetDefaultRequest() {
// TODO: insert return statement here
return *defaultRequest;
}
IScript::Request* ZScriptTCC::NewRequest(const String& entry) {
return new Request(this);
}
TObject<IReflect>& ZScriptTCC::Request::operator () (IReflect& reflect) {
return *this;
}
ZScriptTCC::Request::Request(ZScriptTCC* h) {
state = tcc_new();
}
ZScriptTCC::Request::~Request() {
tcc_delete(state);
}
IScript* ZScriptTCC::Request::GetScript() {
return host;
}
int ZScriptTCC::Request::GetCount() {
return 0;
}
void ZScriptTCC::Request::Debug(std::vector<StackInfo>& debugInfos, std::vector<LocalInfo>& localInfos, const Ref* func) {
assert(false); // not implemented
}
std::vector<IScript::Request::Key> ZScriptTCC::Request::Enumerate() {
assert(false); // not implemented
return std::vector<IScript::Request::Key>();
}
IScript::Request& ZScriptTCC::Request::operator << (const TableStart&) {
assert(GetScript()->GetLockCount() != 0);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (TableStart& ts) {
assert(GetScript()->GetLockCount() != 0);
return *this;
}
IScript::Request& ZScriptTCC::Request::Push() {
assert(GetScript()->GetLockCount() != 0);
assert(false); // not implemented
return *this;
}
IScript::Request& ZScriptTCC::Request::Pop() {
assert(GetScript()->GetLockCount() != 0);
assert(false); // not implemented
return *this;
}
IScript::Request::Ref ZScriptTCC::Request::Load(const String& script, const String& pa) {
assert(binary.empty() != script.empty());
assert(GetScript()->GetLockCount() != 0);
if (binary.empty() && tcc_compile_string(state, script.c_str())) {
// TODO: add all predefined symbols if needed
// allocate space
size_t size = tcc_relocate(state, nullptr);
binary.resize(size);
tcc_relocate(state, const_cast<char*>(binary.data()));
}
return IScript::Request::Ref(binary.empty() ? 0 : reinterpret_cast<size_t>(tcc_get_symbol(state, pa.empty() ? "main" : pa.c_str())));
}
IScript::Request& ZScriptTCC::Request::operator << (const Nil&) {
assert(GetScript()->GetLockCount() != 0);
assert(false); // not implemented
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const Global&) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const Local&) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const Key& k) {
assert(GetScript()->GetLockCount() != 0);
key = k.GetKey();
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (const Key& k) {
assert(GetScript()->GetLockCount() != 0);
key = k.GetKey();
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const LocalInfo& k) {
assert(GetScript()->GetLockCount() != 0);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (const LocalInfo& k) {
assert(GetScript()->GetLockCount() != 0);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (double value) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (double& value) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const String& str) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (String& str) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const char* str) {
assert(GetScript()->GetLockCount() != 0);
assert(str != nullptr);
assert(false);
return *this << String(str);
}
IScript::Request& ZScriptTCC::Request::operator >> (const char*& str) {
assert(GetScript()->GetLockCount() != 0);
assert(false); // Not allowed
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (bool b) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (bool& b) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const BaseDelegate& value) {
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (BaseDelegate& value) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const AutoWrapperBase& wrapper) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (int64_t u) {
assert(GetScript()->GetLockCount() != 0);
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (int64_t& u) {
assert(false);
return *this;
}
void ZScriptTCC::Request::DebugPrint() {}
IScript::Request& ZScriptTCC::Request::MoveVariables(IScript::Request& target, size_t count) {
assert(false);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const TableEnd&) {
assert(GetScript()->GetLockCount() != 0);
return *this;
}
IScript::Request& ZScriptTCC::Request::operator >> (const TableEnd&) {
assert(GetScript()->GetLockCount() != 0);
return *this;
}
bool ZScriptTCC::Request::IsValid(const BaseDelegate& d) {
return d.ptr != nullptr;
}
IScript::Request& ZScriptTCC::Request::operator >> (Ref& ref) {
assert(!binary.empty());
if (!key.empty()) {
ref.value = reinterpret_cast<size_t>(tcc_get_symbol(state, key.c_str()));
}
return *this;
}
IScript::Request& ZScriptTCC::Request::operator << (const Ref& ref) {
assert(binary.empty());
if (!key.empty() && ref) {
tcc_add_symbol(state, key.c_str(), reinterpret_cast<void*>(ref.value));
}
return *this;
}
bool ZScriptTCC::Request::Call(const AutoWrapperBase& wrapper, const Request::Ref& g) {
assert(false);
return false;
}
IScript::Request& ZScriptTCC::Request::operator >> (const Skip& skip) {
assert(false);
return *this;
}
IScript::Request::Ref ZScriptTCC::Request::ReferenceWithDebugInfo(const BaseDelegate& d, const String& tag, int line) {
return IScript::Request::Ref();
}
IScript::Request::Ref ZScriptTCC::Request::ReferenceWithDebugInfo(const Ref& d, const String& tag, int line) {
return IScript::Request::Ref();
}
IScript::Request::Ref ZScriptTCC::Request::ReferenceWithDebugInfo(const LocalInfo& d, const String& tag, int line) {
return IScript::Request::Ref();
}
IScript::Request::TYPE ZScriptTCC::Request::GetReferenceType(const Ref& d) {
return IScript::Request::OBJECT;
}
void ZScriptTCC::Request::Dereference(Ref& ref) {
// No need to dereference
}
const char* ZScriptTCC::GetFileExt() const {
static const char* extc = "c";
return extc;
}
| mit |
planettelex/wpf-bootstrap | SampleApplication.Modules.ModuleB/Views/ModuleBView.xaml.cs | 574 | using SampleApplication.Modules.ModuleB.ViewModels;
namespace SampleApplication.Modules.ModuleB.Views
{
/// <summary>
/// Interaction logic for ModuleBView.xaml
/// </summary>
public partial class ModuleBView
{
/// <summary>
/// Initializes a new instance of the <see cref="ModuleBView"/> class.
/// </summary>
/// <param name="viewModel">The view model.</param>
public ModuleBView(ModuleBViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
}
}
| mit |
goodwinxp/Yorozuya | library/ATF/PMIDL_XMIT_TYPE.hpp | 225 | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
typedef void *PMIDL_XMIT_TYPE;
END_ATF_NAMESPACE
| mit |
vefimov/simon | Gruntfile.js | 1343 | 'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js'],
},
coffee: {
glob_to_multiple: {
expand: true,
cwd: "lib/coffee",
src: ["**/*.coffee"],
dest: "lib/js",
ext: ".js"
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
},
},
watch: {
/*gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'nodeunit']
},*/
coffee: {
files: ["lib/**/*.coffee"],
tasks: ["coffee"],
options: {}
}
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks("grunt-contrib-coffee");
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
| mit |
dotnet236/aloha-rails | vendor/assets/javascripts/aloha/lib/aloha/observable.js | 3357 | /*!
* This file is part of Aloha Editor Project http://aloha-editor.org
* Copyright � 2010-2011 Gentics Software GmbH, [email protected]
* Contributors http://aloha-editor.org/contribution.php
* Licensed unter the terms of http://www.aloha-editor.org/license.html
*//*
* Aloha Editor is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.*
*
* Aloha Editor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
define(
['aloha/jquery'],
function(jQuery, undefined) {
var
$ = jQuery;
return {
_eventHandlers: null,
/**
* Attach a handler to an event
*
* @param {String} eventType A string containing the event name to bind to
* @param {Function} handler A function to execute each time the event is triggered
* @param {Object} scope Optional. Set the scope in which handler is executed
*/
bind: function(eventType, handler, scope) {
this._eventHandlers = this._eventHandlers || {};
if (!this._eventHandlers[eventType]) {
this._eventHandlers[eventType] = [];
}
this._eventHandlers[eventType].push({
handler: handler,
scope: (scope ? scope : window)
});
},
/**
* Remove a previously-attached event handler
*
* @param {String} eventType A string containing the event name to unbind
* @param {Function} handler The function that is to be no longer executed. Optional. If not given, unregisters all functions for the given event.
*/
unbind: function(eventType, handler) {
this._eventHandlers = this._eventHandlers || {};
if (!this._eventHandlers[eventType]) {
return;
}
if (!handler) {
// No handler function given, unbind all event handlers for the eventType
this._eventHandlers[eventType] = [];
} else {
this._eventHandlers[eventType] = $.grep(this._eventHandlers[eventType], function(element) {
if (element.handler === handler) {
return false;
}
return true;
});
}
},
/**
* Execute all handlers attached to the given event type.
* All arguments except the eventType are directly passed to the callback function.
*
* @param (String} eventType A string containing the event name for which the event handlers should be invoked.
*/
trigger: function(eventType) {
this._eventHandlers = this._eventHandlers || {};
if (!this._eventHandlers[eventType]) {
return;
}
// preparedArguments contains all arguments except the first one.
var preparedArguments = [];
$.each(arguments, function(i, argument) {
if (i>0) {
preparedArguments.push(argument);
}
});
$.each(this._eventHandlers[eventType], function(index, element) {
element.handler.apply(element.scope, preparedArguments);
});
},
/**
* Clears all event handlers. Call this method when cleaning up.
*/
unbindAll: function() {
this._eventHandlers = null;
}
};
}); | mit |
Nirklav/Tanks | app/src/main/java/com/ThirtyNineEighty/Base/Menus/BaseMenu.java | 1761 | package com.ThirtyNineEighty.Base.Menus;
import android.view.MotionEvent;
import com.ThirtyNineEighty.Base.Menus.Controls.IControl;
import com.ThirtyNineEighty.Base.BindableHost;
import com.ThirtyNineEighty.Base.Renderable.Renderer;
import java.util.ArrayList;
public abstract class BaseMenu
extends BindableHost<IControl>
implements IMenu
{
private final ArrayList<IControl> controlsCopy = new ArrayList<>();
@Override
public final void processEvent(MotionEvent event)
{
int action = event.getActionMasked();
int pointerIndex = event.getActionIndex();
float widthRatio = Renderer.EtalonWidth / Renderer.getWidth();
float heightRatio = Renderer.EtalonHeight / Renderer.getHeight();
float x = event.getX(pointerIndex) - Renderer.getWidth() / 2;
float y = - (event.getY(pointerIndex) - Renderer.getHeight() / 2);
x *= widthRatio;
y *= heightRatio;
int id = event.getPointerId(pointerIndex);
ArrayList<IControl> controls = getControlsCopy();
switch (action)
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
for (IControl control : controls)
control.processDown(id, x, y);
break;
case MotionEvent.ACTION_MOVE:
for (IControl control : controls)
control.processMove(id, x, y);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL:
for (IControl control : controls)
control.processUp(id, x, y);
break;
}
}
private ArrayList<IControl> getControlsCopy()
{
synchronized (objects)
{
controlsCopy.clear();
for (IControl control : objects)
controlsCopy.add(control);
return controlsCopy;
}
}
}
| mit |
Oxyless/highcharts-export-image | lib/highcharts.com/samples/issues/highcharts-4.0.4/3390-heatmap-single-point/demo.js | 717 | $(function () {
$('#container').highcharts({
chart: {
type: 'heatmap'
},
title: {
text: 'Single point heatmap - border and gradient'
},
series: [{
borderWidth: 1,
borderColor: 'black',
color: {
linearGradient: {
x1: 0,
x2: 1,
y1: 0,
y2: 0
},
stops: [
[0, '#FFFFFF'],
[1, '#007340']
]
},
data: [{
x: 0,
y: 0,
value: 90
}]
}]
});
}); | mit |
WindomZ/go-dice | roll/roll_test.go | 1406 | package roll
import (
"github.com/WindomZ/testify/assert"
"testing"
)
func TestNewRoll(t *testing.T) {
roll := NewRoll()
assert.NotEmpty(t, roll)
}
func Test_Roll_Weight(t *testing.T) {
roll := NewRoll()
assert.NotEmpty(t, roll.AddRoll(-1, -1).AddRoll(0, 0))
assert.NotEmpty(t, roll.AddRoll(int8(1), 1).AddRoll(int16(2), 2).AddRoll(int32(3), 3).AddRoll(int64(4), 4))
assert.NotEmpty(t, roll.AddRoll("a", 1).AddRoll("bb", 2).AddRoll("ccc", 3))
assert.NotEmpty(t, roll.AddRoll(nil, 1).AddRoll(nil, 2).AddRoll(nil, 3))
assert.Equal(t, roll.Weight(-1), 0)
assert.Equal(t, roll.Weight(0), 0)
assert.Equal(t, roll.Weight(int8(1)), 1)
assert.Equal(t, roll.Weight(int16(2)), 2)
assert.Equal(t, roll.Weight(int32(3)), 3)
assert.Equal(t, roll.Weight(int64(4)), 4)
assert.Equal(t, roll.Weight("a"), 1)
assert.Equal(t, roll.Weight("bb"), 2)
assert.Equal(t, roll.Weight("ccc"), 3)
assert.Equal(t, roll.Weight(nil), 6)
}
func Test_Roll_Roll(t *testing.T) {
roll := NewRoll()
assert.Empty(t, roll.Roll())
assert.NotEmpty(t,
roll.AddRoll(int8(1), 1).AddRoll(int16(2), 2).AddRoll(int32(3), 3).AddRoll(int64(4), 4))
assert.NotEmpty(t,
roll.AddRoll("a", 1).AddRoll("bb", 2).AddRoll("ccc", 3))
check := make(map[interface{}]bool)
for i := 0; i < 1000; i++ {
inst := roll.Roll()
if _, ok := check[inst]; !ok {
check[inst] = true
}
}
assert.Equal(t, roll.Size(), len(check))
}
| mit |
Cyberuben/node-postcode | src/request.js | 2223 | const https = require("https");
class JSONRequest {
constructor(options) {
this._options = options;
}
_requestOptions(method, path, headers, encoding) {
if(!headers) {
headers = {
"Content-Type": "application/json"
};
}
if(!encoding) {
encoding = "utf8";
}
return {
method, headers, encoding,
hostname: "api.postcode.nl",
path: "/rest" + path,
auth: this._options.key+":"+this._options.secret
}
}
_parseJsonResponse(response) {
return new Promise((resolve, reject) => {
const strings = [];
response.on("data", (chunk) => {
strings.push(chunk);
});
response.on("end", () => {
try {
const string = strings.join("");
if(response.statusCode === 200) {
resolve(JSON.parse(string));
}else if(response.statusCode === 401) {
reject(Object.assign(new Error("Invalid credentials for call"), {
statusCode: response.statusCode,
headers: response.headers
}));
}else{
let json;
let error = "Request returned HTTP code "+response.statusCode;
try {
json = JSON.parse(string);
if(json && json.exception) {
error = json.exception;
}
} catch (err) {
reject(err)
}
reject(Object.assign(new Error(error), {
string, json,
statusCode: response.statusCode,
headers: response.headers
}));
}
} catch (err) {
reject(err);
}
});
response.on("error", reject);
});
}
get(path) {
return new Promise((resolve, reject) => {
const opts = this._requestOptions("GET", path);
const request = https.request(opts, (res) => {
resolve(this._parseJsonResponse(res));
});
request.on("error", reject);
request.end();
});
}
post(path, data) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify(data);
const opts = this._requestOptions("POST", path, {
"Content-Type": "application/json",
"Content-Length": postData.length
});
const request = https.request(opts, (res) => {
resolve(this._parseJsonResponse(res));
});
request.write(postData);
request.on("error", reject);
request.end();
});
}
};
module.exports = JSONRequest; | mit |
lateefj/fresh | runner/runner.go | 832 | package runner
import (
"flag"
"io"
"os/exec"
"strings"
)
var cmdArgs string
func init() {
flag.StringVar(&cmdArgs, "a", "", "Command line arguments to pass to the process")
}
func run() bool {
runnerLog("Running...")
var cmd *exec.Cmd
if cmdArgs != "" {
args := strings.Split(cmdArgs, " ")
cmd = exec.Command(buildPath(), args...)
} else {
cmd = exec.Command(buildPath())
}
stderr, err := cmd.StderrPipe()
if err != nil {
fatal(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
fatal(err)
}
err = cmd.Start()
if err != nil {
fatal(err)
}
go io.Copy(appLogWriter{}, stderr)
go io.Copy(appLogWriter{}, stdout)
go func() {
<-stopChannel
pid := cmd.Process.Pid
runnerLog("Killing PID %d", pid)
cmd.Process.Kill()
}()
return true
}
| mit |
steamclock/internetmap | Common/Code/DefaultVisualization.hpp | 1851 | //
// DefaultVisualization.h
// InternetMap
//
#ifndef InternetMap_DefaultVisualization_hpp
#define InternetMap_DefaultVisualization_hpp
#include "Visualization.hpp"
//TODO: move these to a better place
#define SELECTED_NODE_COLOR_HEX 0x00A8EC
#define SELECTED_CONNECTION_COLOR_SELF_HEX 0x383838
#define SELECTED_CONNECTION_COLOR_OTHER_HEX 0xE0E0E0
#define ROUTE_COLOR 0xffa300
//#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
class DefaultVisualization : public Visualization {
public:
virtual std::string name(void) { return "Network View"; }
virtual void activate(std::vector<NodePointer> nodes);
virtual Point3 nodePosition(NodePointer node);
virtual float nodeSize(NodePointer node);
virtual float nodeZoom(NodePointer node);
virtual Color nodeColor(NodePointer node);
virtual void updateDisplayForNodes(shared_ptr<DisplayNodes> display, std::vector<NodePointer> nodes);
virtual void updateDisplayForSelectedNodes(shared_ptr<MapDisplay> display, std::vector<NodePointer> nodes);
virtual void resetDisplayForSelectedNodes(shared_ptr<MapDisplay> display, std::vector<NodePointer> nodes);
virtual void updateLineDisplay(shared_ptr<MapDisplay> display);
virtual void updateHighlightRouteLines(shared_ptr<MapDisplay> display, std::vector<NodePointer> nodeList);
virtual void updateConnectionLines(shared_ptr<MapDisplay> display, NodePointer node, std::vector<ConnectionPointer> connections);
static void setPortrait(bool);
static void setNodeScale(float);
static void setSelectedNodeColour(Color);
static Color getSelectedNodeColour();
protected:
static float sNodeScale;
static Color sSelectedColor;
};
#endif
| mit |
degica/barcelona | app/auth/vault/cap_probe.rb | 1526 | module Vault
class CapProbe
# Maps HTTP methods to vault actions
METHOD_MAP = {
'POST' => 'create',
'PATCH' => 'update',
'PUT' => 'update',
'GET' => 'read',
'DELETE' => 'delete'
}.freeze
def initialize(vault_uri, vault_token, vault_path_prefix)
@vault_uri = vault_uri
@vault_token = vault_token
@vault_path_prefix = vault_path_prefix
end
def prefix
return '/' + @vault_path_prefix if @vault_path_prefix.present?
''
end
def authorized?(path, method)
capabilities = retrieve_capabilites(path)
return true if capabilities.include? 'root'
vault_method = METHOD_MAP[method]
raise ExceptionHandler::Unauthorized.new("HTTP method not supported") if vault_method.nil?
capabilities.include? vault_method
end
def retrieve_capabilites(path)
vault_path = "secret/Barcelona#{prefix}#{path}"
req = Net::HTTP::Post.new("/v1/sys/capabilities-self")
req.body = {paths: [vault_path]}.to_json
req['X-Vault-Token'] = @vault_token
http = Net::HTTP.new(@vault_uri.host, @vault_uri.port)
http.use_ssl = true if @vault_uri.scheme == 'https'
res = http.request(req)
if res.code.to_i > 299
Rails.logger.error "ERROR: Vault returned code #{res.code} and #{res.body.inspect}"
raise ExceptionHandler::Forbidden.new("Your Vault token does not have a permission for #{req.path}")
end
JSON.load(res.body)["capabilities"]
end
end
end
| mit |
PokeGroup/pokemon-join | db/seeds/eyedees.js | 195 |
var data = require('../id-data.js')
exports.seed = function(knex, Promise) {
return knex('eyedees')
.del()
.then(function () {
return knex('eyedees').insert(data)
})
}
| mit |
jithu21/acme | packages/custom/analytics/server/controllers/users-online.js | 1543 | var fs = require('fs');
var async = require('async');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/acme';
module.exports.users_online= function(req, res,next) {
res.send(200);
// MongoClient.connect(url, function (err, db) {
// if (err)
// return err;
// var current_timestamp = (new Date((new Date).getTime() - 900000)).toUTCString();
//
// var match = {"$match": {"time": {"$gte": current_timestamp}, "event": {$ne: 'LogOut'}}};
//
// var report_query = [match, {$group: {"_id": "$userId", "userId": {"$first": "$userId"}, "count": {"$sum": 1}}}, {$project: {"_id": 0, userId: 1}}, {"$sort": {"count": -1}}, {"$limit": 100}];
// async.series([function (callback) {
// db.collection("events").aggregate(report_query, function (err, results) {
// var user_ids = [];
// results.forEach(function (data) {
// user_ids.push(data.userId);
// })
// callback(null, user_ids);
// })
// }], function (err, results) {
// find_from_users(results[0]);
// });
// var find_from_users = function (results) {
// async.series([function (callback) {
// db.collection("users").aggregate([
// {"$match": {"id": {$in: results}}},
// {$project: {"name": 1, "email": 1, "gender": 1, "dob": 1, "pincode": 1, "_id": 0}}
// ], function (err, results) {
// callback(null, results);
// })
// }], function (err, results) {
// res.send(results[0]);
// })
// }
// })
}; | mit |
PioBeat/Audio-Home-UI | control/MPDController.php | 4047 | <?php
/*
*/
/**
* Description of MPDController
*
* @author Dome
*/
class MPDController implements IMusicControl {
private $playlistdir;
private $filename;
private $filepath;
private $streamList;
private $server;
public function __construct() {
$this->playlistdir = "/mnt/mpd/radiostreams";
$this->filename = "playlist.m3u";
$this->filepath = $this->playlistdir . "/" . $this->filename;
$this->streamList = "./radio-streams.json";
$this->getServer();
}
/**
* Trys do read the server ip from the config file.
* If it´s not there, than the current server ip from which the script is
* executed will be used.
*/
private function getServer() {
try {
if ( ( $this->server = file_get_contents( "../mpd-server" ) ) === false ) {
throw new Exception( "no config file" );
}
} catch ( Exception $ex ) {
$this->server = $_SERVER['SERVER_ADDR'];
}
return $this->server;
}
public function shutdown() {
//or cat /var/run/mpd.pid if configured in mpd.cfg
exec( "pidof mpd", $pid, $ret );
//var_dump($pid);
//echo $ret;
if ( $ret != 0 ) {
echo "error: mpd cannot be killed because it hasn't started.";
return;
}
exec( "kill " . $pid[0], $null, $ret );
//echo "kill: mpd pid=" . $pid[0] . "<br/>";
echo $ret;
}
public function start() {
exec( "/etc/init.d/mpd start", $output, $ret );
//var_dump($output);
echo $ret;
}
public function initPlaylist() {
$this->loadMP3();
}
public function listAllSongs() {
exec( "mpc -h " . $this->server . " update" );
ob_start();
passthru( "mpc -h " . $this->server . " ls" );
$data = ob_get_contents();
ob_clean();
// var_dump($data);
$data = explode( "\n", $data );
return $data;
}
public function nextSong() {
exec( "mpc -h " . $this->server . " next" );
}
public function play( $songNumber ) {
if ( $songNumber == null ) {
exec( "mpc -h " . $this->server . " play" );
} else {
exec( "mpc -h " . $this->server . " play " . (int) $songNumber );
}
}
public function prevSong() {
exec( "mpc -h " . $this->server . " prev" );
}
public function stop() {
exec( "mpc -h " . $this->server . " stop" );
}
public function pause() {
exec( "mpc -h " . $this->server . " pause" );
}
public function resume() {
exec( "mpc -h " . $this->server . " play" );
}
/**
*
* @param type $url
*/
public function addRadioStreamUrl( $name, $url ) {
$rsl = $this->loadStreamList();
$entry = array();
$entry["name"] = $name;
$entry["url"] = $url;
array_push( $rsl, $entry );
file_put_contents( realpath( dirname( __FILE__ ) . "/../" . $this->streamList ), json_encode( $rsl ) );
$this->createPlaylist();
$this->loadPlaylist();
}
public function createPlaylist() {
unlink( $this->filepath );
$sc = array();
array_push( $sc, "#EXTM3U" );
$streams = $this->loadStreamList();
foreach ( $streams as $key => $value ) {
array_push( $sc, "#EXTINF:-1," . $value["name"] );
array_push( $sc, $value["url"] );
}
// var_dump($sc);
$playlist = implode( "\n", $sc );
// echo $playlist;
file_put_contents( $this->filepath, $playlist );
}
public function loadStreamList() {
$contents = file_get_contents( realpath( dirname( __FILE__ ) . "/../" . $this->streamList ) );
$streams = json_decode( $contents, true );
return $streams;
}
public function loadPlaylist() {
exec( "mpc -h " . $this->server . " clear" );
exec( "mpc -h " . $this->server . " load " . basename( $this->filename, ".m3u" ));
}
public function listPlaylist() {
exec( "mpc -h " . $this->server . " playlist " . basename( $this->filename, ".m3u" ), $output, $ret );
return $output;
}
public function loadMP3() {
exec( "mpc -h " . $this->server . " clear" );
exec( "mpc -h " . $this->server . " listall | mpc -h " . $this->server . " add" );
exec( "mpc -h " . $this->server . " update" );
}
public function getCurrentPlaying() {
exec( "mpc -h " . $this->server . " current", $output);
return $output;
}
}
| mit |
BunqCommunity/BunqDesktop | src/react/Functions/IpChecker.js | 205 | import axios from "axios";
export default async () => {
try {
return await axios.get("https://ipinfo.io/ip").then(response => response.data);
} catch (ex) {
return false;
}
};
| mit |
joergkrause/netrix | NetrixDemo/RibbonLib/Samples/CS/07-RibbonColor/Properties/Settings.Designer.cs | 1068 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace _07_RibbonColor.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| mit |
sguzunov/PingPongGame | PingPong/PingPong.Logic/GameObjects/GameObject.cs | 495 | using System;
using PingPong.Logic.GameObjects.Contracts;
namespace PingPong.Logic.GameObjects
{
public class GameObject : IGameObject
{
private Position position;
public GameObject(Position initialPosition)
{
this.Position = initialPosition;
}
public Position Position
{
get => this.position;
set => this.position = value ?? throw new ArgumentNullException(nameof(position));
}
}
}
| mit |
Aedius/crowfall-royaumes-eternel | src/AppBundle/Controller/Front/ArticleController.php | 4124 | <?php
namespace AppBundle\Controller\Front;
use AppBundle\Component\Helper\Pagination;
use AppBundle\Entity\Article;
use AppBundle\Entity\Comment;
use AppBundle\Repository\ArticleRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\HttpFoundation\Request;
class ArticleController extends BaseController
{
/**
* @Route("/article/{id}/{slug}", name="article_show", requirements={"id": "\d+"})
* @param Request $request
* @param int $id
* @param string $slug
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function articleAction(Request $request, $id, $slug)
{
/** @var ArticleRepository $repo */
$articleRepository = $this->getDoctrine()->getRepository(Article::class);
/** @var Article|null $article */
$article = $articleRepository->find($id);
if ($article === null || !$article->getPublished()) {
throw $this->createNotFoundException('L\'article n\'est pas disponible');
}
if ($article->getSlug() !== $slug) {
return $this->redirectToRoute(
$this->generateUrl(
'article_show',
['slug' => $article->getSlug(),
'id' => $article->getId()]
));
}
$articleSideList = $articleRepository->getAll(3, 1);
$comment = new Comment();
$comment->setDate(new \DateTime());
$comment->setAuthor($this->getUser());
$form = $this->createFormBuilder($comment)
->add('content', TextareaType::class, [
'label' => 'Laisser un commentaire',
'trim' => true,
])
->add('save', SubmitType::class, array('label' => 'Envoyer'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$comment->setArticle($article);
/** @var Comment $comment */
$comment = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
return $this->redirectToRoute('article_show', ['id' => $id, 'slug' => $slug]);
}
return $this->render(':article:show.html.twig', [
'article' => $article,
'articleSideList' => $articleSideList,
'commentList' => $article->getCommentList(),
'commentForm' => $form->createView(),
]);
}
/**
* @Route("/tous-les-articles/{page}", name="article_all", defaults={"page" = 1} )
* @param $page
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function allArticleAction($page)
{
$paginationSize = $this->getParameter('app.pagination');
$articleList = $this->getDoctrine()
->getRepository('AppBundle:Article')
->getAll((int)$paginationSize, (int)$page);
$articleCount = $this->getDoctrine()
->getRepository('AppBundle:Article')
->getAllCount();
$router = $this->get('router');
$pagination = new Pagination();
if ($page > 1) {
$pagination
->setPreviousPageWording('Articles prédédents')
->setPreviousPageUrl(
$router->generate('article_all', ['page' => $page - 1])
);
}
if ($page < ceil($articleCount / $paginationSize)) {
$pagination
->setNextPageWording('Articles suivants')
->setNextPageUrl(
$router->generate('article_all', ['page' => $page + 1])
);
}
return $this->render('article/all.html.twig', [
'articleList' => $articleList,
'pagination' => $pagination,
]);
}
} | mit |
ChibiFR/rythmoos-engine | build/lib/Scene.js | 2108 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Map_1 = require("./Map");
/**
* A scene contains all the game objects in a specific "screen" of your game.<br>
* For example, you may have a "MainScreen" scene that will contain everything
* that is in the main screen of your game.<br>
* You could then have a "Level1" scene that will contain the level 1 of you game. etc.
*/
var Scene = /** @class */ (function () {
function Scene() {
this._gameObjects = new Map_1.Map();
this.create();
}
/**
* Called when the scene is created.<br>
* You can set your game objects (UI, characters, music, etc) from here.
*/
Scene.prototype.create = function () {
};
/**
* Run every frame to update the scene.<br>
* This is useful when you want an update to run as long as your scene is
* being rendered, independently from the game objects it contains.
*/
Scene.prototype.update = function () {
};
/**
* Get a game object from the scene.
* @param gameObjectName The game object to get.
* @return The requested game object, or null if it does not exist in the scene.
*/
Scene.prototype.get = function (gameObjectName) {
return this._gameObjects.get(gameObjectName);
};
/**
* Set a game object.
* @param gameObjectName The name of the game object to set.
* @param gameObject The game object.
*/
Scene.prototype.set = function (gameObjectName, gameObject) {
gameObject.scene = this;
this._gameObjects.set(gameObjectName, gameObject);
};
/**
* Remove a game object.
* @param gameObjectName The name of the game object to remove.
*/
Scene.prototype.remove = function (gameObjectName) {
return this._gameObjects.remove(gameObjectName);
};
/**
* Get all the game objects of this scene as an array.
*/
Scene.prototype.getAll = function () {
return this._gameObjects.getAll();
};
return Scene;
}());
exports.Scene = Scene;
//# sourceMappingURL=Scene.js.map | mit |
Goldinteractive/periskop | src/assets/js/layouts/BaseLayout.js | 491 | define([
'collections/Images',
'components/images-slider/View',
'layoutmanager'
], function(Images, ImagesSliderComponent) {
var imagesCollection = new Images();
return Backbone.Layout.extend({
el: 'body',
collection: imagesCollection,
views: {
'.slider-container': new ImagesSliderComponent({
collection: imagesCollection
})
},
initialize: function() {
},
afterRender: function() {
this.$('#loader').remove();
}
});
}); | mit |
smgladkovskiy/querier | spec/SMGladkovskiy/Querier/ValidationQueryBusSpec.php | 1818 | <?php
namespace spec\SMGladkovskiy\Querier;
use Illuminate\Foundation\Application;
use SMGladkovskiy\Querier\QueryBus;
use SMGladkovskiy\Querier\QueryTranslator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ValidationQueryBusSpec extends ObjectBehavior
{
function let(QueryBus $bus, Application $application, QueryTranslator $translator)
{
$this->beConstructedWith($bus, $application, $translator);
}
function it_does_not_handle_command_if_validation_fails(
Application $application,
QueryTranslator $translator,
QueryBus $bus,
ExampleQuery $query,
ExampleValidator $validator
) {
// Own responsibility
$translator->toValidator($query)->willReturn(ExampleValidator::class);
$application->make(ExampleValidator::class)->willReturn($validator);
$validator->validate($query)->willThrow('RuntimeException');
// Delegated responsibility
$bus->executeQuery($query)->shouldNotBeCalled();
$this->shouldThrow('RuntimeException')->duringExecuteQuery($query);
}
function it_handles_command_if_validation_succeeds(
Application $application,
QueryTranslator $translator,
QueryBus $bus,
ExampleQuery $query,
ExampleValidator $validator
) {
// Own responsibility
$translator->toValidator($query)->willReturn(ExampleValidator::class);
$application->make(ExampleValidator::class)->willReturn($validator);
// Delegated responsibility
$bus->executeQuery($query)->shouldBeCalled();
$this->executeQuery($query);
}
}
// Stub Stuff
class ExampleQuery {}
class ExampleValidator { public function validate($query) {} }
namespace Illuminate\Foundation;
class Application { function make() {} } | mit |
kybarg/material-ui | packages/material-ui-icons/src/MoreVertTwoTone.js | 292 | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" />
, 'MoreVertTwoTone');
| mit |
morkai/h5.modbus | lib/messages/WriteSingleCoilResponse.js | 2970 | // Part of <http://miracle.systems/p/h5.modbus> licensed under <MIT>
'use strict';
const helpers = require('../helpers');
const FunctionCode = require('../FunctionCode');
const Response = require('../Response');
/**
* The write single coil response (code 0x05).
*
* A binary representation of this response is 5 bytes long and consists of:
*
* - a function code (1 byte),
* - an output address (2 bytes),
* - an output value (2 bytes).
*
* The output value of `0xFF00` means that the output is ON.
* The output value of `0x0000` means that the output is OFF.
*/
class WriteSingleCoilResponse extends Response
{
/**
* @param {number} address An address of the set output. Must be between 0 and 0xFFFF.
* @param {boolean} state A state of the set output.
* @throws {Error} If the specified `address` is not a number between 0 and 0xFFFF.
*/
constructor(address, state)
{
super(FunctionCode.WriteSingleCoil);
/**
* An address of the set output. A number between 0 and 0xFFFF.
*
* @readonly
* @type {number}
*/
this.address = helpers.prepareAddress(address, 1);
/**
* A state of the set output.
*
* @readonly
* @type {boolean}
*/
this.state = !!state;
}
/**
* Creates a new response from the specified `options`.
*
* @param {Object} options
* @param {number} [options.address=0] A starting address.
* If specified, must be a number between 0 and 0xFFFF. Defaults to 0.
* @param {boolean} [options.state=false] A state of the output to set. Defaults to `false`.
* @returns {WriteSingleCoilResponse}
* @throws {Error} If any of the specified `options` are invalid.
*/
static fromOptions(options)
{
return new WriteSingleCoilResponse(options.address, options.state);
}
/**
* Creates a new response from its binary representation.
*
* @param {Buffer} buffer A binary representation of this response.
* @returns {WriteSingleCoilResponse}
* @throws {Error} If the specified `buffer` is not a valid binary representation of this response.
*/
static fromBuffer(buffer)
{
helpers.assertBufferLength(buffer, 5);
helpers.assertFunctionCode(buffer[0], FunctionCode.WriteSingleCoil);
return new WriteSingleCoilResponse(
buffer.readUInt16BE(1),
buffer.readUInt16BE(3) === 0xFF00
);
}
/**
* Returns a binary representation of this response.
*
* @returns {Buffer}
*/
toBuffer()
{
const buffer = Buffer.allocUnsafe(5);
buffer[0] = this.functionCode;
buffer.writeUInt16BE(this.address, 1);
buffer.writeUInt16BE(this.state ? 0xFF00 : 0x0000, 3);
return buffer;
}
/**
* Returns a string representation of this response.
*
* @returns {string}
*/
toString()
{
return helpers.formatResponse(this, `Coil at address ${this.address} was set to ${this.state ? 'ON' : 'OFF'}.`);
}
}
module.exports = WriteSingleCoilResponse;
| mit |
SlashGames/slash-framework | Source/Slash.Unity.StrangeIoC/Source/Initialization/Initializer.cs | 868 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Initializer.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.Unity.StrangeIoC.Initialization
{
using Slash.Unity.StrangeIoC.Modules;
public class Initializer : ModuleView
{
private void Awake()
{
// Create and start application context.
var applicationContext = new ApplicationContext();
applicationContext.Init(this);
applicationContext.Start();
applicationContext.SetContextView(this);
this.context = applicationContext;
}
}
} | mit |
mc437-g01/mutant-spotlight | src/main/java/br/unicamp/ic/mc437/g1/entity/package-info.java | 228 | /**
* Created by fernandogoncalves on 10/17/14.
*/
@XmlAccessorType(XmlAccessType.FIELD)
package br.unicamp.ic.mc437.g1.entity;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType; | mit |
lcidral/yii2-brazilian-freight-module | src/validators/DeliveryRangeValidator.php | 632 | <?php
namespace lcidral\yii2\freight\validators;
use lcidral\yii2\freight\models\DeliveryRanges;
use lcidral\yii2\freight\Module;
use yii\validators\Validator;
class DeliveryRangeValidator extends Validator
{
public function validateAttribute($model, $attribute)
{
$range = (int) DeliveryRanges::find()
->select('id')
->where(':new_range between start and end', [
':new_range' => $model->start
])->count();
if ($range) {
$this->addError( $model, 'start', Module::t('delivery_ranges', 'This range is already registered'));
}
}
}
| mit |
AnnArborTees/spree_digital | spec/models/digital_spec.rb | 849 | require 'spec_helper'
describe Spree::Digital do
context 'validation' do
it { should belong_to(:variant) }
end
context "#create" do
end
context "#destroy" do
it "should destroy associated digital_links" do
digital = create(:digital)
3.times { digital.digital_links.create!({ :line_item => create(:line_item) }) }
Spree::DigitalLink.count.should == 3
lambda {
digital.destroy
}.should change(Spree::DigitalLink, :count).by(-3)
end
end
context "Spree::Variant#vhx_product_id=" do
context 'given a full url' do
let(:variant) { create(:variant) }
it 'parses the ID from the URL' do
variant.vhx_product_id = "https://annarborteesonlinestore.vhx.tv/admin/products/15940/edit"
expect(variant.vhx_product_id).to eq '15940'
end
end
end
end
| mit |
getinsomnia/insomnia | packages/openapi-2-kong/src/kubernetes/plugins.test.ts | 20378 | import { HttpMethod } from '../common';
import { dummyPluginDoc, pluginDummy, UserK8sPlugin } from '../declarative-config/jest/test-helpers';
import { OperationPlugin, PathPlugin } from '../types/k8s-plugins';
import {
OA3Components,
OA3Operation,
OA3PathItem,
OA3Paths,
OA3Server,
OpenApi3Spec,
} from '../types/openapi3';
import {
keyAuthPluginDoc,
pluginDocWithName,
pluginKeyAuth,
} from './plugin-helpers';
import {
flattenPluginDocuments,
generateK8sPluginConfig,
getGlobalPlugins,
getOperationPlugins,
getPathPlugins,
getPlugins,
getServerPlugins,
normalizeOperationPlugins,
normalizePathPlugins,
prioritizePlugins,
} from './plugins';
describe('plugins', () => {
let _iterator = 0;
const increment = () => _iterator++;
const blankOperation = {
method: null,
plugins: [],
};
const blankPath = {
path: '',
plugins: [],
operations: [blankOperation],
};
const spec: OpenApi3Spec = {
openapi: '3.0',
info: {
version: '1.0',
title: 'My API',
},
servers: [
{
url: 'http://api.insomnia.rest',
},
],
paths: {},
};
const components: OA3Components = {
securitySchemes: {
// @ts-expect-error -- TSCONVERSION
really_basic: {
type: 'http',
scheme: 'basic',
},
my_api_key: {
type: 'apiKey',
name: 'api_key_by_me',
in: 'header',
},
your_api_key: {
type: 'apiKey',
name: 'api_key_by_you',
in: 'header',
},
petstore_oauth2: {
type: 'oauth2',
// @ts-expect-error -- TSCONVERSION
flows: {
clientCredentials: {
tokenUrl: 'http://example.org/api/oauth/dialog',
scopes: {
'write:pets': 'modify pets in your account',
'read:pets': 'read your pets',
},
},
},
},
// @ts-expect-error -- TSCONVERSION
petstore_openid: {
type: 'openIdConnect',
openIdConnectUrl: 'http://example.org/oid-discovery',
},
},
};
beforeEach(() => {
_iterator = 0;
});
describe('getPlugins()', () => {
it('should return expected result if no plugins on spec', () => {
const result = getPlugins(spec);
const globalPlugins = result.global;
expect(globalPlugins).toHaveLength(0);
expect(result.servers).toEqual([
{
server: spec.servers?.[0],
plugins: [],
},
]);
expect(result.paths).toEqual([blankPath]);
});
it('should return expected result if plugins on global, server, path, and operation', () => {
const api: OpenApi3Spec = {
...spec,
...pluginKeyAuth,
servers: [
{
url: 'http://api.insomnia.rest',
...pluginKeyAuth,
},
],
paths: {
'/path': {
...pluginKeyAuth,
get: {
...pluginKeyAuth,
},
},
},
};
const result = getPlugins(api);
const globalPlugins = result.global;
expect(globalPlugins).toEqual([keyAuthPluginDoc('g0')]);
const serverPlugins = result.servers[0].plugins;
expect(serverPlugins).toEqual([keyAuthPluginDoc('s1')]);
const pathPlugins = result.paths[0].plugins;
expect(pathPlugins).toEqual([keyAuthPluginDoc('p2')]);
const operationPlugins = result.paths[0].operations[0].plugins;
expect(operationPlugins).toEqual([keyAuthPluginDoc('m3')]);
});
it('should throw error if no servers on api', () => {
const action = () => getPlugins({ ...spec, servers: [] });
expect(action).toThrowError('Failed to generate spec: no servers defined in spec.');
});
});
describe('getGlobalPlugins()', () => {
it('returns empty array if no global plugins found on spec', async () => {
const result = getGlobalPlugins(spec, increment);
expect(result).toHaveLength(0);
});
it('returns single plugin doc', () => {
const api: OpenApi3Spec = { ...spec, ...pluginKeyAuth };
const result = getGlobalPlugins(api, increment);
expect(result).toEqual([keyAuthPluginDoc('g0')]);
});
it('returns multiple plugin docs', () => {
const api: OpenApi3Spec = { ...spec, ...pluginKeyAuth, ...pluginDummy };
const result = getGlobalPlugins(api, increment);
expect(result).toEqual<UserK8sPlugin[]>([keyAuthPluginDoc('g0'), dummyPluginDoc('g1')]);
});
it('returns security plugin doc', () => {
const pluginSecurity = {
security: [
{
really_basic: [],
your_api_key: [],
},
],
components: {
securitySchemes: {
really_basic: {
type: 'http',
scheme: 'basic',
},
my_api_key: {
type: 'apiKey',
name: 'api_key_by_me',
in: 'header',
},
your_api_key: {
type: 'apiKey',
name: 'api_key_by_you',
in: 'header',
},
petstore_oauth2: {
type: 'oauth2',
flows: {
clientCredentials: {
tokenUrl: 'http://example.org/api/oauth/dialog',
scopes: {
'write:pets': 'modify pets in your account',
'read:pets': 'read your pets',
},
},
},
},
petstore_openid: {
type: 'openIdConnect',
openIdConnectUrl: 'http://example.org/oid-discovery',
},
},
},
};
const api: OpenApi3Spec = {
...spec,
...pluginDummy,
...pluginSecurity,
components,
};
const result = getGlobalPlugins(api, increment);
expect(result).toEqual([
dummyPluginDoc('g0'),
{
apiVersion: 'configuration.konghq.com/v1',
kind: 'KongPlugin',
plugin: 'basic-auth',
metadata: {
name: 'add-basic-auth-g1',
},
},
{
apiVersion: 'configuration.konghq.com/v1',
kind: 'KongPlugin',
plugin: 'key-auth',
metadata: {
name: 'add-key-auth-g2',
},
config: {
key_names: ['api_key_by_you'],
},
},
]);
});
});
describe('getServerPlugins()', () => {
const server0: OA3Server = {
url: 'http://api-0.insomnia.rest',
};
const server1: OA3Server = {
url: 'http://api-1.insomnia.rest',
};
it('returns no plugins for servers', () => {
const servers = [server0, server1];
const result = getServerPlugins(servers, increment);
expect(result).toHaveLength(2);
result.forEach(s => expect(s.plugins).toHaveLength(0));
});
it('returns plugins from each server', () => {
const servers = [{ ...server0 }, { ...server1, ...pluginKeyAuth, ...pluginDummy }];
const result = getServerPlugins(servers, increment);
expect(result).toHaveLength(2);
expect(result[0].plugins).toEqual([]);
expect(result[1].plugins).toEqual([keyAuthPluginDoc('s0'), dummyPluginDoc('s1')]);
});
});
describe('getPathPlugins()', () => {
it('should return normalized result if no paths', () => {
const paths: OA3Paths = {};
const result = getPathPlugins(paths, increment, spec);
expect(result).toEqual([blankPath]);
});
it('should return normalized result if no path and operation plugins', () => {
const paths: OA3Paths = {
'/path': {
description: 'path',
get: {
description: 'get',
},
},
};
const result = getPathPlugins(paths, increment, spec);
expect(result).toEqual([blankPath]);
});
it('should handle plugins existing on path', () => {
const paths: OA3Paths = {
'/path-no-plugin': {},
'/path': pluginDummy as OA3PathItem,
};
const result = getPathPlugins(paths, increment, spec);
expect(result).toHaveLength(2);
const first = result[0];
expect(first.path).toBe('/path-no-plugin');
expect(first.plugins).toHaveLength(0);
expect(first.operations).toEqual([blankOperation]);
const second = result[1];
expect(second.path).toBe('/path');
expect(second.plugins).toEqual([dummyPluginDoc('p0')]);
expect(second.operations).toEqual([blankOperation]);
});
it('should handle plugins existing on operation and not on path', () => {
const paths: OA3Paths = {
'/path': {
get: pluginDummy as OA3Operation,
put: {},
},
};
const result = getPathPlugins(paths, increment, spec);
expect(result).toHaveLength(1);
expect(result[0].plugins).toHaveLength(0);
expect(result[0].operations).toEqual([
{
method: 'get',
plugins: [dummyPluginDoc('m0')],
},
{
method: 'put',
plugins: [],
},
]);
});
it('should handle plugins existing on path and operation', () => {
const paths: OA3Paths = {
'/path-0': { ...pluginKeyAuth, get: pluginDummy as OA3Operation },
'/path-1': { ...pluginDummy, put: {} },
};
const result = getPathPlugins(paths, increment, spec);
expect(result).toHaveLength(2);
const path0 = result[0];
expect(path0.path).toBe('/path-0');
expect(path0.plugins).toEqual([keyAuthPluginDoc('p0')]);
expect(path0.operations).toEqual([
{
method: 'get',
plugins: [dummyPluginDoc('m1')],
},
]);
const path1 = result[1];
expect(path1.path).toBe('/path-1');
expect(path1.plugins).toEqual([dummyPluginDoc('p2')]);
expect(path1.operations).toEqual([blankOperation]);
});
});
describe('getOperationPlugins()', () => {
it('should return normalized result if no plugins', () => {
const pathItem = {
description: 'test',
};
const result = getOperationPlugins(pathItem, increment, spec);
expect(result).toEqual([blankOperation]);
});
it('should return plugins for all operations on path', () => {
const pathItem: OA3PathItem = {
[HttpMethod.get]: {},
[HttpMethod.put]: { ...pluginKeyAuth, ...pluginDummy },
[HttpMethod.post]: pluginDummy as OA3Operation,
};
const result = getOperationPlugins(pathItem, increment, spec);
expect(result).toHaveLength(3);
const get = result[0];
expect(get.method).toBe(HttpMethod.get);
expect(get.plugins).toHaveLength(0);
const put = result[1];
expect(put.method).toBe(HttpMethod.put);
expect(put.plugins).toEqual([keyAuthPluginDoc('m0'), dummyPluginDoc('m1')]);
const post = result[2];
expect(post.method).toBe(HttpMethod.post);
expect(post.plugins).toEqual([dummyPluginDoc('m2')]);
});
it.each(Object.values(HttpMethod))(
'should extract method plugins for %o from path item',
methodName => {
const pathItem = {
[methodName]: { ...pluginKeyAuth, ...pluginDummy },
};
const result = getOperationPlugins(pathItem, increment, spec);
expect(result).toHaveLength(1);
const first = result[0];
expect(first.method).toBe(methodName);
expect(first.plugins).toEqual([keyAuthPluginDoc('m0'), dummyPluginDoc('m1')]);
},
);
it('should return security plugin from operation', () => {
const api: OpenApi3Spec = { ...spec, components };
const pathItem: OA3PathItem = {
[HttpMethod.get]: {
security: [
{
really_basic: [],
your_api_key: [],
},
],
},
};
const result = getOperationPlugins(pathItem, increment, api);
expect(result[0].plugins).toEqual([
{
apiVersion: 'configuration.konghq.com/v1',
kind: 'KongPlugin',
plugin: 'basic-auth',
metadata: {
name: 'add-basic-auth-m0',
},
},
{
apiVersion: 'configuration.konghq.com/v1',
kind: 'KongPlugin',
plugin: 'key-auth',
metadata: {
name: 'add-key-auth-m1',
},
config: {
key_names: ['api_key_by_you'],
},
},
]);
});
});
describe('generateK8sPluginConfig()', () => {
it('should return empty array if no plugin keys found and not increment', () => {
const incrementMock = jest.fn().mockReturnValue(0);
const result = generateK8sPluginConfig(spec, 's', incrementMock);
expect(result).toHaveLength(0);
expect(incrementMock).not.toHaveBeenCalled();
});
it('should attach config onto plugin if it exists and increment', () => {
const incrementMock = jest.fn().mockReturnValue(0);
// @ts-expect-error -- TSCONVERSION not sure, but this is intentionally different maybe?
const result = generateK8sPluginConfig({ ...spec, ...pluginKeyAuth }, 'greg', incrementMock);
expect(result).toEqual([keyAuthPluginDoc('greg0')]);
expect(incrementMock).toHaveBeenCalledTimes(1);
});
});
describe('normalizePathPlugins()', () => {
it('should return source array if a path with plugins exists', () => {
const source: PathPlugin[] = [
{
path: '/path-with-plugin',
// @ts-expect-error -- TSCONVERSION more work is needed to module augment to include DummyPlugin (but not export those augmentations)
plugins: [dummyPluginDoc('p0')],
operations: [blankOperation],
},
{
path: '/path',
plugins: [],
operations: [blankOperation],
},
];
expect(normalizePathPlugins(source)).toEqual(source);
});
it('should return source array if an operation with plugins exist', () => {
const source: PathPlugin[] = [
{
path: '/path',
plugins: [],
operations: [
{
method: HttpMethod.get,
// @ts-expect-error -- TSCONVERSION more work is needed to module augment to include DummyPlugin (but not export those augmentations)
plugins: [dummyPluginDoc('p0')],
},
{
method: HttpMethod.put,
plugins: [],
},
],
},
];
expect(normalizePathPlugins(source)).toEqual(source);
});
it('should return blank path if no plugins exist on path or operations', () => {
const source: PathPlugin[] = [
{
path: '/path-0',
plugins: [],
operations: [blankOperation],
},
{
path: '/path-1',
plugins: [],
operations: [blankOperation],
},
];
expect(normalizePathPlugins(source)).toEqual([blankPath]);
});
});
describe('normalizeOperationPlugins()', () => {
it('should return source array if operation plugins exist', () => {
const source: OperationPlugin[] = [
{
method: HttpMethod.get,
plugins: [],
},
{
method: HttpMethod.post,
// @ts-expect-error -- TSCONVERSION more work is needed to module augment to include DummyPlugin (but not export those augmentations)
plugins: [dummyPluginDoc('p0')],
},
];
expect(normalizeOperationPlugins(source)).toEqual(source);
});
it('should return blank operation if no plugins exist on operations', () => {
const source: OperationPlugin[] = [
{
method: HttpMethod.get,
plugins: [],
},
{
method: HttpMethod.post,
plugins: [],
},
];
expect(normalizeOperationPlugins(source)).toEqual([blankOperation]);
});
});
describe('flattenPluginDocuments()', () => {
it('should return a flat array with all plugin documents', () => {
const api: OpenApi3Spec = {
...spec,
...pluginKeyAuth,
servers: [
{
url: 'http://api.insomnia.rest',
...pluginKeyAuth,
},
],
paths: {
'/path': { ...pluginKeyAuth, get: { ...pluginKeyAuth } },
},
};
const plugins = getPlugins(api);
const flattened = flattenPluginDocuments(plugins);
expect(flattened).toEqual([
keyAuthPluginDoc('g0'),
keyAuthPluginDoc('s1'),
keyAuthPluginDoc('p2'),
keyAuthPluginDoc('m3'),
]);
});
});
describe('prioritizePlugins', () => {
it('should return empty array if no plugins', () => {
const result = prioritizePlugins([], [], [], []);
expect(result).toHaveLength(0);
});
it('should return all plugins if no two plugins are the same type', () => {
const p1 = pluginDocWithName('p1', 'custom-plugin-1');
const p2 = pluginDocWithName('p2', 'custom-plugin-2');
const p3 = pluginDocWithName('p3', 'custom-plugin-3');
const p4 = pluginDocWithName('p4', 'custom-plugin-4');
const global = [p1];
const server = [p2];
const path = [p3];
const operation = [p4];
const result = prioritizePlugins(global, server, path, operation);
expect(result).toEqual([...operation, ...path, ...server, ...global]);
});
it('should return operation plugin if same type exists in path, server and global', () => {
const pluginType = 'custom-plugin';
const p1 = pluginDocWithName('p1', pluginType);
const p2 = pluginDocWithName('p2', pluginType);
const p3 = pluginDocWithName('p3', pluginType);
const p4 = pluginDocWithName('p4', pluginType);
const global = [p1];
const server = [p2];
const path = [p3];
const operation = [p4];
const result = prioritizePlugins(global, server, path, operation);
expect(result).toEqual([...operation]);
});
it('should return path plugin if same type exists in server and global', () => {
const pluginType = 'custom-plugin';
const p1 = pluginDocWithName('p1', pluginType);
const p2 = pluginDocWithName('p2', pluginType);
const p3 = pluginDocWithName('p3', pluginType);
const global = [p1];
const server = [p2];
const path = [p3];
const result = prioritizePlugins(global, server, path, []);
expect(result).toEqual([...path]);
});
it('should return server plugin if same type exists in global', () => {
const pluginType = 'custom-plugin';
const p1 = pluginDocWithName('p1', pluginType);
const p2 = pluginDocWithName('p2', pluginType);
const global = [p1];
const server = [p2];
const result = prioritizePlugins(global, server, [], []);
expect(result).toEqual([...server]);
});
it('should prioritize as expected', () => {
const typeG = 'custom-plugin-1';
const typeS = 'custom-plugin-2';
const typeP = 'custom-plugin-3';
const typeO = 'custom-plugin-4';
// Note: the variable naming below is [applied-to][resolved-from]
// IE: po implies it is applied to a path, but that plugin type should be resolved by the operation
// Therefore, the result should only contain gg, ss, pp and oo. The others are duplicates
// of the same plugin type and should be filtered out due to prioritization.
const gg = pluginDocWithName('gg', typeG);
const gs = pluginDocWithName('gs', typeS);
const ss = pluginDocWithName('ss', typeS);
const gp = pluginDocWithName('gp', typeP);
const sp = pluginDocWithName('sp', typeP);
const pp = pluginDocWithName('pp', typeP);
const go = pluginDocWithName('go', typeO);
const so = pluginDocWithName('so', typeO);
const po = pluginDocWithName('po', typeO);
const oo = pluginDocWithName('oo', typeO);
const global = [gg, gs, gp, go];
const server = [ss, sp, so];
const path = [pp, po];
const operation = [oo];
const result = prioritizePlugins(global, server, path, operation);
expect(result).toEqual([oo, pp, ss, gg]);
});
});
});
| mit |
Vrturo/Algo-Gem | Algorithms/JS/integers/primeFactors.js | 478 | // How could you find all prime factors of a number?
// the prime factors of a positive integer are the prime numbers that divide that integer exactly.
// Run a while loop. start dividing by two and if not divisible increase divider until u r done.
function primeFactors(n){
var factors = [],
divisor = 2;
while(n>2){
if(n % divisor == 0){
factors.push(divisor);
n = n/ divisor;
}
else{
divisor++;
}
}
return factors;
}
| mit |
pekzeki/PopulationAnalysis | all_cities.py | 1356 | # -*- coding: utf-8 -*-
'''
Reads all the CSV file inside 'data/' folder as a Pandas DataFrame
Plot total population of each city w.r.t their plate numbers to a Line Chart for each year under output/ folder
@author: pekzeki
'''
import commons
import pygal
import glob
import os
from operator import itemgetter
files = glob.glob(os.path.join('data','*.csv'))
for file in files:
year = commons.get_year(file)
tmp = commons.get_population_skipfirst(file)
city_population_list = []
total_population = tmp['Toplam']
city_names = tmp['Sehir']
sum_population = 0
for index, row in total_population.iteritems():
city_population = commons.convert_integer(row)
city_name = city_names.irow(index)
city_population_list.append((index+1, city_population))
sum_population += city_population
#sort list
sorted_list = sorted(city_population_list, key=itemgetter(0))
#calculate the mean
mean = sum_population / index
#Plotting the data
xy_chart = pygal.XY(stroke=True, y_title='Population Count', x_title='Plate Number of the City')
xy_chart.title = 'Population per City in ' + str(year)
xy_chart.add('Cities', sorted_list)
xy_chart.add('Average', [(0, mean), (index, mean)])
xy_chart.render_to_file('output/population_per_city_'+year+'.svg') | mit |
mpapierski/eventspout | utils.py | 671 | from twisted.internet import reactor
from twisted.internet.protocol import Protocol
from twisted.internet.defer import Deferred
def getBody(response):
"""Deferred that delivers body from `response`.
"""
class BodyReceiver(Protocol):
def dataReceived(self, data):
chunks.append(data)
def connectionLost(self, reason):
finished.callback(''.join(chunks))
finished = Deferred()
chunks = []
response.deliverBody(BodyReceiver())
return finished
def waitFor(t):
"""Asynchronous sleep
"""
d = Deferred()
def resolve():
d.callback(None)
reactor.callLater(t, resolve)
return d
| mit |
gocms-io/gocms | domain/plugin/plugin_services/installed_plugins.go | 1593 | package plugin_services
import (
"fmt"
"github.com/gocms-io/gocms/domain/plugin/plugin_model"
"github.com/gocms-io/gocms/utility/log"
"os"
"path/filepath"
"runtime"
)
func (ps *PluginsService) RefreshInstalledPlugins() error {
// find all plugins
err := filepath.Walk("./content/plugins", ps.visitPlugin)
if err != nil {
log.Errorf("Error finding plugins while traversing plugin directory: %s\n", err.Error())
return err
}
return err
}
func (ps *PluginsService) visitPlugin(path string, f os.FileInfo, err error) error {
if err != nil {
log.Errorf("Error traversing %s, %s\n", path, err.Error())
}
// parse manifests as they are found
if f.Mode().IsRegular() && f.Name() == "manifest.json" {
manifest, err := ps.parseManifest(path)
if err != nil {
return err
}
// verify that there is a main.go file
pluginRoot, _ := filepath.Split(path)
// if windows add .exe to the bin
// if windows add exe
if runtime.GOOS == "windows" {
manifest.Services.Bin = fmt.Sprintf("%s.exe", manifest.Services.Bin)
}
binaryStat, err := os.Stat(filepath.Join(pluginRoot, manifest.Services.Bin))
if err != nil {
log.Errorf("No binary for plugin %s: %s\n", manifest.Name, err.Error())
return err
}
if !binaryStat.Mode().IsRegular() {
log.Errorf("binary for plugin %s, apprears to be corrupted: %s\n", manifest.Id, err.Error())
return err
}
plugin := plugin_model.Plugin{
PluginRoot: pluginRoot,
BinaryFile: manifest.Services.Bin,
Manifest: manifest,
}
ps.installedPlugins[plugin.Manifest.Id] = &plugin
}
return nil
}
| mit |
Sowapps/orpheus-website | src/Demo/DemoTest_MSSQL.php | 231 | <?php
namespace Demo;
/** A sample demo test class using MS SQL
*
* Example of how to use the permanent object.
*/
class DemoTest_MSSQL extends DemoTest {
//Attributes
protected static ?string $instanceName = 'mssql';
}
| mit |
Moussi/FullMEANAppSnapShot | client/js/app.js | 4507 | 'use strict';
angular.module('angular-client-side-auth', ['ngCookies', 'ui.router'])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
var access = routingConfig.accessLevels;
// Public routes
$stateProvider
.state('public', {
abstract: true,
template: "<ui-view/>",
data: {
access: access.public
}
})
.state('public.404', {
url: '/404/',
templateUrl: '404'
});
// Anonymous routes
$stateProvider
.state('anon', {
abstract: true,
template: "<ui-view/>",
data: {
access: access.anon
}
})
.state('anon.login', {
url: '/login/',
templateUrl: 'login',
controller: 'LoginCtrl'
})
.state('anon.register', {
url: '/register/',
templateUrl: 'register',
controller: 'RegisterCtrl'
});
// Regular user routes
$stateProvider
.state('user', {
abstract: true,
template: "<ui-view/>",
data: {
access: access.user
}
})
.state('user.home', {
url: '/',
templateUrl: 'home'
})
.state('user.private', {
abstract: true,
url: '/private/',
templateUrl: 'private/layout'
})
.state('user.private.home', {
url: '',
templateUrl: 'private/home'
})
.state('user.private.nested', {
url: 'nested/',
templateUrl: 'private/nested'
})
.state('user.private.admin', {
url: 'admin/',
templateUrl: 'private/nestedAdmin',
data: {
access: access.admin
}
});
// Admin routes
$stateProvider
.state('admin', {
abstract: true,
template: "<ui-view/>",
data: {
access: access.admin
}
})
.state('admin.admin', {
url: '/admin/',
templateUrl: 'admin',
controller: 'AdminCtrl'
});
$urlRouterProvider.otherwise('/404');
// FIX for trailing slashes. Gracefully "borrowed" from https://github.com/angular-ui/ui-router/issues/50
$urlRouterProvider.rule(function($injector, $location) {
if($location.protocol() === 'file')
return;
var path = $location.path()
// Note: misnomer. This returns a query object, not a search string
, search = $location.search()
, params
;
// check to see if the path already ends in '/'
if (path[path.length - 1] === '/') {
return;
}
// If there was no search string / query params, return with a `/`
if (Object.keys(search).length === 0) {
return path + '/';
}
// Otherwise build the search string and return a `/?` prefix
params = [];
angular.forEach(search, function(v, k){
params.push(k + '=' + v);
});
return path + '/?' + params.join('&');
});
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push(function($q, $location) {
return {
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/login');
}
return $q.reject(response);
}
};
});
}])
.run(['$rootScope', '$state', 'Auth', function ($rootScope, $state, Auth) {
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
console.log('toState'+ JSON.stringify(toState.data));
if (!Auth.authorize(toState.data.access)) {
$rootScope.error = "Seems like you tried accessing a route you don't have access to...";
event.preventDefault();
if(fromState.url === '^') {
if(Auth.isLoggedIn()) {
$state.go('user.home');
} else {
$rootScope.error = null;
$state.go('anon.login');
}
}
}
});
}]);
| mit |
adam-boduch/coyote | app/Http/Resources/Elasticsearch/StreamResource.php | 462 | <?php
namespace Coyote\Http\Resources\Elasticsearch;
use Illuminate\Http\Resources\Json\JsonResource;
class StreamResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return array_merge($this->resource->toArray(), ['created_at' => $this->resource->created_at->toIso8601String()]);
}
}
| mit |
BlueDress/School | C# OOP Advanced/Generics Exercises/Custom List Sorter/Sorter.cs | 139 | namespace Custom_List_Sorter
{
public class Sorter
{
public static void Sort()
{
}
}
}
| mit |
baSSiLL/LpmsB.Connect | LpmsB.Connect/LpmsBluetoothDevice.cs | 17516 | using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Sockets;
using LpmsB.Bluetooth;
using LpmsB.Protocol;
namespace LpmsB
{
public class LpmsBluetoothDevice
{
/// <summary>
/// Finds all LPMS-B sensors visible to Bluetooth adapters of this computer.
/// </summary>
/// <param name="deviceSearchTimeout">
/// Timeout for searching available devices for a single Bluetooth adapter.
/// Recommended values aree 5 to 10 seconds.
/// </param>
/// <remarks>
/// Method execution may take a significant time due to Bluetooth discovery operations.
/// </remarks>
/// <returns>Addresses of the sensors.</returns>
public static BluetoothAddress[] Enumerate(TimeSpan deviceSearchTimeout)
{
var radios = BluetoothRadio.FindAll();
var result = radios.SelectMany(radio => radio.FindDevices(deviceSearchTimeout)).
Where(device => device.Name.StartsWith("LPMS")).
Select(device => device.Address).
ToArray();
foreach (var radio in radios)
{
radio.Dispose();
}
return result;
}
private Socket socket;
private volatile SocketException socketConnectException;
private Transmitter transmitter;
private DeviceMode mode = DeviceMode.Unknown;
public LpmsBluetoothDevice(BluetoothAddress address)
{
this.address = address;
NeedUpdateConfiguration = true;
}
public BluetoothAddress Address
{
get { return address; }
}
private readonly BluetoothAddress address;
#region Connection, mode and status
public bool IsConnected
{
get { return socket != null; }
}
public DeviceMode Mode
{
get { return mode; }
set
{
Contract.Requires(value != DeviceMode.Unknown);
Contract.Requires(IsConnected);
if (value != mode)
{
if (mode == DeviceMode.Stream || mode == DeviceMode.Unknown)
{
// When in stream mode, device can be switched only to command mode
EnterMode(Command.GotoCommandMode);
mode = DeviceMode.Command;
}
if (value != mode)
{
EnterMode((Command)value);
mode = value;
}
}
}
}
public DeviceStatus Status
{
get;
private set;
}
private void EnterMode(Command gotoModeCommand)
{
Contract.Requires(gotoModeCommand == Command.GotoCommandMode ||
gotoModeCommand == Command.GotoStreamMode ||
gotoModeCommand == Command.GotoSleepMode);
SendAcknowledgedCommand(new Packet(1, gotoModeCommand));
}
public void Connect(TimeSpan timeout)
{
Contract.Requires(!IsConnected);
Contract.Ensures(IsConnected);
var endPoint = new BluetoothEndPoint(Address, 1);
socket = new Socket(endPoint.AddressFamily, SocketType.Stream, endPoint.ProtocolType);
socketConnectException = null;
var asyncResult = socket.BeginConnect(endPoint, socket_ConnectCompleted, socket);
if (!asyncResult.AsyncWaitHandle.WaitOne(timeout))
{
socket.Close();
asyncResult.AsyncWaitHandle.WaitOne();
socket = null;
throw new SocketException((int)SocketError.TimedOut);
}
else if (socketConnectException != null)
{
socket = null;
throw socketConnectException;
}
transmitter = new Transmitter(socket);
socket.Blocking = false;
}
private void socket_ConnectCompleted(IAsyncResult asyncResult)
{
var socket = (Socket)asyncResult.AsyncState;
try
{
socket.EndConnect(asyncResult);
}
catch (ObjectDisposedException)
{
// Socket is closed already - nothing to do
}
catch (SocketException ex)
{
socketConnectException = ex;
}
}
public void Disconnect()
{
Contract.Ensures(!IsConnected);
Contract.Ensures(Mode == DeviceMode.Unknown);
transmitter = null;
if (socket != null)
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Send);
}
socket.Close();
socket = null;
}
mode = DeviceMode.Unknown;
NeedUpdateConfiguration = true;
}
public void UpdateStatus()
{
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var request = new Packet(1, Command.GetStatus);
var response = SendGetCommand(request);
Status = (DeviceStatus)response.ReadUInt32();
}
#endregion
#region Configuration
private static int[] streamFrequencyTable = new[] { 5, 10, 30, 50, 100, 200, 300, 500 };
public int StreamFrequency
{
get { return streamFrequency; }
set
{
Contract.Requires(value > 0);
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var minDiff = int.MaxValue;
var closestValue = streamFrequencyTable[0];
for (int i = 0; i < streamFrequencyTable.Length; i++)
{
var diff = Math.Abs(value - streamFrequencyTable[i]);
if (diff < minDiff)
{
minDiff = diff;
closestValue = streamFrequencyTable[i];
}
}
var request = new Packet(1, Command.SetStreamFrequency, 4);
request.WriteUInt32((uint)closestValue);
SendAcknowledgedCommand(request);
streamFrequency = closestValue;
NeedUpdateConfiguration = true;
}
}
private int streamFrequency;
public OutputFields OutputFields
{
get { return outputFields; }
set
{
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var filteredValue = value & OutputFields.All;
var request = new Packet(1, Command.SetTransmitData, 4);
request.WriteUInt32((uint)filteredValue);
SendAcknowledgedCommand(request);
outputFields = filteredValue;
NeedUpdateConfiguration = true;
}
}
private OutputFields outputFields;
public OperationOptions OperationOptions
{
get { return options; }
set
{
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var filteredValue = value & OperationOptions.All;
var request = new Packet(1, Command.EnableGyroscopeAutoCalibration, 4);
request.WriteBool((filteredValue & OperationOptions.GyroscopeAutoCalibration) == OperationOptions.GyroscopeAutoCalibration);
SendAcknowledgedCommand(request);
request = new Packet(1, Command.EnableGyroscopeThreshold, 4);
request.WriteBool((filteredValue & OperationOptions.GyroscopeThreshold) == OperationOptions.GyroscopeThreshold);
SendAcknowledgedCommand(request);
options = filteredValue;
NeedUpdateConfiguration = true;
}
}
private OperationOptions options;
public FilterMode FilterMode
{
get { return filterMode; }
set
{
Contract.Requires(Enum.IsDefined(typeof(FilterMode), value));
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var request = new Packet(1, Command.SetFilterMode, 4);
request.WriteUInt32((uint)value);
SendAcknowledgedCommand(request);
filterMode = value;
NeedUpdateConfiguration = true;
}
}
private FilterMode filterMode;
public MagnetometerCorrection MagnetometerCorrection
{
get { return magnetometerCorrection; }
set
{
Contract.Requires(Enum.IsDefined(typeof(MagnetometerCorrection), value));
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var request = new Packet(1, Command.SetFilterPreset, 4);
request.WriteUInt32((uint)value);
SendAcknowledgedCommand(request);
magnetometerCorrection = value;
NeedUpdateConfiguration = true;
}
}
private MagnetometerCorrection magnetometerCorrection;
/// <summary>
/// Coefficient for the current value in the temporal filter, which prefilters
/// raw values before passing to the main Kalman filter.
/// </summary>
/// <remarks>
/// Value <c>1</c> effectively disables temporal filter - raw values remain unchanged.
/// </remarks>
public float TemporalFilterAlpha
{
get { return temporalFilterAlpha; }
set
{
Contract.Requires(0 <= value && value <= 1);
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var request = new Packet(1, Command.SetLowPassStrength, 4);
request.WriteSingle(value);
SendAcknowledgedCommand(request);
temporalFilterAlpha = value;
NeedUpdateConfiguration = true;
}
}
private float temporalFilterAlpha;
public bool NeedUpdateConfiguration
{
get;
private set;
}
public void UpdateConfiguration()
{
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var response = SendGetCommand(new Packet(1, Command.GetConfiguration));
var config = response.ReadUInt32();
streamFrequency = streamFrequencyTable[config & 0x00000007];
outputFields = (OutputFields)(config & (uint)OutputFields.All);
options = (OperationOptions)(config & (uint)OperationOptions.All);
response = SendGetCommand(new Packet(1, Command.GetFilterMode));
var filterMode = response.ReadUInt32();
this.filterMode = (FilterMode)filterMode;
response = SendGetCommand(new Packet(1, Command.GetFilterPreset));
var magCorrection = response.ReadUInt32();
this.magnetometerCorrection = (MagnetometerCorrection)magCorrection;
response = SendGetCommand(new Packet(1, Command.GetLowPassStrength));
this.temporalFilterAlpha = response.ReadSingle();
NeedUpdateConfiguration = false;
ComputeDataPacketLayout();
}
#endregion
#region Data samples
private int dataPacketSize;
private int rawDataOffset;
private int quaternionOffset;
public int RawDataSize
{
get
{
Contract.Requires(IsConnected);
Contract.Requires(!NeedUpdateConfiguration);
return dataPacketSize - rawDataOffset;
}
}
public void ResetTimeStamp()
{
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Command);
var request = new Packet(1, Command.ResetTimeStamp);
SendAcknowledgedCommand(request);
}
/// <summary>
/// Gets the size of the raw data in each data packet according to
/// current output fields settings.
/// </summary>
/// <returns></returns>
private void ComputeDataPacketLayout()
{
Contract.Requires(!NeedUpdateConfiguration);
var test = new Packet(1, Command.GetSensorData, 1024);
// timestamp
test.WriteSingle(0f);
rawDataOffset = test.DataOffset;
if (OutputFields.HasFlag(OutputFields.Gyroscope))
{
test.WriteVector3d(Vector3d.Zero);
}
if (OutputFields.HasFlag(OutputFields.Accelerometer))
{
test.WriteVector3d(Vector3d.Zero);
}
if (OutputFields.HasFlag(OutputFields.Magnetometer))
{
test.WriteVector3d(Vector3d.Zero);
}
if (OutputFields.HasFlag(OutputFields.AngularVelocity))
{
test.WriteVector3d(Vector3d.Zero);
}
quaternionOffset = -1;
if (OutputFields.HasFlag(OutputFields.Quaternion))
{
quaternionOffset = test.DataOffset;
test.WriteQuaternion(Quaternion.Zero);
}
if (OutputFields.HasFlag(OutputFields.EulerAngles))
{
test.WriteVector3d(Vector3d.Zero);
}
if (OutputFields.HasFlag(OutputFields.LinearAcceleration))
{
test.WriteVector3d(Vector3d.Zero);
}
if (OutputFields.HasFlag(OutputFields.Pressure))
{
test.ReadSingle();
}
if (OutputFields.HasFlag(OutputFields.Altitude))
{
test.ReadSingle();
}
if (OutputFields.HasFlag(OutputFields.Temperature))
{
test.ReadSingle();
}
if (OutputFields.HasFlag(OutputFields.HeaveMotion))
{
test.ReadSingle();
}
dataPacketSize = test.DataSize;
}
public void ReadData(out float timeStamp, out Quaternion orientation, byte[] rawDataBuffer = null)
{
Contract.Requires(IsConnected);
Contract.Requires(Mode == DeviceMode.Stream);
Contract.Requires(!NeedUpdateConfiguration);
Contract.Requires(rawDataBuffer == null || rawDataBuffer.Length >= RawDataSize);
Packet packet;
do
{
packet = transmitter.ReceivePacket(TimeSpan.FromSeconds(0.5));
}
while (packet.Command != Command.GetSensorData);
if (packet.DataSize != dataPacketSize)
throw new FormatException("Data packet size does not correspond to data fields settings.");
timeStamp = packet.ReadSingle();
if (quaternionOffset >= 0)
{
packet.DataOffset = quaternionOffset;
orientation = packet.ReadQuaternion();
}
else
{
orientation = Quaternion.Identity;
}
if (rawDataBuffer != null)
{
Buffer.BlockCopy(packet.Data, rawDataOffset, rawDataBuffer, 0, RawDataSize);
}
}
#endregion
#region Commands
private void SendAcknowledgedCommand(Packet request)
{
if (transmitter == null)
throw new InvalidOperationException();
var answerCommand = Command.ReplyNegativeAcknowledge;
do
{
if (answerCommand == Command.ReplyNegativeAcknowledge)
{
transmitter.DiscardPendingPackets();
transmitter.SendPacket(request);
}
answerCommand = transmitter.ReceivePacket(TimeSpan.FromSeconds(3)).Command;
}
while (answerCommand != Command.ReplyAcknowledge);
}
private Packet SendGetCommand(Packet request)
{
if (transmitter == null)
throw new InvalidOperationException();
var answerCommand = Command.ReplyNegativeAcknowledge;
Packet answer;
do
{
if (answerCommand == Command.ReplyNegativeAcknowledge)
{
transmitter.DiscardPendingPackets();
transmitter.SendPacket(request);
}
answer = transmitter.ReceivePacket(TimeSpan.FromSeconds(3));
answerCommand = answer.Command;
}
while (answerCommand != request.Command);
return answer;
}
#endregion
}
}
| mit |
stefanw/froide | froide/foirequest/urls/__init__.py | 2032 | from django.conf.urls import url, include
from django.conf import settings
from django.utils.translation import pgettext_lazy
from ..views import (
search, auth, shortlink, AttachmentFileDetailView,
project_shortlink
)
from . import (
make_request_urls,
list_requests_urls,
request_urls,
project_urls,
account_urls
)
urlpatterns = [
# Translators: request URL
url(pgettext_lazy('url part', r'^make-request/'), include(make_request_urls)),
# Translators: URL part
url(pgettext_lazy('url part', r'^requests/'), include(list_requests_urls)),
# Translators: request URL
url(pgettext_lazy('url part', r'^request/'), include(request_urls)),
# Translators: project URL
url(pgettext_lazy('url part', r'^project/'), include(project_urls)),
# Translators: project URL
url(pgettext_lazy('url part', r'^account/'), include(account_urls)),
# Translators: request URL
url(pgettext_lazy('url part', r'^search/'), search, name="foirequest-search"),
# Translators: Short request URL
# Translators: Short project URL
url(pgettext_lazy('url part', r"^p/(?P<obj_id>\d+)/?$"),
project_shortlink, name="foirequest-project_shortlink"),
# Translators: Short-request auth URL
url(pgettext_lazy('url part', r"^r/(?P<obj_id>\d+)/auth/(?P<code>[0-9a-f]+)/$"),
auth, name="foirequest-auth"),
url(pgettext_lazy('url part', r"^r/(?P<obj_id>\d+)/?$"), shortlink,
name="foirequest-shortlink"),
url(pgettext_lazy('url part', r"^r/(?P<obj_id>\d+)/(?P<url_part>[\w/\-]*)$"), shortlink,
name="foirequest-shortlink_url"),
]
MEDIA_PATH = settings.MEDIA_URL
# Split off domain and leading slash
if MEDIA_PATH.startswith('http'):
MEDIA_PATH = MEDIA_PATH.split('/', 3)[-1]
else:
MEDIA_PATH = MEDIA_PATH[1:]
urlpatterns += [
url(r'^%s%s/(?P<message_id>\d+)/(?P<attachment_name>.+)' % (
MEDIA_PATH, settings.FOI_MEDIA_PATH
), AttachmentFileDetailView.as_view(), name='foirequest-auth_message_attachment')
]
| mit |
bjdixon/js-unit-test-template | js/tests.js | 169 | module("Unit tests");
test( "smoke test", function() {
ok( 1 == "1", "Passed!" );
});
module("Lint tests");
jsHintTest("Test file against linter", "../js/app.js"); | mit |
darklilium/Factigis_2 | arcgis_js_api/library/3.17/3.17/esri/dijit/editing/nls/Editor_pt-pt.js | 7909 | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.17/esri/copyright.txt for details.
//>>built
define("esri/dijit/editing/nls/Editor_pt-pt",{"dijit/_editor/nls/commands":{bold:"Negrito",copy:"Copiar",cut:"Cortar","delete":"Eliminar",indent:"Indentar",insertHorizontalRule:"R\u00e9gua horizontal",insertOrderedList:"Lista numerada",insertUnorderedList:"Lista marcada",italic:"It\u00e1lico",justifyCenter:"Alinhar ao centro",justifyFull:"Justificar",justifyLeft:"Alinhar \u00e0 esquerda",justifyRight:"Alinhar \u00e0 direita",outdent:"Recuar",paste:"Colar",redo:"Repetir",removeFormat:"Remover formato",
selectAll:"Seleccionar tudo",strikethrough:"Rasurado",subscript:"Inferior \u00e0 linha",superscript:"Superior \u00e0 linha",underline:"Sublinhado",undo:"Anular",unlink:"Remover liga\u00e7\u00e3o",createLink:"Criar liga\u00e7\u00e3o",toggleDir:"Alternar direc\u00e7\u00e3o",insertImage:"Inserir imagem",insertTable:"Inserir/Editar tabela",toggleTableBorder:"Alternar contorno da tabela",deleteTable:"Eliminar tabela",tableProp:"Propriedades da tabela",htmlToggle:"Origem HTML",foreColor:"Cor de primeiro plano",
hiliteColor:"Cor de segundo plano",plainFormatBlock:"Estilo de par\u00e1grafo",formatBlock:"Estilo de par\u00e1grafo",fontSize:"Tamanho do tipo de letra",fontName:"Nome do tipo de letra",tabIndent:"Indentar com a tecla Tab",fullScreen:"Alternar ecr\u00e3 completo",viewSource:"Ver origem HTML",print:"Imprimir",newPage:"Nova p\u00e1gina",systemShortcut:'A ac\u00e7\u00e3o "${0}" apenas est\u00e1 dispon\u00edvel no navegador utilizando um atalho de teclado. Utilize ${1}.',ctrlKey:"ctrl+${0}",appleKey:"\u2318${0}",
_localized:{}},"dijit/form/nls/ComboBox":{previousMessage:"Op\u00e7\u00f5es anteriores",nextMessage:"Mais op\u00e7\u00f5es",_localized:{}},"dojo/cldr/nls/islamic":{"dateFormatItem-Ehm":"E h:mm a","days-standAlone-short":"do sg te qu qi sx sb".split(" "),"months-format-narrow":"1 2 3 4 5 6 7 8 9 10 11 12".split(" "),"field-second-relative+0":"agora","quarters-standAlone-narrow":["1","2","3","4"],"field-weekday":"Dia da semana","field-wed-relative+0":"esta quarta-feira","field-wed-relative+1":"pr\u00f3xima quarta-feira",
"dateFormatItem-GyMMMEd":"E, d 'de' MMM 'de' y G","dateFormatItem-MMMEd":"E, d 'de' MMM",eraNarrow:["AH"],"field-tue-relative+-1":"ter\u00e7a-feira passada","days-format-short":"do sg te qu qi sx sb".split(" "),"dateTimeFormats-appendItem-Day-Of-Week":"{0} {1}","dateFormat-long":"d 'de' MMMM 'de' y G","field-fri-relative+-1":"sexta-feira passada","field-wed-relative+-1":"quarta-feira passada","months-format-wide":"Muharram;Safar;Rabi\u02bb I;Rabi\u02bb II;Jumada I;Jumada II;Rajab;Sha\u02bbban;Ramadan;Shawwal;Dhu\u02bbl-Qi\u02bbdah;Dhu\u02bbl-Hijjah".split(";"),
"dateFormatItem-yyyyQQQ":"QQQQ 'de' y G","dateTimeFormat-medium":"{1}, {0}","dayPeriods-format-wide-pm":"da tarde","dateFormat-full":"EEEE, d 'de' MMMM 'de' y G","dateFormatItem-yyyyMEd":"E, dd/MM/y GGGGG","field-thu-relative+-1":"quinta-feira passada","dateFormatItem-Md":"d/M","dayPeriods-format-abbr-am":"a.m.","dateTimeFormats-appendItem-Second":"{0} ({2}: {1})","dayPeriods-format-wide-noon":"meio-dia","field-era":"Era","months-standAlone-wide":"Muharram;Safar;Rabi\u02bb I;Rabi\u02bb II;Jumada I;Jumada II;Rajab;Sha\u02bbban;Ramadan;Shawwal;Dhu\u02bbl-Qi\u02bbdah;Dhu\u02bbl-Hijjah".split(";"),
"timeFormat-short":"HH:mm","quarters-format-wide":["1.\u00ba trimestre","2.\u00ba trimestre","3.\u00ba trimestre","4.\u00ba trimestre"],"timeFormat-long":"HH:mm:ss z","field-year":"Ano","dateTimeFormats-appendItem-Era":"{1} {0}","field-hour":"Hora","months-format-abbr":"Muh.;Saf.;Rab. I;Rab. II;Jum. I;Jum. II;Raj.;Sha.;Ram.;Shaw.;Dhu\u02bbl-Q.;Dhu\u02bbl-H.".split(";"),"field-sat-relative+0":"este s\u00e1bado","field-sat-relative+1":"pr\u00f3ximo s\u00e1bado","timeFormat-full":"HH:mm:ss zzzz","dateTimeFormats-appendItem-Week":"{0} ({2}: {1})",
"field-day-relative+0":"hoje","field-thu-relative+0":"esta quinta-feira","field-day-relative+1":"amanh\u00e3","field-thu-relative+1":"pr\u00f3xima quinta-feira","dateFormatItem-GyMMMd":"d 'de' MMM 'de' y G","dateFormatItem-H":"HH","months-standAlone-abbr":"Muh.;Saf.;Rab. I;Rab. II;Jum. I;Jum. II;Raj.;Sha.;Ram.;Shaw.;Dhu\u02bbl-Q.;Dhu\u02bbl-H.".split(";"),"quarters-format-abbr":["T1","T2","T3","T4"],"quarters-standAlone-wide":["1.\u00ba trimestre","2.\u00ba trimestre","3.\u00ba trimestre","4.\u00ba trimestre"],
"dateFormatItem-Gy":"y G","dateFormatItem-yyyyMMMEd":"E, d/MM/y G","dateFormatItem-M":"L","days-standAlone-wide":"domingo segunda-feira ter\u00e7a-feira quarta-feira quinta-feira sexta-feira s\u00e1bado".split(" "),"dateFormatItem-yyyyMMM":"MM/y G","dateFormatItem-yyyyMMMd":"d/MM/y G","dayPeriods-format-abbr-noon":"noon","timeFormat-medium":"HH:mm:ss","field-sun-relative+0":"este domingo","dateFormatItem-Hm":"HH:mm","field-sun-relative+1":"pr\u00f3ximo domingo","quarters-standAlone-abbr":["T1","T2",
"T3","T4"],eraAbbr:["AH"],"field-minute":"Minuto","field-dayperiod":"Da manh\u00e3/da tarde","days-standAlone-abbr":"dom seg ter qua qui sex s\u00e1b".split(" "),"dateFormatItem-d":"d","dateFormatItem-ms":"mm:ss","quarters-format-narrow":["1","2","3","4"],"field-day-relative+-1":"ontem","dateTimeFormat-long":"{1} '\u00e0s' {0}","dayPeriods-format-narrow-am":"a.m.","dateFormatItem-h":"h a","dateFormatItem-MMMd":"d 'de' MMM","dateFormatItem-MEd":"E, dd/MM","dateTimeFormat-full":"{1} '\u00e0s' {0}",
"field-fri-relative+0":"esta sexta-feira","field-fri-relative+1":"pr\u00f3xima sexta-feira","field-day":"Dia","days-format-wide":"domingo segunda-feira ter\u00e7a-feira quarta-feira quinta-feira sexta-feira s\u00e1bado".split(" "),"field-zone":"Fuso hor\u00e1rio","months-standAlone-narrow":"1 2 3 4 5 6 7 8 9 10 11 12".split(" "),"dateFormatItem-y":"y G","dateTimeFormats-appendItem-Day":"{0} ({2}: {1})","field-year-relative+-1":"ano passado","field-month-relative+-1":"m\u00eas passado","dateTimeFormats-appendItem-Year":"{1} {0}",
"dateFormatItem-hm":"h:mm a","dateTimeFormats-appendItem-Hour":"{0} ({2}: {1})","dayPeriods-format-abbr-pm":"p.m.","days-format-abbr":"dom seg ter qua qui sex s\u00e1b".split(" "),eraNames:["AH"],"days-format-narrow":"DSTQQSS".split(""),"dateFormatItem-yyyyMd":"dd/MM/y GGGGG","field-month":"M\u00eas","days-standAlone-narrow":"DSTQQSS".split(""),"dateFormatItem-MMM":"LLL","field-tue-relative+0":"esta ter\u00e7a-feira","field-tue-relative+1":"pr\u00f3xima ter\u00e7a-feira","dateTimeFormats-appendItem-Quarter":"{0} ({2}: {1})",
"dayPeriods-format-wide-am":"da manh\u00e3","dateTimeFormats-appendItem-Month":"{0} ({2}: {1})","dateTimeFormats-appendItem-Minute":"{0} ({2}: {1})","dateFormatItem-EHm":"E HH:mm","field-mon-relative+0":"esta segunda-feira","field-mon-relative+1":"pr\u00f3xima segunda-feira","dateFormat-short":"d/M/y G","dateFormatItem-EHms":"E HH:mm:ss","dateFormatItem-Ehms":"E h:mm:ss a","dayPeriods-format-narrow-noon":"n","field-second":"Segundo","field-sat-relative+-1":"s\u00e1bado passado","field-sun-relative+-1":"domingo passado",
"field-month-relative+0":"este m\u00eas","field-month-relative+1":"pr\u00f3ximo m\u00eas","dateTimeFormats-appendItem-Timezone":"{0} {1}","dateFormatItem-Ed":"E, d","field-week":"Semana","dateFormat-medium":"d 'de' MMM, y G","field-week-relative+-1":"semana passada","field-year-relative+0":"este ano","dateFormatItem-yyyyM":"MM/y GGGGG","field-year-relative+1":"pr\u00f3ximo ano","dayPeriods-format-narrow-pm":"p.m.","dateFormatItem-yyyyQQQQ":"QQQQ 'de' y G","dateTimeFormat-short":"{1}, {0}","dateFormatItem-Hms":"HH:mm:ss",
"dateFormatItem-hms":"h:mm:ss a","dateFormatItem-GyMMM":"MMM 'de' y G","field-mon-relative+-1":"segunda-feira passada","dateFormatItem-yyyy":"y G","field-week-relative+0":"esta semana","field-week-relative+1":"pr\u00f3xima semana","field-day-relative+2":"depois de amanh\u00e3","field-day-relative+-2":"anteontem",_localized:{}}}); | mit |
MartinRemi/yolo-octo-meme | src/client/display/GraphicCircle.js | 2630 | /**
* @author Rémi MARTIN <[email protected]>
* @copyright 2014 Rémi MARTIN
*/
/**
* Creates a new GraphicCircle object.
* The GraphicCircle is defined with a circle and some colors.
* @class GraphicCircle
* @classdesc yom - GraphicCircle
* @constructor
* @param {yom.Circle} [circle] - The circle to copy
* @param {Object} [style] - The style (attributes : borderWidth, borderColor, fillColor, z, image)
* @return {yom.GraphicCircle} The GraphicCicle object
*
* TODO : Add color
*/
yom.GraphicCircle = function (circle, style) {
/**
* @property {yom.Circle} circle - The circle we want to display
*/
this.circle = circle || {};
/**
* @property {Object} style - The style of the shape
*/
this.style = style || {borderWidth: 1, borderColor: '#000000'};
this.centroid = circle.centroid;
};
// ----- Method(s) ----- \\
/**
* Copies this into a new object of type 'yom.GraphicCircle'
* @method yom.GraphicCircle#copy
* @return {yom.GraphicCircle} The new GraphicCircle object
*/
yom.GraphicCircle.prototype.copy = function () {
return new yom.GraphicCircle(this.circle, this.style);
};
/**
* Moves the graphic circle by x for the x coordinate, and by y for the y coordinate
* @method yom.GraphicCircle#move
* @param {number} [x=0] - The x-coordinate offset
* @param {number} [y=0] - The y-coordinate offset
*/
yom.GraphicCircle.prototype.move = function (x, y) {
this.circle.move(x, y);
};
/**
* Draw the graphic circle.
* @method yom.GraphicCircle#draw
* @param {yom.DrawManager} [drawManager] - The drawManager object
*/
yom.GraphicCircle.prototype.draw = function(drawManager) {
drawManager.drawCircle(this, true);
};
/**
* Fill the graphic circle with color.
* @method yom.GraphicCircle#fillWithColor
* @param {yom.DrawManager} [drawManager] - The drawManager object
*/
yom.GraphicCircle.prototype.fillWithColor = function(drawManager) {
drawManager.fillCircleWithColor(this);
};
/**
* Fill the graphic circle with image.
* @method yom.GraphicCircle#fillWithImage
* @param {yom.DrawManager} [drawManager] - The drawManager object
*/
yom.GraphicCircle.prototype.fillWithImage = function(drawManager) {
drawManager.fillCircleWithImage(this);
};
/**
* Render the circle
* @method yom.GraphicCircle#render
* @param {yom.DrawManager} [drawManager] - The drawManager object
*/
yom.GraphicCircle.prototype.render = function(drawManager) {
if(typeof this.style.image !== 'undefined' && this.style.image != yom.images.DEFAULT_IMAGE) {
this.fillWithImage(drawManager);
} else {
this.draw(drawManager);
}
};
| mit |
ankitagupta12/karafka | spec/lib/karafka/errors_spec.rb | 867 | # frozen_string_literal: true
RSpec.describe Karafka::Errors do
describe 'BaseError' do
subject(:error) { described_class::BaseError }
specify { expect(error).to be < StandardError }
end
describe 'ParserError' do
subject(:error) { described_class::ParserError }
specify { expect(error).to be < described_class::BaseError }
end
describe 'NonMatchingRouteError' do
subject(:error) { described_class::NonMatchingRouteError }
specify { expect(error).to be < described_class::BaseError }
end
describe 'InvalidConfiguration' do
subject(:error) { described_class::InvalidConfiguration }
specify { expect(error).to be < described_class::BaseError }
end
describe 'MissingBootFile' do
subject(:error) { described_class::MissingBootFile }
specify { expect(error).to be < described_class::BaseError }
end
end
| mit |
Artem-Romanenia/machine-learning | LearningVisualizer/Views/TrainingResultsDialog.xaml.cs | 323 | using System.Windows;
namespace LearningVisualizer.Views
{
/// <summary>
/// Interaction logic for ExperimentResultsDialog.xaml
/// </summary>
public partial class TrainingResultsDialog : Window
{
public TrainingResultsDialog()
{
InitializeComponent();
}
}
}
| mit |
huwylphi/nPOauditTrailViewer | reportLastYear.php | 361 | <?php
/*
* version: 1.0
* date: 2015-03-04
* developer: Ph. Huwyler
*/
// get start-date and end-date for last month
$startDate = date('Y-m-d', strtotime(date('Y')."-01-01 -1 year"));
$endDate = date('Y-m-d', strtotime(date('Y')."-01-01 -1 day"));
// export data to csv (out path will be got in exportCsv.php).
require('exportCsv.php');
?> | mit |
kbdancer/myTools | headerScan/updateArea.py | 2202 | #!/usr/bin/env python
# coding=gb2312
# code by 92ez.com
from threading import Thread
import requests
import Queue
import json
import sys
reload(sys)
sys.setdefaultencoding('gb2312')
requests.packages.urllib3.disable_warnings()
def bThread(iplist):
thread_list = []
queue = Queue.Queue()
hosts = iplist
for host in hosts:
queue.put(host)
for x in xrange(0, int(sys.argv[1])):
thread_list.append(tThread(queue))
for t in thread_list:
try:
t.daemon = True
t.start()
except:
pass
for t in thread_list:
t.join()
class tThread(Thread):
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def run(self):
while not self.queue.empty():
host = self.queue.get()
do_main_action(host)
def get_location_by_taobao(host):
try:
ip_url = "http://ip.taobao.com/service/getip_info.php?ip=" + host
header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"}
req = requests.get(url=ip_url, headers=header, verify=False, timeout=10)
json_data = json.loads(req.content.decode('utf8').encode('utf8'))['data']
info = [json_data['country'], json_data['region'], json_data['city'], json_data['isp']]
return info
except Exception, e:
# print e
pass
def get_no_area():
try:
result = json.loads(requests.get('http://www.abc.com/noarea.php').content)
bThread(result['data'])
except Exception, e:
print e
def do_main_action(ip_info):
id = json.loads(ip_info)['id']
ip = json.loads(ip_info)['ip']
location_string = get_location_by_taobao(ip)
try:
url = 'http://www.abc.com/setarea.php?id=' + str(id) + '&country=' + location_string[0] + '&province=' + location_string[1] + '&city=' + location_string[2]
set_result = json.loads(requests.get(url).content)
if set_result['code'] == 0:
print url + ' -> OK'
else:
print url + ' -> error'
except Exception, e:
# print e
pass
if __name__ == '__main__':
get_no_area() | mit |
ActiveState/code | recipes/Python/111971_Format_version_numbers/recipe-111971.py | 148 | def StringVersion( seq ):
return '.'.join( ['%s'] * len( seq )) % tuple( seq )
def TupleVersion( str ):
return map( int, str.split( '.' ))
| mit |
bitmazk/django-libs | django_libs/static/django_libs/js/libs_image_widget.js | 1289 | $(document).ready(function() {
// showing the correct elements
$('.libsImageWidgetHidden').hide();
$('.libsImageWidget').show();
// TODO styling to be moved into css file
$('.libsImageWidgetControls').css({
'display': 'inline-block'
});
$('.libsImageWidgetLabel').css('display', 'inline-block');
$('.libsImageWidgetLabel input').css('margin', '0');
$('.libsImageWidget a img').css({
'vertical-align': 'top'
,'display': 'inline-block'
});
// pass click event to actual hidden file input
$('.libsImageWidgetButton').on('click', function() {
var input_id = $(this).attr('data-id');
$(input_id).click();
return false;
})
// display correct values
$('.libsImageWidgetHidden input:file').each( function() {
var fileInput = $(this);
var input_id = '#' + fileInput.attr('id');
if ($('[data-label-for-id=' + input_id + ']').length | fileInput.val()) {
$('[data-id=' + input_id + ']').text('Change file');
}
fileInput.change(function(){
var value = fileInput.val();
var filename = '...\\' + value.split('\\').slice(-1)
$('[data-label-for-id=' + input_id + ']').text(filename);
})
});
})
| mit |
Nabid/BluetoothRobotController | app/src/main/java/com/prome/bluetoothdevicecontroller/fragments/AboutFragment.java | 734 | package com.prome.bluetoothdevicecontroller.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.prome.bluetoothdevicecontroller.R;
/**
* Created by root on 3/6/15.
*/
public class AboutFragment extends Fragment {
// set tag
public static final String TAG = "AboutFragment";
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_about, container, false);
}
}
| mit |
LiuXiaotian/ProtocolTestFramework | src/reportingtool/DerivedRequirement.cs | 5806 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Protocols.ReportingTool
{
internal enum DerivedType
{
Unknown = 0,
Inferred,
Partial,
Cases
}
internal enum CoveredStatus
{
Unverified = 0,
Partial,
Verified
}
/// <summary>
/// A structure represent the current derived requirement.
/// use this structure to build a graph of derived requirements.
/// </summary>
internal struct DerivedRequirement
{
private string id;
private List<string> originalReqs;
private Dictionary<string, DerivedType> derivedReqs;
private CoveredStatus status;
private string timeStamp;
/// <summary>
/// The constructor.
/// </summary>
/// <param name="id">The requirement ID.</param>
/// <param name="status">The requirement covered status.</param>
public DerivedRequirement(string id, CoveredStatus status)
{
this.id = id;
this.status = status;
this.timeStamp = string.Empty;
originalReqs = new List<string>();
derivedReqs = new Dictionary<string, DerivedType>();
}
/// <summary>
/// Add parent requirement.
/// </summary>
/// <param name="reqID">The requirement ID.</param>
public void AddOriginalRequirement(string reqID)
{
if (!originalReqs.Contains(reqID))
{
originalReqs.Add(reqID);
}
else
{
if (ReportingLog.Log != null)
{
ReportingLog.Log.TraceWarning(
string.Format("Found duplicate original requirement {0} in requirement {1}.", reqID, id));
}
}
}
/// <summary>
/// Remove the relationship of the requirements
/// </summary>
/// <param name="reqId">The target requirment ID</param>
public void RemoveOriginalRequirement(string reqId)
{
if (originalReqs.Contains(reqId))
{
originalReqs.Remove(reqId);
}
}
/// <summary>
/// Add child requirement.
/// </summary>
/// <param name="reqID">The requirement ID.</param>
/// <param name="type">The derived requirement type.</param>
public void AddDerivedRequirement(string reqID, DerivedType type)
{
//self loop
if (reqID == this.id)
{
throw new InvalidOperationException("Found loop in the derived requirements: " + reqID + " is derived from itself.");
}
if (!derivedReqs.ContainsKey(reqID))
{
derivedReqs.Add(reqID, type);
}
else
{
if (ReportingLog.Log != null)
{
ReportingLog.Log.TraceWarning(
string.Format("Found duplicate derived requirement {0} in requirement {1}.", reqID, id));
}
derivedReqs[reqID] = type;
}
}
/// <summary>
/// remove relationship of the requirements
/// </summary>
/// <param name="reqID">The target requirement ID</param>
public void RemoveDerivedRequirement(string reqID)
{
if (derivedReqs.ContainsKey(reqID))
{
derivedReqs.Remove(reqID);
}
}
/// <summary>
/// Gets the ID of current derived requirement.
/// </summary>
public string ReqID
{
get
{
return id;
}
}
/// <summary>
/// Gets or Sets the covered status of current derived requirement.
/// </summary>
public CoveredStatus CoveredStatus
{
get
{
return status;
}
set
{
status = value;
}
}
/// <summary>
/// Gets the parent requirements.
/// </summary>
public List<string> OriginalReqs
{
get
{
return originalReqs;
}
}
/// <summary>
/// Gets all the direct or undirect derived requirements.
/// </summary>
public Dictionary<string, DerivedType> DerivedReqs
{
get
{
return derivedReqs;
}
}
/// <summary>
/// Gets the count of case type requirements derived from the current requirement.
/// </summary>
public uint CaseCount
{
get
{
uint count = 0;
foreach (KeyValuePair<string, DerivedType> kvp in derivedReqs)
{
if (kvp.Value == DerivedType.Cases)
{
count++;
}
}
return count;
}
}
/// <summary>
/// Gets or sets the time stamp string for the current requirement.
/// </summary>
public string TimeStamp
{
get
{
if (string.IsNullOrEmpty(timeStamp))
{
return null;
}
return timeStamp;
}
set
{
timeStamp = value;
}
}
}
}
| mit |
telemed-duth/carre-edu | client/app/translations/translation.service.js | 2629 | 'use strict';
angular.module('edumaterialApp')
.service('Translate', function (Auth) {
var TranslationObj = {
'en':{
'depth_of_coverage':'Depth of Coverage',
'comprehensiveness':'Comprehensiveness',
'relevancy':'Relevancy',
'accuracy':'Accuracy',
'educational_level':'Educational level',
'validity':'Validity',
'total_results':'results',
'no_results':'No results...',
'back_button':'Back',
'rating_button':'Rating',
'rating_title':'Article Rating',
'home_page':'Home',
'login':'Log in',
'logout':'Log out',
"pagination_next":"Next",
"pagination_prev":"Previous"
},
'el':{
'depth_of_coverage':'Βάθος ανάλυσης περιεχομένου',
'comprehensiveness':'Κατανόηση',
'relevancy':'Σχετικότητα',
'accuracy':'Ακρίβεια',
'educational_level':'Απαιτούμενο επίπεδο εκπαίδευσης',
'validity':'Εγκυρότητα',
'total_results':'αποτελέσματα',
'no_results':'Κανένα αποτέλεσμα...',
'back_button':'Πίσω',
'rating_button':'Αξιολόγηση',
'rating_title':'Αξιολόγηση περιεχομένου',
'home_page':'Αρχική',
'login':'Σύνδεση',
'logout':'Αποσύνδεση',
"pagination_next":"Επόμενα",
"pagination_prev":"Προηγούμενα"
},
'lt':{
'depth_of_coverage':'Gylis dangos',
'comprehensiveness':'Išsamumas',
'relevancy':'Tinkamumas',
'accuracy':'Tikslumas',
'educational_level':'Išsilavinimo lygis reikalavimai',
'validity':'Galiojimas',
'total_results':'rezultatai',
'no_results':'Jokių rezultatų...',
'back_button':'Atgal',
'rating_button':'Reitingas',
'rating_title':'Vertinimas straipsnis',
'home_page':'Titulinis puslapis',
'login':'Prisijungti',
'logout':'Atsijungti',
"pagination_next":"Kitas",
"pagination_prev":"Ankstesnis"
},
}
return function(str){
if(!Auth.language) return str;
return TranslationObj[Auth.language].hasOwnProperty(str)?TranslationObj[Auth.language][str]:str;
}
})
.filter('translate',function(Translate){
return function(input){
return Translate(input);
}
});
| mit |
jazdev/interactivepy | Mini-project-3.py | 1660 | # template for "Stopwatch: The Game"
import simplegui
# define global variables
t=0 # stores time
time='' # stores time in string
suc = 0 # number of successes
alle = 0 # total number of presses
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
A = t // 600
B = t % 600 // 100
C = t % 100 // 10
D = t % 10
tmp = str(A) + ":" + str(B) + str(C) + "." + str(D)
return tmp
# define event handlers for buttons; "Start", "Stop", "Reset"
def start_handler():
timer.start()
def stop_handler():
global alle, suc
if not timer.is_running():
return
timer.stop()
alle += 1
# increment only if stopped in +/- 0.1 of time
if str(t)[-1] in ['9','0','1'] and str(t)[-2] in ['4','0','5']:
suc += 1
def reset_handler():
global t, suc, alle
t=0
suc=0
alle=0
# define event handler for timer with 0.1 sec interval
def tick():
global t
t+=1
# define draw handler
def draw(c):
time = format(t)
c.draw_text(time, (120, 180), 96, "White")
c.draw_text(str(suc)+' / '+str(alle), (400, 50), 36, "Aqua")
c.draw_text("+/- 0.1 Stopping error is acceptable", (115, 270), 18, "Aqua")
# create frame
frame = simplegui.create_frame("Stopwatch: The Game", 500, 300,100)
# register event handlers
frame.set_draw_handler(draw)
timer = simplegui.create_timer(100, tick)
frame.add_button('Start', start_handler, 100)
frame.add_button('Stop', stop_handler, 100)
frame.add_button('Reset', reset_handler, 100)
# start frame
frame.start()
# Please remember to review the grading rubric
| mit |
fadre/sandhills | src/main/java/ch/fadre/sandhills/Main.java | 2021 | package ch.fadre.sandhills;
import ch.fadre.sandhills.output.CSVWriter;
import ch.fadre.sandhills.output.ImageWriter;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Main {
private static int width = 250;
private static int height = 250;
private static long iterationCount = 100_000;
public static void main(String[] args) throws IOException, InterruptedException {
parseArguments(args);
String simulationName = createSimulationName();
SandSimulation sandSimulation = new SandSimulation(width, height, iterationCount, true, simulationName);
int[][] result = sandSimulation.performSimulation();
CSVWriter csvWriter = new CSVWriter();
csvWriter.writeToFile(result,simulationName);
ImageWriter imageWriter = new ImageWriter();
BufferedImage bufferedImage = imageWriter.generateImage(result, width, height);
imageWriter.writeToFile(bufferedImage, simulationName+"-final");
imageWriter.displayInFrame(bufferedImage);
}
private static void parseArguments(String[] args) {
if(args == null || args.length == 0) {
System.out.println("Warning: No parameters set, using defaults");
showUsage();
} else if (args.length == 3){
width = Integer.parseInt(args[0]);
height = Integer.parseInt(args[1]);
iterationCount = Long.parseLong(args[2]);
System.out.println("Starting simulation with grid (" + width+"w/" + height +"h) and " + iterationCount + " iterations...");
} else {
System.out.println("Too many parameters given! Using defaults");
showUsage();
}
}
private static String createSimulationName() {
return "Simulation-" + width + "x" + height + "-It" + iterationCount+"-At"+System.currentTimeMillis()/1000;
}
private static void showUsage() {
System.out.println("Usage: gradle run -Dexec.args=\"500 500 10000\"");
}
}
| mit |
openstax/action_interceptor | lib/action_interceptor/action_controller/base.rb | 2725 | require 'addressable/uri'
module ActionInterceptor
module ActionController
module Base
def self.included(base)
base.helper_method :current_page?, :current_url, :stored_url
end
protected
def current_page?(url)
# Return true for blank (blank links redirect to the same page)
return true if url.blank?
uri = Addressable::URI.parse(url)
uri.path == request.path && (
uri.relative? || uri.host == request.host_with_port || (
uri.host == request.host && uri.port == request.port
)
)
end
def current_url
"#{request.protocol}#{request.host_with_port}#{request.fullpath}"
end
# Stores the given url or the current url
# If the current request is not a GET request, stores the referer instead
def store_url(options = {})
strats = ActionInterceptor::Strategies.find_all(self, options[:strategies])
key = options[:key] || ActionInterceptor.config.default_key
url = options.has_key?(:url) ?
options[:url] : (request.get? ? current_url : request.referer)
strats.each{ |strat| strat.set(key, url) }
url
end
# Retrieves the stored url
def stored_url(options = {})
strats = ActionInterceptor::Strategies.find_all(self, options[:strategies])
key = options[:key] || ActionInterceptor.config.default_key
strats.each do |strat|
url = strat.get(key)
return url unless url.blank?
end
nil
end
# Stores the given url or the referer if no stored url is present
def store_fallback(options = {})
store_url({url: request.referer}.merge(options)) \
if stored_url(options).blank?
end
# Deletes to the stored url
def delete_stored_url(options = {})
strats = ActionInterceptor::Strategies.find_all(self, options[:strategies])
key = options[:key] || ActionInterceptor.config.default_key
strats.each do |strat|
strat.unset(key)
end
nil
end
# Redirects to the stored url and deletes it from storage
def redirect_back(options = {})
interceptor_options = options.slice(:key, :strategies)
redirect_options = options.except(:key, :strategies)
url = stored_url(interceptor_options)
delete_stored_url(interceptor_options)
# Prevent self redirects
url = (ActionInterceptor.config.default_url || main_app.root_url) if current_page?(url)
redirect_to url, redirect_options
end
end
end
end
ActionController::Base.send :include, ActionInterceptor::ActionController::Base
| mit |
rkeplin/sf2-blog | src/Keplin/BlogBundle/Service/CategoryService.php | 2521 | <?php
/**
* Rob's Blog (http://www.robkeplin.com)
*
* @link http://www.robkeplin.com
* @copyright Copyright (c) 2012 Rob Keplin
* @license TBD
*/
namespace Keplin\BlogBundle\Service;
/**
* Category Service
*
* @package Blog\Service
*/
class CategoryService
extends AbstractService
{
/**
* @const string
**/
const ENTITY_CATEGORY = 'Keplin\BlogBundle\Entity\Category';
/**
* Saves a category
*
* @param array $data
* @return boolean
* @todo
**/
public function save($data = array())
{
//todo
}
/**
* Gets all categories
*
* @param void
* @return array
**/
public function getAll()
{
$qb = $this->em->createQueryBuilder();
$qb->select('c')
->from(self::ENTITY_CATEGORY, 'c')
->orderBy('c.name', 'ASC');
$query = $qb->getQuery();
$result = $query->getResult();
return $result;
}
/**
* Gets a category from it's name
*
* @param string $name
* @return Category
**/
public function getFromName($name)
{
$qb = $this->em->createQueryBuilder();
$qb->select('c')
->from(self::ENTITY_CATEGORY, 'c')
->where('c.name = :name')
->setParameter('name', $name);
$query = $qb->getQuery();
$result = $query->getSingleResult();
return $result;
}
/**
* Finds a category from it's ID
*
* @param int $id
* @return Category
**/
public function findById($id)
{
$qb = $this->em->createQueryBuilder();
$qb->select('c')
->from(self::ENTITY_CATEGORY, 'c')
->where('c.id = :id')
->setParameter('id', $id);
$query = $qb->getQuery();
$result = $query->getSingleResult();
return $result;
}
/**
* Gets categories with their total number of published posts
*
* @param void
* @return array
**/
public function getPublishedWithCount()
{
$sql = "SELECT COUNT(c.id) AS count, c.id, c.name "
. "FROM categories c "
. "INNER JOIN posts p ON p.category_id = c.id "
. "WHERE is_published = ? "
. "GROUP BY c.id "
. "ORDER BY c.name ASC";
$stmt = $this->em->getConnection()->prepare($sql);
$stmt->bindValue(1, 1);
$stmt->execute();
$data = $stmt->fetchAll();
return $data;
}
} | mit |
RConDev/RaptoRCon | src/RaptoRCon.Server/Startup.cs | 641 | using Owin;
using RaptoRCon.Server.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;
namespace RaptoRCon.Server
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
MefConfig.RegisterMef(config);
app.UseWebApi(config);
app.MapSignalR();
}
}
}
| mit |
nisrinabia/KomplainTelkom | application/views/design/footer.php | 13112 | <footer class="main-footer no-print">
<div class="pull-right hidden-xs">
<b>Version</b> 1.0
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Anggota Kerja Praktik<br/>Teknik Informatika ITS 2015</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-6">
<p style="text-align:center;">
<img src="<?php echo base_url() ?>assets/dist/img/dinar.jpg" alt="User Image" style="border-radius:50%;max-width:100%;height:auto;"/>
<a class="users-list-name" href="#">Dinar Winia Mahandhira</a>
<span class="users-list-date">5112100002</span>
<span class="users-list-date"><a href="mailto:[email protected]" target="_blank">[email protected]</a></span>
</p>
<p style="text-align:center;">
<img src="<?php echo base_url() ?>assets/dist/img/ratih.jpg" alt="User Image" style="border-radius:50%;max-width:100%;height:auto;"/>
<a class="users-list-name" href="#">Ratih Ayu Indraswari</a>
<span class="users-list-date">5112100122</span>
<span class="users-list-date"><a href="mailto:[email protected]" target="_blank">[email protected]</a></span>
</p>
</div>
<div class="col-xs-6">
<p style="text-align:center;">
<img src="<?php echo base_url() ?>assets/dist/img/fariz2.jpg" alt="User Image" style="border-radius:50%;max-width:100%;height:auto;"/>
<a class="users-list-name" href="#">Fariz Aulia Pradipta</a>
<span class="users-list-date">5112100021</span>
<span class="users-list-date"><a href="mailto:[email protected]" target="_blank">[email protected]</a></span>
</p>
<p style="text-align:center;">
<img src="<?php echo base_url() ?>assets/dist/img/azis.jpg" alt="User Image" style="border-radius:50%;max-width:100%;height:auto;"/>
<a class="users-list-name" href="#">Azis Arijaya</a>
<span class="users-list-date">5112100155</span>
<span class="users-list-date"><a href="mailto:[email protected]" target="_blank">[email protected]</a></span>
</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
</div>
</div>
</div>
</div>
</div>
<strong>Copyright © 2015 <a href="#" data-toggle="modal" data-target="#myModal">Kerja Praktik Teknik Informatika ITS</a>.</strong> All rights reserved.
</footer>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class='control-sidebar-bg'></div>
</div><!-- ./wrapper -->
<!-- jQuery 2.1.4 -->
<script src="<?php echo base_url() ?>assets/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.2 JS -->
<script src="<?php echo base_url() ?>assets/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<!-- FastClick -->
<script src='<?php echo base_url() ?>assets/plugins/fastclick/fastclick.min.js'></script>
<!-- AdminLTE App -->
<script src="<?php echo base_url() ?>assets/dist/js/app.min.js" type="text/javascript"></script>
<!-- AdminLTE for demo purposes -->
<!-- <script src="<?php echo base_url() ?>assets/dist/js/demo.js" type="text/javascript"></script> -->
<!-- InputMask -->
<script src="<?php echo base_url() ?>assets/plugins/input-mask/jquery.inputmask.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/plugins/input-mask/jquery.inputmask.date.extensions.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/plugins/input-mask/jquery.inputmask.extensions.js" type="text/javascript"></script>
<!-- date-range-picker -->
<script src="<?php echo base_url() ?>assets/moment.min.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/plugins/daterangepicker/daterangepicker.js" type="text/javascript"></script>
<!-- bootstrap color picker -->
<script src="<?php echo base_url() ?>assets/plugins/colorpicker/bootstrap-colorpicker.min.js" type="text/javascript"></script>
<!-- bootstrap time picker -->
<script src="<?php echo base_url() ?>assets/plugins/timepicker/bootstrap-timepicker.min.js" type="text/javascript"></script>
<!-- SlimScroll 1.3.0 -->
<script src="<?php echo base_url() ?>assets/plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<!-- iCheck 1.0.1 -->
<script src="<?php echo base_url() ?>assets/plugins/iCheck/icheck.min.js" type="text/javascript"></script>
<!-- DATA TABES SCRIPT -->
<script src="<?php echo base_url() ?>assets/plugins/datatables/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/plugins/datatables/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/bootstrap3/base.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/bootstrap3/bootstrap-datetimepicker.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/bootstrap3/moment-with-locales.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/bootstrap3/prettify-1.0.min.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/bootstrap/js/bootstrap-datepicker.js" type="text/javascript"></script>
<script src="<?php echo base_url() ?>assets/docs.js"></script>
<!-- Page script -->
<script>
if (top.location != location) {
top.location.href = document.location.href ;
}
$(function(){
window.prettyPrint && prettyPrint();
$('#dp1').datepicker({
format: 'mm-dd-yyyy'
});
$('#dp2').datepicker();
$('#dp3').datepicker();
$('#dp3').datepicker();
$('#dpYears').datepicker();
$('#dpMonths').datepicker();
var startDate = new Date(2012,1,20);
var endDate = new Date(2012,1,25);
$('#dp4').datepicker()
.on('changeDate', function(ev){
if (ev.date.valueOf() > endDate.valueOf()){
$('#alert').show().find('strong').text('The start date can not be greater then the end date');
} else {
$('#alert').hide();
startDate = new Date(ev.date);
$('#startDate').text($('#dp4').data('date'));
}
$('#dp4').datepicker('hide');
});
$('#dp5').datepicker()
.on('changeDate', function(ev){
if (ev.date.valueOf() < startDate.valueOf()){
$('#alert').show().find('strong').text('The end date can not be less then the start date');
} else {
$('#alert').hide();
endDate = new Date(ev.date);
$('#endDate').text($('#dp5').data('date'));
}
$('#dp5').datepicker('hide');
});
// disabling dates
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#dpd1').datepicker({
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
}
checkin.hide();
$('#dpd2')[0].focus();
}).data('datepicker');
var checkout = $('#dpd2').datepicker({
onRender: function(date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
checkout.hide();
}).data('datepicker');
});
</script>
<script type="text/javascript">
$(function () {
//Datemask dd/mm/yyyy
$("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"});
//Datemask2 mm/dd/yyyy
$("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});
//Money Euro
$("[data-mask]").inputmask();
//Date range picker
$('#reservation').daterangepicker();
//Date range picker with time picker
$('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'});
//Date range as a button
$('#daterange-btn').daterangepicker(
{
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
'Last 7 Days': [moment().subtract('days', 6), moment()],
'Last 30 Days': [moment().subtract('days', 29), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
},
startDate: moment().subtract('days', 29),
endDate: moment()
},
function (start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
);
//iCheck for checkbox and radio inputs
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue'
});
//Red color scheme for iCheck
$('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
checkboxClass: 'icheckbox_minimal-red',
radioClass: 'iradio_minimal-red'
});
//Flat red color scheme for iCheck
$('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass: 'iradio_flat-green'
});
//Colorpicker
$(".my-colorpicker1").colorpicker();
//color picker with addon
$(".my-colorpicker2").colorpicker();
//Timepicker
$(".timepicker").timepicker({
showInputs: false
});
});
</script>
<script type="text/javascript">
$(function () {
$("#example1").dataTable();
$('#example2').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": false,
"bSort": true,
"bInfo": true,
"bAutoWidth": false
});
});
</script>
<script language="javascript">
function batal()
{
document.getElementById('awal').style.display='block';
document.getElementById('editkan').style.display='none';
document.getElementById('status').value="lama";
}
function edit_tanggal()
{
document.getElementById('awal').style.display='none';
document.getElementById('editkan').style.display='block';
document.getElementById('status').value="baru";
}
function showJanji()
{
document.getElementById('janji').style.display='block';
document.getElementById('noJanji').style.display='none';
document.getElementById('status').value="janji";
}
function hideJanji()
{
document.getElementById('janji').style.display='none';
document.getElementById('noJanji').style.display='block';
document.getElementById('status').value="";
}
</script>
<script type="text/javascript">
$(function () {
$('#datetimepicker12').datetimepicker({
inline: true,
sideBySide: true
});
});
</script>
<script type="text/javascript">
$(function () {
$('#yearpicker').datetimepicker({
format: 'YYYY',
sideBySide: true,
inline: true
});
});
</script>
</body>
</html>
| mit |
cfranklin11/budget-pie | public/javascripts/views/budget-view.js | 1343 | 'use strict';
var bbApp = bbApp || {};
(function($) {
bbApp.BudgetView = Backbone.View.extend({
className: 'col-xs-12 col-sm-6 col-md-3 col-lg-3 flip',
events: {
'click .flipControl': 'flip'
},
initialize: function () {
},
flip: function (e) {
var personas, thisCard;
e.preventDefault();
thisCard = $(e.currentTarget).closest('.card');
if (!thisCard.hasClass('flipped')) {
personas = window.localStorage.getItem('personas');
this.model.save({
data: {
personas: personas,
metric: 'clicks'
},
method: 'POST',
success: function(res) {
console.log(res);
},
error: function(res) {
console.log(res);
}
});
}
thisCard.toggleClass('flipped');
},
render: function () {
var attributes, self;
self = this;
attributes = this.model.toJSON();
$.get('templates/card-flip.html', function (data) {
var template = _.template(data);
self.$el.html(template(attributes));
}, 'html')
.complete(function() {
bbApp.D3Helper.createCircleChart(attributes);
bbApp.D3Helper.createBarChart(attributes);
});
return this;
}
});
})(jQuery);
| mit |
boxmein/boxnode | lib/toplog/index.js | 2946 | // Simple logger
var util = require('util');
var DEFAULTS = {
// Logging levels. Case insensitive.
// Smallest index is most verbose, biggest index is most important.
'loglevels': ['VERBOSE', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL'],
// Level at which log entries are allowed in the output.
'loglevel': 'VERBOSE',
// If you need to pass in a concern if you want a logger
'separation_of_concerns': true,
// Default concern
'concern': '(global)',
// If to timestamp the logging
'timestamp': true,
// Format string for everything
'formatstring': '%time | %concern %loglevel1 %message',
// If to color the format string with ANSI escape sequences
'color': true,
// Colors corresponding to the log level
'colors': {
'VERBOSE': '37;0',
'DEBUG': '37;0',
'INFO': '36;1',
'WARNING': '33;1',
'ERROR': '31;1',
'FATAL': '31;1' }
};
function clone(obj) {
var target = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
target[i] = obj[i];
}
}
return target;
}
module.exports = function(props) {
this.currprops = clone(DEFAULTS);
if (typeof props == 'string') {
this.currprops.concern = props;
} else {
for (var k in props) {
if (props.hasOwnProperty(k)) {
this.currprops[k] = props[k];
}
}
}
var that = this;
var prop = that.currprops;
var logIndex = prop.loglevels.indexOf(prop.loglevel);
function log(loglevel, text) {
var endstr = prop.formatstring;
// Coloring
if (prop.color) {
endstr = '\x1b[' + prop.colors[loglevel.toUpperCase()] + 'm' +
endstr + '\x1b[0m';
}
// Date stamps
var d = new Date();
var dstr = '' + ('0'+d.getHours()).slice(-2) + ':' +
('0'+d.getMinutes()).slice(-2) + ':' +
('0'+d.getSeconds()).slice(-2);
endstr = endstr.replace('%time', prop.timestamp ? dstr : '');
// Separation of concerns
endstr = endstr.replace('%concern', prop.separation_of_concerns ? prop.concern : '');
// Output log levels
endstr = endstr.replace('%loglevel1', loglevel[0]);
endstr = endstr.replace('%loglevel', loglevel);
// Concat other arguments
var msg = '';
for (var i = 1; i < arguments.length; i++) {
if (!arguments.hasOwnProperty(i))
break;
var s = arguments[i];
if (typeof s == 'string') {
msg += ' ' + s;
} else {
msg += ' ' + util.inspect(s);
}
}
// And the actual message >_>
endstr = endstr.replace('%message', msg);
if (prop.loglevels.indexOf(loglevel) >= logIndex) {
console.log(endstr);
}
}
var endobj = {};
for (var i = 0; i < prop.loglevels.length; i++) {
endobj[prop.loglevels[i].toLowerCase()] = log.bind(that, prop.loglevels[i]);
}
// usable as a swap for conso
endobj.log = log.bind(that, prop.loglevels[0]);
endobj.properties = prop;
return endobj;
};
| mit |
qx/FullRobolectricTestSample | src/test/java/org/robolectric/shadows/RemoteViewsTest.java | 2817 | package org.robolectric.shadows;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.R;
import org.robolectric.Robolectric;
import org.robolectric.TestRunners;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.Robolectric.shadowOf;
@RunWith(TestRunners.WithDefaults.class)
public class RemoteViewsTest {
private final String packageName = Robolectric.application.getPackageName();
private final Activity activity = buildActivity(Activity.class).create().get();
@Test
public void apply_shouldInflateLayout() {
RemoteViews views = new RemoteViews(packageName, R.layout.remote_views);
assertThat(views.apply(activity, null)).isNotNull();
}
@Test
public void setTextViewText_shouldUpdateView() {
RemoteViews views = new RemoteViews(packageName, R.layout.remote_views);
views.setTextViewText(R.id.remote_view_1, "Foo");
View layout = views.apply(activity, null);
TextView text = (TextView) layout.findViewById(R.id.remote_view_1);
assertThat(text.getText().toString()).isEqualTo("Foo");
}
@Test
public void setImageViewBitmap_shouldUpdateView() {
Bitmap bitmap = Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888);
RemoteViews views = new RemoteViews(packageName, R.layout.remote_views);
views.setImageViewBitmap(R.id.remote_view_2, bitmap);
View layout = views.apply(activity, null);
ImageView image = (ImageView) layout.findViewById(R.id.remote_view_2);
assertThat(shadowOf(image).getImageBitmap()).isEqualTo(bitmap);
}
@Test
public void setViewVisibility_shouldUpdateView() {
RemoteViews views = new RemoteViews(packageName, R.layout.remote_views);
views.setViewVisibility(R.id.remote_view_1, View.INVISIBLE);
View layout = views.apply(activity, null);
assertThat(layout.findViewById(R.id.remote_view_1).getVisibility()).isEqualTo(View.INVISIBLE);
}
@Test
public void setOnClickPendingIntent_shouldFireSuppliedIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW);
PendingIntent pendingIntent = PendingIntent.getActivity(Robolectric.application, 0, intent, 0);
RemoteViews views = new RemoteViews(packageName, R.layout.remote_views);
views.setOnClickPendingIntent(R.id.remote_view_3, pendingIntent);
View layout = views.apply(activity, null);
layout.findViewById(R.id.remote_view_3).performClick();
assertThat(shadowOf(Robolectric.application).getNextStartedActivity()).isEqualTo(intent);
}
}
| mit |
lowang/bluemedia_payments | spec/bluemedia_payments/verification_spec.rb | 4044 | require 'spec_helper'
describe BluemediaPayments::Verification do
let(:itn_xml) {
<<-EOS
<?xml version="1.0" encoding="UTF-8"?>
<transactionList>
<merchantID>1</merchantID>
<transactions>
<transaction>
<orderID>11_4234</orderID>
<transID>9F1LQWXK</transID>
<transDate>20010101</transDate>
<amount>11.11</amount>
<currency>PLN</currency>
<paywayID>1</paywayID>
<statusDate>20010101111111</statusDate>
<status>1</status>
<param>CustomerAddress=SmFuIEtvbHdhc2tp|CustomerNRB=92874710181271009158695384|VerificationStatus=POSITIVE</param>
</transaction>
</transactions>
<docHash>355ec265ee8e3321b7aa32c6e63ad1f4</docHash>
</transactionList>
EOS
}
let(:service_params) do
{ verification_shared_key: 'ver', merchant_id: 1 }
end
let(:service) { BluemediaPayments::Service.new(service_params) }
let(:verification_itn) { BluemediaPayments::Verification.from_itn(itn_xml, service) }
describe 'parse itn' do
subject { verification_itn }
#before { BluemediaPayments::Verification.logger = Logger.new(STDOUT)}
it { is_expected.to be_kind_of(BluemediaPayments::Verification) }
it { expect(subject.order_id).to eq('11_4234') }
it { expect(subject.transaction_id).to eq('9F1LQWXK') }
it { expect(subject.transaction_date).to eq(Date.parse "2001-01-01") }
it { expect(subject.amount).to eq(BigDecimal.new('11.11')) }
it { expect(subject.currency).to eq('PLN') }
it { expect(subject.payway_id).to eq(1) }
it { expect(subject.status_date).to eq(DateTime.parse '2001-01-01 11:11:11') }
it { expect(subject.status).to eq(1) }
it { expect(subject.properties).to be_kind_of(Hash) }
it { expect(subject.properties[:customer_address]).to eq('Jan Kolwaski') }
it { expect(subject.properties[:customer_nrb]).to eq('92874710181271009158695384') }
it { expect(subject.properties[:verification_status]).to eq('POSITIVE') }
it { expect(subject.hash_signature).to eq('355ec265ee8e3321b7aa32c6e63ad1f4') }
it { expect(subject.service_id).to eq('11') }
it { expect(subject.hash_signature_verified?).to be_truthy }
it { expect(subject.valid?).to be_truthy, subject.errors.full_messages.join("\n") }
end
describe 'respond to itn' do
let(:expected_confirmation_status) { 'CONFIRMED'}
let(:expected_hash) { '2e898b19152af74f2b7f52b1f4a3b6ea'}
let(:xml_confirmation) { <<-EOS }
<?xml version="1.0" encoding="UTF-8"?>
<confirmationList>
<merchantID>1</merchantID>
<transactionsConfirmations>
<transactionConfirmed>
<orderID>11_4234</orderID>
<confirmation>#{expected_confirmation_status}</confirmation>
</transactionConfirmed>
</transactionsConfirmations>
<docHash>#{expected_hash}</docHash>
</confirmationList>
EOS
subject { verification_itn.xml_response }
describe 'and confirm' do
before { verification_itn.confirmation_status = true}
it { is_expected.to eq(xml_confirmation) }
end
describe 'without confirmation' do
let(:expected_confirmation_status) { 'NOTCONFIRMED'}
let(:expected_hash) { 'f91e0c0f0ce56271ec4905af6dc968dd'}
describe 'by declining confirmation' do
it { is_expected.to eq(xml_confirmation) }
it { expect(verification_itn.valid?).to be_truthy }
end
describe 'by verification hash mismatch' do
before do
verification_itn.confirmation_status = true
verification_itn.hash_signature = '1'*32
end
it { is_expected.to eq(xml_confirmation) }
it { expect(verification_itn.valid?).to be_falsey }
end
end
end
describe 'validation' do
let(:service) { BluemediaPayments::Service.new }
it "wont be valid with invalid service" do
expect(service.valid?(:verification)).to be_falsey
expect(verification_itn.valid?).to be_falsey
expect(verification_itn.errors.keys).to eq([:hash_signature, :service])
end
end
end
| mit |
rogersd/php-resque | lib/Resque/Log.php | 1698 | <?php
/**
* Resque default logger PSR-3 compliant
*
* @package Resque/Stat
* @author Chris Boulton <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php
*/
class Resque_Log extends Psr\Log\AbstractLogger
{
public $verbose;
public function __construct($verbose = false) {
$this->verbose = $verbose;
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level PSR-3 log level constant, or equivalent string
* @param string $message Message to log, may contain a { placeholder }
* @param array $context Variables to replace { placeholder }
* @return null
*/
public function log($level, $message, array $context = array())
{
if ($this->verbose) {
fwrite(
STDOUT,
'[' . $level . '] [' . strftime('%T %Y-%m-%d') . '] ' . $this->interpolate($message, $context) . PHP_EOL
);
return;
}
if (!($level === Psr\Log\LogLevel::INFO || $level === Psr\Log\LogLevel::DEBUG)) {
fwrite(
STDOUT,
'[' . $level . '] [' . strftime('%T %Y-%m-%d') . '] ' . $this->interpolate($message, $context) . PHP_EOL
);
}
}
/**
* Fill placeholders with the provided context
* @author Jordi Boggiano [email protected]
*
* @param string $message Message to be logged
* @param array $context Array of variables to use in message
* @return string
*/
public function interpolate($message, array $context = array())
{
// build a replacement array with braces around the context keys
$replace = array();
foreach ($context as $key => $val) {
$replace['{' . $key . '}'] = $val;
}
// interpolate replacement values into the message and return
return strtr($message, $replace);
}
}
| mit |
FormsCommunityToolkit/FormsCommunityToolkit | src/CommunityToolkit/Xamarin.CommunityToolkit/ObjectModel/ObservableRangeCollection.shared.cs | 5300 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
#nullable enable
namespace Xamarin.CommunityToolkit.ObjectModel
{
/// <summary>
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObservableRangeCollection<T> : ObservableCollection<T>
{
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class.
/// </summary>
public ObservableRangeCollection()
: base()
{
}
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">collection: The collection from which the elements are copied.</param>
/// <exception cref="System.ArgumentNullException">The collection parameter cannot be null.</exception>
public ObservableRangeCollection(IEnumerable<T> collection)
: base(collection)
{
}
/// <summary>
/// Adds the elements of the specified collection to the end of the ObservableCollection(Of T).
/// </summary>
public void AddRange(IEnumerable<T> collection, NotifyCollectionChangedAction notificationMode = NotifyCollectionChangedAction.Add)
{
if (notificationMode != NotifyCollectionChangedAction.Add && notificationMode != NotifyCollectionChangedAction.Reset)
throw new ArgumentException("Mode must be either Add or Reset for AddRange.", nameof(notificationMode));
if (collection == null)
throw new ArgumentNullException(nameof(collection));
CheckReentrancy();
var startIndex = Count;
var itemsAdded = AddArrangeCore(collection);
if (!itemsAdded)
return;
if (notificationMode == NotifyCollectionChangedAction.Reset)
{
RaiseChangeNotificationEvents(action: NotifyCollectionChangedAction.Reset);
return;
}
var changedItems = collection is List<T>
? (List<T>)collection
: new List<T>(collection);
RaiseChangeNotificationEvents(
action: NotifyCollectionChangedAction.Add,
changedItems: changedItems,
startingIndex: startIndex);
}
/// <summary>
/// Removes the first occurence of each item in the specified collection from ObservableCollection(Of T). NOTE: with notificationMode = Remove, removed items starting index is not set because items are not guaranteed to be consecutive.
/// </summary>
public void RemoveRange(IEnumerable<T> collection, NotifyCollectionChangedAction notificationMode = NotifyCollectionChangedAction.Reset)
{
if (notificationMode != NotifyCollectionChangedAction.Remove && notificationMode != NotifyCollectionChangedAction.Reset)
throw new ArgumentException("Mode must be either Remove or Reset for RemoveRange.", nameof(notificationMode));
if (collection == null)
throw new ArgumentNullException(nameof(collection));
CheckReentrancy();
if (notificationMode == NotifyCollectionChangedAction.Reset)
{
var raiseEvents = false;
foreach (var item in collection)
{
Items.Remove(item);
raiseEvents = true;
}
if (raiseEvents)
RaiseChangeNotificationEvents(action: NotifyCollectionChangedAction.Reset);
return;
}
var changedItems = new List<T>(collection);
for (var i = 0; i < changedItems.Count; i++)
{
if (!Items.Remove(changedItems[i]))
{
changedItems.RemoveAt(i); // Can't use a foreach because changedItems is intended to be (carefully) modified
i--;
}
}
if (changedItems.Count == 0)
return;
RaiseChangeNotificationEvents(
action: NotifyCollectionChangedAction.Remove,
changedItems: changedItems);
}
/// <summary>
/// Clears the current collection and replaces it with the specified item.
/// </summary>
public void Replace(T item) => ReplaceRange(new T[] { item });
/// <summary>
/// Clears the current collection and replaces it with the specified collection.
/// </summary>
public void ReplaceRange(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
CheckReentrancy();
var previouslyEmpty = Items.Count == 0;
Items.Clear();
AddArrangeCore(collection);
var currentlyEmpty = Items.Count == 0;
if (previouslyEmpty && currentlyEmpty)
return;
RaiseChangeNotificationEvents(action: NotifyCollectionChangedAction.Reset);
}
bool AddArrangeCore(IEnumerable<T> collection)
{
var itemAdded = false;
foreach (var item in collection)
{
Items.Add(item);
itemAdded = true;
}
return itemAdded;
}
void RaiseChangeNotificationEvents(NotifyCollectionChangedAction action, List<T>? changedItems = null, int startingIndex = -1)
{
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
if (changedItems == null)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action));
else
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, changedItems: changedItems, startingIndex: startingIndex));
}
}
} | mit |
abendaniocarlo/seatwork | application/views/students/new_student.php | 1553 | <h2>New Student</h2>
<form role="form" class="" method="post" action="<?php echo base_url('sms/save?a=add'); ?>" >
<div class="text-danger">
<?php
if( isset($errors) ){
echo $errors;
}
?>
</div>
<div class="form-group">
<label for="idno">ID No.:</label>
<input type="text" class="form-control" id="idno" name="idno" />
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" name="lname" />
</div>
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" name="fname" />
</div>
<div class="form-group">
<label for="mname">Middle Name:</label>
<input type="text" class="form-control" id="mname" name="mname" />
</div>
<div class="form-group">
<label for="course">Course:</label>
<select class="form-control" id="course" name="course">
<?php
foreach($course as $s){
echo '<option >'.$s['coursename'].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="sex">Sex: </label>
<input type="radio" class="" id="sex" name="sex" value="M" /> Male
<input type="radio" class="" id="sex" name="sex" value="F" /> Female
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" onclick="alert('Saved Sucessfully')">
Save <span class="glyphicon glyphicon-save"></span>
</button>
</div>
</form> | mit |
ShreyK/Android-Game-Development-Framework | Framework/RenderView.java | 1845 | package shreyk.o.Framework;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by Shrey on 12/16/2015.
*/
public class RenderView extends SurfaceView implements Runnable {
Game game;
Bitmap framebuffer;
Thread renderThread = null;
SurfaceHolder holder;
volatile boolean running = false;
public RenderView(Game game, Bitmap framebuffer) {
super(game);
this.game = game;
this.framebuffer = framebuffer;
this.holder = getHolder();
}
public void resume() {
running = true;
renderThread = new Thread(this);
renderThread.start();
}
public void run() {
Rect dstRect = new Rect();
long startTime = System.nanoTime();
while (running) {
if (!holder.getSurface().isValid())
continue;
float deltaTime = (System.nanoTime() - startTime) / 10000000.000f;
startTime = System.nanoTime();
if (deltaTime > 3.15) {
deltaTime = (float) 3.15;
}
game.getCurrentScreen().update(deltaTime);
game.getCurrentScreen().paint(deltaTime);
Canvas canvas = holder.lockCanvas();
canvas.getClipBounds(dstRect);
canvas.drawBitmap(framebuffer, null, dstRect, null);
holder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
running = false;
while (true) {
try {
renderThread.join();
break;
} catch (InterruptedException e) {
// retry
}
}
}
}
| mit |
Jayser/angular2-bootstraping | src/app/core/components/core-component.module.ts | 353 | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderModule } from './header';
import { FooterModule } from './footer';
@NgModule({
imports: [
CommonModule,
HeaderModule,
FooterModule,
],
exports: [
HeaderModule,
FooterModule
]
})
export class CoreComponentsModule { }
| mit |
centurionmedia/blank_altumo | htdocs/project/plugins/sfGuardPlugin/lib/form/base/BasesfGuardUserForm.class.php | 5263 | <?php
/**
* sfGuardUser form base class.
*
* @method sfGuardUser getObject() Returns the current form's model object
*
* @package ##PROJECT_NAME##
* @subpackage form
* @author ##AUTHOR_NAME##
*/
abstract class BasesfGuardUserForm extends BaseFormPropel
{
public function setup()
{
$this->setWidgets(array(
'id' => new sfWidgetFormInputHidden(),
'username' => new sfWidgetFormInputText(),
'algorithm' => new sfWidgetFormInputText(),
'salt' => new sfWidgetFormInputText(),
'password' => new sfWidgetFormInputText(),
'created_at' => new sfWidgetFormDateTime(),
'last_login' => new sfWidgetFormDateTime(),
'is_active' => new sfWidgetFormInputCheckbox(),
'is_super_admin' => new sfWidgetFormInputCheckbox(),
'sf_guard_user_group_list' => new sfWidgetFormPropelChoice(array('multiple' => true, 'model' => 'sfGuardGroup')),
'sf_guard_user_permission_list' => new sfWidgetFormPropelChoice(array('multiple' => true, 'model' => 'sfGuardPermission')),
));
$this->setValidators(array(
'id' => new sfValidatorPropelChoice(array('model' => 'sfGuardUser', 'column' => 'id', 'required' => false)),
'username' => new sfValidatorString(array('max_length' => 128)),
'algorithm' => new sfValidatorString(array('max_length' => 128)),
'salt' => new sfValidatorString(array('max_length' => 128)),
'password' => new sfValidatorString(array('max_length' => 128)),
'created_at' => new sfValidatorDateTime(array('required' => false)),
'last_login' => new sfValidatorDateTime(array('required' => false)),
'is_active' => new sfValidatorBoolean(),
'is_super_admin' => new sfValidatorBoolean(),
'sf_guard_user_group_list' => new sfValidatorPropelChoice(array('multiple' => true, 'model' => 'sfGuardGroup', 'required' => false)),
'sf_guard_user_permission_list' => new sfValidatorPropelChoice(array('multiple' => true, 'model' => 'sfGuardPermission', 'required' => false)),
));
$this->validatorSchema->setPostValidator(
new sfValidatorPropelUnique(array('model' => 'sfGuardUser', 'column' => array('username')))
);
$this->widgetSchema->setNameFormat('sf_guard_user[%s]');
$this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
parent::setup();
}
public function getModelName()
{
return 'sfGuardUser';
}
public function updateDefaultsFromObject()
{
parent::updateDefaultsFromObject();
if (isset($this->widgetSchema['sf_guard_user_group_list']))
{
$values = array();
foreach ($this->object->getsfGuardUserGroups() as $obj)
{
$values[] = $obj->getGroupId();
}
$this->setDefault('sf_guard_user_group_list', $values);
}
if (isset($this->widgetSchema['sf_guard_user_permission_list']))
{
$values = array();
foreach ($this->object->getsfGuardUserPermissions() as $obj)
{
$values[] = $obj->getPermissionId();
}
$this->setDefault('sf_guard_user_permission_list', $values);
}
}
protected function doSave($con = null)
{
parent::doSave($con);
$this->savesfGuardUserGroupList($con);
$this->savesfGuardUserPermissionList($con);
}
public function savesfGuardUserGroupList($con = null)
{
if (!$this->isValid())
{
throw $this->getErrorSchema();
}
if (!isset($this->widgetSchema['sf_guard_user_group_list']))
{
// somebody has unset this widget
return;
}
if (null === $con)
{
$con = $this->getConnection();
}
$c = new Criteria();
$c->add(sfGuardUserGroupPeer::USER_ID, $this->object->getPrimaryKey());
sfGuardUserGroupPeer::doDelete($c, $con);
$values = $this->getValue('sf_guard_user_group_list');
if (is_array($values))
{
foreach ($values as $value)
{
$obj = new sfGuardUserGroup();
$obj->setUserId($this->object->getPrimaryKey());
$obj->setGroupId($value);
$obj->save();
}
}
}
public function savesfGuardUserPermissionList($con = null)
{
if (!$this->isValid())
{
throw $this->getErrorSchema();
}
if (!isset($this->widgetSchema['sf_guard_user_permission_list']))
{
// somebody has unset this widget
return;
}
if (null === $con)
{
$con = $this->getConnection();
}
$c = new Criteria();
$c->add(sfGuardUserPermissionPeer::USER_ID, $this->object->getPrimaryKey());
sfGuardUserPermissionPeer::doDelete($c, $con);
$values = $this->getValue('sf_guard_user_permission_list');
if (is_array($values))
{
foreach ($values as $value)
{
$obj = new sfGuardUserPermission();
$obj->setUserId($this->object->getPrimaryKey());
$obj->setPermissionId($value);
$obj->save();
}
}
}
}
| mit |
lKaza/VideoJuegosFisicosChile | ScrapySVGTodoJuegos/ScrapySVGTodoJuegos/settings.py | 3258 | # -*- coding: utf-8 -*-
# Scrapy settings for ScrapySVGTodoJuegos project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'ScrapySVGTodoJuegos'
SPIDER_MODULES = ['ScrapySVGTodoJuegos.spiders']
NEWSPIDER_MODULE = 'ScrapySVGTodoJuegos.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'ScrapySVGTodoJuegos (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'ScrapySVGTodoJuegos.middlewares.ScrapysvgtodojuegosSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'ScrapySVGTodoJuegos.middlewares.MyCustomDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'ScrapySVGTodoJuegos.pipelines.ScrapysvgtodojuegosPipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
| mit |
lidongkai/god | laravel/storage/framework/views/fa55a065b99ed46f7a51b385bc020c5b1f26d159.php | 29654 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<title><?php echo e(config('app.name')); ?>-<?php echo e($title); ?></title>
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php echo e(config('app.name')); ?> -<?php echo e($title); ?></title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/bootstrap/css/bootstrap.min.css')); ?>">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/dist/css/AdminLTE.min.css')); ?>">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/dist/css/skins/_all-skins.min.css')); ?>">
<!-- iCheck -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/plugins/iCheck/flat/blue.css')); ?>">
<!-- Morris chart -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/plugins/morris/morris.css')); ?>">
<!-- jvectormap -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css')); ?>">
<!-- Date Picker -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/plugins/datepicker/datepicker3.css')); ?>">
<!-- Daterange picker -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/plugins/daterangepicker/daterangepicker.css')); ?>">
<!-- bootstrap wysihtml5 - text editor -->
<link rel="stylesheet" href="<?php echo e(asset('/admin/AdminLTE/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css')); ?>">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<<<<<<< HEAD
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
=======
<script src="<?php echo e(asset('/admin/AdminLTE/https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js')); ?>"></script>
<script src="<?php echo e(asset('/admin/AdminLTE/https://oss.maxcdn.com/respond/1.4.2/respond.min.js')); ?>"></script>
>>>>>>> 0c23601c8819844de8510290fba92fdae62fbed0
<![endif]-->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="index2.html" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>A</b>LT</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>Admin</b>LTE</span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success">4</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 4 messages</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- start message -->
<a href="#">
<div class="pull-left">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user2-160x160.jpg')); ?>" class="img-circle" alt="User Image">
</div>
<h4>
Support Team
<small><i class="fa fa-clock-o"></i> 5 mins</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<!-- end message -->
<li>
<a href="#">
<div class="pull-left">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user3-128x128.jpg')); ?>" class="img-circle" alt="User Image">
</div>
<h4>
AdminLTE Design Team
<small><i class="fa fa-clock-o"></i> 2 hours</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user4-128x128.jpg')); ?>" class="img-circle" alt="User Image">
</div>
<h4>
Developers
<small><i class="fa fa-clock-o"></i> Today</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user3-128x128.jpg')); ?>" class="img-circle" alt="User Image">
</div>
<h4>
Sales Department
<small><i class="fa fa-clock-o"></i> Yesterday</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user4-128x128.jpg')); ?>" class="img-circle" alt="User Image">
</div>
<h4>
Reviewers
<small><i class="fa fa-clock-o"></i> 2 days</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">See All Messages</a></li>
</ul>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="dropdown notifications-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell-o"></i>
<span class="label label-warning">10</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 10 notifications</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li>
<a href="#">
<i class="fa fa-users text-aqua"></i> 5 new members joined today
</a>
</li>
<li>
<a href="#">
<i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the
page and may cause design problems
</a>
</li>
<li>
<a href="#">
<i class="fa fa-users text-red"></i> 5 new members joined
</a>
</li>
<li>
<a href="#">
<i class="fa fa-shopping-cart text-green"></i> 25 sales made
</a>
</li>
<li>
<a href="#">
<i class="fa fa-user text-red"></i> You changed your username
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">View all</a></li>
</ul>
</li>
<!-- Tasks: style can be found in dropdown.less -->
<li class="dropdown tasks-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag-o"></i>
<span class="label label-danger">9</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 9 tasks</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- Task item -->
<a href="#">
<h3>
Design some buttons
<small class="pull-right">20%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">20% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Create a nice theme
<small class="pull-right">40%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Some task I need to do
<small class="pull-right">60%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">60% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Make beautiful transitions
<small class="pull-right">80%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">80% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
</ul>
</li>
<li class="footer">
<a href="#">View all tasks</a>
</li>
</ul>
</li>
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user2-160x160.jpg')); ?>" class="user-image" alt="User Image">
<span class="hidden-xs">Alexander Pierce</span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user2-160x160.jpg')); ?>" class="img-circle" alt="User Image">
<p>
Alexander Pierce - Web Developer
<small>Member since Nov. 2012</small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="row">
<div class="col-xs-4 text-center">
<a href="#">Followers</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Sales</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Friends</a>
</div>
</div>
<!-- /.row -->
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">Profile</a>
</div>
<div class="pull-right">
<a href="<?php echo e(url('/admin/logout')); ?>" class="btn btn-default btn-flat">退出</a>
</div>
</li>
</ul>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="<?php echo e(asset('/admin/AdminLTE/dist/img/user2-160x160.jpg')); ?>" class="img-circle" alt="User Image">
</div>
<div class="pull-left info">
<p>Alexander Pierce</p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form -->
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
<!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="header">MAIN NAVIGATION</li>
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>用户管理</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li class="active"><a href="<?php echo e(url('/admin/user/index')); ?>"><i class="fa fa-circle-o"></i> 用户列表</a></li>
<li><a href="<?php echo e(url('/admin/user/add')); ?>"><i class="fa fa-circle-o"></i> 用户添加</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i>
<span>友情链接管理</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="<?php echo e(url('/admin/links/index')); ?>"><i class="fa fa-circle-o"></i> 友情链接列表</a></li>
<li><a href="<?php echo e(url('/admin/links/add')); ?>"><i class="fa fa-circle-o"></i> 友情链接添加</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i>
<span>商品分类管理</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="<?php echo e(url('/admin/goods/create')); ?>"><i class="fa fa-circle-o"></i> 分类添加</a></li>
<li><a href="<?php echo e(url('/admin/goods')); ?>"><i class="fa fa-circle-o"></i> 分类列表</a></li>
</ul>
</li>
<li class=" treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>商品管理</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li class=""><a href="<?php echo e(url('/admin/goodsDetail/create')); ?>"><i class="fa fa-circle-o"></i> 商品添加</a></li>
<li><a href="<?php echo e(url('/admin/goodsDetail')); ?>"><i class="fa fa-circle-o"></i> 商品列表</a></li>
</ul>
</li>
<li class=" treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>订单管理</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li class="active"><a href="<?php echo e(url('/admin/order/index')); ?>"><i class="fa fa-circle-o"></i> 订单列表</a></li>
</ul>
</li>
<li class=" treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>栏目管理</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li ><a href="<?php echo e(url('/admin/column/index')); ?>"><i class="fa fa-circle-o"></i> 栏目列表</a></li>
<li><a href="<?php echo e(url('/admin/column/add')); ?>"><i class="fa fa-circle-o"></i>栏目添加</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i>
<span>文章管理</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="<?php echo e(url('/admin/article/index')); ?>"><i class="fa fa-circle-o"></i> 文章列表</a></li>
<li><a href="<?php echo e(url('/admin/article/add')); ?>"><i class="fa fa-circle-o"></i> 文章添加</a></li>
</ul>
</li>
<<<<<<< HEAD
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i>
<span>轮播图管理</span>
=======
<li class=" treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>网络配置</span>
>>>>>>> 7b74b8e6bfbb28f622ee765ccc02056b1e462bcd
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<<<<<<< HEAD
<li><a href="<?php echo e(url('/admin/turn/index')); ?>"><i class="fa fa-circle-o"></i> 轮播图列表</a></li>
<li><a href="<?php echo e(url('/admin/turn/add')); ?>"><i class="fa fa-circle-o"></i> 轮播图添加</a></li>
</ul>
</li>
=======
<li ><a href="<?php echo e(url('/admin/config/index')); ?>"><i class="fa fa-circle-o"></i>配置信息</a></li>
</ul>
</li>
>>>>>>> 7b74b8e6bfbb28f622ee765ccc02056b1e462bcd
</ul>
</section>
<!-- /.sidebar -->
</aside>
<?php echo $__env->yieldContent('content'); ?>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified control-sidebar-tabs">
<li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li>
<li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane" id="control-sidebar-home-tab">
<h3 class="control-sidebar-heading">Recent Activity</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-birthday-cake bg-red"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Langdon's Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-user bg-yellow"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Frodo Updated His Profile</h4>
<p>New phone +1(800)555-1234</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-envelope-o bg-light-blue"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Nora Joined Mailing List</h4>
<p>[email protected]</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-file-code-o bg-green"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Cron Job 254 Executed</h4>
<p>Execution time 5 seconds</p>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
<h3 class="control-sidebar-heading">Tasks Progress</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Custom Template Design
<span class="label label-danger pull-right">70%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-danger" style="width: 70%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Update Resume
<span class="label label-success pull-right">95%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-success" style="width: 95%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Laravel Integration
<span class="label label-warning pull-right">50%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-warning" style="width: 50%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Back End Framework
<span class="label label-primary pull-right">68%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-primary" style="width: 68%"></div>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
</div>
<!-- /.tab-pane -->
<!-- Stats tab content -->
<div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div>
<!-- /.tab-pane -->
<!-- Settings tab content -->
<div class="tab-pane" id="control-sidebar-settings-tab">
<form method="post">
<h3 class="control-sidebar-heading">General Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Report panel usage
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Some information about this general settings option
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Allow mail redirect
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Other sets of options are available
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Expose author name in posts
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Allow the user to show his name in blog posts
</p>
</div>
<!-- /.form-group -->
<h3 class="control-sidebar-heading">Chat Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Show me as online
<input type="checkbox" class="pull-right" checked>
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Turn off notifications
<input type="checkbox" class="pull-right">
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Delete chat history
<a href="javascript:void(0)" class="text-red pull-right"><i class="fa fa-trash-o"></i></a>
</label>
</div>
<!-- /.form-group -->
</form>
</div>
<!-- /.tab-pane -->
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- jQuery 2.2.3 -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/jQuery/jquery-2.2.3.min.js')); ?>"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<!-- Bootstrap 3.3.6 -->
<script src="<?php echo e(asset('/admin/AdminLTE/bootstrap/js/bootstrap.min.js')); ?>"></script>
<!-- Morris.js charts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<!-- <script src="<?php echo e(asset('/admin/AdminLTE/plugins/morris/morris.min.js')); ?>"></script> -->
<!-- Sparkline -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/sparkline/jquery.sparkline.min.js')); ?>"></script>
<!-- jvectormap -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js')); ?>"></script>
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/jvectormap/jquery-jvectormap-world-mill-en.js')); ?>"></script>
<!-- jQuery Knob Chart -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/knob/jquery.knob.js')); ?>"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/daterangepicker/daterangepicker.js')); ?>"></script>
<!-- datepicker -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/datepicker/bootstrap-datepicker.js')); ?>"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js')); ?>"></script>
<!-- Slimscroll -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/slimScroll/jquery.slimscroll.min.js')); ?>"></script>
<!-- FastClick -->
<script src="<?php echo e(asset('/admin/AdminLTE/plugins/fastclick/fastclick.js')); ?>"></script>
<!-- AdminLTE App -->
<script src="<?php echo e(asset('/admin/AdminLTE/dist/js/app.min.js')); ?>"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<!-- <script src="<?php echo e(asset('/admin/AdminLTE/dist/js/pages/dashboard.js')); ?>"></script> -->
<!-- AdminLTE for demo purposes -->
<script src="<?php echo e(asset('/admin/AdminLTE/dist/js/demo.js')); ?>"></script>
<?php echo $__env->yieldContent('js'); ?>
</body>
</html>
| mit |
isaacs/website | config/app.js | 5218 | var express = require('express')
, auth = require('mongoose-auth')
, env = require('./env')
, util = require('util')
, port = env.port
, secrets = env.secrets
, EventEmitter = require('events').EventEmitter
, commits = require('./../controllers/commits');
// express
var app = module.exports = express.createServer();
// some paths
app.paths = {
public: __dirname + '/../public',
views: __dirname + '/../views'
};
// error handling
var airbrake = require('airbrake').createClient('b76b10945d476da44a0eac6bfe1aeabd');
process.on('uncaughtException', function(e) {
util.debug(e.stack.red);
if (env.node_env === 'production')
airbrake.notify(e);
});
// utilities & hacks
require('colors');
require('../lib/render2');
require('../lib/underscore.shuffle');
require('../lib/regexp-extensions');
// events
app.events = new EventEmitter();
// db
app.db = require('../models')(env.mongo_url);
// config
app.disable('voting');
app.configure(function() {
var coffee = require('coffee-script')
, stylus = require('stylus');
var assetManager = require('connect-assetmanager')({
js: {
route: /\/javascripts\/all-[a-z0-9]+\.js/,
path: __dirname + '/../public/javascripts/',
dataType: 'javascript',
debug: env.node_env === 'development',
preManipulate: {
'^': [
function(src, path, index, isLast, callback) {
callback(src.replace(/#socketIoPort#/g, env.port));
}
, function(src, path, index, isLast, callback) {
if (/\.coffee$/.test(path)) {
callback(coffee.compile(src));
} else {
callback(src);
}
}
]
},
files: [ // order matters here
'polyfills.js',
'vendor/hoptoad-notifier.js',
'vendor/hoptoad-key.js',
'vendor/json2.js',
'vendor/jquery-1.7.2.js',
'vendor/jquery.ba-hashchange.js',
'vendor/jquery.border-image.js',
'vendor/jquery.fancybox.js',
'vendor/jquery.infinitescroll.js',
'vendor/jquery.keylisten.js',
'vendor/jquery.pjax.js',
'vendor/jquery.transform.light.js',
'vendor/jquery.transloadit2.js',
'vendor/md5.js',
'vendor/underscore-1.3.3.js',
'watchmaker.js',
'application.coffee',
'*'
]
},
css: {
route: /\/stylesheets\/all-[a-z0-9]+\.css/,
path: __dirname + '/../public/stylesheets/',
dataType: 'css',
debug: env.node_env === 'development',
preManipulate: {
'^': [
function(src, path, index, isLast, callback) {
if (/\.styl$/.test(path)) {
stylus(src)
.set('compress', false)
.set('filename', path)
.set('paths', [ __dirname, app.paths.public ])
.render(function(err, css) {
callback(err || css);
});
} else {
callback(src);
}
}
]
},
files: [ // order matters here
'vendor/normalize.css',
'vendor/jquery.fancybox.css',
'application.styl'
]
}
});
app.use(assetManager);
app.helpers({ assetManager: assetManager });
});
app.configure('development', function() {
app.use(express.static(app.paths.public));
app.use(express.profiler());
require('../lib/mongo-log')(app.db.mongo);
});
app.configure('production', function() {
app.use(express.static(app.paths.public, { maxAge: 1000 * 5 * 60 }));
app.use(function(req, res, next) {
if (req.headers.host !== 'nodeknockout.com')
res.redirect('http://nodeknockout.com' + req.url);
else
next();
});
});
app.configure(function() {
var RedisStore = require('connect-redis')(express);
app.use(express.cookieParser());
app.use(express.session({
secret: secrets.session,
store: new RedisStore
}));
app.use(express.bodyParser());
app.use(express.methodOverride());
// hacky solution for post commit hooks not to check csrf
// app.use(commits(app));
app.use(express.csrf());
app.use(function(req, res, next) { if (req.body) delete req.body._csrf; next(); });
app.use(express.logger());
app.use(auth.middleware());
app.use(app.router);
app.use(function(e, req, res, next) {
if (typeof(e) === 'number')
return res.render2('errors/' + e, { status: e });
if (typeof(e) === 'string')
e = Error(e);
if (env.node_env === 'production')
airbrake.notify(e);
res.render2('errors/500', { error: e });
});
app.set('views', app.paths.views);
app.set('view engine', 'jade');
});
// helpers
auth.helpExpress(app);
require('../helpers')(app);
app.listen(port);
app.ws = require('socket.io').listen(app);
app.ws.set('log level', 1);
app.ws.set('browser client minification', true);
app.on('listening', function() {
require('util').log('listening on ' + ('0.0.0.0:' + port).cyan);
// if run as root, downgrade to the owner of this file
if (env.production && process.getuid() === 0)
require('fs').stat(__filename, function(err, stats) {
if (err) return util.log(err)
process.setuid(stats.uid);
});
});
| mit |
shiftkey/electron | atom/browser/session_preferences.cc | 1642 | // Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/session_preferences.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/memory/ptr_util.h"
namespace atom {
namespace {
#if defined(OS_WIN)
const base::FilePath::CharType kPathDelimiter = FILE_PATH_LITERAL(';');
#else
const base::FilePath::CharType kPathDelimiter = FILE_PATH_LITERAL(':');
#endif
} // namespace
// static
int SessionPreferences::kLocatorKey = 0;
SessionPreferences::SessionPreferences(content::BrowserContext* context) {
context->SetUserData(&kLocatorKey, base::WrapUnique(this));
}
SessionPreferences::~SessionPreferences() {}
// static
SessionPreferences* SessionPreferences::FromBrowserContext(
content::BrowserContext* context) {
return static_cast<SessionPreferences*>(context->GetUserData(&kLocatorKey));
}
// static
void SessionPreferences::AppendExtraCommandLineSwitches(
content::BrowserContext* context,
base::CommandLine* command_line) {
SessionPreferences* self = FromBrowserContext(context);
if (!self)
return;
base::FilePath::StringType preloads;
for (const auto& preload : self->preloads()) {
if (!base::FilePath(preload).IsAbsolute()) {
LOG(ERROR) << "preload script must have absolute path: " << preload;
continue;
}
if (preloads.empty())
preloads = preload;
else
preloads += kPathDelimiter + preload;
}
if (!preloads.empty())
command_line->AppendSwitchNative(switches::kPreloadScripts, preloads);
}
} // namespace atom
| mit |
fmingorance/laradoc | src/Cache/NullProvider.php | 298 | <?php namespace Mingorance\LaraDoc\Cache;
class NullProvider implements Provider
{
public function make($config = null)
{
return null;
}
public function isAppropriate($provider)
{
return $provider == null || $provider == 'null' || $provider == 'NULL';
}
}
| mit |
selfrefactor/rambda | source/partitionAsync.js | 933 | import {_isArray} from './_internals/_isArray'
async function whenObject(predicate, input) {
const yes = {}
const no = {}
Object.entries(input).forEach(([prop, value]) => {
if (predicate(value, prop)) {
yes[prop] = value
} else {
no[prop] = value
}
})
return [yes, no]
}
async function partitionAsyncFn(predicate, input) {
if (!_isArray(input)) return whenObject(predicate, input)
const yes = []
const no = []
for (const i in input) {
const predicateResult = await predicate(input[i], Number(i))
if (predicateResult) {
yes.push(input[i])
} else {
no.push(input[i])
}
}
return [yes, no]
}
export function partitionAsync(predicate, list) {
if (arguments.length === 1) {
return async _list => partitionAsyncFn(predicate, _list)
}
return new Promise((resolve, reject) => {
partitionAsyncFn(predicate, list).then(resolve).catch(reject)
})
}
| mit |
IsaacMiguel/Maresa | models/mCondicion.js | 140 | var conn = require('../config/db').conn;
module.exports = {
getAll: getAll
}
function getAll(cb){
conn("select * from condicion", cb);
} | mit |
Broomspun/shanque | framework/builtin/video/processor.php | 682 | <?php
/**
* [WeEngine System] Copyright (c) 2014 shanque.zhangshuoyin.cn
* WeEngine is NOT a free software, it under the license terms, visited http://shanque.zhangshuoyin.cn/ for more details.
*/
defined('IN_IA') or exit('Access Denied');
class VideoModuleProcessor extends WeModuleProcessor {
public function respond() {
global $_W;
$rid = $this->rule;
$sql = "SELECT * FROM " . tablename('video_reply') . " WHERE `rid`=:rid";
$item = pdo_fetch($sql, array(':rid' => $rid));
if (empty($item)) {
return false;
}
return $this->respVideo(array(
'MediaId' => $item['mediaid'],
'Title' => $item['title'],
'Description' => $item['description']
));
}
}
| mit |
Adrianacmy/Classic-Interesting-CS-Mini-Programs | Python-language/global_local.py | 253 | '''
# 作用域
globals()
locals()
LEGB
local -> enclosing function -> globals -> buitins
check all builtins
dir(__buitins__)
'''
n = 100
def space():
n = 200
def space2():
n = 300
print(n)
return space2
n = space()
n() | mit |
thiagodebastos/react-future-stack | components/TodoApp/Input.js | 529 | // @flow
import React from 'react';
import { Button, Input } from 'semantic-ui-react';
import 'semantic-ui-css/components/icon.css';
type Props = {
onChange: Function,
onSubmit: Function,
value: string
};
const InputComponent = ({ onChange, onSubmit, value }: Props) =>
<form onSubmit={onSubmit}>
<Input
type="text"
onChange={onChange}
value={value}
placeholder="Add new todo"
label={<Button>+</Button>}
labelPosition="right"
/>
</form>;
export default InputComponent;
| mit |
bound1ess/codeforces-problemset-2 | 349/a.cpp | 634 | #include <cstdio>
int main() {
freopen("input", "rt", stdin);
freopen("output", "wt", stdout);
int n, x, v25 = 0, v50 = 0, v100 = 0;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &x);
++(25 == x ? v25 : (50 == x ? v50 : v100));
if (25 == x) {
continue;
}
if (50 == x) {
if (0 < v25) {
--v25;
} else {
puts("NO");
return 0;
}
continue;
}
// 100 == x
if (0 < v25 && 0 < v50) {
--v25, --v50;
} else if (3 <= v25) {
v25 -= 3;
} else {
puts("NO");
return 0;
}
}
puts("YES");
return 0;
}
| mit |
dieng444/projet-miriade | web/assets/versions/miriade/plan.php | 2202 | <?php include('header.inc'); ?>
<div class="container">
<div class="row">
<div class="col-md-9">
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function init_map() {
var var_location = new google.maps.LatLng(49.1871015,-0.3131677);
var var_mapoptions = {
center: var_location,
zoom: 14
};
var var_marker = new google.maps.Marker({
position: var_location,
map: var_map,
title:"Venice"});
var var_map = new google.maps.Map(document.getElementById("map-container"),
var_mapoptions);
var_marker.setMap(var_map);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
<style>
#map-outer { height: 440px;
padding: 20px;
border: 2px solid #CCC;
margin-bottom: 20px;
background-color:#FFF }
#map-container { height: 400px }
@media all and (max-width: 991px) {
#map-outer { height: 650px }
}
</style>
<h1>Plan d'accès</h1>
<div class="row">
<div id="map-outer" class="col-md-12">
<div id="address" class="col-md-4">
<h2>Notre position</h2>
<address>
<strong>MIRIADE INNOVATION</strong><br>
Campus EffiScience <br>
2 Esplanade Anton Philips <br>
14460 COLOMBELLES<br>
FRANCE
</address>
</div>
<div id="map-container" class="col-md-8"></div>
</div><!-- /map-outer -->
</div> <!-- /row -->
</div>
<?php include('aside.inc'); ?>
</div>
<!-- /.row -->
<footer>
<p>© Miriade 2015</p>
</footer>
</div> <!-- /container -->
<?php include('footer.inc'); ?> | mit |
qrush/skyway-railsconf2016 | config/routes.rb | 1544 | Skyway::Application.routes.draw do
resource :tour
resources :shows do
resource :setlist
collection do
get :latest, format: :json
end
end
resources :songs do
member do
patch :merge
end
end
resources :venues do
member do
patch :merge
end
end
resources :imports do
member do
patch :confirm
end
end
resources :articles, path: :news
resources :searches, path: "search"
resources :announcements
resource :admin
get "/home" => "home#show"
get "/setlists" => "home#index"
get "/sampler", to: redirect('https://aqueous1.bandcamp.com/album/sonic-farm-presents-aqueous-2015-09-26')
get "/street.php", format: false, to: redirect('/mobilize')
get "/setlists/setlists.php", format: false, to: redirect('/setlists')
%w(mike dave evan nick).each do |player|
get "/#{player}.php", format: false, to: redirect('/about')
end
get "/setlists/:slug.php", format: false, to: redirect { |path_params, req|
date = Date.parse(path_params[:slug]) rescue nil
if date
"/shows/#{date}"
else
"/setlists"
end
}
get "/setlists/:year/:slug.php", format: false, to: redirect { |path_params, req|
year = path_params[:year]
slug = path_params[:slug]
if slug =~ /_/
"/shows/#{year}-#{slug.gsub("_", "-")}"
else
"/shows?year=#{year}"
end
}
get "/:page.php", format: false, to: redirect('/%{page}')
root to: "home#show"
get "/*id" => 'high_voltage/pages#show', as: :page, format: false
end
| mit |