code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
require 'spec_helper'
describe Unitpay do
it 'has a version number' do
expect(Unitpay::VERSION).not_to be nil
end
end
| ssnikolay/unitpay | spec/unitpay_spec.rb | Ruby | mit | 127 |
package org.ethereum.net.rlpx.discover;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.ethereum.crypto.ECKey;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.rlpx.discover.table.NodeTable;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class UDPListener {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");
private final int port;
private final String address;
private final ECKey key;
private NodeTable table;
public UDPListener(String address, int port) {
this.address = address;
this.port = port;
key = ECKey.fromPrivate(BigInteger.TEN).decompress();
}
public void start() throws Exception {
NioEventLoopGroup group = new NioEventLoopGroup();
byte[] nodeID = new byte[64];
System.arraycopy(key.getPubKey(), 1, nodeID, 0, 64);
Node homeNode = new Node(nodeID, address, port);
table = new NodeTable(homeNode);
//add default node on local to connect
// byte[] peerId = Hex.decode("621168019b7491921722649cd1aa9608f23f8857d782e7495fb6765b821002c4aac6ba5da28a5c91b432e5fcc078931f802ffb5a3ababa42adee7a0c927ff49e");
// Node p = new Node(peerId, "127.0.0.1", 30303);
// table.addNode(p);
//Persist the list of known nodes with their reputation
byte[] cppId = Hex.decode("487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a");
Node cppBootstrap = new Node(cppId, "5.1.83.226", 30303);
table.addNode(cppBootstrap);
byte[] cpp2Id = Hex.decode("1637a970d987ddb8fd18c5ca01931210cd2ac5d2fe0f42873c0b31f110c5cbedf68589ec608ec5421e1d259b06cba224127c6bbddbb7c26eaaea56423a23bd31");
Node cpp2Bootstrap = new Node(cpp2Id, "69.140.163.94", 30320);
table.addNode(cpp2Bootstrap);
try {
Bootstrap b = new Bootstrap();
b.group(group)
.option(ChannelOption.SO_TIMEOUT, 1000)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
public void initChannel(NioDatagramChannel ch)
throws Exception {
ch.pipeline().addLast(new PacketDecoder());
ch.pipeline().addLast(new MessageHandler(key, table));
}
});
Channel channel = b.bind(address, port).sync().channel();
DiscoveryExecutor discoveryExecutor = new DiscoveryExecutor(channel, table, key);
discoveryExecutor.discover();
channel.closeFuture().sync();
} catch (Exception e) {
logger.error("{}", e);
} finally {
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
String address = "0.0.0.0";
int port = 30303;
if (args.length >= 2) {
address = args[0];
port = Integer.parseInt(args[1]);
}
new UDPListener(address, port).start();
}
}
| BlockchainSociety/ethereumj-android | ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/UDPListener.java | Java | mit | 3,443 |
# frozen_string_literal: true
require 'request_store'
# Requiring this file, or calling `Gecko.enable_logging` will hook into the provided
# ActiveSupport::Notification hooks on requests and log ActiveRecord-style messages
# on API requests.
class GeckoLogSubscriber < ActiveSupport::LogSubscriber
ENV_KEY = :"gecko-logger"
def initialize
super
@odd = false
end
def request(event) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
RequestStore.store[ENV_KEY] = []
payload = event.payload
request_path = payload[:request_path]
if payload[:params] && payload[:verb] == :get
request_path = request_path + "?" + payload[:params].to_param
RequestStore.store[ENV_KEY] << request_path
end
name = "#{payload[:model_class]} Load (#{event.duration.round(1)}ms)"
query = "#{payload[:verb].to_s.upcase} /#{request_path}"
name = if odd?
color(name, CYAN, true)
else
color(name, MAGENTA, true)
end
query = color(query, nil, true)
debug(" #{name} #{query}")
end
def odd?
@odd = !@odd
end
end
GeckoLogSubscriber.attach_to :gecko
| tradegecko/gecko | lib/gecko/ext/log_subscriber.rb | Ruby | mit | 1,160 |
import os
import numpy as np
import pandas as pd
import patools.packing as pck
class Trial:
def __init__(self, directory=os.getcwd(), nbs=False):
self.packings = self.loadTrials(directory, nbs)
self.df = pd.DataFrame(index=self.packings.keys())
self._getSphereRads()
self._getParticleRads()
def __len__(self):
return sum([len(packing) for packing in self.packings.values()])
def _getSphereRads(self):
rads = {}
for key, val in self.packings.items():
rads[key] = val.sphereRad
radS = pd.Series(rads, name='rad')
self.df['rad'] = radS
def _getParticleRads(self):
pck = self.packings[list(self.packings.keys())[0]]
self.bigRad = pck.bigRad
self.littleRad = pck.littleRad
def loadTrials(self, directory, nbs=False):
"""
Loads a set of packings corresponding to one parameter set. The
subdirectories should contain packings files themselves.
ParamDirectory -> Trial Subdirs -> Packing Files
"""
subdirs = os.listdir(directory)
trialPackings = {}
for trial in subdirs:
trialDir = os.path.join(directory, trial)
if not os.path.isdir(trialDir): # Only look in dirs
continue
newPacking = pck.Packing(trialDir,nbs=nbs)
if len(newPacking) <= 1: # Remove broken packings
continue
trialPackings[trial] = newPacking
return trialPackings
def calculatePF_all(self):
"""
Calculates the packing fraction for each packing in a trial. The packing
fractions for each trial are stored in a dataframe. This function is
most often accessed from the dataset object, where different statistics
of the packing fractions are reported, such as the mean, median, max, or
min.
"""
pfs = {}
for key, val in self.packings.items():
pfs[key] = val.calculatePF()
pfS = pd.Series(pfs, name='pf')
self.df['pf'] = pfS
return pfs
def calculateOP_all(self, n=6):
"""
Calculates the n-atic order parameter for each packing in a trial. The
average order parameter for a packing is stored in a dataframe. This
function is most often accessed from the dataset object, where different
statistics of the packing fractions are reported, such as the mean,
median, max, or min.
"""
ops = {}
for key, val in self.packings.items():
val.calculateOP(n)
ops[key] = val.op[n]
opS = pd.Series(ops, name=str(n) + '-atic')
self.df[str(n) + '-atic'] = opS
return opS
def calculateSegOP_all(self, n=6):
"""
Calculates the segregated n-atic order parameter for each packing in a
trial. The average order parameter for big-big and little-little for a
packing is stored in a dataframe. This function is most often accessed
from the dataset object, where different statistics of the packing
fractions are reported, such as the mean, median, max, or min.
"""
opsBig = {}
opsLittle = {}
for key, val in self.packings.items():
val.calculateSegOP(n)
opsBig[key] = val.ops[str(n) + 'B']
opsLittle[key] = val.ops[str(n) + 'L']
opSBig = pd.Series(opsBig, name=str(n) + '-aticBig')
opSLittle = pd.Series(opsLittle, name=str(n) + '-aticLittle')
self.df[str(n) + '-aticBig'] = opSBig
self.df[str(n) + '-aticLittle'] = opSLittle
def calculateDFG_all(self):
"""
Calculuates the defect graph size for all of the packings in a given
trial.
"""
dfgs = {}
for key, val in self.packings.items():
val.calculateDefectGraphSize()
dfgs[key] = val.dfG
dfgS = pd.Series(dfgs, name='DFGS')
self.df['DFGS'] = dfgS
return dfgS
def calculateDFF_all(self):
"""
Calculates the defect fraction for all of the packings in a given trial.
"""
dffs = {}
for key, val in self.packings.items():
val.calculateDefectFraction()
dffs[key] = val.dfN
dffS = pd.Series(dffs, name='DFF')
self.df['DFF'] = dffS
return dffS
def calculateCM_all(self):
"""
Calculates the coordination matrix for all of the packings in a given
trial.
"""
cmsbb = {}; cmsbl = {}; cmslb = {}; cmsll = {}
for key, val in self.packings.items():
val.calculateCoordinationMatrix()
cmsbb[key] = val.cm[0]
cmsbl[key] = val.cm[1]
cmslb[key] = val.cm[2]
cmsll[key] = val.cm[3]
self.df['BB'] = pd.Series(cmsbb)
self.df['BL'] = pd.Series(cmsbl)
self.df['LB'] = pd.Series(cmslb)
self.df['LL'] = pd.Series(cmsll)
def calculateRDF_all(self, nBins=50, nTestPts=0):
"""
Computes the RDF over a full trial of one parameter.
"""
self.gsBB = np.zeros([len(self.df), nBins])
self.gsBL = np.zeros([len(self.df), nBins])
self.gsLB = np.zeros([len(self.df), nBins])
self.gsLL = np.zeros([len(self.df), nBins])
empty = []
for i, val in enumerate(self.packings.values()):
val.calculateRadialDF(nBins, nTestPts)
try:
self.gsBB[i] = val.gsBB
self.gsBL[i] = val.gsBL
self.gsLB[i] = val.gsLB
self.gsLL[i] = val.gsLL
except AttributeError:
empty.append(i)
pass
self.gsBB = np.delete(self.gsBB, empty, axis=0)
self.gsBL = np.delete(self.gsBL, empty, axis=0)
self.gsLB = np.delete(self.gsLB, empty, axis=0)
self.gsLL = np.delete(self.gsLL, empty, axis=0)
| amas0/patools | patools/trial.py | Python | mit | 5,966 |
txt = "the quick brown fox jumped over thethe lazy dog"
txt2 = txt.replace("the","a")
print txt
print txt2
| treeform/pystorm | tests/strings/replace.py | Python | mit | 110 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.apimanagement;
import com.azure.core.util.Context;
/** Samples for ContentItem Get. */
public final class ContentItemGetSamples {
/*
* operationId: ContentItem_Get
* api-version: 2020-12-01
* x-ms-examples: ApiManagementGetContentTypeContentItem
*/
/**
* Sample code: ApiManagementGetContentTypeContentItem.
*
* @param manager Entry point to ApiManagementManager.
*/
public static void apiManagementGetContentTypeContentItem(
com.azure.resourcemanager.apimanagement.ApiManagementManager manager) {
manager
.contentItems()
.getWithResponse("rg1", "apimService1", "page", "4e3cf6a5-574a-ba08-1f23-2e7a38faa6d8", Context.NONE);
}
}
| Azure/azure-sdk-for-java | sdk/apimanagement/azure-resourcemanager-apimanagement/src/samples/java/com/azure/resourcemanager/apimanagement/ContentItemGetSamples.java | Java | mit | 918 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace WebApiProxy.Api.Sample.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type.
/// </summary>
/// <param name="mediaType">The media type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
ActionName = String.Empty;
ControllerName = String.Empty;
MediaType = mediaType;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
: this(mediaType)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ParameterType = type;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
: this(sampleDirection, controllerName, actionName, parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
MediaType = mediaType;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
| lust4life/WebApiProxy | WebApiProxy.Api.Sample/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs | C# | mit | 6,486 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injectable } from '@angular/core';
@Injectable()
export class Service839Service {
constructor() { }
}
| angular/angular-cli-stress-test | src/app/services/service-839.service.ts | TypeScript | mit | 320 |
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode*> q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
TreeLinkNode *p = q.front();
q.pop();
if (!p) {
if (!q.empty()) q.push(NULL);
continue;
}
p->next = q.front();
if (p->left) q.push(p->left);
if (p->right) q.push(p->right);
}
}
};
| cloudzfy/leetcode | src/117.populating_next_right_pointers_in_each_node_ii/code2.cpp | C++ | mit | 717 |
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View\Widget;
use Cake\View\Form\ContextInterface;
/**
* Interface for input widgets.
*/
interface WidgetInterface
{
/**
* Converts the $data into one or many HTML elements.
*
* @param array $data The data to render.
* @param \Cake\View\Form\ContextInterface $context The current form context.
* @return string Generated HTML for the widget element.
*/
public function render(array $data, ContextInterface $context): string;
/**
* Returns a list of fields that need to be secured for
* this widget. Fields are in the form of Model[field][suffix]
*
* @param array $data The data to render.
* @return array Array of fields to secure.
*/
public function secureFields(array $data): array;
}
| dakota/cakephp | src/View/Widget/WidgetInterface.php | PHP | mit | 1,400 |
const FliprYaml = require('../lib/flipr-yaml');
const source = new FliprYaml({
filePath: 'sample/config/basic.yaml',
});
source.preload()
.then(() => {
console.log('Config file has been read and cached. Any changes to the .yaml file will not be read by flipr-yaml.');
})
.then(() => source.flush())
.then(() => {
console.log('Cache has been flushed. The next call to flipr-yaml will result in the file being read and cached again.');
});
| godaddy/node-flipr-yaml | sample/flush-cache.js | JavaScript | mit | 461 |
#pragma once
#include <cstddef> // size_t
struct InputEvent {
struct Player *player = 0;
virtual void apply(struct Game &) {}
virtual ~InputEvent() {}
static InputEvent *parse(const char *, size_t);
};
struct Connect : InputEvent {
Connect() {}
void apply(struct Game &) override;
};
struct Disconnect : InputEvent {
Disconnect() {}
void apply(struct Game &) override;
};
| xzfc/agarsk | inputEvent.hpp | C++ | mit | 392 |
package be.ugent.oomt.labo3;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| VDBBjorn/Mobiele-applicaties | Labo_03/Labo3/app/src/main/java/be/ugent/oomt/labo3/MainActivity.java | Java | mit | 304 |
/*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
const expect = require('chai').expect;
const activateAndControlSW = require('../../../infra/testing/activate-and-control');
const cleanSWEnv = require('../../../infra/testing/clean-sw');
const runInSW = require('../../../infra/testing/comlink/node-interface');
describe(`[workbox-precaching] cleanupOutdatedCaches()`, function () {
const baseURL = `${global.__workbox.server.getAddress()}/test/workbox-precaching/static/cleanup-outdated-caches/`;
beforeEach(async function () {
// Navigate to our test page and clear all caches before this test runs.
await cleanSWEnv(global.__workbox.webdriver, `${baseURL}integration.html`);
});
it(`should clean up outdated precached after activation`, async function () {
// Add an item to an outdated cache.
const preActivateKeys = await global.__workbox.webdriver.executeAsyncScript(
(cb) => {
// Opening a cache with a given name will cause it to "exist", even if it's empty.
caches
.open(
'workbox-precache-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
)
.then(() => caches.keys())
.then((keys) => cb(keys))
.catch((err) => cb(err.message));
},
);
expect(preActivateKeys).to.include(
'workbox-precache-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
expect(preActivateKeys).to.not.include(
'workbox-precache-v2-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
// Register the first service worker.
await activateAndControlSW(`${baseURL}sw.js`);
const postActivateKeys = await runInSW('cachesKeys');
expect(postActivateKeys).to.not.include(
'workbox-precache-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
expect(postActivateKeys).to.include(
'workbox-precache-v2-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
});
});
| GoogleChrome/workbox | test/workbox-precaching/integration/test-cleanup-outdated-caches.js | JavaScript | mit | 2,212 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run regression test suite.
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts.
Functional tests are disabled on Windows by default. Use --force to run them anyway.
For a description of arguments recognized by test scripts, see
`test/functional/test_framework/test_framework.py:BitcoinTestFramework.main`.
"""
import argparse
import configparser
import os
import time
import shutil
import sys
import subprocess
import tempfile
import re
import logging
# Formatting. Default colors to empty strings.
BOLD, BLUE, RED, GREY = ("", ""), ("", ""), ("", ""), ("", "")
TICK = "✓ "
CROSS = "✖ "
CIRCLE = "○ "
if os.name == 'posix':
# primitive formatting on supported
# terminal via ANSI escape sequences:
BOLD = ('\033[0m', '\033[1m')
BLUE = ('\033[0m', '\033[0;34m')
RED = ('\033[0m', '\033[0;31m')
GREY = ('\033[0m', '\033[1;30m')
TEST_EXIT_PASSED = 0
TEST_EXIT_SKIPPED = 77
BASE_SCRIPTS= [
# Scripts that are run by the travis build process.
# Longest test should go first, to favor running tests in parallel
'wallet-hd.py',
'walletbackup.py',
# vv Tests less than 5m vv
'p2p-fullblocktest.py',
'fundrawtransaction.py',
'p2p-compactblocks.py',
'segwit.py',
# vv Tests less than 2m vv
'wallet.py',
'wallet-accounts.py',
'p2p-segwit.py',
'wallet-dump.py',
'listtransactions.py',
# vv Tests less than 60s vv
'sendheaders.py',
'zapwallettxes.py',
'importmulti.py',
'mempool_limit.py',
'merkle_blocks.py',
'receivedby.py',
'abandonconflict.py',
'bip68-112-113-p2p.py',
'rawtransactions.py',
'reindex.py',
# vv Tests less than 30s vv
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
'getchaintips.py',
'rest.py',
'mempool_spendcoinbase.py',
'mempool_reorg.py',
'httpbasics.py',
'multi_rpc.py',
'proxy_test.py',
'signrawtransactions.py',
'nodehandling.py',
'decodescript.py',
'blockchain.py',
'disablewallet.py',
'net.py',
'keypool.py',
'p2p-mempool.py',
'prioritise_transaction.py',
'invalidblockrequest.py',
'invalidtxrequest.py',
'p2p-versionbits-warning.py',
'preciousblock.py',
'importprunedfunds.py',
'signmessages.py',
'nulldummy.py',
'import-rescan.py',
'bumpfee.py',
'rpcnamedargs.py',
'listsinceblock.py',
'p2p-leaktests.py',
]
ZMQ_SCRIPTS = [
# ZMQ test can only be run if bitcoin was built with zmq-enabled.
# call test_runner.py with -nozmq to explicitly exclude these tests.
'zmq_test.py']
EXTENDED_SCRIPTS = [
# These tests are not run by the travis build process.
# Longest test should go first, to favor running tests in parallel
'pruning.py',
# vv Tests less than 20m vv
'smartfees.py',
# vv Tests less than 5m vv
'maxuploadtarget.py',
'mempool_packages.py',
# vv Tests less than 2m vv
'bip68-sequence.py',
'getblocktemplate_longpoll.py',
'p2p-timeouts.py',
# vv Tests less than 60s vv
'bip9-softforks.py',
'p2p-feefilter.py',
'rpcbind_test.py',
# vv Tests less than 30s vv
'assumevalid.py',
'bip65-cltv.py',
'bip65-cltv-p2p.py',
'bipdersig-p2p.py',
'bipdersig.py',
'getblocktemplate_proposals.py',
'txn_doublespend.py',
'txn_clone.py --mineblock',
'forknotify.py',
'invalidateblock.py',
'maxblocksinflight.py',
'p2p-acceptblock.py',
'replace-by-fee.py',
]
ALL_SCRIPTS = BASE_SCRIPTS + ZMQ_SCRIPTS + EXTENDED_SCRIPTS
NON_SCRIPTS = [
# These are python files that live in the functional tests directory, but are not test scripts.
"combine_logs.py",
"create_cache.py",
"test_runner.py",
]
def main():
# Parse arguments and pass through unrecognised args
parser = argparse.ArgumentParser(add_help=False,
usage='%(prog)s [test_runner.py options] [script options] [scripts]',
description=__doc__,
epilog='''
Help text and arguments for individual test script:''',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
parser.add_argument('--exclude', '-x', help='specify a comma-seperated-list of scripts to exclude. Do not include the .py extension in the name.')
parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
parser.add_argument('--force', '-f', action='store_true', help='run tests even on platforms where they are disabled by default (e.g. windows).')
parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
parser.add_argument('--quiet', '-q', action='store_true', help='only print results summary and failure logs')
parser.add_argument('--nozmq', action='store_true', help='do not run the zmq tests')
args, unknown_args = parser.parse_known_args()
# Create a set to store arguments and create the passon string
tests = set(arg for arg in unknown_args if arg[:2] != "--")
passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
# Read config generated by configure.
config = configparser.ConfigParser()
config.read_file(open(os.path.dirname(__file__) + "/config.ini"))
# Set up logging
logging_level = logging.INFO if args.quiet else logging.DEBUG
logging.basicConfig(format='%(message)s', level=logging_level)
enable_wallet = config["components"].getboolean("ENABLE_WALLET")
enable_utils = config["components"].getboolean("ENABLE_UTILS")
enable_bitcoind = config["components"].getboolean("ENABLE_BITCOIND")
enable_zmq = config["components"].getboolean("ENABLE_ZMQ") and not args.nozmq
if config["environment"]["EXEEXT"] == ".exe" and not args.force:
# https://github.com/bitcoin/bitcoin/commit/d52802551752140cf41f0d9a225a43e84404d3e9
# https://github.com/bitcoin/bitcoin/pull/5677#issuecomment-136646964
print("Tests currently disabled on Windows by default. Use --force option to enable")
sys.exit(0)
if not (enable_wallet and enable_utils and enable_bitcoind):
print("No functional tests to run. Wallet, utils, and bitcoind must all be enabled")
print("Rerun `configure` with -enable-wallet, -with-utils and -with-daemon and rerun make")
sys.exit(0)
# python3-zmq may not be installed. Handle this gracefully and with some helpful info
if enable_zmq:
try:
import zmq
except ImportError:
print("ERROR: \"import zmq\" failed. Use -nozmq to run without the ZMQ tests."
"To run zmq tests, see dependency info in /test/README.md.")
raise
# Build list of tests
if tests:
# Individual tests have been specified. Run specified tests that exist
# in the ALL_SCRIPTS list. Accept the name with or without .py extension.
test_list = [t for t in ALL_SCRIPTS if
(t in tests or re.sub(".py$", "", t) in tests)]
else:
# No individual tests have been specified. Run base tests, and
# optionally ZMQ tests and extended tests.
test_list = BASE_SCRIPTS
if enable_zmq:
test_list += ZMQ_SCRIPTS
if args.extended:
test_list += EXTENDED_SCRIPTS
# TODO: BASE_SCRIPTS and EXTENDED_SCRIPTS are sorted by runtime
# (for parallel running efficiency). This combined list will is no
# longer sorted.
# Remove the test cases that the user has explicitly asked to exclude.
if args.exclude:
for exclude_test in args.exclude.split(','):
if exclude_test + ".py" in test_list:
test_list.remove(exclude_test + ".py")
if not test_list:
print("No valid test scripts specified. Check that your test is in one "
"of the test lists in test_runner.py, or run test_runner.py with no arguments to run all tests")
sys.exit(0)
if args.help:
# Print help for test_runner.py, then print help of the first script (with args removed) and exit.
parser.print_help()
subprocess.check_call([(config["environment"]["SRCDIR"] + '/test/functional/' + test_list[0].split()[0])] + ['-h'])
sys.exit(0)
check_script_list(config["environment"]["SRCDIR"])
run_tests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], args.jobs, args.coverage, passon_args)
def run_tests(test_list, src_dir, build_dir, exeext, jobs=1, enable_coverage=False, args=[]):
#Set env vars
if "BITCOIND" not in os.environ:
os.environ["BITCOIND"] = build_dir + '/src/bitcoind' + exeext
tests_dir = src_dir + '/test/functional/'
flags = ["--srcdir={}/src".format(build_dir)] + args
flags.append("--cachedir=%s/test/cache" % build_dir)
if enable_coverage:
coverage = RPCCoverage()
flags.append(coverage.flag)
logging.debug("Initializing coverage directory at %s" % coverage.dir)
else:
coverage = None
if len(test_list) > 1 and jobs > 1:
# Populate cache
subprocess.check_output([tests_dir + 'create_cache.py'] + flags)
#Run Tests
job_queue = TestHandler(jobs, tests_dir, test_list, flags)
time0 = time.time()
test_results = []
max_len_name = len(max(test_list, key=len))
for _ in range(len(test_list)):
test_result, stdout, stderr = job_queue.get_next()
test_results.append(test_result)
if test_result.status == "Passed":
logging.debug("\n%s%s%s passed, Duration: %s s" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
elif test_result.status == "Skipped":
logging.debug("\n%s%s%s skipped" % (BOLD[1], test_result.name, BOLD[0]))
else:
print("\n%s%s%s failed, Duration: %s s\n" % (BOLD[1], test_result.name, BOLD[0], test_result.time))
print(BOLD[1] + 'stdout:\n' + BOLD[0] + stdout + '\n')
print(BOLD[1] + 'stderr:\n' + BOLD[0] + stderr + '\n')
print_results(test_results, max_len_name, (int(time.time() - time0)))
if coverage:
coverage.report_rpc_coverage()
logging.debug("Cleaning up coverage data")
coverage.cleanup()
all_passed = all(map(lambda test_result: test_result.status == "Passed", test_results))
sys.exit(not all_passed)
def print_results(test_results, max_len_name, runtime):
results = "\n" + BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "STATUS ", "DURATION") + BOLD[0]
test_results.sort(key=lambda result: result.name.lower())
all_passed = True
time_sum = 0
for test_result in test_results:
all_passed = all_passed and test_result.status != "Failed"
time_sum += test_result.time
test_result.padding = max_len_name
results += str(test_result)
status = TICK + "Passed" if all_passed else CROSS + "Failed"
results += BOLD[1] + "\n%s | %s | %s s (accumulated) \n" % ("ALL".ljust(max_len_name), status.ljust(9), time_sum) + BOLD[0]
results += "Runtime: %s s\n" % (runtime)
print(results)
class TestHandler:
"""
Trigger the testscrips passed in via the list.
"""
def __init__(self, num_tests_parallel, tests_dir, test_list=None, flags=None):
assert(num_tests_parallel >= 1)
self.num_jobs = num_tests_parallel
self.tests_dir = tests_dir
self.test_list = test_list
self.flags = flags
self.num_running = 0
# In case there is a graveyard of zombie bitcoinds, we can apply a
# pseudorandom offset to hopefully jump over them.
# (625 is PORT_RANGE/MAX_NODES)
self.portseed_offset = int(time.time() * 1000) % 625
self.jobs = []
def get_next(self):
while self.num_running < self.num_jobs and self.test_list:
# Add tests
self.num_running += 1
t = self.test_list.pop(0)
port_seed = ["--portseed={}".format(len(self.test_list) + self.portseed_offset)]
log_stdout = tempfile.SpooledTemporaryFile(max_size=2**16)
log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16)
test_argv = t.split()
self.jobs.append((t,
time.time(),
subprocess.Popen([self.tests_dir + test_argv[0]] + test_argv[1:] + self.flags + port_seed,
universal_newlines=True,
stdout=log_stdout,
stderr=log_stderr),
log_stdout,
log_stderr))
if not self.jobs:
raise IndexError('pop from empty list')
while True:
# Return first proc that finishes
time.sleep(.5)
for j in self.jobs:
(name, time0, proc, log_out, log_err) = j
if proc.poll() is not None:
log_out.seek(0), log_err.seek(0)
[stdout, stderr] = [l.read().decode('utf-8') for l in (log_out, log_err)]
log_out.close(), log_err.close()
if proc.returncode == TEST_EXIT_PASSED and stderr == "":
status = "Passed"
elif proc.returncode == TEST_EXIT_SKIPPED:
status = "Skipped"
else:
status = "Failed"
self.num_running -= 1
self.jobs.remove(j)
return TestResult(name, status, int(time.time() - time0)), stdout, stderr
print('.', end='', flush=True)
class TestResult():
def __init__(self, name, status, time):
self.name = name
self.status = status
self.time = time
self.padding = 0
def __repr__(self):
if self.status == "Passed":
color = BLUE
glyph = TICK
elif self.status == "Failed":
color = RED
glyph = CROSS
elif self.status == "Skipped":
color = GREY
glyph = CIRCLE
return color[1] + "%s | %s%s | %s s\n" % (self.name.ljust(self.padding), glyph, self.status.ljust(7), self.time) + color[0]
def check_script_list(src_dir):
"""Check scripts directory.
Check that there are no scripts in the functional tests directory which are
not being run by pull-tester.py."""
script_dir = src_dir + '/test/functional/'
python_files = set([t for t in os.listdir(script_dir) if t[-3:] == ".py"])
missed_tests = list(python_files - set(map(lambda x: x.split()[0], ALL_SCRIPTS + NON_SCRIPTS)))
if len(missed_tests) != 0:
print("The following scripts are not being run:" + str(missed_tests))
print("Check the test lists in test_runner.py")
sys.exit(1)
class RPCCoverage(object):
"""
Coverage reporting utilities for test_runner.
Coverage calculation works by having each test script subprocess write
coverage files into a particular directory. These files contain the RPC
commands invoked during testing, as well as a complete listing of RPC
commands per `bitcoin-cli help` (`rpc_interface.txt`).
After all tests complete, the commands run are combined and diff'd against
the complete list to calculate uncovered RPC commands.
See also: test/functional/test_framework/coverage.py
"""
def __init__(self):
self.dir = tempfile.mkdtemp(prefix="coverage")
self.flag = '--coveragedir=%s' % self.dir
def report_rpc_coverage(self):
"""
Print out RPC commands that were unexercised by tests.
"""
uncovered = self._get_uncovered_rpc_commands()
if uncovered:
print("Uncovered RPC commands:")
print("".join((" - %s\n" % i) for i in sorted(uncovered)))
else:
print("All RPC commands covered.")
def cleanup(self):
return shutil.rmtree(self.dir)
def _get_uncovered_rpc_commands(self):
"""
Return a set of currently untested RPC commands.
"""
# This is shared from `test/functional/test-framework/coverage.py`
reference_filename = 'rpc_interface.txt'
coverage_file_prefix = 'coverage.'
coverage_ref_filename = os.path.join(self.dir, reference_filename)
coverage_filenames = set()
all_cmds = set()
covered_cmds = set()
if not os.path.isfile(coverage_ref_filename):
raise RuntimeError("No coverage reference found")
with open(coverage_ref_filename, 'r') as f:
all_cmds.update([i.strip() for i in f.readlines()])
for root, dirs, files in os.walk(self.dir):
for filename in files:
if filename.startswith(coverage_file_prefix):
coverage_filenames.add(os.path.join(root, filename))
for filename in coverage_filenames:
with open(filename, 'r') as f:
covered_cmds.update([i.strip() for i in f.readlines()])
return all_cmds - covered_cmds
if __name__ == '__main__':
main()
| jimmysong/bitcoin | test/functional/test_runner.py | Python | mit | 17,927 |
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
| xingjian-f/Leetcode-solution | 30. Substring with Concatenation of All Words.py | Python | mit | 173 |
#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
// unitlist.append(BTC);
unitlist.append(mBTC);
// unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
return QString::fromUtf8("Chips");
switch(unit)
{
case BTC: return QString("BTC");
case mBTC: return QString("mBTC");
case uBTC: return QString::fromUtf8("μBTC");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
return QString("Chips");
switch(unit)
{
case BTC: return QString("Bitcoins");
case mBTC: return QString("Milli-Bitcoins (1 / 1,000)");
case uBTC: return QString("Micro-Bitcoins (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
return 100000;
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess 0's after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| bitchip/bitchip | src/qt/bitcoinunits.cpp | C++ | mit | 4,375 |
package test
import (
"net/http"
"net/http/httptest"
"testing"
"runtime"
"path/filepath"
_ "github.com/vladiibine/go-beego-already/src/routers"
"github.com/astaxie/beego"
. "github.com/smartystreets/goconvey/convey"
)
func init() {
_, file, _, _ := runtime.Caller(1)
apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".." + string(filepath.Separator))))
beego.TestBeegoInit(apppath)
}
// TestMain is a sample to run an endpoint test
func TestMain(t *testing.T) {
r, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
beego.BeeApp.Handlers.ServeHTTP(w, r)
beego.Trace("testing", "TestMain", "Code[%d]\n%s", w.Code, w.Body.String())
Convey("Subject: Test Station Endpoint\n", t, func() {
Convey("Status Code Should Be 200", func() {
So(w.Code, ShouldEqual, 200)
})
Convey("The Result Should Not Be Empty", func() {
So(w.Body.Len(), ShouldBeGreaterThan, 0)
})
})
}
| vladiibine/go-beego-already | src/tests/default_test.go | GO | mit | 982 |
require 'test_helper'
class Test50Test < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| thejhubbs/permissionary | test/dummy/test/models/test50_test.rb | Ruby | mit | 120 |
import { AudioStreamFormat } from 'microsoft-cognitiveservices-speech-sdk';
export { AudioStreamFormat };
| billba/botchat | packages/testharness/pre/external/microsoft-cognitiveservices-speech-sdk/index.js | JavaScript | mit | 107 |
app.controller('MapsCTRL2', function($scope) {
app.value('NEW_TODO_ID', -1);
app.service('mapService', function () {
var map;
this.setMap = function (myMap) {
map = myMap;
};
this.getMap = function () {
if (map) return map;
throw new Error("Map not defined");
};
this.getLatLng = function () {
var center = map.getCenter();
return {
lat: center.lat(),
lng: center.lng()
};
};
});
app.service('todosService', function ($filter) {
// nextId and list both have mock starting data
this.nextId = 4;
this.items = [
{
id: 1,
completed: false,
title: 'Play Tennis',
desc: '',
lat: 43.09278984218124,
lng: -89.36774236078266
}, {
id: 2,
completed: true,
title: 'Buy Groceries',
desc: 'Steak, Pasta, Spinach',
lat: 43.06487353914984,
lng: -89.41749499107603
}, {
id: 3,
completed: false,
title: 'Picnic Time',
desc: 'Hang out with friends',
lat: 43.0869882068853,
lng: -89.42141638065578
}
];
this.filter = {};
this.filtered = function () {
return $filter('filter')(this.items, this.filter);
};
this.remainingCount = function () {
return $filter('filter')(this.items, {completed: false}).length;
};
this.getTodoById = function (todoId) {
var todo, i;
for (i = this.items.length - 1; i >= 0; i--) {
todo = this.items[i];
if (todo.id === todoId) {
return todo;
}
}
return false;
};
this.addTodo = function (title, desc, lat, lng) {
var newTodo = {
id: this.nextId++,
completed: false,
title: title,
desc: desc,
lat: lat,
lng: lng
};
this.items.push(newTodo);
};
this.updateTodo = function (todoId, title, desc, lat, lng, comp) {
var todo = this.getTodoById(todoId);
if (todo) {
todo.title = title;
todo.desc = desc;
todo.lat = lat;
todo.lng = lng;
todo.completed = comp;
todo.id = this.nextId++;
}
};
this.prune = function () {
var flag = false, i;
for (var i = this.items.length - 1; i >= 0; i--) {
if (this.items[i].completed) {
flag = true;
this.items.splice(i, 1);
}
}
if (flag) this.nextId++;
};
});
app.service('markersService', function () {
this.markers = [];
this.getMarkerByTodoId = function (todoId) {
var marker, i;
for (i = this.markers.length - 1; i >= 0; i--) {
marker = this.markers[i];
if (marker.get("id") === todoId) {
return marker;
}
}
return false;
};
});
app.service('infoWindowService', function (mapService) {
var infoWindow;
this.data = {};
this.registerInfoWindow = function (myInfoWindow) {
infowindow = myInfoWindow;
};
this.setData = function (todoId, todoTitle, todoDesc) {
this.data.id = todoId;
this.data.title = todoTitle;
this.data.desc = todoDesc;
};
this.open = function (marker) {
infowindow.open(mapService.getMap(), marker);
};
this.close = function () {
if (infowindow) {
infowindow.close();
this.data = {};
}
};
});
app.service('mapControlsService', function (infoWindowService, markersService, NEW_TODO_ID) {
this.editTodo = false;
this.editTodoId = NEW_TODO_ID;
this.newTodo = function () {
this.editTodoById();
};
this.editTodoById = function (todoId) {
this.editTodoId = todoId || NEW_TODO_ID;
this.editTodo = true;
};
this.openInfoWindowByTodoId = function (todoId) {
var marker = markersService.getMarkerByTodoId(todoId);
if (marker) {
infoWindowService.setData(todoId, marker.getTitle(), marker.get("desc"));
infoWindowService.open(marker);
return;
}
};
});
app.controller('EditTodoCtrl', function ($scope, mapService, todosService, infoWindowService, mapControlsService, NEW_TODO_ID) {
var editPinImage,
editMarker;
$scope.editTodo = {};
// editMarker Setup Start
editPinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + "55FF00",
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
editMarker = new google.maps.Marker({
title: "Drag Me",
draggable: true,
clickable: false,
icon: editPinImage,
position: new google.maps.LatLng(0, 0)
});
function editMarkerDragCallback (scope, myMarker) {
return function () {
var pos = myMarker.getPosition();
scope.editTodo.lat = pos.lat();
scope.editTodo.lng = pos.lng();
if(!scope.$$phase) scope.$apply();
};
}
google.maps.event.addListener(editMarker, 'drag', editMarkerDragCallback($scope, editMarker));
function editMarkerDblClickCallback (scope) {
return function () {
scope.$apply(function () {
scope.submitTodo();
});
};
}
google.maps.event.addListener(editMarker, 'dblclick', editMarkerDblClickCallback($scope));
$scope.$watch('editTodo.lat + editTodo.lng', function (newValue, oldValue) {
if (newValue !== oldValue) {
var pos = editMarker.getPosition(),
latitude = pos.lat(),
longitude = pos.lng();
if ($scope.editTodo.lat !== latitude || $scope.editTodo.lng !== longitude)
editMarker.setPosition(new google.maps.LatLng($scope.editTodo.lat || 0, $scope.editTodo.lng || 0));
}
});
// editMarker Setup End
$scope.$watch('controls.editTodo + controls.editTodoId', function () {
var pos, todo = mapControlsService.editTodoId !== NEW_TODO_ID && todosService.getTodoById(mapControlsService.editTodoId);
infoWindowService.close();
if (mapControlsService.editTodo) {
if (todo) {
$scope.editTodo = {
id: todo.id,
title: todo.title,
desc: todo.desc,
lat: todo.lat,
lng: todo.lng,
comp: todo.completed,
saveMsg: "Update Todo",
cancelMsg: "Discard Changes"
};
} else {
pos = mapService.getLatLng();
$scope.editTodo = {
id: NEW_TODO_ID,
lat: pos.lat,
lng: pos.lng,
saveMsg: "Save Todo",
cancelMsg: "Discard Todo"
};
}
editMarker.setMap(mapService.getMap());
}
});
$scope.submitTodo = function () {
if ($scope.editTodoForm.$valid) {
if ($scope.editTodo.id === NEW_TODO_ID)
addTodo();
else
editTodo();
}
}
$scope.resetCloseTodoForm = function () {
editMarker.setMap(null);
mapControlsService.editTodo = false;
mapControlsService.editTodoId = NEW_TODO_ID;
$scope.editTodo = {};
}
function addTodo () {
todosService.addTodo(
$scope.editTodo.title,
$scope.editTodo.desc,
$scope.editTodo.lat,
$scope.editTodo.lng);
$scope.resetCloseTodoForm();
}
function editTodo () {
todosService.updateTodo(
$scope.editTodo.id,
$scope.editTodo.title,
$scope.editTodo.desc,
$scope.editTodo.lat,
$scope.editTodo.lng,
$scope.editTodo.comp);
$scope.resetCloseTodoForm();
}
});
app.directive('todoMaps', function ($compile) {
return {
controller: function ($scope, $location, mapService, mapControlsService, infoWindowService, todosService, markersService) {
if ($location.path() === '') {
$location.path('/');
}
$scope.location = $location;
$scope.infow = infoWindowService;
$scope.controls = mapControlsService;
this.registerInfoWindow = function (myInfoWindow) {
infoWindowService.registerInfoWindow(myInfoWindow);
};
this.registerMap = function (myMap) {
mapService.setMap(myMap);
$scope.todos = todosService;
};
$scope.$watch('location.path()', function (path) {
todosService.filter = (path === '/active') ?
{ completed: false } : (path === '/completed') ?
{ completed: true } : null;
});
$scope.$watch('location.path() + todos.nextId + todos.remainingCount()', function () {
var i,
todos = todosService.filtered(),
map = mapService.getMap(),
todoId,
marker,
markers = markersService.markers,
markerId,
uniqueTodos = {};
function addMarkerByTodoIndex (todoIndex) {
var marker,
markerOptions,
todo = todos[todoIndex];
markerOptions = {
map: map,
title: todo.title,
position: new google.maps.LatLng(todo.lat, todo.lng)
};
marker = new google.maps.Marker(markerOptions);
marker.setValues({
id: todo.id,
desc: todo.desc
});
markersService.markers.push(marker);
function markerClickCallback (scope, todoId) {
return function () {
scope.$apply(function () {
mapControlsService.openInfoWindowByTodoId(todoId);
});
};
}
google.maps.event.addListener(marker, 'click', markerClickCallback($scope, todo.id));
function markerDblClickCallback (scope, todoId) {
return function () {
scope.$apply(function () {
mapControlsService.editTodoById(todoId);
});
};
}
google.maps.event.addListener(marker, 'dblclick', markerDblClickCallback($scope, todo.id));
}
for (i = todos.length - 1; i >= 0; i--) {
uniqueTodos[todos[i].id] = i;
}
for (i = markers.length - 1; i >= 0; i--) {
marker = markers[i];
markerId = marker.get("id");
if (uniqueTodos[markerId] !== undefined) {
delete uniqueTodos[markerId];
} else {
marker.setMap(null);
markers.splice(i,1);
}
}
for (todoId in uniqueTodos) {
if (uniqueTodos.hasOwnProperty(todoId)) {
addMarkerByTodoIndex(uniqueTodos[todoId]);
}
}
});
},
link: function (scope, elem, attrs, ctrl) {
var mapOptions,
latitude = attrs.latitude,
longitude = attrs.longitude,
infoWindowTemplate,
infoWindowElem,
infowindow,
todosControlTemplate,
todosControlElem,
editTodoControlTemplate,
editTodoControlElem,
mapStyles,
map;
latitude = latitude && parseFloat(latitude, 10) || 43.074688;
longitude = longitude && parseFloat(longitude, 10) || -89.384294;
infoWindowTemplate = document.getElementById('infoWindowTemplate').innerHTML.trim();
infoWindowElem = $compile(infoWindowTemplate)(scope);
infowindow = new google.maps.InfoWindow({
content: infoWindowElem[0]
});
ctrl.registerInfoWindow(infowindow);
mapStyles = [{
featureType: 'water',
stylers: [
{hue: '#000b0'},
{invert_lightness: 'false'},
{saturation: -30}
]
}];
mapOptions = {
zoom: 12,
disableDefaultUI: false,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: mapStyles
};
google.maps.visualRefresh = true;
map = new google.maps.Map(elem[0], mapOptions);
ctrl.registerMap(map);
todosControlTemplate = document.getElementById('todosControlTemplate').innerHTML.trim();
todosControlElem = $compile(todosControlTemplate)(scope);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(todosControlElem[0]);
editTodoControlTemplate = document.getElementById('editTodoControlTemplate').innerHTML.trim();
editTodoControlElem = $compile(editTodoControlTemplate)(scope);
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(editTodoControlElem[0]);
}
};
});
}); | hopeeen/instaApp | www/scripts/controllers/maps2.js | JavaScript | mit | 13,504 |
import mongoose from 'mongoose';
import request from 'supertest-as-promised';
import httpStatus from 'http-status';
import chai, { expect } from 'chai';
import app from '../../index';
chai.config.includeStack = true;
/**
* root level hooks
*/
after((done) => {
// required because https://github.com/Automattic/mongoose/issues/1251#issuecomment-65793092
mongoose.models = {};
mongoose.modelSchemas = {};
mongoose.connection.close();
done();
});
before()
describe('## User APIs', () => {
let user = {
username: 'KK123',
mobileNumber: '1234567890'
};
describe('# POST /api/users', () => {
it('should create a new user', (done) => {
request(app)
.post('/api/users')
.send(user)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal(user.username);
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
user = res.body;
done();
})
.catch(done);
});
});
describe('# GET /api/users/:userId', () => {
it('should get user details', (done) => {
request(app)
.get(`/api/users/${user._id}`)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal(user.username);
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
done();
})
.catch(done);
});
it('should report error with message - Not found, when user does not exists', (done) => {
request(app)
.get('/api/users/56c787ccc67fc16ccc1a5e92')
.expect(httpStatus.NOT_FOUND)
.then((res) => {
expect(res.body.message).to.equal('Not Found');
done();
})
.catch(done);
});
});
describe('# PUT /api/users/:userId', () => {
it('should update user details', (done) => {
user.username = 'KK';
request(app)
.put(`/api/users/${user._id}`)
.send(user)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal('KK');
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
done();
})
.catch(done);
});
});
describe('# GET /api/users/', () => {
it('should get all users', (done) => {
request(app)
.get('/api/users')
.expect(httpStatus.OK)
.then((res) => {
expect(res.body).to.be.an('array');
done();
})
.catch(done);
});
it('should get all users (with limit and skip)', (done) => {
request(app)
.get('/api/users')
.query({ limit: 10, skip: 1 })
.expect(httpStatus.OK)
.then((res) => {
expect(res.body).to.be.an('array');
done();
})
.catch(done);
});
});
describe('# DELETE /api/users/', () => {
it('should delete user', (done) => {
request(app)
.delete(`/api/users/${user._id}`)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal('KK');
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
done();
})
.catch(done);
});
});
});
| CaptainSid/WarSid-Swissport | server/tests/Compte.test.js | JavaScript | mit | 3,205 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AppActions from '../../actions/AppActions';
/*
|--------------------------------------------------------------------------
| Child - Audio settings
|--------------------------------------------------------------------------
*/
export default class SettingsAudio extends Component {
static propTypes = {
config: PropTypes.object,
}
constructor(props) {
super(props);
}
setPlaybackRate(e) {
AppActions.player.setPlaybackRate(e.currentTarget.value);
}
render() {
const config = this.props.config;
return (
<div className='setting setting-audio'>
<div className='setting-section'>
<h4>Playback rate</h4>
<div className='formGroup'>
<label>
Increase the playback rate: a value of 2 will play your music at a 2x speed
</label>
<input type='number'
className='form-control'
defaultValue={config.audioPlaybackRate}
onChange={this.setPlaybackRate}
min='0.5'
max='5'
step='0.1'
/>
</div>
</div>
</div>
);
}
}
| Eeltech/SpaceMusik | src/ui/components/Settings/SettingsAudio.react.js | JavaScript | mit | 1,248 |
var path = require('path');
var config = {
contentBase: path.join(__dirname, "docs"),
watchContentBase: true,
host: 'localhost',
port: 8080,
// Recommended for hot module replacement
hot: true,
inline: true,
// Open the browser does not work when webpack dev server called from node.
// open: true,
// Showing errors
overlay: {
errors: true,
warnings: true,
},
// Proxy API requests
// proxy: {
// 'api': "http://localhost:3000"
// },
// Show only error information
stats: "errors-only",
// Using HTML 5 History API Webpack Dev Server will redirect routes to index.html, so SPA can handle it
historyApiFallback: true,
};
module.exports = config; | manu-garcia/react-pwa-from-scratch | webpack.devserver.config.js | JavaScript | mit | 712 |
using System.IO;
namespace Benchmark
{
using System;
using System.Diagnostics;
public static unsafe class Benchmark
{
private const string OutputFilename = "results.csv";
private static readonly double TicksPerMicrosecond = (double)Stopwatch.Frequency/1000000;
private static StreamWriter outputFile = null;
public static void Main(string[] args)
{
var random = false;
var arraySize = -1;
if (args.Length > 0)
{
random = bool.Parse(args[0]);
}
if (args.Length > 1)
{
arraySize = int.Parse(args[1]);
}
// Do some warmup to ensure JITing occurs
RunBenchmark(1000, false, true);
using (outputFile = new StreamWriter(OutputFilename))
{
outputFile.WriteLine("Test,Array Size,Type,Execution Time (us)");
if (arraySize > 0)
{
RunBenchmark(arraySize, random, false);
}
else
{
for (var i = 10; i < 1000000; i *= 10)
{
RunBenchmark(i, false, false);
RunBenchmark(i, true, false);
}
}
}
}
private static void RunBenchmark(int size, bool random, bool silent)
{
var array = Generate(size, random);
BenchmarkArray(silent ? null : "inline safe", array, random, InlineSafeSort);
BenchmarkArray(silent ? null : "nested safe", array, random, NestedSafeSort);
BenchmarkArray(silent ? null : "inline unsafe", array, random, InlineUnsafeSort);
BenchmarkArray(silent ? null : "nested unsafe", array, random, NestedUnsafeSort);
}
private static void BenchmarkArray(string name, int[] array, bool random, Action<int[]> runner)
{
var arrayCopy = new int[array.Length];
Buffer.BlockCopy(array, 0, arrayCopy, 0, array.Length);
GC.Collect(2);
var watch = new Stopwatch();
watch.Start();
runner(arrayCopy);
watch.Stop();
Validate(arrayCopy);
if (name != null)
{
var data = string.Format("{0},{1},{2},{3}", name, array.Length, random ? "random" : "inverted",
watch.ElapsedTicks/TicksPerMicrosecond);
Console.WriteLine(data);
outputFile.WriteLine(data);
}
}
private static int[] Generate(int size, bool random)
{
var array = new int[size];
var rng = new Random();
for (var i = 0; i < size; ++i)
{
array[i] = (random ? rng.Next(size) : size - i);
}
return array;
}
private static void Validate(int[] array)
{
for (var i = 0; i < array.Length - 1; ++i)
{
if (array[i] > array[i + 1])
{
throw new Exception("Sort fail");
}
}
}
private static void InlineSafeSort(int[] array)
{
for (var i = 0; i < array.Length; ++i)
{
for (var j = i + 1; j < array.Length; ++j)
{
if (array[i] > array[j])
{
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
private static void NestedSafeSort(int[] array)
{
for (var i = 0; i < array.Length; ++i)
{
NestedSafeSortInner(array, i + 1);
}
}
private static void NestedSafeSortInner(int[] array, int startIndex)
{
var valueIndex = startIndex - 1;
for (var i = startIndex; i < array.Length; ++i)
{
if (array[valueIndex] > array[i])
{
var temp = array[valueIndex];
array[valueIndex] = array[i];
array[i] = temp;
}
}
}
private static void InlineUnsafeSort(int[] array)
{
fixed (int* a = array)
{
var end = a + array.Length;
for (var i = a; i < end; ++i)
{
for (var j = i + 1; j < end; ++j)
{
if (*i > *j)
{
var temp = *i;
*i = *j;
*j = temp;
}
}
}
}
}
private static void NestedUnsafeSort(int[] array)
{
fixed (int* a = array)
{
var end = a + array.Length;
for (var i = a; i < end; ++i)
{
NestedUnsafeSortInner(i + 1, end);
}
}
}
private static void NestedUnsafeSortInner(int* start, int* end)
{
var value = start - 1;
for (var i = start; i < end; ++i)
{
if (*value > *i)
{
var temp = *value;
*value = *i;
*i = temp;
}
}
}
}
} | doubleyewdee/dotnet-fixed-benchmark | src/Program.cs | C# | mit | 5,659 |
require_relative 'extensions/encoding_extensions'
require_relative 'extensions/string_extensions'
module Rubikey
class KeyConfig
using Rubikey::EncodingExtensions
using Rubikey::StringExtensions
attr_reader :public_id
attr_reader :secret_id
attr_reader :insert_counter
def initialize(unique_passcode, secret_key)
raise InvalidKey, 'Secret key must be 32 hexadecimal characters' unless secret_key.is_hexadecimal? && secret_key.length == 32
@unique_passcode = unique_passcode
@public_id = @unique_passcode.first(12)
decrypter = OpenSSL::Cipher.new('AES-128-ECB').decrypt
decrypter.key = secret_key.hexadecimal_to_binary
decrypter.padding = 0
@token = decrypter.update(base) + decrypter.final
raise BadRedundancyCheck unless cyclic_redundancy_check_is_valid?
@secret_id, @insert_counter, timestamp, timestamp_lo, session_counter, random_number, crc = @token.unpack('H12vvCCvv')
end
private
def base
@unique_passcode.last(32).modified_hexadecimal_to_binary
end
def cyclic_redundancy_check_is_valid?
crc = 0xffff
@token.each_byte do |byte|
crc ^= byte & 0xff
8.times do
test = (crc & 1) == 1
crc >>= 1
crc ^= 0x8408 if test
end
end
crc == 0xf0b8
end
end
end
| sigfrid/rubikey | lib/rubikey/key_config.rb | Ruby | mit | 1,393 |
package br.com.portalCliente.util.dateUtilities;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DateInterceptorUtils {
private static TimeZone tz = TimeZone.getTimeZone("America/Recife");
public static int FIRST_HOUR_DAY [] = {0,0,0};
public static int LAST_HOUR_DAY [] = {23,59,59};
public static boolean START_YEAR = true;
public static boolean END_YEAR = false;
public static Date startOrEndYear(Date date, boolean option){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
if(option){
calendar.set(Calendar.MONTH, 1 - 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
}
else{
calendar.set(Calendar.MONTH, 12 - 1);
calendar.set(Calendar.DAY_OF_MONTH, 31);
}
return calendar.getTime();
}
/**
* Esse método ira alterar o dia da data para o primeiro dia do mês
* <br />
* Se não for setado o parâmetro, o <b>Date</b> retornado será <b>Null</b>
* @param date
* @return Date
*/
public static Date firstDayOfMonth(Date date){
return genericDayOfMonth(date, null, true);
}
/**
* Esse método ira alterar o dia da data para o primeiro dia do mês
* <br />
* O parâmetro a ser passado no value é: SaleDateFactory.FIRST_HOUR_DAY ou SaleDateFactory.LAST_HOUR_DAY
* <br />
* Se não for setado nenhum dos parametros citados, o <b>Date</b> retornado será <b>Null</b>
* @param date, value
* @return <b>Date</b>
*/
public static Date firstDayOfMonth(Date date, int[] value){
return genericDayOfMonth(date, value, true);
}
// ------------------------------- iniciao de metodos para alterar o ultimo dia do mês -------------------
/**
* Esse método ira alterar o dia da data para o último dia do mês
* <br />
* Se não for setado o parâmetro, o <b>Date</b> retornado será <b>Null</b>
* @param date
* @return Date
*/
public static Date lastDayOfMonth(Date date){
return genericDayOfMonth(date, null, false);
}
/**
* Esse método ira alterar o dia da data para o último dia do mês
* <br />
* O parâmetro a ser passado no value é: SaleDateFactory.FIRST_HOUR_DAY ou SaleDateFactory.LAST_HOUR_DAY
* <br />
* Se não for setado nenhum dos parametros citados, o <b>Date</b> retornado será <b>Null</b>
* @param date, value
* @return <b>Date</b>
*/
public static Date lastDayOfMonth(Date date, int [] value){
return genericDayOfMonth(date, value, false);
}
// ---------------------------- Inicio dos metodos para alterar hora do dia ------------------------------
/**
* O parâmetro a ser passado no value é: SaleDateFactory.FIRST_HOUR_DAY ou SaleDateFactory.LAST_HOUR_DAY
* <br />
* Se não for setado nenhum dos parametros citados, o <b>Date</b> retornado será <b>Null</b>
* @param value
* @return <b>Date</b>
*/
public static Date firstOrLastHourOfDay(int [] value){
return firstOrLastHourOfDay(null, value);
}
/**
* O parâmetro a ser passado no value é: SaleDateFactory.FIRST_HOUR_DAY ou SaleDateFactory.LAST_HOUR_DAY
* <br />
* Se não for setado nenhum dos parametros citados, o <b>Date</b> retornado será <b>Null</b>
* @param value
* @return <b>Date</b>
*/
public static Date firstOrLastHourOfDay(Date date, int [] value){
Calendar calendar = Calendar.getInstance(tz);
Date resultDate = null;
if(date != null){
calendar.setTime(date);
}
if(value != null && value.length == 3){
calendar.set(Calendar.HOUR_OF_DAY, value[0]);
calendar.set(Calendar.MINUTE, value[1]);
calendar.set(Calendar.SECOND, value[2]);
resultDate = calendar.getTime();
}
return resultDate;
}
// ---------------------- métodos generico para primeira e última data do mês --------------------------
private static Date genericDayOfMonth(Date date, int [] value, boolean firstDay){
Calendar calendar = Calendar.getInstance(tz);
if(date == null){
return null;
}
Date dateResult = firstOrLastHourOfDay(date, value);
if(dateResult == null){
return null;
}
calendar.setTime(dateResult);
int day = 1;
if(!firstDay){
day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
calendar.set(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
public static Date setMinuteInDate(Date date, int hour, int minute, int second) {
try {
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.setTime(date);
dateCalendar.add(Calendar.HOUR_OF_DAY, hour);
dateCalendar.add(Calendar.MINUTE, minute);
dateCalendar.add(Calendar.SECOND, second);
return dateCalendar.getTime();
} catch (Exception e) {
return null;
}
}
public static Calendar getCalendarNotTime() {
return getCalendarNotTime(null);
}
public static Calendar getCalendarNotTime(Date date) {
Calendar dateCalendar = Calendar.getInstance(tz);
if(date != null){
dateCalendar.setTime(date);
}
dateCalendar.set(Calendar.HOUR_OF_DAY, 0);
dateCalendar.set(Calendar.MINUTE, 0);
dateCalendar.set(Calendar.SECOND, 0);
dateCalendar.set(Calendar.MILLISECOND, 0);
return dateCalendar;
}
} | dfslima/portalCliente | src/main/java/br/com/portalCliente/util/dateUtilities/DateInterceptorUtils.java | Java | mit | 5,148 |
// WARNING
//
// This file has been generated automatically by Xamarin Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace Thingamabot
{
[Register ("JoystickViewController")]
partial class JoystickViewController
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
JoystickControl joystick { get; set; }
void ReleaseDesignerOutlets ()
{
if (joystick != null) {
joystick.Dispose ();
joystick = null;
}
}
}
}
| petergolde/wheelchair-robot | iOS/Thingamabot/JoystickViewController.designer.cs | C# | mit | 602 |
%%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%
$project=Qt5xHb
$module=QtScriptTools
$header
#include <QtCore/Qt>
#ifndef __XHARBOUR__
#include <QtScriptTools/QtScriptToolsVersion>
#endif
#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#ifdef __XHARBOUR__
#include <QtScriptTools/QtScriptToolsVersion>
#endif
HB_FUNC( QTSCRIPTTOOLS_VERSION_STR )
{
hb_retc( (const char *) QTSCRIPTTOOLS_VERSION_STR );
}
HB_FUNC( QTSCRIPTTOOLS_VERSION )
{
hb_retni( QTSCRIPTTOOLS_VERSION );
}
| marcosgambeta/Qt5xHb | codegen/QtScriptTools/QtScriptToolsVersion.cpp | C++ | mit | 666 |
/**
Copyright (c) 2015, 2017, Oracle and/or its affiliates.
The Universal Permissive License (UPL), Version 1.0
*/
/**
* # oraclejet-build.js
* This script allows users to configure and customize the grunt build tasks.
* Configurable tasks include:
* copySrcToStaging
* copyCustomLibsToStaging
* injectTheme
* injectPaths
* uglify
* requireJs
* sass
* To configure a task, uncomment the corresponding sections below, and pass in your configurations.
* Any options will be merged with default configuration found in node_modules/oraclejet-tooling/lib/defaultconfig.js
* Any fileList options will replace the corresponding option defined by the default configuration in its entirety - ie. arrays are not merged.
*/
module.exports = function (grunt) {
return {
/**
* # copyCustomLibsToStaging
* This task copies any custom libraries that are not provided by JET to staging directory.
* This task supports a single option: fileList. The fileList option defines an array of file objects.
* Each file object contains the following properties:
* cwd, current working directory
* dest, destination path
* src, array of source file patterns
* rename, function to return the full path of desired destination
* If a fileList value is specified, it completely replaces the default fileList value defined by JET
* Example: {cwd: 'app', src: ['**', '!test.js'], dest: 'staging', rename: function (dest, file) {return renamed path}}
*/
copyCustomLibsToStaging: {
fileList: [
{cwd: 'node_modules/font-awesome/fonts', src: ['*'], dest: 'web/css/fonts/'},
{cwd: 'node_modules/font-awesome/css', src: ['*'], dest: 'web/css/font-awesome/'}
]
},
/**
* # copySrcToStaging
* This task copies all source files and libraries to staging directory.
* This task supports a single option: fileList. The fileList option defines an array of file objects.
* See descriptions and example in copyCustomLibsToStaging for configuring the fileList.
*/
// copySrcToStaging: {
// fileList: [],
// },
/**
* # injectTheme
* This task injects css stylesheet links for the current theme into index.html using the injection start and end markers defined below.
*/
// injectTheme: {
// startTag: '<!-- injector:theme -->',
// endTag: '<!-- endinjector -->'
// }
/**
* # injectPaths
* Configuration for path injection during build in release mode
* This task reads the release paths from the mainReleasePaths json file and injects the path configuration in main.js when run in release mode.
*/
// injectPaths: paths => ({
// startTag: '//injector:mainReleasePaths',
// endTag: '//endinjector',
// mainJs: 'path to mainjs',
// destMainJs: 'path to the inject destination',
// mainReleasePaths: 'path to the main-release-paths.json'
// }),
/**
* # uglify
* This task minifies source files and libraries that don't have minified distributions.
* It runs only when build in release mode. Support input of fileList that contains an array of file objects.
* See the example in copyCustomLibsToStaging for configuring the fileList.
* See detailed uglify options at https://github.com/mishoo/UglifyJS
*/
// uglify: {
// fileList: [{}],
// options: {}
// },
/**
* # requireJs
* This task runs requirejs optimizer to bundle all scripts in to a large minified main.js for release.
* It runs only when build in release mode.
* The task mirrors the configuration in this link https://github.com/gruntjs/grunt-contrib-requirejs
*/
// requireJs: {
// baseUrl: 'path to the js directory in staging area',
// name: 'the main.js file name',
// mainConfigFile: `the main configuration file`,
// optimize: 'option for optimize',
// out: 'output file path'
// },
/**
* # sass
* This task runs sass compile for scss files.
* It takes a fileList as input, see copyCustomLibsToStaging section for examples of fileList
* See detailed node sass options available here https://github.com/sass/node-sass
*/
// sass: {
// fileList: [],
// options: {}
// },
/**
* This is the web specific configuration. You can specify configurations targeted only for web apps.
* The web specific configurations will override the general configuration.
*/
web: {
},
/**
* This is the hybrid specific configuration. You can specify configurations targeted only hybrid apps.
* The hybrid specific configurations will override the general configuration.
*/
hybrid: {
}
};
};
| amalbose/media-manager | scripts/grunt/config/oraclejet-build.js | JavaScript | mit | 4,603 |
package mg.fishchicken.core.conditions;
import groovy.lang.Binding;
import java.util.Locale;
import mg.fishchicken.gamelogic.characters.GameCharacter;
import mg.fishchicken.gamelogic.characters.GameCharacter.Skill;
import mg.fishchicken.gamelogic.inventory.Inventory.ItemSlot;
import mg.fishchicken.gamelogic.inventory.items.InventoryItem;
import mg.fishchicken.gamelogic.inventory.items.Weapon;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.XmlReader.Element;
/**
* Returns true if the supplied character has a melee weapon equipped
* in any hand.
* <br /><br />
* If the optional parameter weaponSkill is defined, the weapon
* must be of that skill type.
* <br /><br />
* If the optional parameter dualWielding is set to true, a melee
* weapon must be equipped in both hands of the character.
*
* <br /><br />
* Example:
*
* <pre>
* <hasMeleeWeaponEquipped weaponSkill="Dagger" dualWielding = "true" />
* </pre>
*
* @author ANNUN
*
*/
public class HasMeleeWeaponEquipped extends Condition {
private static final String XML_WEAPON_SKILL = "weaponSkill";
private static final String XML_DUAL_WIELDING = "dualWielding";
@Override
protected boolean evaluate(Object object, Binding parameters) {
if (object instanceof GameCharacter) {
GameCharacter character = (GameCharacter) object;
String weaponSkillString = getParameter(XML_WEAPON_SKILL);
boolean dualWieldingOnly = Boolean.valueOf(getParameter(XML_DUAL_WIELDING));
InventoryItem leftHand = character.getInventory().getEquipped(ItemSlot.LEFTHAND);
InventoryItem rightHand = character.getInventory().getEquipped(ItemSlot.RIGHTHAND);
Skill leftHandSkill = null;
Skill righHandSkill = null;
if (!(leftHand instanceof Weapon) && !(rightHand instanceof Weapon)) {
return false;
}
boolean hasRightType = false;
boolean isDualWielding = true;
if (leftHand instanceof Weapon) {
leftHandSkill = ((Weapon) leftHand).getWeaponSkill();
hasRightType = !((Weapon) leftHand).isRanged();
if (!checkingForMelee()) {
hasRightType = !hasRightType;
}
} else {
isDualWielding = false;
}
if (rightHand instanceof Weapon) {
righHandSkill = ((Weapon) rightHand).getWeaponSkill();
hasRightType |= checkingForMelee() ? !((Weapon) rightHand)
.isRanged() : ((Weapon) rightHand).isRanged();
} else {
isDualWielding = false;
}
if (!hasRightType || (!isDualWielding && dualWieldingOnly)) {
return false;
}
// if no type was specified, any weapon will do, so we are done
if (weaponSkillString == null) {
return true;
}
Skill weaponSkill = Skill.valueOf(weaponSkillString.toUpperCase(Locale.ENGLISH));
if (!weaponSkill.equals(righHandSkill) && !weaponSkill.equals(leftHandSkill)) {
return false;
}
return true;
}
return false;
}
protected boolean checkingForMelee() {
return true;
}
@Override
protected String getStringTableNameKey() {
return Boolean.valueOf(getParameter(XML_DUAL_WIELDING)) ? "meleeWeaponEquippedDual" : "meleeWeaponEquipped";
}
@Override
public void validateAndLoadFromXML(Element conditionElement) {
String skillName = conditionElement.get(XML_WEAPON_SKILL, null);
if (skillName != null) {
try {
Skill.valueOf(skillName.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e){
throw new GdxRuntimeException(XML_WEAPON_SKILL+" contains invalid value "+skillName+", which is not an existing skill in condition "+this.getClass().getSimpleName()+" in element: \n\n"+conditionElement);
}
}
}
}
| mganzarcik/fabulae | core/src/mg/fishchicken/core/conditions/HasMeleeWeaponEquipped.java | Java | mit | 3,758 |
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ItemsComponent } from './items/items.component';
@NgModule({
declarations: [
AppComponent,
ItemsComponent
],
imports: [
BrowserModule
],
providers: [
Title
],
bootstrap: [AppComponent]
})
export class AppModule { }
| railsstudent/angular-30 | Day27-Click-And-Drag/src/app/app.module.ts | TypeScript | mit | 412 |
<?php
declare(strict_types = 1);
namespace Innmind\TimeContinuum\Earth\Timezone\Europe;
use Innmind\TimeContinuum\Earth\Timezone;
/**
* @psalm-immutable
*/
final class Simferopol extends Timezone
{
public function __construct()
{
parent::__construct('Europe/Simferopol');
}
}
| Innmind/TimeContinuum | src/Earth/Timezone/Europe/Simferopol.php | PHP | mit | 301 |
package live;
/**
* A class implements this interface can call back
* @author Han
*/
public interface Callback {
public void callback();
}
| haneev/TweetRetriever | src/live/Callback.java | Java | mit | 153 |
//---------------------------------------------------------------------------
// Copyright (c) 2016 Michael G. Brehm
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------
#include "stdafx.h"
#include "ExtentExtensions.h"
#include "Extent.h"
#include "Location.h"
#pragma warning(push, 4) // Enable maximum compiler warnings
namespace zuki::tools::llvm::clang::extensions {
//---------------------------------------------------------------------------
// ExtentExtensions::GetCharacterLength (static)
//
// Gets the length of the extent in characters by subtracting the end location
// offset from the start location
//
// Arguments:
//
// extent - Extent instance being extended
int ExtentExtensions::GetCharacterLength(Extent^ extent)
{
if(Object::ReferenceEquals(extent, nullptr)) throw gcnew ArgumentNullException("extent");
if(Extent::IsNull(extent)) return 0;
if(Location::IsNull(extent->Start) || Location::IsNull(extent->End)) return 0;
// This returns a signed integer for convenience, but never return a negative
return Math::Max(extent->End->Offset - extent->Start->Offset, 0);
}
//---------------------------------------------------------------------------
} // zuki::tools::llvm::clang::extensions
#pragma warning(pop)
| djp952/tools-llvm | clang/ExtentExtensions.cpp | C++ | mit | 2,354 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TriggerSAmples")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TriggerSAmples")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| CNinnovation/WPFWorkshopSep2016 | WPF/WPFSamples/TriggerSAmples/Properties/AssemblyInfo.cs | C# | mit | 2,387 |
package com.thales.ntis.subscriber.services;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.thales.ntis.subscriber.datex.BasicData;
import com.thales.ntis.subscriber.datex.D2LogicalModel;
import com.thales.ntis.subscriber.datex.ElaboratedData;
import com.thales.ntis.subscriber.datex.ElaboratedDataPublication;
import com.thales.ntis.subscriber.datex.LocationByReference;
import com.thales.ntis.subscriber.datex.TrafficConcentration;
import com.thales.ntis.subscriber.datex.TrafficFlow;
import com.thales.ntis.subscriber.datex.TrafficHeadway;
import com.thales.ntis.subscriber.datex.TrafficSpeed;
import com.thales.ntis.subscriber.datex.TravelTimeData;
/**
* This is an example service class implementation.
*
*/
@Service
public class FusedSensorOnlyTrafficDataServiceImpl implements TrafficDataService {
private static final Logger LOG = LoggerFactory.getLogger(FusedSensorOnlyTrafficDataServiceImpl.class);
private static final String PUBLICATION_TYPE = "Fused Sensor-Only Traffic Data Publication";
@Override
public void handle(D2LogicalModel d2LogicalModel) {
LOG.info(PUBLICATION_TYPE + ": received...");
ElaboratedDataPublication elaboratedDataPublication = null;
try {
elaboratedDataPublication = (ElaboratedDataPublication) d2LogicalModel.getPayloadPublication();
if (elaboratedDataPublication != null) {
List<ElaboratedData> elaboratedDataList = elaboratedDataPublication.getElaboratedData();
LOG.info("Number of data items in the publication: " + elaboratedDataList.size());
for(ElaboratedData dataItem : elaboratedDataList) {
extractTrafficDataFromElaboratedData(dataItem);
}
LOG.info(PUBLICATION_TYPE + ": processed successfully.");
}
} catch (Exception e) {
LOG.error(e.getMessage());
}
}
private void extractTrafficDataFromElaboratedData(ElaboratedData dataItem) {
// Location is always specified as LocationByReference (referenced to a
// single Network Link)
LocationByReference location = (LocationByReference) dataItem.getBasicData().getPertinentLocation();
LOG.info("Data for Network Link: " + location.getPredefinedLocationReference().getId());
BasicData basicData = dataItem.getBasicData();
// Determine what class (type) of traffic data is contained in the basic
// data
if (TrafficSpeed.class.equals(basicData.getClass())) {
TrafficSpeed speed = (TrafficSpeed) basicData;
LOG.info("Average Speed: " + speed.getAverageVehicleSpeed().getSpeed());
} else if (TravelTimeData.class.equals(basicData.getClass())) {
TravelTimeData travelTimeData = (TravelTimeData) basicData;
LOG.info("Travel Time: " + travelTimeData.getTravelTime().getDuration());
LOG.info("Free Flow Travel Time: " + travelTimeData.getFreeFlowTravelTime().getDuration());
LOG.info("Normally Expected Travel Time: " + travelTimeData.getNormallyExpectedTravelTime().getDuration());
} else if (TrafficFlow.class.equals(basicData.getClass())) {
TrafficFlow flow = (TrafficFlow) basicData;
LOG.info("Traffic Flow: " + flow.getVehicleFlow().getVehicleFlowRate());
} else if (TrafficConcentration.class.equals(basicData.getClass())) {
TrafficConcentration concentration = (TrafficConcentration) basicData;
LOG.info("Occupancy (%age): " + concentration.getOccupancy().getPercentage());
} else if (TrafficHeadway.class.equals(basicData.getClass())) {
TrafficHeadway headway = (TrafficHeadway) basicData;
LOG.info("Headway: " + headway.getAverageTimeHeadway().getDuration());
} else {
LOG.error("Unexpected traffic data type contained in publication: " + dataItem.getClass().getSimpleName());
}
}
} | ntisservices/ntis-java-web-services-Release2.5 | SubscriberService/src/main/java/com/thales/ntis/subscriber/services/FusedSensorOnlyTrafficDataServiceImpl.java | Java | mit | 4,105 |
// @flow
import type { ChooView } from "../app";
const html = require("choo/html");
const messages = require("../messages");
const textInput = ({ label, name }) => html`
<label>
${label}
<input name=${name}/>
</label>`;
const signupForm = ({ onSubmit }) => html`
<form onsubmit=${onSubmit}>
${textInput({ label: messages.form.name, name: "name" })}
${textInput({ label: messages.form.email, name: "email" })}
<input type="submit" value=${messages.form.signup} />
</form>`;
const signupView: ChooView = (state, emit) => {
const onSubmit = event => {
event.preventDefault();
const formElements = event.target.elements;
const name = formElements.namedItem("name").value;
const email = formElements.namedItem("email").value;
const user = { name, email };
emit("api:signup", user);
};
return html`
<div>
${signupForm({ onSubmit })}
<a href="#">back</a>
</div>`;
};
module.exports = signupView;
| fczuardi/videochat-client | src/views/signup.js | JavaScript | mit | 981 |
package net.lemonfactory.sudokusolver.gui;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
/**
* ResourceBundle with UTF-8. See
* http://www.thoughtsabout.net/blog/archives/000044.html.
*
* @author Choongmin Lee
* @version 19 Aug 2008
*/
class Utf8ResourceBundle {
// Prevent instatiation
private Utf8ResourceBundle() {}
public static ResourceBundle getBundle(String baseName) {
return filter(ResourceBundle.getBundle(baseName));
}
public static ResourceBundle getBundle(String baseName, Locale locale) {
return filter(ResourceBundle.getBundle(baseName, locale));
}
public static ResourceBundle getBundle(
String baseName, Locale locale, ClassLoader loader) {
return filter(ResourceBundle.getBundle(baseName, locale, loader));
}
private static ResourceBundle filter(ResourceBundle bundle) {
if (!(bundle instanceof PropertyResourceBundle))
return bundle;
return new Utf8PropertyResourceBundle((PropertyResourceBundle) bundle);
}
private static class Utf8PropertyResourceBundle extends ResourceBundle {
private final PropertyResourceBundle bundle;
Utf8PropertyResourceBundle(PropertyResourceBundle bundle) {
this.bundle = bundle;
}
@Override
public Enumeration<String> getKeys() {
return bundle.getKeys();
}
@Override
protected Object handleGetObject(String key) {
String value = (String) bundle.handleGetObject(key);
if (value == null)
return null;
try {
return new String(value.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 is unsupported", e);
}
}
}
}
| clee704/sudokusolver | src/main/net/lemonfactory/sudokusolver/gui/Utf8ResourceBundle.java | Java | mit | 1,980 |
//Copyright (c) 2011 Kenneth Evans
//
//Permission is hereby granted, free of charge, to any person obtaining
//a copy of this software and associated documentation files (the
//"Software"), to deal in the Software without restriction, including
//without limitation the rights to use, copy, modify, merge, publish,
//distribute, sublicense, and/or sell copies of the Software, and to
//permit persons to whom the Software is furnished to do so, subject to
//the following conditions:
//
//The above copyright notice and this permission notice shall be included
//in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package net.kenevans.android.misc;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import androidx.appcompat.app.AppCompatActivity;
import static net.kenevans.android.misc.MessageUtils.formatDate;
/**
* Manages a ListView of all the messages in the database specified by the
* URI field.
*/
public class SMSActivity extends AppCompatActivity implements IConstants {
/**
* The current position when ACTIVITY_DISPLAY_MESSAGE is requested. Used
* with the resultCodes RESULT_PREV and RESULT_NEXT when they are returned.
*/
private int mCurrentPosition;
/**
* The current id when ACTIVITY_DISPLAY_MESSAGE is requested. Used with the
* resultCodes RESULT_PREV and RESULT_NEXT when they are returned.
*/
private long mCurrentId;
/**
* The mIncrement for displaying the next message.
*/
private long mIncrement = 0;
/**
* The Uri to use.
*/
private static final Uri URI = SMS_URI;
/**
* The date multiplier to use to get ms. MMS message timestamps are in sec
* not ms.
*/
private static final Long DATE_MULTIPLIER = 1L;
/**
* Enum to specify the sort order.
*/
private enum Order {
TIME(COL_DATE + " DESC"), ID(COL_ID + " DESC");
public final String sqlCommand;
Order(String sqlCommand) {
this.sqlCommand = sqlCommand;
}
}
/**
* The sort order to use.
*/
private Order mSortOrder = Order.TIME;
private CustomListAdapter mListAdapter;
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
mListView = findViewById(R.id.mainListView);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
onListItemClick(mListView, view, position, id);
}
});
// Set fast scroll
mListView.setFastScrollEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.smsmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.refresh:
refresh();
return true;
case R.id.order:
setOrder();
return true;
}
return false;
}
protected void onListItemClick(ListView lv, View view, int position, long
id) {
Log.d(TAG, this.getClass().getSimpleName() + ": onListItemClick: " +
"position=" + position + " id=" + id);
Data data = mListAdapter.getData(position);
if (data == null) return;
Log.d(TAG, "data: id=" + data.getId() + " " + data.getAddress());
// Save the position when starting the activity
mCurrentPosition = position;
mCurrentId = data.getId();
mIncrement = 0;
displayMessage();
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
// DEBUG
Log.d(TAG, this.getClass().getSimpleName()
+ ".onActivityResult: requestCode=" + requestCode
+ " resultCode=" + resultCode + " mCurrentPosition="
+ mCurrentPosition);
if (requestCode == DISPLAY_MESSAGE) {
mIncrement = 0;
// Note that earlier items are at higher positions in the list
if (resultCode == RESULT_PREV) {
mIncrement = -1;
} else if (resultCode == RESULT_NEXT) {
mIncrement = +1;
}
}
}
@Override
protected void onResume() {
Log.d(TAG, this.getClass().getSimpleName()
+ ".onResume: mCurrentPosition=" + mCurrentPosition
+ " mCurrentId=" + mCurrentId + " mIncrement=" + mIncrement);
super.onResume();
refresh();
// If mIncrement is set display a new message
if (mIncrement != 0) {
displayMessage();
}
}
@Override
protected void onPause() {
Log.d(TAG, this.getClass().getSimpleName()
+ ".onPause: mCurrentPosition=" + mCurrentPosition);
Log.d(TAG, this.getClass().getSimpleName() + ".onPause: mCurrentId="
+ mCurrentId);
super.onPause();
}
/**
* Bring up a dialog to change the sort order.
*/
private void setOrder() {
final CharSequence[] items = {getText(R.string.sort_time),
getText(R.string.sort_id)};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getText(R.string.sort_title));
builder.setSingleChoiceItems(items, mSortOrder == Order.TIME ? 0 : 1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
dialog.dismiss();
mSortOrder = item == 0 ? Order.TIME : Order.ID;
refresh();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/**
* Displays the message at the current position plus the current mIncrement,
* adjusting for being within range. Resets the mIncrement to 0 after.
*/
private void displayMessage() {
if (mListAdapter == null) {
return;
}
try {
int count = mListAdapter.getCount();
Log.d(TAG, this.getClass().getSimpleName()
+ ".displayMessage: count=" + count + " mCurrentId=" +
mCurrentId + " mCurrentPosition=" + mCurrentPosition);
if (count == 0) {
Utils.infoMsg(this, "There are no items in the list");
return;
}
// Check if the item is still at the same position in the list
boolean changed = false;
long id = -1;
if (mCurrentPosition > count - 1 || mCurrentPosition < 0) {
changed = true;
} else {
Data data = mListAdapter.getData(mCurrentPosition);
if (data == null) {
Utils.errMsg(this, "Error displaying message: Missing " +
"data for position " + mCurrentPosition);
return;
}
id = data.getId();
if (id != mCurrentId) {
changed = true;
}
}
// Determine the new mCurrentPosition
Log.d(TAG, this.getClass().getSimpleName()
+ ".displayMessage: position=" + mCurrentPosition + " id="
+ id + " changed=" + changed);
if (changed) {
for (int i = 0; i < count; i++) {
Data data = mListAdapter.getData(mCurrentPosition);
if (data == null) {
Utils.errMsg(this, "Error displaying message: Missing" +
" " + "data for position " + mCurrentPosition);
return;
}
id = data.getId();
if (id == mCurrentId) {
mCurrentPosition = i;
break;
}
}
}
// mCurrentPosition may still be invalid, check it is in range
if (mCurrentPosition < 0) {
mCurrentPosition = 0;
} else if (mCurrentPosition > count - 1) {
mCurrentPosition = count - 1;
}
// Display messages if a requested mIncrement is not possible
if (mIncrement > 0) {
mCurrentPosition += mIncrement;
if (mCurrentPosition > count - 1) {
Toast.makeText(getApplicationContext(),
"At the last item in the list", Toast.LENGTH_LONG)
.show();
mCurrentPosition = count - 1;
}
} else if (mIncrement < 0) {
mCurrentPosition += mIncrement;
if (mCurrentPosition < 0) {
Toast.makeText(getApplicationContext(),
"At the first item in the list", Toast.LENGTH_LONG)
.show();
mCurrentPosition = 0;
}
}
// Request the new message
Data data = mListAdapter.getData(mCurrentPosition);
if (data == null) {
Utils.errMsg(this, "Error displaying message: Missing " +
"data for position " + mCurrentPosition);
return;
}
mCurrentId = data.getId();
Intent i = new Intent(this, DisplaySMSActivity.class);
i.putExtra(COL_ID, mCurrentId);
i.putExtra(URI_KEY, URI.toString());
Log.d(TAG, this.getClass().getSimpleName()
+ ".displayMessage: position=" + mCurrentPosition
+ " mCurrentId=" + mCurrentId);
startActivityForResult(i, DISPLAY_MESSAGE);
} catch (Exception ex) {
Utils.excMsg(this, "Error displaying message", ex);
} finally {
// Reset mIncrement
mIncrement = 0;
}
}
/**
* Gets a new cursor and starts managing it.
*/
private void refresh() {
// Initialize the list view mAapter
mListAdapter = new CustomListAdapter();
mListView.setAdapter(mListAdapter);
}
// /**
// * Method used to test what is happening with a database.
// *
// * @param testNum
// * Prefix to log message.
// * @param cls
// * The calling class (will be part of the log message).
// * @param context
// * The calling context. Used to get the content resolver if the
// * input cursor is null.
// * @param cursor
// * The calling cursor or null to use a cursor with all columns.
// * @param id
// * The _id.
// * @param mUri
// * The URI of the content database (will be part of the log
// * message).
// */
// public static void test(int testNum, Class<?> cls, Context context,
// Cursor cursor, String id, Uri mUri) {
// Cursor cursor1;
// if (cursor == null) {
// String selection = COL_ID + "=" + id;
// // String[] projection = { "*" };
// String[] projection = null;
// cursor1 = context.getContentResolver().query(mUri, projection,
// selection, null, null);
// cursor1.moveToFirst();
// } else {
// cursor1 = cursor;
// }
//
// int indexId = cursor1.getColumnIndex(COL_ID);
// int indexDate = cursor1.getColumnIndex(COL_DATE);
// int indexAddress = cursor1.getColumnIndex(COL_ADDRESS);
// int indexThreadId = cursor1.getColumnIndex(COL_THREAD_ID);
//
// do {
// String id1 = cursor1.getString(indexId);
// String address = "<Address NA>";
// if (indexAddress > -1) {
// address = cursor1.getString(indexAddress);
// }
// Long dateNum = -1L;
// if (indexDate > -1) {
// dateNum = cursor1.getLong(indexDate);
// }
// String threadId = "<ThreadID NA>";
// if (indexThreadId > -1) {
// threadId = cursor1.getString(indexThreadId);
// }
// Log.d(TAG,
// testNum + " " + cls.getSimpleName() + ".test" + "id=(" + id
// + "," + id1 + ") address=" + address + " dateNum="
// + dateNum + " threadId=" + threadId + " mUri=" + mUri
// + " cursor=(" + cursor1.getColumnCount() + ","
// + cursor1.getCount() + "," + cursor1.getPosition()
// + ")");
// } while (cursor == null && cursor1.moveToNext());
//
// if (cursor == null) {
// // Close the cursor if we created it here
// cursor1.close();
// }
// }
/**
* Class to manage the data needed for an item in the ListView.
*/
private static class Data {
private final long id;
private String address;
private long dateNum = -1;
private boolean invalid = true;
private Data(long id) {
this.id = id;
}
private void setValues(String address, long dateNum) {
this.address = address;
this.dateNum = dateNum;
invalid = false;
}
private long getId() {
return id;
}
private String getAddress() {
return address;
}
private long getDateNum() {
return dateNum;
}
private boolean isInvalid() {
return invalid;
}
}
/**
* ListView adapter class for this activity.
*/
private class CustomListAdapter extends BaseAdapter {
private String[] mDesiredColumns;
private Data[] mDataArray;
private final LayoutInflater mInflator;
private int mIndexId;
private int mIndexDate;
private int mIndexAddress;
private CustomListAdapter() {
super();
// DEBUG
// Log.d(TAG, this.getClass().getSimpleName() + " Start");
// Date start = new Date();
mInflator = getLayoutInflater();
Cursor cursor = null;
int nItems = 0;
try {
// First get the names of all the columns in the database
String[] availableColumns;
cursor = getContentResolver().query(URI, null, null,
null, null);
if (cursor == null) {
availableColumns = new String[0];
} else {
availableColumns = cursor.getColumnNames();
cursor.close();
}
// Make an array of the desired ones that are available
String[] desiredColumns = {COL_ID, COL_ADDRESS, COL_DATE};
ArrayList<String> list = new ArrayList<>();
for (String col : desiredColumns) {
for (String col1 : availableColumns) {
if (col.equals(col1)) {
list.add(col);
break;
}
}
}
mDesiredColumns = new String[list.size()];
list.toArray(mDesiredColumns);
// Get the available columns from all rows
cursor = getContentResolver().query(URI, mDesiredColumns,
null, null, mSortOrder.sqlCommand);
if (cursor == null) {
Utils.errMsg(SMSActivity.this,
"ListAdapter: Error getting data: No items in " +
"database");
return;
}
mIndexId = cursor.getColumnIndex(COL_ID);
mIndexDate = cursor.getColumnIndex(COL_DATE);
mIndexAddress = cursor.getColumnIndex(COL_ADDRESS);
int count = cursor.getCount();
mDataArray = new Data[count];
if (count <= 0) {
Utils.infoMsg(SMSActivity.this, "No items in database");
} else {
// Loop over items
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
long id = cursor.getLong(mIndexId);
mDataArray[nItems] = new Data(id);
nItems++;
cursor.moveToNext();
}
}
}
} catch (Exception ex) {
Utils.excMsg(SMSActivity.this,
"ListAdapter: Error getting data", ex);
} finally {
try {
if (cursor != null) cursor.close();
} catch (Exception ex) {
// Do nothing
}
}
// DEBUG
// Date end = new Date();
// double elapsed = (end.getTime() - start.getTime()) / 1000.;
// Log.d(TAG, "Elapsed time=" + elapsed);
Log.d(TAG, "Data list created with " + nItems + " items");
}
private Data getData(int i) {
if (mDataArray == null || i < 0 || i >= mDataArray.length) {
return null;
}
return mDataArray[i];
}
@Override
public int getCount() {
return mDataArray == null ? 0 : mDataArray.length;
}
@Override
public Object getItem(int i) {
if (mDataArray == null || i < 0 || i >= mDataArray.length) {
return null;
}
return mDataArray[i];
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
// DEBUG
// Log.d(TAG, this.getClass().getSimpleName() + ": i=" + i);
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.list_row, viewGroup,
false);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) view.findViewById(R.id.title);
viewHolder.subTitle = (TextView) view.findViewById(R.id
.subtitle);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
String titleText;
String subTitleText;
// Check if index is OK.
if (i < 0 || i >= mDataArray.length) {
titleText = "Error";
subTitleText = "Bad view index" + i + " (Should be 0 to "
+ mDataArray.length + ")";
viewHolder.title.setText(titleText);
viewHolder.subTitle.setText(subTitleText);
return view;
}
Data data = mDataArray[i];
if (data == null) {
titleText = "Error";
subTitleText = "Cannot find data for i=" + i;
viewHolder.title.setText(titleText);
viewHolder.subTitle.setText(subTitleText);
return view;
}
// Only calculate what is needed (i.e visible)
// Speeds up tremendously over calculating everything before
if (data.isInvalid()) {
// Get the values for this item
Cursor cursor = getContentResolver().query(URI,
mDesiredColumns,
COL_ID + "=" + mDataArray[i].getId(), null, mSortOrder
.sqlCommand);
if (cursor != null && cursor.moveToFirst()) {
String address = "<Address NA>";
if (mIndexAddress > -1) {
address = cursor.getString(mIndexAddress);
}
Long dateNum = -1L;
if (mIndexDate > -1) {
dateNum = cursor.getLong(mIndexDate) *
DATE_MULTIPLIER;
}
data.setValues(address, dateNum);
}
if (cursor != null) cursor.close();
}
titleText = String.format(Locale.US, "%d", data.getId()) +
": " + MessageUtils.formatAddress(data.getAddress());
subTitleText = formatDate(data.getDateNum());
String contactName = MessageUtils.getContactNameFromNumber(
SMSActivity.this, data.getAddress());
if (contactName != null && !contactName.equals("Unknown")) {
titleText += " " + contactName;
}
viewHolder.title.setText(titleText);
viewHolder.subTitle.setText(subTitleText);
return view;
}
}
/**
* Convience class for managing views for a ListView row.
*/
private static class ViewHolder {
TextView title;
TextView subTitle;
}
}
| KennethEvans/Misc | app/src/main/java/net/kenevans/android/misc/SMSActivity.java | Java | mit | 22,554 |
package lamrongol.javatools;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Collection;
import java.util.List;
/**
* known bugs:
* Serializable will be duplicate if a class already has Serializable
* doesn't work correctly for generics with extends
*/
public class MakeClassSerializable {
public static void main(String[] args) throws Exception {
String TARGET_DIRECTORY = "<Input directory containing java files you want to make Serializable>";
String ENCODING = "UTF-8";
Collection<File> files = FileUtils.listFiles(new File(TARGET_DIRECTORY), new String[]{"java"}, true);
for (File file : files) {
System.out.println(file);
// creates an input stream for the file to be parsed
List<String> lines = FileUtils.readLines(file, ENCODING);
boolean classDeclarationStart = false;
String implStr = null;
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (line.startsWith("package ")) {
lines.add(i + 1, "");
lines.add(i + 2, "import java.io.Serializable;");
continue;
}
if (!classDeclarationStart) {
if (line.startsWith("public")) {
if (line.contains(" class ")) {
implStr = "implements";
} else if (line.contains(" interface ")) {
implStr = "extends";
} else continue;
classDeclarationStart = true;
}
}
if (classDeclarationStart) {
if (line.contains(implStr + " ")) {
line = line.replace(implStr + " ", implStr + " Serializable, ");
lines.set(i, line);
break;
} else if (line.contains("{")) {
line = line.replace("{", implStr + " Serializable {");
lines.set(i, line);
break;
}
}
}
FileUtils.writeLines(file, ENCODING, lines);
}
}
}
| lamrongol/MakeJavaClassSerializable | src/main/java/lamrongol/javatools/MakeClassSerializable.java | Java | mit | 2,307 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AgenciasPromotores extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('AgenciasPromotores_Model', 'model');
}
//------------------------------------------------------------------------
//FUNCIONES CATALOGO AGENCIAS
//------------------------------------------------------------------------
public function agencias() {
$this->load->view('header');
$this->load->view('agenciasPromotores/agencias');
$this->load->view('footer');
}
public function getAgencias() {
$agencias = $this->model->getAgencias();
$json_data = array("data" => $agencias);
echo json_encode($json_data);
}
public function insertUpdateAgencia() {
$data = array(
'nombre' => strtoupper($this->input->post("nombre")),
'estado' => strtoupper($this->input->post("estado")),
'domicilio' => $this->input->post("domicilio"),
'telefono' => $this->input->post("telefono"),
'estatus' => $this->input->post("estatus"),
);
$action = $this->input->post("action");
//si action =0 no hay id entonces inserta de lo contrario hace update
//con el id dado
if ($action == 0) {
echo $this->model->insertAgencia($data);
} else {
$id = $action;
echo $this->model->updateAgencia($data, $id);
}
}
//------------------------------------------------------------------------
//FUNCIONES RELACION DE AGENCIAS - PRODUCTOS
//------------------------------------------------------------------------
public function agenciasProductos($idAgencia) {
$data['agencia'] = $this->model->getAgencia($idAgencia);
$data['productos'] = $this->model->getProductos();
$query = $this->model->getRelacionesAP($idAgencia);
//convertimos el array para validar las relaciones en la vista
$array = array();
if (isset($query)) {
foreach ($query as $key => $val) {
$temp = array_values($val);
$array[] = $temp[0];
}
}
$data['relaciones'] = $array;
$this->load->view('header');
$this->load->view('agenciasPromotores/agencias-productos', $data);
$this->load->view('footer');
}
public function insertDeleteRelacionAP() {
$idProducto = $this->input->post("idProducto");
$idAgencia = $this->input->post("idAgencia");
$action = $this->input->post("action");
if ($action == "add") {
echo $this->model->insertRelacionAP($idAgencia, $idProducto);
} else {
echo $this->model->deleteRelacionAP($idAgencia, $idProducto);
}
}
//------------------------------------------------------------------------
//FUNCIONES CATALOGO DE PROMOTORES
//------------------------------------------------------------------------
public function promotores() {
$data['personas']=$this->model->getPersonas();
$this->load->view('header');
$this->load->view('agenciasPromotores/promotores',$data);
$this->load->view('footer');
}
public function getPromotores() {
$promotores = $this->model->getPromotores();
$json_data = array("data" => $promotores);
echo json_encode($json_data);
}
public function insertUpdatePromotor() {
$data = array(
'Personas_idPersona' => strtoupper($this->input->post("idPersona")),
'estatus' => $this->input->post("estatus"),
);
$action = $this->input->post("action");
//si action =0 no hay id entonces inserta de lo contrario hace update
//con el id dado
if ($action == 0) {
echo $this->model->insertPromotor($data);
} else {
$id = $action;
echo $this->model->updatePromotor($data, $id);
}
}
//------------------------------------------------------------------------
//FUNCIONES RELACION DE AGENCIAS - PROMOTORES
//------------------------------------------------------------------------
public function agenciasPromotores($idPromotor) {
$data['promotor']=$this->model->getPromotor($idPromotor);
$data['agencias'] = $this->model->getAgencias();
$query = $this->model->getRelacionesAPT($idPromotor);
//convertimos el array para validar las relaciones en la vista
$array = array();
if (isset($query)) {
foreach ($query as $key => $val) {
$temp = array_values($val);
$array[] = $temp[0];
}
}
$data['relaciones'] = $array;
$this->load->view('header');
$this->load->view('agenciasPromotores/agencias-promotores', $data);
$this->load->view('footer');
}
public function insertDeleteRelacionAPT() {
$idPromotor = $this->input->post("idPromotor");
$idAgencia = $this->input->post("idAgencia");
$action = $this->input->post("action");
if ($action == "add") {
echo $this->model->insertRelacionAPT($idAgencia, $idPromotor);
} else {
echo $this->model->deleteRelacionAPT($idAgencia, $idPromotor);
}
}
}
| naycont/naybam | application/controllers/AgenciasPromotores.php | PHP | mit | 5,333 |
import { DRAFT_MIME_TYPES, PACKAGE_TYPE } from '../constants';
export interface AutoResponder {
StartTime: number;
EndTime: number;
Repeat: number;
DaysSelected: number[];
Subject: string;
Message: string;
IsEnabled: boolean;
Zone: string;
}
export interface MailSettings {
DisplayName: string;
Signature: string;
Theme: string;
AutoResponder: AutoResponder;
AutoSaveContacts: number;
AutoWildcardSearch: number;
ComposerMode: number;
MessageButtons: number;
ShowImages: number;
ShowMoved: number;
ViewMode: number;
ViewLayout: number;
SwipeLeft: number;
SwipeRight: number;
AlsoArchive: number;
Hotkeys: number; // used by v3 (Angular)
Shortcuts: number; // used by v4
PMSignature: number;
ImageProxy: number;
TLS: number;
RightToLeft: number;
AttachPublicKey: number;
Sign: number;
PGPScheme: PACKAGE_TYPE;
PromptPin: number;
Autocrypt: number;
NumMessagePerPage: number;
DraftMIMEType: DRAFT_MIME_TYPES;
ReceiveMIMEType: string;
ShowMIMEType: string;
StickyLabels: number;
ConfirmLink: number;
DelaySendSeconds: number;
EnableFolderColor: number;
InheritParentFolderColor: number;
FontFace: string | undefined;
FontSize: number | undefined;
}
| ProtonMail/WebClient | packages/shared/lib/interfaces/MailSettings.ts | TypeScript | mit | 1,328 |
var notice_this_is_a_global_var = "WAT?";
window.getGlobalTemplate = function() {
var compiled = _.template('<h1>Hello from a <strong>Global</strong> module running a <%= templateName %>!</h1>');
return compiled({
'templateName': 'Lodash template'
});
};
| staxmanade/jspm-presentation | demo-commonjs-amd-global/globalModule.js | JavaScript | mit | 270 |
const DrawCard = require('../../drawcard.js');
const { Locations, Players, CardTypes } = require('../../Constants');
class MyAncestorsStrength extends DrawCard {
setupCardAbilities(ability) { // eslint-disable-line no-unused-vars
this.action({
title: 'Modify base military and political skills',
condition: () => this.game.isDuringConflict(),
targets: {
shugenja: {
activePromptTitle: 'Choose a shugenja character',
cardType: CardTypes.Character,
controller: Players.Self,
cardCondition: card => card.hasTrait('shugenja') && card.isParticipating()
},
ancestor: {
dependsOn: 'shugenja',
activePromptTitle: 'Choose a character to copy from',
cardType: CardTypes.Character,
location: Locations.DynastyDiscardPile,
controller: Players.Self,
gameAction: ability.actions.cardLastingEffect(context => {
let effects = [];
let ancestor = context.targets.ancestor;
if(ancestor.hasDash('military')) {
effects.push(ability.effects.setDash('military'));
} else {
effects.push(ability.effects.setBaseMilitarySkill(ancestor.militarySkill));
}
if(ancestor.hasDash('political')) {
effects.push(ability.effects.setDash('political'));
} else {
effects.push(ability.effects.setBasePoliticalSkill(ancestor.politicalSkill));
}
return {
target: context.targets.shugenja,
effect: effects
};
})
}
},
effect: 'set {1}\'s base skills to those of {2}',
effectArgs: context => [context.targets.shugenja, context.targets.ancestor]
});
}
}
MyAncestorsStrength.id = 'my-ancestor-s-strength';
module.exports = MyAncestorsStrength;
| jeremylarner/ringteki | server/game/cards/04.4-TEaF/MyAncestorsStrength.js | JavaScript | mit | 2,289 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.property;
import org.junit.Test;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Michael Rudolf
*/
public class DirectPropertyAccessorTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue( jiraKey="HHH-3718" )
public void testDirectIdPropertyAccess() throws Exception {
Session s = openSession();
final Transaction transaction = s.beginTransaction();
Item i = new Item();
s.persist( i );
Order o = new Order();
o.setOrderNumber( 1 );
o.getItems().add( i );
s.persist( o );
transaction.commit();
s.clear();
o = ( Order ) s.load( Order.class, 1 );
assertFalse( Hibernate.isInitialized( o ) );
o.getOrderNumber();
// If you mapped with field access, any method call initializes the proxy
assertTrue( Hibernate.isInitialized( o ) );
s.close();
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Order.class,
Item.class,
};
}
}
| HerrB92/obp | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/property/DirectPropertyAccessorTest.java | Java | mit | 2,264 |
import { createStore } from 'redux';
import reducers from './reducers';
const store = createStore(reducers);
if (module.hot) {
module.hot.accept(() => {
const nextRootReducer = require('./reducers').default;
store.replaceReducer(nextRootReducer);
});
}
export default store;
| entria/entria-components | storybook/store.js | JavaScript | mit | 291 |
/**
* Cineast RESTful API
* Cineast is vitrivr\'s content-based multimedia retrieval engine. This is it\'s RESTful API.
*
* The version of the OpenAPI document: v1
* Contact: contact@vitrivr.org
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Tag } from './tag';
export interface TagsQueryResult {
queryId?: string;
tags?: Array<Tag>;
}
| vitrivr/vitrivr-ng | openapi/cineast/model/tagsQueryResult.ts | TypeScript | mit | 484 |
<?
namespace Core\Entity;
use Appcia\Webwork\Core\App;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
class Manager extends EntityManager
{
/**
* Application
*
* @var App
*/
protected $app;
/**
* Not inherited from parent class (private)
*
* @var array
*/
protected $repositories = array();
/**
* Additional data associated with entities
*
* @var array
*/
protected $descriptors = array();
/**
* Constructor
*
* @param App $app
* @param Connection $conn
* @param Configuration $config
* @param EventManager $eventManager
*/
public function __construct(App $app, Connection $conn, Configuration $config, EventManager $eventManager)
{
parent::__construct($conn, $config, $eventManager);
$this->app = $app;
}
/**
* @return App
*/
public function getApp()
{
return $this->app;
}
/**
* @param string $entity Entity name
*
* @return Manager
*/
public function getRepository($entity)
{
if (isset($this->repositories[$entity])) {
return $this->repositories[$entity];
}
$repository = parent::getRepository($entity);
$this->app->getConfig()
->grab('entity.manager.repository.' . $entity)
->inject($repository);
$this->repositories[$entity] = $repository;
return $repository;
}
/**
* @param string $entity Entity name
*
* @return Descriptor
*/
public function getDescriptor($entity)
{
if (isset($this->descriptors[$entity])) {
return $this->descriptors[$entity];
}
$config = $this->app->getConfig()
->grab('entity.manager.descriptor.' . $entity);
$descriptor = new Descriptor($config->getData(), $entity);
$this->descriptors[$entity] = $descriptor;
return $descriptor;
}
} | appcia/webwork-core | lib/Core/Entity/Manager.php | PHP | mit | 2,086 |
(function () {
var fullpage = (function () {
'use strict';
var Cell = function (initial) {
var value = initial;
var get = function () {
return value;
};
var set = function (v) {
value = v;
};
var clone = function () {
return Cell(get());
};
return {
get: get,
set: set,
clone: clone
};
};
var PluginManager = tinymce.util.Tools.resolve('tinymce.PluginManager');
var Tools = tinymce.util.Tools.resolve('tinymce.util.Tools');
var DomParser = tinymce.util.Tools.resolve('tinymce.html.DomParser');
var Node = tinymce.util.Tools.resolve('tinymce.html.Node');
var Serializer = tinymce.util.Tools.resolve('tinymce.html.Serializer');
var shouldHideInSourceView = function (editor) {
return editor.getParam('fullpage_hide_in_source_view');
};
var getDefaultXmlPi = function (editor) {
return editor.getParam('fullpage_default_xml_pi');
};
var getDefaultEncoding = function (editor) {
return editor.getParam('fullpage_default_encoding');
};
var getDefaultFontFamily = function (editor) {
return editor.getParam('fullpage_default_font_family');
};
var getDefaultFontSize = function (editor) {
return editor.getParam('fullpage_default_font_size');
};
var getDefaultTextColor = function (editor) {
return editor.getParam('fullpage_default_text_color');
};
var getDefaultTitle = function (editor) {
return editor.getParam('fullpage_default_title');
};
var getDefaultDocType = function (editor) {
return editor.getParam('fullpage_default_doctype', '<!DOCTYPE html>');
};
var $_e0ugg1bdje5nvbsm = {
shouldHideInSourceView: shouldHideInSourceView,
getDefaultXmlPi: getDefaultXmlPi,
getDefaultEncoding: getDefaultEncoding,
getDefaultFontFamily: getDefaultFontFamily,
getDefaultFontSize: getDefaultFontSize,
getDefaultTextColor: getDefaultTextColor,
getDefaultTitle: getDefaultTitle,
getDefaultDocType: getDefaultDocType
};
var parseHeader = function (head) {
return DomParser({
validate: false,
root_name: '#document'
}).parse(head);
};
var htmlToData = function (editor, head) {
var headerFragment = parseHeader(head);
var data = {};
var elm, matches;
function getAttr(elm, name) {
var value = elm.attr(name);
return value || '';
}
data.fontface = $_e0ugg1bdje5nvbsm.getDefaultFontFamily(editor);
data.fontsize = $_e0ugg1bdje5nvbsm.getDefaultFontSize(editor);
elm = headerFragment.firstChild;
if (elm.type === 7) {
data.xml_pi = true;
matches = /encoding="([^"]+)"/.exec(elm.value);
if (matches) {
data.docencoding = matches[1];
}
}
elm = headerFragment.getAll('#doctype')[0];
if (elm) {
data.doctype = '<!DOCTYPE' + elm.value + '>';
}
elm = headerFragment.getAll('title')[0];
if (elm && elm.firstChild) {
data.title = elm.firstChild.value;
}
Tools.each(headerFragment.getAll('meta'), function (meta) {
var name = meta.attr('name');
var httpEquiv = meta.attr('http-equiv');
var matches;
if (name) {
data[name.toLowerCase()] = meta.attr('content');
} else if (httpEquiv === 'Content-Type') {
matches = /charset\s*=\s*(.*)\s*/gi.exec(meta.attr('content'));
if (matches) {
data.docencoding = matches[1];
}
}
});
elm = headerFragment.getAll('html')[0];
if (elm) {
data.langcode = getAttr(elm, 'lang') || getAttr(elm, 'xml:lang');
}
data.stylesheets = [];
Tools.each(headerFragment.getAll('link'), function (link) {
if (link.attr('rel') === 'stylesheet') {
data.stylesheets.push(link.attr('href'));
}
});
elm = headerFragment.getAll('body')[0];
if (elm) {
data.langdir = getAttr(elm, 'dir');
data.style = getAttr(elm, 'style');
data.visited_color = getAttr(elm, 'vlink');
data.link_color = getAttr(elm, 'link');
data.active_color = getAttr(elm, 'alink');
}
return data;
};
var dataToHtml = function (editor, data, head) {
var headerFragment, headElement, html, elm, value;
var dom = editor.dom;
function setAttr(elm, name, value) {
elm.attr(name, value ? value : undefined);
}
function addHeadNode(node) {
if (headElement.firstChild) {
headElement.insert(node, headElement.firstChild);
} else {
headElement.append(node);
}
}
headerFragment = parseHeader(head);
headElement = headerFragment.getAll('head')[0];
if (!headElement) {
elm = headerFragment.getAll('html')[0];
headElement = new Node('head', 1);
if (elm.firstChild) {
elm.insert(headElement, elm.firstChild, true);
} else {
elm.append(headElement);
}
}
elm = headerFragment.firstChild;
if (data.xml_pi) {
value = 'version="1.0"';
if (data.docencoding) {
value += ' encoding="' + data.docencoding + '"';
}
if (elm.type !== 7) {
elm = new Node('xml', 7);
headerFragment.insert(elm, headerFragment.firstChild, true);
}
elm.value = value;
} else if (elm && elm.type === 7) {
elm.remove();
}
elm = headerFragment.getAll('#doctype')[0];
if (data.doctype) {
if (!elm) {
elm = new Node('#doctype', 10);
if (data.xml_pi) {
headerFragment.insert(elm, headerFragment.firstChild);
} else {
addHeadNode(elm);
}
}
elm.value = data.doctype.substring(9, data.doctype.length - 1);
} else if (elm) {
elm.remove();
}
elm = null;
Tools.each(headerFragment.getAll('meta'), function (meta) {
if (meta.attr('http-equiv') === 'Content-Type') {
elm = meta;
}
});
if (data.docencoding) {
if (!elm) {
elm = new Node('meta', 1);
elm.attr('http-equiv', 'Content-Type');
elm.shortEnded = true;
addHeadNode(elm);
}
elm.attr('content', 'text/html; charset=' + data.docencoding);
} else if (elm) {
elm.remove();
}
elm = headerFragment.getAll('title')[0];
if (data.title) {
if (!elm) {
elm = new Node('title', 1);
addHeadNode(elm);
} else {
elm.empty();
}
elm.append(new Node('#text', 3)).value = data.title;
} else if (elm) {
elm.remove();
}
Tools.each('keywords,description,author,copyright,robots'.split(','), function (name) {
var nodes = headerFragment.getAll('meta');
var i, meta;
var value = data[name];
for (i = 0; i < nodes.length; i++) {
meta = nodes[i];
if (meta.attr('name') === name) {
if (value) {
meta.attr('content', value);
} else {
meta.remove();
}
return;
}
}
if (value) {
elm = new Node('meta', 1);
elm.attr('name', name);
elm.attr('content', value);
elm.shortEnded = true;
addHeadNode(elm);
}
});
var currentStyleSheetsMap = {};
Tools.each(headerFragment.getAll('link'), function (stylesheet) {
if (stylesheet.attr('rel') === 'stylesheet') {
currentStyleSheetsMap[stylesheet.attr('href')] = stylesheet;
}
});
Tools.each(data.stylesheets, function (stylesheet) {
if (!currentStyleSheetsMap[stylesheet]) {
elm = new Node('link', 1);
elm.attr({
rel: 'stylesheet',
text: 'text/css',
href: stylesheet
});
elm.shortEnded = true;
addHeadNode(elm);
}
delete currentStyleSheetsMap[stylesheet];
});
Tools.each(currentStyleSheetsMap, function (stylesheet) {
stylesheet.remove();
});
elm = headerFragment.getAll('body')[0];
if (elm) {
setAttr(elm, 'dir', data.langdir);
setAttr(elm, 'style', data.style);
setAttr(elm, 'vlink', data.visited_color);
setAttr(elm, 'link', data.link_color);
setAttr(elm, 'alink', data.active_color);
dom.setAttribs(editor.getBody(), {
style: data.style,
dir: data.dir,
vLink: data.visited_color,
link: data.link_color,
aLink: data.active_color
});
}
elm = headerFragment.getAll('html')[0];
if (elm) {
setAttr(elm, 'lang', data.langcode);
setAttr(elm, 'xml:lang', data.langcode);
}
if (!headElement.firstChild) {
headElement.remove();
}
html = Serializer({
validate: false,
indent: true,
apply_source_formatting: true,
indent_before: 'head,html,body,meta,title,script,link,style',
indent_after: 'head,html,body,meta,title,script,link,style'
}).serialize(headerFragment);
return html.substring(0, html.indexOf('</body>'));
};
var $_6ivrn3b9je5nvbsd = {
parseHeader: parseHeader,
htmlToData: htmlToData,
dataToHtml: dataToHtml
};
var open = function (editor, headState) {
var data = $_6ivrn3b9je5nvbsd.htmlToData(editor, headState.get());
editor.windowManager.open({
title: 'Document properties',
data: data,
defaults: {
type: 'textbox',
size: 40
},
body: [
{
name: 'title',
label: 'Title'
},
{
name: 'keywords',
label: 'Keywords'
},
{
name: 'description',
label: 'Description'
},
{
name: 'robots',
label: 'Robots'
},
{
name: 'author',
label: 'Author'
},
{
name: 'docencoding',
label: 'Encoding'
}
],
onSubmit: function (e) {
var headHtml = $_6ivrn3b9je5nvbsd.dataToHtml(editor, Tools.extend(data, e.data), headState.get());
headState.set(headHtml);
}
});
};
var $_12r4fvb7je5nvbsa = { open: open };
var register = function (editor, headState) {
editor.addCommand('mceFullPageProperties', function () {
$_12r4fvb7je5nvbsa.open(editor, headState);
});
};
var $_f7sik6b6je5nvbs9 = { register: register };
var protectHtml = function (protect, html) {
Tools.each(protect, function (pattern) {
html = html.replace(pattern, function (str) {
return '<!--mce:protected ' + escape(str) + '-->';
});
});
return html;
};
var unprotectHtml = function (html) {
return html.replace(/<!--mce:protected ([\s\S]*?)-->/g, function (a, m) {
return unescape(m);
});
};
var $_54m0yxbfje5nvbst = {
protectHtml: protectHtml,
unprotectHtml: unprotectHtml
};
var each = Tools.each;
var low = function (s) {
return s.replace(/<\/?[A-Z]+/g, function (a) {
return a.toLowerCase();
});
};
var handleSetContent = function (editor, headState, footState, evt) {
var startPos, endPos, content, headerFragment, styles = '';
var dom = editor.dom;
var elm;
if (evt.selection) {
return;
}
content = $_54m0yxbfje5nvbst.protectHtml(editor.settings.protect, evt.content);
if (evt.format === 'raw' && headState.get()) {
return;
}
if (evt.source_view && $_e0ugg1bdje5nvbsm.shouldHideInSourceView(editor)) {
return;
}
if (content.length === 0 && !evt.source_view) {
content = Tools.trim(headState.get()) + '\n' + Tools.trim(content) + '\n' + Tools.trim(footState.get());
}
content = content.replace(/<(\/?)BODY/gi, '<$1body');
startPos = content.indexOf('<body');
if (startPos !== -1) {
startPos = content.indexOf('>', startPos);
headState.set(low(content.substring(0, startPos + 1)));
endPos = content.indexOf('</body', startPos);
if (endPos === -1) {
endPos = content.length;
}
evt.content = Tools.trim(content.substring(startPos + 1, endPos));
footState.set(low(content.substring(endPos)));
} else {
headState.set(getDefaultHeader(editor));
footState.set('\n</body>\n</html>');
}
headerFragment = $_6ivrn3b9je5nvbsd.parseHeader(headState.get());
each(headerFragment.getAll('style'), function (node) {
if (node.firstChild) {
styles += node.firstChild.value;
}
});
elm = headerFragment.getAll('body')[0];
if (elm) {
dom.setAttribs(editor.getBody(), {
style: elm.attr('style') || '',
dir: elm.attr('dir') || '',
vLink: elm.attr('vlink') || '',
link: elm.attr('link') || '',
aLink: elm.attr('alink') || ''
});
}
dom.remove('fullpage_styles');
var headElm = editor.getDoc().getElementsByTagName('head')[0];
if (styles) {
dom.add(headElm, 'style', { id: 'fullpage_styles' }, styles);
elm = dom.get('fullpage_styles');
if (elm.styleSheet) {
elm.styleSheet.cssText = styles;
}
}
var currentStyleSheetsMap = {};
Tools.each(headElm.getElementsByTagName('link'), function (stylesheet) {
if (stylesheet.rel === 'stylesheet' && stylesheet.getAttribute('data-mce-fullpage')) {
currentStyleSheetsMap[stylesheet.href] = stylesheet;
}
});
Tools.each(headerFragment.getAll('link'), function (stylesheet) {
var href = stylesheet.attr('href');
if (!href) {
return true;
}
if (!currentStyleSheetsMap[href] && stylesheet.attr('rel') === 'stylesheet') {
dom.add(headElm, 'link', {
'rel': 'stylesheet',
'text': 'text/css',
'href': href,
'data-mce-fullpage': '1'
});
}
delete currentStyleSheetsMap[href];
});
Tools.each(currentStyleSheetsMap, function (stylesheet) {
stylesheet.parentNode.removeChild(stylesheet);
});
};
var getDefaultHeader = function (editor) {
var header = '', value, styles = '';
if ($_e0ugg1bdje5nvbsm.getDefaultXmlPi(editor)) {
var piEncoding = $_e0ugg1bdje5nvbsm.getDefaultEncoding(editor);
header += '<?xml version="1.0" encoding="' + (piEncoding ? piEncoding : 'ISO-8859-1') + '" ?>\n';
}
header += $_e0ugg1bdje5nvbsm.getDefaultDocType(editor);
header += '\n<html>\n<head>\n';
if (value = $_e0ugg1bdje5nvbsm.getDefaultTitle(editor)) {
header += '<title>' + value + '</title>\n';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultEncoding(editor)) {
header += '<meta http-equiv="Content-Type" content="text/html; charset=' + value + '" />\n';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultFontFamily(editor)) {
styles += 'font-family: ' + value + ';';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultFontSize(editor)) {
styles += 'font-size: ' + value + ';';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultTextColor(editor)) {
styles += 'color: ' + value + ';';
}
header += '</head>\n<body' + (styles ? ' style="' + styles + '"' : '') + '>\n';
return header;
};
var handleGetContent = function (editor, head, foot, evt) {
if (!evt.selection && (!evt.source_view || !$_e0ugg1bdje5nvbsm.shouldHideInSourceView(editor))) {
evt.content = $_54m0yxbfje5nvbst.unprotectHtml(Tools.trim(head) + '\n' + Tools.trim(evt.content) + '\n' + Tools.trim(foot));
}
};
var setup = function (editor, headState, footState) {
editor.on('BeforeSetContent', function (evt) {
handleSetContent(editor, headState, footState, evt);
});
editor.on('GetContent', function (evt) {
handleGetContent(editor, headState.get(), footState.get(), evt);
});
};
var $_g4dxr5beje5nvbsp = { setup: setup };
var register$1 = function (editor) {
editor.addButton('fullpage', {
title: 'Document properties',
cmd: 'mceFullPageProperties'
});
editor.addMenuItem('fullpage', {
text: 'Document properties',
cmd: 'mceFullPageProperties',
context: 'file'
});
};
var $_e0bg5mbgje5nvbsu = { register: register$1 };
PluginManager.add('fullpage', function (editor) {
var headState = Cell(''), footState = Cell('');
$_f7sik6b6je5nvbs9.register(editor, headState);
$_e0bg5mbgje5nvbsu.register(editor);
$_g4dxr5beje5nvbsp.setup(editor, headState, footState);
});
function Plugin () {
}
return Plugin;
}());
})();
| AnttiKurittu/kirjuri | vendor/tinymce/tinymce/plugins/fullpage/plugin.js | JavaScript | mit | 16,270 |
/* Copyright 1987, 1989, 1990 by Abacus Research and
* Development, Inc. All rights reserved.
*/
/* Forward declarations in ResourceMgr.h (DO NOT DELETE THIS LINE) */
#include <base/common.h>
#include <ResourceMgr.h>
#include <FileMgr.h>
#include <MemoryMgr.h>
#include <res/resource.h>
using namespace Executor;
LONGINT Executor::C_GetMaxResourceSize(Handle h) /* IMIV-16 */
{
resmaphand map;
typref *tr;
resref *rr;
LONGINT dl, mdl, nl;
INTEGER i, j;
ROMlib_setreserr(ROMlib_findres(h, &map, &tr, &rr));
if(LM(ResErr) != noErr)
return (-1);
if(!rr->rhand || !(*(Handle)rr->rhand))
{
dl = B3TOLONG(rr->doff);
mdl = (*map)->rh.datlen;
WALKTANDR(map, i, tr, j, rr)
if((nl = B3TOLONG(rr->doff)) > dl && nl < mdl)
mdl = nl;
EWALKTANDR(tr, rr)
return (mdl - dl);
}
else
return (GetHandleSize((Handle)rr->rhand));
}
LONGINT Executor::C_RsrcMapEntry(Handle h) /* IMIV-16 */
{
resmaphand map;
typref *tr;
resref *rr;
ROMlib_setreserr(ROMlib_findres(h, &map, &tr, &rr));
if(LM(ResErr) != noErr)
return (0);
return ((char *)rr - (char *)*map);
}
/* OpenRFPerm is in resOpen.c */
Handle Executor::C_RGetResource(ResType typ, INTEGER id)
{
return GetResource(typ, id);
}
| autc04/executor | src/res/resIMIV.cpp | C++ | mit | 1,328 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMstDataUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('mst_data_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('mst_user_id'); //relasi dengan tabel mst_user
$table->string('tempat_lahir'); // tempat lahir user
$table->date('tgl_lahir'); //tgl lahir user
$table->enum('jenis_kelamin', ['L', 'P']); //jenis kelamin user
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('mst_data_user');
}
}
| r3k4/ujianonline | database/migrations/2015_10_27_130540_create_MstDataUser_table.php | PHP | mit | 833 |
package UIComponent
import (
"github.com/chslink/JinYongXGo/system/input"
"github.com/chslink/JinYongXGo/utils/logs"
"github.com/hajimehoshi/ebiten"
)
//TODO event
//Button Sprites
type Button struct {
*Sprite
Text *Lable
Active bool
Pressed bool
clickFun func()
activeFun func(screen *ebiten.Image)
pressedFun func(screen *ebiten.Image)
mouse input.ICursor
}
func (btn *Button) Update(screen *ebiten.Image) error {
//update input first
btn.checkStatus()
//draw pics
btn.Op.ColorM.Reset()
if btn.Active {
if btn.Pressed {
if btn.pressedFun == nil {
btn.Op.ColorM.ChangeHSV(0, 1, 0.8)
screen.DrawImage(btn.Img, btn.Op)
} else {
btn.pressedFun(screen)
}
} else {
if btn.activeFun == nil {
btn.Op.ColorM.ChangeHSV(0, 1, 1.2)
screen.DrawImage(btn.Img, btn.Op)
} else {
btn.activeFun(screen)
}
}
} else {
screen.DrawImage(btn.Img, btn.Op)
}
//do other things
return nil
}
// checkStatus check mouse status
func (btn *Button) checkStatus() {
btn.Active = false
if btn.IsInSprite(btn.mouse.GetPos()) {
btn.Active = true
}
if btn.mouse.IsPressed() {
if btn.Active {
btn.Pressed = true
} else {
btn.Pressed = false
}
} else {
if btn.Pressed {
if btn.clickFun == nil {
logs.Debug("Button clicked ", btn)
} else {
btn.clickFun()
}
}
btn.Pressed = false
}
}
func (btn *Button) RegClickFun(fun func()) {
btn.clickFun = fun
}
//RegDrawFun funType:active,pressed
func (btn *Button) RegDrawFun(fun func(screen *ebiten.Image), funType string) {
switch funType {
case "active":
btn.activeFun = fun
case "pressed":
btn.pressedFun = fun
}
}
func (btn *Button) SetInput(in input.ICursor) {
btn.mouse = in
}
func (btn *Button) GetInput() input.ICursor {
return btn.mouse
}
//NewButton new object
func NewButton(path, msg string) *Button {
btn := &Button{Sprite: NewSprite(path), Text: NewLable(msg), mouse: input.GetCursorInput()}
btn.Text.DrawTextCenter(btn.Sprite.Img)
return btn
}
| chslink/JinYongXGo | system/UIComponent/button.go | GO | mit | 2,010 |
$(document).ready(function(){
SC.initialize({
client_id: "472760520d39b9fa470e56cdffc71923",
});
$('.leaderboard tr').each(function(){
var datacell = $(this).find('.datacell').data('url');
var data = datacell.data('url');
SC.oEmbed(data, {auto_play: false}, datacell);
})
/*
SC.oEmbed($('#crunch1').attr('url'), {auto_play: false}, document.getElementById('crunch1'));
SC.oEmbed($('#crunch2').attr('url'), {auto_play: false}, document.getElementById('crunch2'));
*/
}) | srhoades28/CI_Crunchoff | assets/js/leaderboard.js | JavaScript | mit | 498 |
/**
* SmithNgine Game Framework
*
* Copyright (C) 2013 by Erno Pakarinen / Codesmith (www.codesmith.fi)
* All Rights Reserved
*/
namespace Codesmith.SmithNgine.Gfx
{
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Codesmith.SmithNgine.Input;
using Codesmith.SmithNgine.MathUtil;
// Defines the animation style of the spritebutton
[Flags]
public enum ButtonStyle : int
{
NoAnimation = 1,
Highlight = NoAnimation << 1, // Scales a bit larger when hovered
AnimateOnPress = NoAnimation << 2, // Animates when pressed
AnimateIdle = NoAnimation << 3 // Animates slightly when idle
}
/// <summary>
/// Implements a Button by extending a Sprite
///
/// Gains new event, ButtonClicked which is called when the button
/// is either clicked with a mouse or bound shortcut key is pressed
/// </summary>
public class SpriteButton : Sprite
{
#region Fields
float idleAnimAngle;
int direction;
float hoverScale;
protected PlayerIndex? activePlayerIndex = null;
Keys activationKey = Keys.None;
float currentAngle = 0.0f;
float currentAmplify = 1.0f;
const float AngleMin = MathHelper.Pi / 2f;
const float AngleMax = MathHelper.Pi;
const int MaxIterations = 5;
bool animatingIn = false;
bool animatingOut = false;
#endregion
#region Properties
public ButtonStyle ButtonClickStyle
{
get;
set;
}
public TimeSpan ClickBounceSpeed
{
set;
get;
}
public float AnimState
{
get { return this.idleAnimAngle; }
set { this.idleAnimAngle = value; }
}
#endregion
#region Constructors
public SpriteButton(Texture2D texture)
: base(texture)
{
ClickBounceSpeed = TimeSpan.FromSeconds(0.15f);
idleAnimAngle = 0.0f;
ButtonClickStyle = ButtonStyle.NoAnimation;
hoverScale = 1.0f;
}
#endregion
#region Events
/// <summary>
/// Event which will trigger when this button was pressed
/// </summary>
public event EventHandler<EventArgs> ButtonClicked;
#endregion
#region New methods
/// <summary>
/// Causes this button to listen for the defined key. Acts like Mouse click
/// </summary>
/// <param name="key">Key to bind to this button</param>
public void BindKey(Keys key)
{
activationKey = key;
InputEventSource.KeysPressed += keySource_KeysPressed;
}
/// <summary>
/// Unbind the previously set key.
/// </summary>
/// <param name="key">Key to unbind, if not bound before this does nothing</param>
public void UnbindKey(Keys key)
{
if (key == activationKey)
{
InputEventSource.KeysPressed -= keySource_KeysPressed;
}
}
#endregion
#region Methods overridden from base
public override void Update(GameTime gameTime)
{
if (IsHovered && ( ( ButtonClickStyle & ButtonStyle.Highlight ) == ButtonStyle.Highlight))
{
this.hoverScale = 1.1f;
}
else
{
this.hoverScale = 1.0f;
}
float animScale = 1.0f;
// Are we animating
if ( (animatingIn || animatingOut ) && ((ButtonClickStyle & ButtonStyle.AnimateOnPress)==ButtonStyle.AnimateOnPress))
{
animScale = GetAnimationScale(gameTime);
}
float idleScale = 1.0f;
if( (ButtonClickStyle & ButtonStyle.AnimateIdle) == ButtonStyle.AnimateIdle)
{
idleAnimAngle += 0.15f;
idleAnimAngle = MathHelper.WrapAngle(idleAnimAngle);
idleScale = 1.0f + ((float)Math.Sin(idleAnimAngle) / 70);
}
Scale = hoverScale * animScale * idleScale;
}
public override void GainFocus()
{
base.GainFocus();
LostDrag += SpriteButton_LostDrag;
if (this.ButtonClicked != null)
{
ButtonClicked(this, EventArgs.Empty);
}
animatingIn = true;
ResetAnimation();
}
public override void LooseFocus()
{
base.LooseFocus();
LostDrag -= SpriteButton_LostDrag;
this.direction = 0;
}
public override void Dismiss()
{
InputEventSource.KeysPressed -= keySource_KeysPressed;
this.direction = 0;
this.Scale = 1.0f;
}
#endregion
#region Private methods
private void ResetAnimation()
{
currentAngle = AngleMin;
currentAmplify = 1.0f;
direction = 1;
}
private void keySource_KeysPressed(object sender, KeyboardEventArgs e)
{
if (ObjectIsActive && e.keys.Length > 0 && activationKey != Keys.None)
{
foreach (Keys k in e.keys)
{
if (k == activationKey)
{
activePlayerIndex = e.player;
GainFocus();
}
}
}
}
private float GetAnimationScale(GameTime gameTime)
{
if (!Interpolations.LinearTransition2(gameTime.ElapsedGameTime, ClickBounceSpeed, direction, ref currentAngle, AngleMin, AngleMax))
{
if (direction > 0)
{
currentAngle = AngleMax;
direction = -1;
currentAmplify *= 0.5f;
if (currentAmplify <= 0.05f)
{
currentAmplify = 0.0f;
}
}
else
{
currentAngle = AngleMin;
direction = 1;
}
}
float scale;
if (animatingIn)
{
scale = (3.0f / 4f) + (float)Math.Sin(currentAngle) / 4f * currentAmplify;
}
else
{
scale = 1.0f - ((float)Math.Sin(currentAngle) / 4f * currentAmplify);
}
return scale;
}
private void SpriteButton_LostDrag(object sender, DragEventArgs e)
{
LostDrag -= SpriteButton_LostDrag;
animatingIn = false;
animatingOut = true;
ResetAnimation();
}
#endregion
}
}
| codesmith-fi/smithngine | smithNgine/Gfx/SpriteButton.cs | C# | mit | 6,992 |
"use strict";
describe("PROXY", function () {
beforeEach(function () {
this.p = new PubnubProxy();
});
describe('setFlashObjectId ', function () {
it('should accept flash object name (string) as only argument', function () {
var _test = this,
failFn = function () {
_test.p.setFlashObjectId(15);
},
successFn = function () {
_test.p.setFlashObjectId('someId');
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
});
describe('initialization', function () {
it('should have empty instances object', function () {
expect(Object.keys(this.p.instances)).to.have.length(0);
});
it('should set default value for flash object', function () {
expect(this.p.flashObjectId).to.equal('pubnubFlashObject');
});
it('should set default value for flash object', function () {
expect(this.p.flashObject).to.be(null);
});
});
describe('delegate methods', function () {
it('should accept array as only argument', function () {
var _test = this,
failFn = function () {
_test.p.delegateAsync('oneMethod');
},
successFn = function () {
_test.p.delegateAsync(['oneMethod']);
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
it('should dynamically define methods that are passed as params', function () {
var methods = ['oneMethod', 'anotherMethod'];
this.p.delegateAsync(methods);
expect(this.p.oneMethod).to.be.a('function');
expect(this.p.anotherMethod).to.be.a('function');
});
});
describe('delegate synchronous methods', function () {
it('should accept array as only argument', function () {
var _test = this,
failFn = function () {
_test.p.delegateSync('oneMethod');
},
successFn = function () {
_test.p.delegateSync(['oneMethod']);
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
it('should dynamically define methods that are passed as params', function () {
var methods = ['oneMethod', 'anotherMethod'];
this.p.delegateSync(methods);
expect(this.p.oneMethod).to.be.a('function');
expect(this.p.anotherMethod).to.be.a('function');
});
});
describe('instance creation', function () {
beforeEach(function () {
this.setupObject = {};
this.i = this.p.createInstance('uglyInstanceId', this.setupObject);
});
it('should accept only string as instanceId', function () {
var _test = this,
failFn = function () {
_test.p.createInstance([], {});
},
successFn = function () {
_test.p.createInstance('correctInstanceId');
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
it('should add created instance to instances object', function () {
var ids = Object.keys(this.p.instances);
expect(ids[0]).to.equal('uglyInstanceId');
});
});
describe('instance getter', function () {
it('should throw error when instanceId is not present in instances object', function () {
var _test = this,
failFn = function () {
_test.p.getInstance('wrongInstanceId');
},
successFn = function () {
_test.p.getInstance('uglyInstanceId');
};
this.p.instances = {uglyInstanceId: {}};
expectFailAndSuccessFns(failFn, successFn, Error);
});
});
}); | pubnub/flash | pubnub-as2js-proxy/test/unit/pubnubProxy_test.js | JavaScript | mit | 4,174 |
#!/usr/bin/env node
/**
* Extremely simple static website serving script
* This is provided in case you need to deploy a quick demo
*
* Install + run:
*
* # from parent directory
*
* cd demo
* npm install
* node server
*
*/
var bodyParser = require('body-parser');
var express = require('express');
var humanize = require('humanize');
var fs = require('fs');
var multer = require('multer');
var root = __dirname + '/..';
var app = express();
app.use(bodyParser.json());
app.use('/node_modules', express.static(root + '/node_modules'));
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
app.get('/app.js', function(req, res) {
res.sendFile('app.js', {root: root + '/demo'});
});
app.get('/dist/angular-ui-history.js', function(req, res) {
res.sendFile('angular-ui-history.js', {root: root + '/dist'});
});
app.get('/dist/angular-ui-history.css', function(req, res) {
res.sendFile('angular-ui-history.css', {root: root + '/dist'});
});
// Fake server to originally serve history.json + then mutate it with incomming posts
var history = JSON.parse(fs.readFileSync(root + '/demo/history.json', 'utf-8')).map(post => {
post.date = new Date(post.date);
return post;
});
app.get('/history.json', function(req, res) {
res.send(history);
});
app.post('/history.json', multer().any(), function(req, res) {
if (req.files) { // Uploading file(s)
history.push({
_id: history.length,
type: 'user.upload',
date: new Date(),
user: {
name: 'Fake User',
email: 'fake@mfdc.biz',
},
files: req.files.map(f => ({
filename: f.originalname,
size: humanize.filesize(f.size),
icon:
// Very abridged list of mimetypes -> font-awesome lookup {{{
/^audio\//.test(f.mimetype) ? 'fa fa-file-audio-o' :
/^image\//.test(f.mimetype) ? 'fa fa-file-image-o' :
/^text\//.test(f.mimetype) ? 'fa fa-file-text-o' :
/^video\//.test(f.mimetype) ? 'fa fa-file-video-o' :
f.mimetype == 'application/vnd.ms-excel' || f.mimetype == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || f.mimetype == 'application/vnd.openxmlformats-officedocument.spreadsheetml.template' ? 'fa fa-file-excel-o' :
f.mimetype == 'application/msword' || f.mimetype == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || f.mimetype == 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' ? 'fa fa-file-word-o' :
f.mimetype == 'application/vnd.ms-powerpoint' || f.mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.presentation' || f.mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' || f.mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.template' ? 'fa fa-file-word-o' :
f.mimetype == 'application/pdf' ? 'fa fa-file-pdf-o' :
f.mimetype == 'application/zip' || f.mimetype == 'application/x-compressed-zip' || f.mimetype == 'application/x-tar' || f.mimetype == 'application/x-bzip2' ? 'fa fa-file-archive-o' :
'fa fa-file-o',
// }}}
})),
});
// If we did want to actually save the file we would do something like:
// req.files.forEach(f => fs.writeFile(`/some/directory/${f.originalname}`, f.buffer));
}
if (req.body.body) { // Posting a comment
history.push({
_id: history.length,
date: new Date(),
user: {
name: 'Fake User',
email: 'fake@mfdc.biz',
},
type: 'user.comment',
body: req.body.body,
tags: req.body.tags,
});
}
// Respond that all was well
res.status(200).end();
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500).send('Something broke!').end();
});
var port = process.env.PORT || process.env.VMC_APP_PORT || 8080;
var server = app.listen(port, function() {
console.log('Web interface listening on port', port);
});
| MomsFriendlyDevCo/angular-ui-history | demo/server.js | JavaScript | mit | 3,855 |
'use strict';
/**
* Password based signin and OAuth signin functions.
*/
var qs = require('querystring'),
route = require('koa-route'),
parse = require('co-body'),
jwt = require('koa-jwt'),
request = require('co-request'),
config = require('../config/config'),
mongo = require('../config/mongo');
// register koa routes
exports.init = function (app) {
app.use(route.post('/signin', signin));
app.use(route.get('/signin/facebook', facebookSignin));
app.use(route.get('/signin/facebook/callback', facebookCallback));
app.use(route.get('/signin/google', googleSignin));
app.use(route.get('/signin/google/callback', googleCallback));
};
/**
* Retrieves the user credentials and returns a JSON Web Token along with user profile info in JSON format.
*/
function *signin() {
var credentials = yield parse(this);
var user = yield mongo.users.findOne({email: credentials.email}, {email: 1, name: 1, password: 1});
if (!user) {
this.throw(401, 'Incorrect e-mail address.');
} else if (user.password !== credentials.password) {
this.throw(401, 'Incorrect password.');
} else {
user.id = user._id;
delete user._id;
delete user.password;
user.picture = '/api/users/' + user.id + '/picture';
}
// sign and send the token along with the user info
var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
this.body = {token: token, user: user};
}
/**
* Facebook OAuth 2.0 signin endpoint.
*/
function *facebookSignin() {
this.redirect(
'https://www.facebook.com/dialog/oauth?client_id=' + config.oauth.facebook.clientId +
'&redirect_uri=' + config.oauth.facebook.callbackUrl + '&response_type=code&scope=email');
}
/**
* Facebook OAuth 2.0 callback endpoint.
*/
function *facebookCallback() {
if (this.query.error) {
this.redirect('/signin');
return;
}
// get an access token from facebook in exchange for oauth code
var tokenResponse = yield request.get(
'https://graph.facebook.com/oauth/access_token?client_id=' + config.oauth.facebook.clientId +
'&redirect_uri=' + config.oauth.facebook.callbackUrl +
'&client_secret=' + config.oauth.facebook.clientSecret +
'&code=' + this.query.code);
var token = qs.parse(tokenResponse.body);
if (!token.access_token) {
this.redirect('/signin');
return;
}
// get user profile (including email address) from facebook and save user data in our database if necessary
var profileResponse = yield request.get('https://graph.facebook.com/me?fields=name,email,picture&access_token=' + token.access_token);
var profile = JSON.parse(profileResponse.body);
var user = yield mongo.users.findOne({email: profile.email}, {email: 1, name: 1});
if (!user) {
user = {
_id: (yield mongo.getNextSequence('userId')),
email: profile.email,
name: profile.name,
picture: (yield request.get(profile.picture.data.url, {encoding: 'base64'})).body
};
var results = yield mongo.users.insert(user);
}
// redirect the user to index page along with user profile object as query string
user.id = user._id;
delete user._id;
user.picture = '/api/users/' + user.id + '/picture';
var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user})));
}
/**
* Google OAuth 2.0 signin endpoint.
*/
function *googleSignin() {
this.redirect(
'https://accounts.google.com/o/oauth2/auth?client_id=' + config.oauth.google.clientId +
'&redirect_uri=' + config.oauth.google.callbackUrl + '&response_type=code&scope=profile%20email');
}
function *googleCallback() {
if (this.query.error) {
this.redirect('/signin');
return;
}
// get an access token from google in exchange for oauth code
var tokenResponse = yield request.post('https://accounts.google.com/o/oauth2/token', {form: {
code: this.query.code,
client_id: config.oauth.google.clientId,
client_secret: config.oauth.google.clientSecret,
redirect_uri: config.oauth.google.callbackUrl,
grant_type: 'authorization_code'
}});
var token = JSON.parse(tokenResponse.body);
if (!token.access_token) {
this.redirect('/signin');
return;
}
// get user profile (including email address) from facebook and save user data in our database if necessary
var profileResponse = yield request.get('https://www.googleapis.com/plus/v1/people/me?access_token=' + token.access_token);
var profile = JSON.parse(profileResponse.body);
var user = yield mongo.users.findOne({email: profile.emails[0].value}, {email: 1, name: 1});
if (!user) {
user = {
_id: (yield mongo.getNextSequence('userId')),
email: profile.emails[0].value,
name: profile.displayName,
picture: (yield request.get(profile.image.url, {encoding: 'base64'})).body
};
var results = yield mongo.users.insert(user);
}
// redirect the user to index page along with user profile object as query string
user.id = user._id;
delete user._id;
user.picture = '/api/users/' + user.id + '/picture';
var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user})));
}
| nileshlg2003/koan | server/controllers/signin.js | JavaScript | mit | 5,541 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lab2PassedOrFailed")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lab2PassedOrFailed")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e8b901ca-c941-45c3-afb7-4e3a040d854c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| DenicaAtanasova/02.TechModule | 01. Programming Fundamentals/Lesson2ConditionsAndLoops/Lab2PassedOrFailed/Properties/AssemblyInfo.cs | C# | mit | 1,407 |
import { I18N } from "../../src/i18n";
import { BindingSignaler } from "aurelia-templating-resources";
import { NfValueConverter } from "../../src/nf/nf-value-converter";
import { EventAggregator } from "aurelia-event-aggregator";
describe("nfvalueconverter tests", () => {
let sut: I18N;
let nfvc: NfValueConverter;
beforeEach(() => {
sut = new I18N(new EventAggregator(), new BindingSignaler());
nfvc = new NfValueConverter(sut);
sut.setup({
lng: "en",
fallbackLng: "en",
debug: false
});
});
it("should display number in the setup locale format by default", () => {
const testNumber = 123456.789;
expect(nfvc.toView(testNumber)).toEqual("123,456.789");
});
it("should display number in the previously modified locale", async () => {
const testNumber = 123456.789;
await sut.setLocale("de");
expect(nfvc.toView(testNumber)).toEqual("123.456,789");
});
it("should return undefined if undefined value given", () => {
const val = undefined;
expect(nfvc.toView(val)).toBe(undefined);
});
it("should return null if null value given", () => {
const val = null;
expect(nfvc.toView(val)).toBe(null);
});
it("should return empty string if empty string value given", () => {
const val = "";
expect(nfvc.toView(val)).toBe("");
});
it("should display number as currency", () => {
const testNumber = 123456.789;
expect(nfvc.toView(testNumber, { style: "currency", currency: "JPY" }, "de")).toBe("123.457 ¥");
});
});
| aurelia/i18n | test/unit/nfvalueconverter.spec.ts | TypeScript | mit | 1,542 |
/**
* Plural rules for the fi (Finnish, suomi, suomen kieli) language
*
* This plural file is generated from CLDR-DATA
* (http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html)
* using js-simple-plurals and universal-i18n
*
* @param {number} p
* @return {number} 0 - one, 1 - other
*
* @example
* function pluralize_en(number, one, many) {
* var rules = [one, many];
* var position = plural.en(number)
* return rules[position];
* }
*
* console.log('2 ' + pluralize_en(2, 'day', 'days')); // prints '2 days'
*/
plural = window.plural || {};
plural.fi = function (p) { var n = Math.abs(p)||0, i = Math.floor(n,10)||0, v = ((p+'').split('.')[1]||'').length; return i === 1 && v === 0 ? 0 : 1; }; | megahertz/js-simple-plurals | web/fi.js | JavaScript | mit | 750 |
package controller;
import javafx.scene.Node;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.stage.Stage;
import model.FileManager;
import model.FileManagerInterface;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.testfx.api.FxToolkit;
import org.testfx.framework.junit.ApplicationTest;
import utils.TestUtils;
import java.io.FileNotFoundException;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
/**
* Created by SH on 2016-06-04.
*/
public class TabPaneSceneControllerTest extends ApplicationTest {
private Stage s;
private Node leftSplit, rightSplit;
private HighlightEditorInterface leftEditor, rightEditor;
@Override
public void init() throws Exception {
FxToolkit.registerStage(Stage::new);
}
@Override
public void start(Stage stage) {
s = TestUtils.startStage(stage);
if( s.getScene() != null ) {
leftSplit = s.getScene().lookup("#leftSplit");
rightSplit = s.getScene().lookup("#rightSplit");
leftEditor = (HighlightEditorController)leftSplit.lookup("#editor");
rightEditor = (HighlightEditorController)rightSplit.lookup("#editor");
}
}
@Override
public void stop() throws Exception {
FxToolkit.hideStage();
FxToolkit.cleanupStages();
}
@Before
public void setUp() throws TimeoutException {
FxToolkit.registerPrimaryStage();
}
@Test
public void TabPaneSceneBothSideLoadTest() throws FileNotFoundException{
String leftFile = getClass().getResource("../test1-1.txt").getPath();
String rightFile = getClass().getResource("../test1-2.txt").getPath();
FileManager.getFileManagerInterface().loadFile(leftFile, FileManagerInterface.SideOfEditor.Left);
FileManager.getFileManagerInterface().loadFile(rightFile, FileManagerInterface.SideOfEditor.Right);
assertEquals( FileManager.getFileManagerInterface().getString(FileManagerInterface.SideOfEditor.Left),
"a\nb\nc\nd\ne\nc\n\ne\nd\nd\ne\nd\nc\n\nd\nd\nd\nd\nd" );
assertEquals( FileManager.getFileManagerInterface().getString(FileManagerInterface.SideOfEditor.Right),
"e\nb\nc\nd\ne\nc\n\ne\nd\nd\ne\nd\nc\n\nd\nd\nd\nd\ne" );
}
@Test
public void TabPaneSceneSplitPaneDragTest(){
Node divider = find(".split-pane-divider");
drag(divider).moveBy(-1000, 0);
assertEquals(300, find("#leftSplit").getLayoutBounds().getWidth(), 10);
drag(divider).moveBy(1000, 0);
assertEquals(300, find("#rightSplit").getLayoutBounds().getWidth(), 10);
}
@After
public void tearDown() throws TimeoutException {
FxToolkit.cleanupStages();
FxToolkit.hideStage();
release(new KeyCode[] {});
release(new MouseButton[] {});
}
private <T extends Node> T find(final String query) {
return lookup(query).query();
}
} | leesnhyun/SE2016 | src/test/java/controller/TabPaneSceneControllerTest.java | Java | mit | 3,085 |
using Microsoft.SharePoint.Client.NetCore.Runtime;
using System;
using System.ComponentModel;
namespace Microsoft.SharePoint.Client.NetCore
{
[ScriptType("SP.EventReceiverDefinition", ServerTypeId = "{a8d3515c-1135-4fff-95a6-4e5e5fff4adc}")]
public sealed class EventReceiverDefinition : ClientObject
{
[Remote]
public string ReceiverAssembly
{
get
{
base.CheckUninitializedProperty("ReceiverAssembly");
return (string)base.ObjectData.Properties["ReceiverAssembly"];
}
}
[Remote]
public string ReceiverClass
{
get
{
base.CheckUninitializedProperty("ReceiverClass");
return (string)base.ObjectData.Properties["ReceiverClass"];
}
}
[Remote]
public Guid ReceiverId
{
get
{
base.CheckUninitializedProperty("ReceiverId");
return (Guid)base.ObjectData.Properties["ReceiverId"];
}
}
[Remote]
public string ReceiverName
{
get
{
base.CheckUninitializedProperty("ReceiverName");
return (string)base.ObjectData.Properties["ReceiverName"];
}
}
[Remote]
public int SequenceNumber
{
get
{
base.CheckUninitializedProperty("SequenceNumber");
return (int)base.ObjectData.Properties["SequenceNumber"];
}
}
[Remote]
public EventReceiverSynchronization Synchronization
{
get
{
base.CheckUninitializedProperty("Synchronization");
return (EventReceiverSynchronization)base.ObjectData.Properties["Synchronization"];
}
}
[Remote]
public EventReceiverType EventType
{
get
{
base.CheckUninitializedProperty("EventType");
return (EventReceiverType)base.ObjectData.Properties["EventType"];
}
}
[Remote]
public string ReceiverUrl
{
get
{
base.CheckUninitializedProperty("ReceiverUrl");
return (string)base.ObjectData.Properties["ReceiverUrl"];
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public EventReceiverDefinition(ClientRuntimeContext context, ObjectPath objectPath) : base(context, objectPath)
{
}
protected override bool InitOnePropertyFromJson(string peekedName, JsonReader reader)
{
bool flag = base.InitOnePropertyFromJson(peekedName, reader);
if (flag)
{
return flag;
}
switch (peekedName)
{
case "ReceiverAssembly":
flag = true;
reader.ReadName();
base.ObjectData.Properties["ReceiverAssembly"] = reader.ReadString();
break;
case "ReceiverClass":
flag = true;
reader.ReadName();
base.ObjectData.Properties["ReceiverClass"] = reader.ReadString();
break;
case "ReceiverId":
flag = true;
reader.ReadName();
base.ObjectData.Properties["ReceiverId"] = reader.ReadGuid();
break;
case "ReceiverName":
flag = true;
reader.ReadName();
base.ObjectData.Properties["ReceiverName"] = reader.ReadString();
break;
case "SequenceNumber":
flag = true;
reader.ReadName();
base.ObjectData.Properties["SequenceNumber"] = reader.ReadInt32();
break;
case "Synchronization":
flag = true;
reader.ReadName();
base.ObjectData.Properties["Synchronization"] = reader.ReadEnum<EventReceiverSynchronization>();
break;
case "EventType":
flag = true;
reader.ReadName();
base.ObjectData.Properties["EventType"] = reader.ReadEnum<EventReceiverType>();
break;
case "ReceiverUrl":
flag = true;
reader.ReadName();
base.ObjectData.Properties["ReceiverUrl"] = reader.ReadString();
break;
}
return flag;
}
[Remote]
public void Update()
{
ClientRuntimeContext context = base.Context;
ClientAction query = new ClientActionInvokeMethod(this, "Update", null);
context.AddQuery(query);
}
[Remote]
public void DeleteObject()
{
ClientRuntimeContext context = base.Context;
ClientAction query = new ClientActionInvokeMethod(this, "DeleteObject", null);
context.AddQuery(query);
base.RemoveFromParentCollection();
}
}
}
| OneBitSoftware/NetCore.CSOM | Microsoft.SharePoint.Client.NetCore/EventReceiverDefinition.cs | C# | mit | 5,375 |
from functools import wraps
import os
from flask import request
from werkzeug.utils import redirect
ssl_required_flag = os.environ.get('SSL_REQUIRED', False) == 'True'
def ssl_required(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
if ssl_required_flag and not request.is_secure:
return redirect(request.url.replace("http://", "https://"))
return fn(*args, **kwargs)
return decorated_view
| hectorbenitez/flask-heroku | flas/decorators.py | Python | mit | 408 |
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Xml;
namespace RSSFeed
{
public partial class RssView : Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindRssRepeater();
}
private void BindRssRepeater()
{
const string rssFeedUrl = "https://www.readability.com/rseero/latest/feed";
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(rssFeedUrl);
if (xmlDocument.DocumentElement != null)
{
List<Feed> feedList = new List<Feed>();
XmlNodeList nodeList = xmlDocument.DocumentElement.SelectNodes("/rss/channel/item");
if (nodeList != null)
{
foreach (XmlNode xmlNode in nodeList)
{
Feed feed = new Feed();
feed.Title = xmlNode.SelectSingleNode("title") == null ? string.Empty : xmlNode.SelectSingleNode("title").InnerText;
feed.Link = xmlNode.SelectSingleNode("link") == null ? string.Empty : xmlNode.SelectSingleNode("link").InnerText;
feed.PublishDate = xmlNode.SelectSingleNode("pubDate") == null ? string.Empty : xmlNode.SelectSingleNode("pubDate").InnerText.Substring(0, xmlNode.SelectSingleNode("pubDate").InnerText.Length - 5);
feed.Description = xmlNode.SelectSingleNode("description") == null ? string.Empty : xmlNode.SelectSingleNode("description").InnerText;
feedList.Add(feed);
}
}
else
{
errorLabel.Text = "Failed to load RSS feed";
}
rssRepeater.DataSource = feedList;
rssRepeater.DataBind();
}
else
{
errorLabel.Text = "Failed to load RSS feed";
}
}
catch (Exception ex)
{
errorLabel.Text = String.Format("Failed to populate RSS feed, exception: {0}", ex.Message);
}
}
}
} | dsjomina/RSSFeed | RSSFeed/RSSFeed/RssView.aspx.cs | C# | mit | 2,341 |
/*global Ghetto*/
(function ($) {
$('div').on('click', '.save-button', function (e) {
var id = $(this).attr('data-id');
//trim genre off the end of id (it was there for uniqueness on the page)
id = id.substring(0, id.indexOf('_'));
$('[id^=save-button-div-' + id + ']').collapse('hide');
$('[id^=watched-buttons-' + id + ']').collapse('show');
});
$('.delete-btn').click(function (e) {
e.preventDefault();
var id = $(this).attr('data-id');
if (!id) {
return;
}
var req = {
url: '/api/user/removeMovie',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
id: id
})
};
$.ajax(req).then(function (res) {
if (res.success === true) {
$('.movie-' + id).collapse('hide');
Ghetto.alert('Movie deleted!');
} else {
Ghetto.alert(res.error, { level: 'danger' });
}
});
});
$('div').on('click', '.watched-btn', function (e) {
var id = $(this).attr('data-id');
var state = $(this).attr('data-state');
//trim genre off the end of id (it was there for uniqueness on the page)
id = id.substring(0, id.indexOf('_'));
var request = {
url: '/api/user/watchMovie/' + id,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
state: state
})
};
$.ajax(request).then(function (response) {
if (!response.err) {
$('[id^=watched-buttons-' + id + ']').collapse('hide');
if (state == 2) {
$('[id^=movie-panel-' + id + ']').unbind('mouseleave mouseenter');
$('[id^=rate-' + id + ']').collapse('show');
} else {
$('.save-button[data-id^="' + id + '"]').attr('disabled', 'disabled');
$('[id^=save-button-div-' + id + ']').collapse('show');
}
} else {
console.log(response.err);
}
});
});
$('.featured .btn').click( function (e) {
e.preventDefault();
var mid = $(this).attr('data-id');
var request = {
url: '/movies/my/feature/' + mid,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({})
};
$.ajax(request).then(function (response) {
if(response.err) {
console.log(response.err);
Ghetto.alert(response.err, { level: 'danger' });
} else {
Ghetto.alert('Featured movie saved!');
}
});
});
$('.save-rating-btn').click(function (e) {
var id = $(this).attr('data-id');
var rating = parseInt($('#rating-' + id).val());
//trim genre off the end of id (it was there for uniqueness on the page)
id = id.substring(0, id.indexOf('_'));
if (rating) {
var request = {
url: '/api/movies/' + id + '/vote',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
rating: rating
})
};
$.ajax(request).then(function (response) {
resetButtons(id);
});
}
});
$('.cancel-rating-btn').click(function (e) {
var id = $(this).attr('data-id');
resetButtons(id);
});
function resetButtons (id) {
// Reset buttons and re-attach event handler
$('[id^=rate-' + id + ']').collapse('hide');
$('.save-button[data-id^="' + id + '"]').attr('disabled', 'disabled');
$('[id^=save-button-div-' + id + ']').collapse('show');
$('[id^=movie-panel-' + id + ']').bind('mouseenter', function () {
$(this).find('.movie-panel-overlay').finish();
$(this).find('.movie-panel-overlay').fadeIn(150);
}).bind('mouseleave', function () {
$(this).find('.movie-panel-overlay').fadeOut(150);
});
}
$('h2').on('click', '.btn-collapse', function (e) {
if (this.dataset.expanded === 'true') {
$(this).animate({ rotateAmount: -90 }, {
step: function (now, fx) {
$(this).css('transform', 'rotate(' + now + 'deg)');
},
duration: 150
});
this.dataset.expanded = false;
} else {
$(this).animate({ rotateAmount: 0 }, {
step: function (now, fx) {
$(this).css('transform', 'rotate(' + now + 'deg)');
},
duration: 150
});
this.dataset.expanded = true;
}
});
// For every <li><a href=[path]></a></li>, if the path is equal to the current
// browser location, give the anchor the 'active' class so it is properly
// highlighted by bootstrap
$('.navbar .navbar-nav li').each(function (_, li) {
if (li.children instanceof HTMLCollection && li.children.length > 0) {
$(li.children).each(function (_, child) {
if (child.href === document.location.href.split('#')[0]) {
li.classList.add('active');
}
});
}
});
// Display overlay when the user hovers over a movie panel
$('.movie-panel').on('mouseenter', function () {
$(this).find('.movie-panel-overlay').finish();
$(this).find('.movie-panel-overlay').fadeIn(150);
}).on('mouseleave', function () {
$(this).find('.movie-panel-overlay').fadeOut(150);
});
// Why do I need to specify this hook? I'm not sure -- maybe because
// bootstrap = dick
$('.input-group').on('focus', '.form-control', function () {
$(this).closest('.form-group, .input-group').addClass('focus');
}).on('blur', '.form-control', function () {
$(this).closest('.form-group, .input-group').removeClass('focus');
});
})(window.jQuery);
| jajmo/Ghetto-IMDB | static/js/movies.js | JavaScript | mit | 6,246 |
'use strict';
var fs = require( 'fs' );
var path = require( 'path' );
var readlineSync = require( 'readline-sync' );
require( 'plus_arrays' );
require( 'colors' );
var freqTable = require( './freqTable' );
function annotateRandomSample( inputFile, options ) {
// if path is not absolute, make it absolute with respect to dirname
if ( path.resolve( inputFile ) !== path.normalize( inputFile ) ) {
inputFile = path.normalize(__dirname + '/../' + inputFile);
}
var input = require(inputFile);
if ( options.output === undefined ){
throw new TypeError( 'Invalid argument for --output. Must provide a file name. Value: `' + options.output + '`.' );
}
if ( options.categories === undefined ) {
throw new TypeError('Invalid argument for --categories. Must provide a space-separated list of categories. Value: `' + options.categories + '`.' );
}
var categories = options.categories.split(' ');
var result = input.map(function( elem, index ) {
var o = {};
o.text = elem;
console.log('DOCUMENT ' + index + ':');
console.log(elem.green.bold);
console.log('CATEGORIES:');
console.log(categories.map(function(e,i){
return i + ':' + e;
}).join('\t'));
console.log('Please enter correct category:'.grey);
var chosenCategories = [];
function isSelection(e, i) {
return selection.contains(i) === true;
}
while ( chosenCategories.length === 0 ) {
var selection = readlineSync.question('CHOICE(S):'.white.inverse + ': ').split(' ');
chosenCategories = categories.filter(isSelection);
if ( chosenCategories.length === 0){
console.log('Not a valid input. Try again.');
}
}
o.categories = chosenCategories;
return o;
});
fs.writeFileSync(options.output, JSON.stringify(result) );
var table = freqTable( result, categories );
console.log(table);
}
module.exports = exports = annotateRandomSample;
| Planeshifter/node-wordnetify-sample | lib/annotateRandomSample.js | JavaScript | mit | 1,860 |
<?php
/*
[UCenter] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: user.php 1078 2011-03-30 02:00:29Z monkey $
*/
!defined('IN_UC') && exit('Access Denied');
class usermodel
{
var $db;
var $base;
function __construct(&$base)
{
$this->usermodel($base);
}
function usermodel(&$base)
{
$this->base = $base;
$this->db = $base->db;
}
function get_user_by_uid($uid)
{
$arr = $this->db->fetch_first("SELECT * FROM " . UC_DBTABLEPRE . "members WHERE uid='$uid'");
return $arr;
}
function get_user_by_email($email)
{
$arr = $this->db->fetch_first("SELECT * FROM " . UC_DBTABLEPRE . "members WHERE email='$email'");
return $arr;
}
function check_username($username)
{
$guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
$len = $this->dstrlen($username);
if ($len > 15 || $len < 3 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) {
return FALSE;
} else {
return TRUE;
}
}
function dstrlen($str)
{
if (strtolower(UC_CHARSET) != 'utf-8') {
return strlen($str);
}
$count = 0;
for ($i = 0; $i < strlen($str); $i++) {
$value = ord($str[$i]);
if ($value > 127) {
$count++;
if ($value >= 192 && $value <= 223) $i++;
elseif ($value >= 224 && $value <= 239) $i = $i + 2;
elseif ($value >= 240 && $value <= 247) $i = $i + 3;
}
$count++;
}
return $count;
}
function check_mergeuser($username)
{
$data = $this->db->result_first("SELECT count(*) FROM " . UC_DBTABLEPRE . "mergemembers WHERE appid='" . $this->base->app['appid'] . "' AND username='$username'");
return $data;
}
function check_usernamecensor($username)
{
$_CACHE['badwords'] = $this->base->cache('badwords');
$censorusername = $this->base->get_setting('censorusername');
$censorusername = $censorusername['censorusername'];
$censorexp = '/^(' . str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($censorusername = trim($censorusername)), '/')) . ')$/i';
$usernamereplaced = isset($_CACHE['badwords']['findpattern']) && !empty($_CACHE['badwords']['findpattern']) ? @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $username) : $username;
if (($usernamereplaced != $username) || ($censorusername && preg_match($censorexp, $username))) {
return FALSE;
} else {
return TRUE;
}
}
function check_usernameexists($username)
{
$data = $this->db->result_first("SELECT username FROM " . UC_DBTABLEPRE . "members WHERE username='$username'");
return $data;
}
function check_emailformat($email)
{
return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
function check_emailaccess($email)
{
$setting = $this->base->get_setting(array('accessemail', 'censoremail'));
$accessemail = $setting['accessemail'];
$censoremail = $setting['censoremail'];
$accessexp = '/(' . str_replace("\r\n", '|', preg_quote(trim($accessemail), '/')) . ')$/i';
$censorexp = '/(' . str_replace("\r\n", '|', preg_quote(trim($censoremail), '/')) . ')$/i';
if ($accessemail || $censoremail) {
if (($accessemail && !preg_match($accessexp, $email)) || ($censoremail && preg_match($censorexp, $email))) {
return FALSE;
} else {
return TRUE;
}
} else {
return TRUE;
}
}
function check_emailexists($email, $username = '')
{
$sqladd = $username !== '' ? "AND username<>'$username'" : '';
$email = $this->db->result_first("SELECT email FROM " . UC_DBTABLEPRE . "members WHERE email='$email' $sqladd");
return $email;
}
function check_login($username, $password, &$user)
{
$user = $this->get_user_by_username($username);
if (empty($user['username'])) {
return -1;
} elseif ($user['password'] != md5(md5($password) . $user['salt'])) {
return -2;
}
return $user['uid'];
}
function get_user_by_username($username)
{
$arr = $this->db->fetch_first("SELECT * FROM " . UC_DBTABLEPRE . "members WHERE username='$username'");
return $arr;
}
function add_user($username, $password, $email, $uid = 0, $questionid = '', $answer = '', $regip = '')
{
$regip = empty($regip) ? $this->base->onlineip : $regip;
$salt = substr(uniqid(rand()), -6);
$password = md5(md5($password) . $salt);
$sqladd = $uid ? "uid='" . intval($uid) . "'," : '';
$sqladd .= $questionid > 0 ? " secques='" . $this->quescrypt($questionid, $answer) . "'," : " secques='',";
$this->db->query("INSERT INTO " . UC_DBTABLEPRE . "members SET $sqladd username='$username', password='$password', email='$email', regip='$regip', regdate='" . $this->base->time . "', salt='$salt'");
$uid = $this->db->insert_id();
$this->db->query("INSERT INTO " . UC_DBTABLEPRE . "memberfields SET uid='$uid'");
return $uid;
}
function quescrypt($questionid, $answer)
{
return $questionid > 0 && $answer != '' ? substr(md5($answer . md5($questionid)), 16, 8) : '';
}
function edit_user($username, $oldpw, $newpw, $email, $ignoreoldpw = 0, $questionid = '', $answer = '')
{
$data = $this->db->fetch_first("SELECT username, uid, password, salt FROM " . UC_DBTABLEPRE . "members WHERE username='$username'");
if ($ignoreoldpw) {
$isprotected = $this->db->result_first("SELECT COUNT(*) FROM " . UC_DBTABLEPRE . "protectedmembers WHERE uid = '$data[uid]'");
if ($isprotected) {
return -8;
}
}
if (!$ignoreoldpw && $data['password'] != md5(md5($oldpw) . $data['salt'])) {
return -1;
}
$sqladd = $newpw ? "password='" . md5(md5($newpw) . $data['salt']) . "'" : '';
$sqladd .= $email ? ($sqladd ? ',' : '') . " email='$email'" : '';
if ($questionid !== '') {
if ($questionid > 0) {
$sqladd .= ($sqladd ? ',' : '') . " secques='" . $this->quescrypt($questionid, $answer) . "'";
} else {
$sqladd .= ($sqladd ? ',' : '') . " secques=''";
}
}
if ($sqladd) {
$this->db->query("UPDATE " . UC_DBTABLEPRE . "members SET $sqladd WHERE username='$username'");
return $this->db->affected_rows();
} else {
return -7;
}
}
function delete_user($uidsarr)
{
$uidsarr = (array)$uidsarr;
if (!$uidsarr) {
return 0;
}
$uids = $this->base->implode($uidsarr);
$arr = $this->db->fetch_all("SELECT uid FROM " . UC_DBTABLEPRE . "protectedmembers WHERE uid IN ($uids)");
$puids = array();
foreach ((array)$arr as $member) {
$puids[] = $member['uid'];
}
$uids = $this->base->implode(array_diff($uidsarr, $puids));
if ($uids) {
$this->db->query("DELETE FROM " . UC_DBTABLEPRE . "members WHERE uid IN($uids)");
$this->db->query("DELETE FROM " . UC_DBTABLEPRE . "memberfields WHERE uid IN($uids)");
uc_user_deleteavatar($uidsarr);
$this->base->load('note');
$_ENV['note']->add('deleteuser', "ids=$uids");
return $this->db->affected_rows();
} else {
return 0;
}
}
function get_total_num($sqladd = '')
{
$data = $this->db->result_first("SELECT COUNT(*) FROM " . UC_DBTABLEPRE . "members $sqladd");
return $data;
}
function get_list($page, $ppp, $totalnum, $sqladd)
{
$start = $this->base->page_get_start($page, $ppp, $totalnum);
$data = $this->db->fetch_all("SELECT * FROM " . UC_DBTABLEPRE . "members $sqladd LIMIT $start, $ppp");
return $data;
}
function name2id($usernamesarr)
{
$usernamesarr = uc_addslashes($usernamesarr, 1, TRUE);
$usernames = $this->base->implode($usernamesarr);
$query = $this->db->query("SELECT uid FROM " . UC_DBTABLEPRE . "members WHERE username IN($usernames)");
$arr = array();
while ($user = $this->db->fetch_array($query)) {
$arr[] = $user['uid'];
}
return $arr;
}
function id2name($uidarr)
{
$arr = array();
$query = $this->db->query("SELECT uid, username FROM " . UC_DBTABLEPRE . "members WHERE uid IN (" . $this->base->implode($uidarr) . ")");
while ($user = $this->db->fetch_array($query)) {
$arr[$user['uid']] = $user['username'];
}
return $arr;
}
}
?> | MyController/ucclient | src/uc_client/model/user.php | PHP | mit | 9,134 |
<?php
/**
* Configula Library
*
* @license http://opensource.org/licenses/MIT
* @link https://github.com/caseyamcl/configula
* @version 4
* @package caseyamcl/configula
* @author Casey McLaughlin <caseyamcl@gmail.com>
*
* For the full copyright and license information, - please view the LICENSE.md
* file that was distributed with this source code.
*
* ------------------------------------------------------------------
*/
declare(strict_types=1);
namespace Configula\Util;
use Generator;
use IteratorAggregate;
use SplFileInfo;
/**
* Local/Dist file iterator
*
* Iterates over files in the following order:
*
* *.dist.EXT ('.dist' is configurable)
* *.EXT
* *.local.EXT ('.local' is configurable)
*
* @author Casey McLaughlin <caseyamcl@gmail.com>
*/
class LocalDistFileIterator implements IteratorAggregate
{
/**
* @var iterable
*/
private $iterator;
/**
* @var string
*/
private $localSuffix;
/**
* @var string
*/
private $distSuffix;
/**
* LocalDistFileIterator constructor.
* @param iterable|SplFileInfo[]|string[] $fileIterator Iterate either file paths or SplFileInfo instances
* @param string $localSuffix File suffix denoting 'local' (high priority) files (always comes before extension)
* @param string $distSuffix File suffix denoting 'dist' (low priority) files (always comes before extension)
*/
public function __construct(iterable $fileIterator, string $localSuffix = '.local', string $distSuffix = '.dist')
{
$this->iterator = $fileIterator;
$this->localSuffix = $localSuffix;
$this->distSuffix = $distSuffix;
}
/**
* @return Generator|SplFileInfo[]
*/
public function getIterator()
{
$localFiles = [];
$normalFiles = [];
foreach ($this->iterator as $file) {
$basename = rtrim($file->getBasename(strtolower($file->getExtension())), '.');
if (strcasecmp(substr($basename, 0 - strlen($this->localSuffix)), $this->localSuffix) === 0) {
$localFiles[] = $file;
} elseif (strcasecmp(substr($basename, 0 - strlen($this->distSuffix)), $this->distSuffix) === 0) {
yield $file;
} else {
$normalFiles[] = $file;
}
}
foreach (array_merge($normalFiles, $localFiles) as $item) {
yield $item;
}
}
}
| caseyamcl/Configula | src/Util/LocalDistFileIterator.php | PHP | mit | 2,452 |
package pad
//
// Paxos library, to be included in an application.
// Multiple applications will run, each including
// a Paxos peer.
//
// Manages a sequence of agreed-on values.
// The set of peers is fixed.
// Copes with network failures (partition, msg loss, &c).
// Does not store anything persistently, so cannot handle crash+restart.
//
// The application interface:
//
// px = paxos.Make(peers []string, me string)
// px.Start(seq int, v interface{}) -- start agreement on new instance
// px.Status(seq int) (decided bool, v interface{}) -- get info about an instance
// px.Done(seq int) -- ok to forget all instances <= seq
// px.Max() int -- highest instance seq known, or -1
// px.Min() int -- instances before this seq have been forgotten
//
import "net"
import "net/rpc"
import "log"
/*import "os"*/
import "syscall"
import "sync"
import "fmt"
import "math/rand"
import "math"
type Paxos struct {
mu sync.Mutex
l net.Listener
dead bool
unreliable bool
rpcCount int
peers []string
me int // index into peers[]
// Your data here.
lock sync.Mutex
leader bool
n int
v interface{}
// acceptance map
A map[int]*AcceptorState
//decision state
decision map[int]Proposition
doneMap map[int]int
max int
min int
}
type AcceptorState struct {
//acceptor state
n_p int //highest prepare seen
n_a int //highest accept seen
v_a Proposition // highest accept value seen
}
const (
PrepareOK = "PrepareOK"
PrepareNand = "PrepareReject"
AcceptOK = "AcceptOK"
AcceptNand = "AcceptReject"
LearnOK = "LearnOK"
)
type PrepareArgs struct {
N int
Seq int
Peer int
DoneWith int
}
type PrepareReply struct {
Status string
N_a int
V_a Proposition
}
type AcceptArgs struct {
N int
Seq int
Val Proposition
}
type AcceptReply struct {
Status string
N int
Val Proposition
}
type LearnArgs struct {
Seq int
Val Proposition
}
type LearnReply struct {
Status string
}
type MinArgs struct {
}
type MinReply struct {
Min int
}
type Proposition struct {
Id int64
Val interface{}
}
//
// call() sends an RPC to the rpcname handler on server srv
// with arguments args, waits for the reply, and leaves the
// reply in reply. the reply argument should be a pointer
// to a reply structure.
//
// the return value is true if the server responded, and false
// if call() was not able to contact the server. in particular,
// the replys contents are only valid if call() returned true.
//
// you should assume that call() will time out and return an
// error after a while if it does not get a reply from the server.
//
// please use call() to send all RPCs, in client.go and server.go.
// please do not change this function.
//
func call(srv string, name string, args interface{}, reply interface{}) bool {
c, err := rpc.Dial("tcp", srv)
if err != nil {
err1 := err.(*net.OpError)
if err1.Err != syscall.ENOENT && err1.Err != syscall.ECONNREFUSED {
fmt.Printf("paxos Dial() failed: %v\n", err1)
}
return false
}
defer c.Close()
err = c.Call(name, args, reply)
if err == nil {
return true
}
return false
}
func (px *Paxos) Me() string {
return px.peers[px.me]
}
func (px *Paxos) Prepare(args *PrepareArgs, reply *PrepareReply) error {
px.lock.Lock()
defer px.lock.Unlock()
//adjust map of who is done with what and clear memory if possible
px.doneMap[args.Peer] = int(math.Max(float64(px.doneMap[args.Peer]), float64(args.DoneWith)))
px.delete()
state, ok := px.A[args.Seq]
if !ok {
state = &AcceptorState{-1, -1, Proposition{}}
}
if args.N > state.n_p {
state.n_p = args.N
reply.Status = PrepareOK
reply.N_a = state.n_a
reply.V_a = state.v_a
px.A[args.Seq] = state
} else {
reply.Status = PrepareNand
}
return nil
}
func (px *Paxos) Accept(args *AcceptArgs, reply *AcceptReply) error {
px.lock.Lock()
defer px.lock.Unlock()
state, ok := px.A[args.Seq]
if !ok {
state = &AcceptorState{-1, -1, Proposition{}}
}
if args.N >= state.n_p {
state.n_p = args.N
state.n_a = args.N
state.v_a = args.Val
reply.Status = AcceptOK
reply.N = args.N
reply.Val = args.Val
px.A[args.Seq] = state
} else {
reply.Status = AcceptNand
}
return nil
}
func (px *Paxos) Learn(args *LearnArgs, reply *LearnReply) error {
px.lock.Lock()
defer px.lock.Unlock()
px.decision[args.Seq] = args.Val
if args.Seq > px.max {
px.max = args.Seq
}
return nil
}
func (px *Paxos) Minquery(args *MinArgs, reply *MinReply) error {
reply.Min = px.min
return nil
}
func nrand2() int64 {
x := rand.Int63()
return x
}
//
// the application wants paxos to start agreement on
// instance seq, with proposed value v.
// Start() returns right away; the application will
// call Status() to find out if/when agreement
// is reached.
//
func (px *Paxos) Start(seq int, val interface{}) {
v := Proposition{nrand2(), val}
//proposer
go func(seq int, v Proposition) {
_, ok := px.decision[seq]
px.lock.Lock()
px.A[seq] = &AcceptorState{-1, -1, Proposition{}}
px.lock.Unlock()
n := px.me
for !ok {
//choose n, unique and higher than any n seen so far
px.lock.Lock()
for {
if px.A[seq].n_p >= n {
n += len(px.peers)
} else {
break
}
}
px.lock.Unlock()
// ------------------------ PREPARE -------------------------
//send prepare(n) to all servers including self
prepareResponseChannel := make(chan *PrepareReply, len(px.peers))
for i := 0; i < len(px.peers); i++ {
args := PrepareArgs{n, seq, px.me, px.doneMap[px.me]}
reply := &PrepareReply{}
if i == px.me {
px.Prepare(&args, reply)
prepareResponseChannel <- reply
} else {
go func(i int) {
success := call(px.peers[i], "Paxos.Prepare", args, reply)
if !success {
reply.Status = PrepareNand
}
prepareResponseChannel <- reply
return
}(i)
}
}
//prepare response handler
prepareMajorityChannel := make(chan bool, len(px.peers))
majority := false
numReplies := 0
numOK := 0
highestN := -1
value := v
go func() {
for numReplies < len(px.peers) {
reply := <-prepareResponseChannel
numReplies += 1
if reply.Status == PrepareOK {
numOK += 1
if reply.N_a > highestN {
highestN = reply.N_a
blank := Proposition{}
if reply.V_a.Id != blank.Id {
value = reply.V_a
}
}
}
if numOK > len(px.peers)/2 {
majority = true
}
}
close(prepareResponseChannel)
prepareMajorityChannel <- majority
return
}()
prepareMajority := <-prepareMajorityChannel
close(prepareMajorityChannel)
// ------------------------ ACCEPT -------------------------
// prepare majority achieved -> propose value
// begin accept phase
if prepareMajority {
//send accept to all servers including self
acceptResponseChannel := make(chan *AcceptReply, len(px.peers))
for i := 0; i < len(px.peers); i++ {
args := AcceptArgs{n, seq, value}
reply := &AcceptReply{}
if i == px.me {
px.Accept(&args, reply)
acceptResponseChannel <- reply
} else {
go func(i int) {
success := call(px.peers[i], "Paxos.Accept", args, reply)
if !success {
reply.Status = AcceptNand
}
acceptResponseChannel <- reply
return
}(i)
}
}
//accept response handler
acceptMajorityChannel := make(chan bool, len(px.peers))
majority := false
numReplies := 0
numOK := 0
go func() {
for numReplies < len(px.peers) {
reply := <-acceptResponseChannel
numReplies += 1
if reply.Status == AcceptOK && reply.Val.Id == value.Id {
numOK += 1
}
if numOK > len(px.peers)/2 {
majority = true
}
}
acceptMajorityChannel <- majority
close(acceptResponseChannel)
return
}()
acceptMajority := <-acceptMajorityChannel
close(acceptMajorityChannel)
// ------------------------ LEARN -------------------------
if acceptMajority {
//begin learn phase
// accepted by majority
for i := 0; i < len(px.peers); i++ {
args := LearnArgs{seq, value}
reply := &LearnReply{}
if i == px.me {
px.Learn(&args, reply)
} else {
go func(i int) {
success := false
// for !success {
success = call(px.peers[i], "Paxos.Learn", args, reply)
// }
if !success {
reply.Status = LearnOK
}
return
}(i)
}
}
break
} else {
// fmt.Println("Accept did not get majority")
}
} else {
// fmt.Println("Prepare did not get majority")
}
_, ok = px.decision[seq]
}
}(seq, v)
}
//
// the application on this machine is done with
// all instances <= seq.
//
// see the comments for Min() for more explanation.
//
func (px *Paxos) Done(seq int) {
// Your code here.
if seq > px.min {
px.min = seq
}
px.doneMap[px.me] = int(math.Max(float64(seq), float64(px.doneMap[px.me])))
px.delete()
}
func (px *Paxos) delete() {
px.mu.Lock()
defer px.mu.Unlock()
// delete only up to min in case server is partitioned
globalMin := px.Min()
for key := range px.A {
if key < globalMin {
delete(px.A, key)
}
}
for key := range px.decision {
if key < globalMin {
delete(px.decision, key)
}
}
}
//
// the application wants to know the
// highest instance sequence known to
// this peer.
//
func (px *Paxos) Max() int {
// Your code here.
return px.max
}
//
// Min() should return one more than the minimum among z_i,
// where z_i is the highest number ever passed
// to Done() on peer i. A peers z_i is -1 if it has
// never called Done().
//
// Paxos is required to have forgotten all information
// about any instances it knows that are < Min().
// The point is to free up memory in long-running
// Paxos-based servers.
//
// Paxos peers need to exchange their highest Done()
// arguments in order to implement Min(). These
// exchanges can be piggybacked on ordinary Paxos
// agreement protocol messages, so it is OK if one
// peers Min does not reflect another Peers Done()
// until after the next instance is agreed to.
//
// The fact that Min() is defined as a minimum over
// *all* Paxos peers means that Min() cannot increase until
// all peers have been heard from. So if a peer is dead
// or unreachable, other peers Min()s will not increase
// even if all reachable peers call Done. The reason for
// this is that when the unreachable peer comes back to
// life, it will need to catch up on instances that it
// missed -- the other peers therefor cannot forget these
// instances.
//
func (px *Paxos) Min() int {
globalMin := px.doneMap[px.me]
for _, peerMin := range px.doneMap {
globalMin = int(math.Min(float64(globalMin), float64(peerMin)))
}
return globalMin + 1
}
//
// the application wants to know whether this
// peer thinks an instance has been decided,
// and if so what the agreed value is. Status()
// should just inspect the local peer state;
// it should not contact other Paxos peers.
//
func (px *Paxos) Status(seq int) (bool, interface{}) {
// Your code here.
if val, ok := px.decision[seq]; ok {
return true, val.Val
}
return false, nil
}
//
// tell the peer to shut itself down.
// for testing.
// please do not change this function.
//
func (px *Paxos) Kill() {
px.dead = true
if px.l != nil {
px.l.Close()
}
}
//
// the application wants to create a paxos peer.
// the ports of all the paxos peers (including this one)
// are in peers[]. this servers port is peers[me].
//
func MakePaxosInstance(peers []string, me int, rpcs *rpc.Server) *Paxos {
px := &Paxos{}
px.peers = peers
px.me = me
// Your initialization code here.
px.doneMap = make(map[int]int)
for i, _ := range px.peers {
px.doneMap[i] = -1
}
px.decision = make(map[int]Proposition)
px.A = make(map[int]*AcceptorState)
px.max = -1
px.min = -1
if rpcs != nil {
// caller will create socket &c
rpcs.Register(px)
} else {
rpcs = rpc.NewServer()
rpcs.Register(px)
// prepare to receive connections from clients.
// change "unix" to "tcp" to use over a network.
// os.Remove(peers[me]) // only needed for "unix"
l, e := net.Listen("tcp", peers[me])
if e != nil {
log.Fatal("listen error: ", e)
}
px.l = l
// please do not change any of the following code,
// or do anything to subvert it.
// create a thread to accept RPC connections
go func() {
for px.dead == false {
conn, err := px.l.Accept()
if err == nil && px.dead == false {
if px.unreliable && (rand.Int63()%1000) < 100 {
// discard the request.
conn.Close()
} else if px.unreliable && (rand.Int63()%1000) < 200 {
// process the request but force discard of reply.
c1 := conn.(*net.UnixConn)
f, _ := c1.File()
err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
if err != nil {
fmt.Printf("shutdown: %v\n", err)
}
px.rpcCount++
go rpcs.ServeConn(conn)
} else {
px.rpcCount++
go rpcs.ServeConn(conn)
}
} else if err == nil {
conn.Close()
}
if err != nil && px.dead == false {
fmt.Printf("Paxos(%v) accept: %v\n", me, err.Error())
}
}
}()
}
return px
}
| jdhenke/pad | server/pad/paxos.go | GO | mit | 13,355 |
<?php
namespace Jenny\ImportBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class JennyImportBundle extends Bundle
{
}
| jennydjen/NoteDeFrais | src/Jenny/ImportBundle/JennyImportBundle.php | PHP | mit | 130 |
using System;
namespace LexicalAnalysis {
/// <summary>
/// String literal
/// </summary>
public sealed class TokenString : Token {
public TokenString(String val, String raw) {
if (val == null) {
throw new ArgumentNullException(nameof(val));
}
this.Val = val;
this.Raw = raw;
}
public override TokenKind Kind { get; } = TokenKind.STRING;
public String Raw { get; }
public String Val { get; }
public override String ToString() =>
$"{this.Kind}: \"{this.Raw}\"\n\"{this.Val}\"";
}
public sealed class FSAString : FSA {
private enum State {
START,
END,
ERROR,
L,
Q,
QQ
};
private State _state;
private readonly FSAChar _fsachar;
private String _val;
private String _raw;
public FSAString() {
this._state = State.START;
this._fsachar = new FSAChar('\"');
this._raw = "";
this._val = "";
}
public override void Reset() {
this._state = State.START;
this._fsachar.Reset();
this._raw = "";
this._val = "";
}
public override FSAStatus GetStatus() {
if (this._state == State.START) {
return FSAStatus.NONE;
}
if (this._state == State.END) {
return FSAStatus.END;
}
if (this._state == State.ERROR) {
return FSAStatus.ERROR;
}
return FSAStatus.RUNNING;
}
public override Token RetrieveToken() {
return new TokenString(this._val, this._raw);
}
public override void ReadChar(Char ch) {
switch (this._state) {
case State.END:
case State.ERROR:
this._state = State.ERROR;
break;
case State.START:
switch (ch) {
case 'L':
this._state = State.L;
break;
case '\"':
this._state = State.Q;
this._fsachar.Reset();
break;
default:
this._state = State.ERROR;
break;
}
break;
case State.L:
if (ch == '\"') {
this._state = State.Q;
this._fsachar.Reset();
} else {
this._state = State.ERROR;
}
break;
case State.Q:
if (this._fsachar.GetStatus() == FSAStatus.NONE && ch == '\"') {
this._state = State.QQ;
this._fsachar.Reset();
} else {
this._fsachar.ReadChar(ch);
switch (this._fsachar.GetStatus()) {
case FSAStatus.END:
this._state = State.Q;
this._val = this._val + this._fsachar.RetrieveChar();
this._raw = this._raw + this._fsachar.RetrieveRaw();
this._fsachar.Reset();
ReadChar(ch);
break;
case FSAStatus.ERROR:
this._state = State.ERROR;
break;
default:
break;
}
}
break;
case State.QQ:
this._state = State.END;
break;
default:
this._state = State.ERROR;
break;
}
}
public override void ReadEOF() {
if (this._state == State.QQ) {
this._state = State.END;
} else {
this._state = State.ERROR;
}
}
}
} | phisiart/C-Compiler | Scanner/String.cs | C# | mit | 4,376 |
package org.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
/**
* Common utilities and code shared for both the client and server.
*
*/
public class Utils
{
public static final String SUCCESS_STS = "status 000 OK";
public static final String FAIL_INTERNAL = "status 200 Internal Error";
public static final String FAIL_LOGIN_USERNAME_TAKEN = "status 111 Username Taken";
public static final String FAIL_LOGIN_USERNAME_INVALID = "status 112 Username Invalid";
public static final String FAIL_LOGIN_PASSWORD_INVALID = "status 113 Password Invalid";
public static final String FAIL_LOGIN_PERMISSION_DENIED = "status 212 Permission Denied";
public static final String FAIL_USER_NOT_ONLINE = "status 131 User Not Online";
/**
* Does nothing but provide an easy way to test our test harness.
*
* @return Life, the universe, everything
*/
public int get42( )
{
return 42;
}
/**
* Send message out provided printwriter, terminated with EOT.
*
* @param out - the output stream for the connected socket associated with the user
* @param msg - formatted message to send
*
* @return integer 0 on success, -1 on fail
*/
public static int sendMessage(PrintWriter out, String msg) {
int EOT = 0x04;
msg = msg + Character.toString((char) EOT);
out.print(msg);
out.flush();
return 0;
}
/**
* Receive an EOT terminated message.
*
* @param - in - buffered reader for socket to receive on
*
* @return msg - received message without the EOT character
*/
public static String receiveMessage(BufferedReader in) {
String message = "";
int EOT = 0x04;
int character = 0;
try {
// read until failure or until end of message
while((character = in.read()) != -1) {
if(character == EOT) {
// that's the end of message
break;
}
message = message + Character.toString((char) character);
}
} catch (IOException e) {
System.out.println("Failed to receive message. Make sure to provide proper certificate store.");
// error case return empty string
return "";
}
// now we have the message read in
return message;
}
/**
* Given a protocol message, tokenize it into a TokenPair. This
* just means that the first word is split out from the rest, and a tuple
* of the first and rest is returned.
*
* @param str - the entire protocol message to tokenize
*
* @return TokenPair of the tokenized strings
*/
public static TokenPair tokenize(String str) {
String first = str.substring(0, str.indexOf(' '));
String rest = str.substring(str.indexOf(' ') + 1);
TokenPair tp = new TokenPair(first, rest);
return tp;
}
/**
* Given a plaintext password, return the SHA256 hash for storage and verification.
*
* @param plaintext - String to calculate SHA-256 hash of
*
* @return hex string of SHA-256 hash. Empty string on error, which means the algorithm
* was not found. Since we do not vary the algorithm, this is never expected.
*/
public static String hashPass(String plaintext) {
// SHA 256 is a 32-byte output, which is too large to store as an integer
// in sqlite (max 8 bytes). We could truncate, instead we'll convert to
// String and store characters.
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
System.out.println("ERR: Unable to calculate hash, Algorithm not found.");
return "";
}
md.update(plaintext.getBytes());
byte[] result = md.digest();
// Now we have the hash bytes in result, format as a string and return.
return DatatypeConverter.printHexBinary(result);
}
/**
* Check of whether a username is valid.
*
* @param username - String of the username to check
*
* @return boolean true if OK, false if not
*/
public static boolean isValidUsername(String username) {
// We'll use a single regular expression to allow only regular characters and
// digits for the username
return username.matches("[a-zA-Z0-9]+");
}
/**
* Check of whether a password is valid.
*
* @param password - String of the password to check
*
* @return boolean true if OK, false if not
*/
public static boolean isValidPassword(String password) {
// Password is more permissive than username, allow some punctuation
// as well.
return password.matches("[a-zA-Z0-9_!.,@]+");
}
}
| or-drop-tables-team/sup | common/src/main/java/org/common/Utils.java | Java | mit | 5,092 |
<?php namespace Rareloop\Primer\Commands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Rareloop\Primer\Primer;
class PatternMake extends Command
{
protected function configure()
{
$this
->setName('pattern:make')
->setDescription('Create a pattern')
->addArgument(
'id',
InputArgument::REQUIRED,
'Full ID of the pattern (e.g. components/group/name'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument('id');
$cleanId = Primer::cleanId($id);
// Does the pattern already exist?
$patternPath = Primer::$PATTERN_PATH . '/' . $cleanId;
if (file_exists($patternPath)) {
$output->writeln('');
$output->writeln('<error>`'.$cleanId.'` already exists</error>');
$output->writeln('');
return;
}
$success = @mkdir($patternPath, 0777, true);
if (!$success) {
$error = error_get_last();
$output->writeln('');
$output->writeln('<error>`'.$error['message'].'` already exists</error>');
$output->writeln('');
return;
}
$templateClass = Primer::$TEMPLATE_CLASS;
$templateExtension = $templateClass::$extension;
@touch($patternPath . '/template.' . $templateExtension);
@touch($patternPath . '/data.json');
$output->writeln('<info>Pattern `' . $cleanId . '` created</info>');
}
}
| joelambert/primer-core | src/Primer/Commands/PatternMake.php | PHP | mit | 1,788 |
using System.ComponentModel.DataAnnotations;
using KPI.Infrastructure;
namespace KPI.Catalog.Domain
{
public class Brand : Entity
{
public string Name { get; set; }
public string SeoTitle { get; set; }
[StringLength(5000)]
public string Description { get; set; }
public bool IsPublished { get; set; }
public bool IsDeleted { get; set; }
}
}
| netcoreangular2group/Dot-Net-Core-Rest-Api | Modules/Catalog/KPI.Catalog.Domain/Brand.cs | C# | mit | 409 |
<?php
namespace App\UserBundle\DataFixtures\ORM;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use App\SettingsBundle\Entity\Settings;
class SettingsData extends AbstractFixture implements OrderedFixtureInterface {
public function load(ObjectManager $manager) {
$entity = new Settings();
$entity->setValue("slogan");
$entity->setValue("Twój slogan");
$entity->setValue("company_name");
$entity->setValue("Nazwa Firmy");
$entity->setValue("company_host");
$entity->setValue("www.companyhost.pl");
$entity->setValue("first_name");
$entity->setValue("Imie");
$entity->setValue("last_name");
$entity->setValue("Nazwisko");
$entity->setValue("email_main");
$entity->setValue("info@gisoft.pl");
$entity->setValue("email");
$entity->setValue("ostraszewski@o2.pl");
$entity->setValue("phone");
$entity->setValue("telefin");
$entity->setValue("culture");
$entity->setValue("pl_PL");
$entity->setValue("lang");
$entity->setValue("pl");
$manager->persist($entity);
$manager->flush();
}
public function getOrder() {
return 2; // the order in which fixtures will be loaded
}
}
| gisoftlab/SymfonyCMS | src/App/SettingsBundle/DataFixtures/ORM/SettingsData.php | PHP | mit | 1,535 |
using UnityEngine;
using System.Collections;
public class SelfDestructPS : MonoBehaviour {
ParticleSystem ps;
// Use this for initialization
void Start () {
ps = GetComponent<ParticleSystem>();
}
// Update is called once per frame
void Update () {
if (!ps.IsAlive())
Destroy(gameObject);
}
}
| thk123/WizardsRitual | Get Off My Spawn/Assets/SelfDestructPS.cs | C# | mit | 338 |
//@@author A0147996E
package seedu.address.testutil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.TaskManager;
import seedu.address.model.task.Task;
import seedu.address.model.task.UniqueTaskList;
public class TypicalTestEvents {
public TestEvent gym, gym2, gym3, cs2103, study, assignment, date, date2, date3, date4, meeting,
familyDinner, travel, shopping, shopping2;
public TypicalTestEvents() {
try {
gym = new EventBuilder().withName("gym").withDate("20/12/2017").withTime(
"20:00").withDescription("50min workout").withStartDate("20/11/2017").withStartTime("19:00").
withTag("personal").withVenue("gym").withPriority("2").withFavorite(true)
.withFinished(false).withEvent(true).build();
//gym2 and gym3 are built for findCommandTest
gym2 = new EventBuilder().withName("gym").withDate("21/12/2017").withTime(
"20:00").withDescription("50min workout").withStartDate("20/11/2017").withStartTime("").
withTag("personal").withVenue("gym").withPriority("2").withFavorite(false)
.withFinished(false).withEvent(true).build();
gym3 = new EventBuilder().withName("gym").withDate("22/12/2017").withTime(
"20:00").withDescription("50min workout").withStartDate("20/11/2017").withStartTime("").
withTag("personal").withVenue("gym").withPriority("2").withFavorite(false)
.withFinished(false).withEvent(true).build();
cs2103 = new EventBuilder().withName("cs2103").withDate("01/02").withTime(
"16:00").withDescription("Crazy but useful mod").
withTag("school").withVenue("icube").withPriority("1").withFavorite(true)
.withStartDate("20/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build();
study = new EventBuilder().withName("study").withDate("21/03").withTime(
"15:34").withDescription("Study for MTE").
withTag("school").withVenue("Central lib").withPriority("2").withFavorite(true)
.withStartDate("20/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build();
assignment = new EventBuilder().withName("assignment").withDate("10/12/2017").withTime(
"10:00").withDescription("IE2150").
withTag("study").withVenue("Utown").withPriority("2").withFavorite(true)
.withStartDate("02/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build();
//The test tasks below are for duplicate task testing
date = new EventBuilder().withName("date").withDate("14/02/2018").withTime(
"12:00").withDescription("Most important day").withFinished(false).
withTag("personal").withVenue("Gardens by the bay").withPriority("3")
.withStartDate("11/02/2018").withStartTime("08:00").withFavorite(false).withEvent(true).build();
date2 = new EventBuilder().withName("date").withDate("14/02/2020").withTime(
"12:00").withDescription("Most important day").withFinished(false).
withTag("personal").withVenue("Gardens by the bay").withPriority("3")
.withStartDate("tmr").withStartTime("19:00").withFavorite(false).withEvent(true).build();
date3 = new EventBuilder().withName("date").withDate("14/02/2018").withTime(
"12:00").withDescription("Most important day").withFinished(false).
withTag("personal").withVenue("Gardens by the bay").withPriority("3")
.withStartDate("11/02/2018").withStartTime("09:00").withFavorite(false).withEvent(true).build();
date4 = new EventBuilder().withName("date").withDate("14/02/2018").withTime(
"12:00").withDescription("Most important day").
withTag("private").withVenue("Gardens by the bay").withPriority("3").withFinished(false)
.withStartDate("11/02/2018").withStartTime("08:00").withFavorite(false).withEvent(true).build();
//The test tasks above are for duplicate task testing
meeting = new EventBuilder().withName("meeting").withDate("27/04/2017").withTime(
"12:00").withDescription("Meeting old friends").
withTag("school").withVenue("PGP").withPriority("2").withFavorite(false)
.withStartDate("25/04/2017").withStartTime("19:00").withFinished(false).withEvent(true).build();
familyDinner = new EventBuilder().withName("family dinner").withDate("1/1").withTime(
"20:00").withDescription("Meeting families").
withTag("family").withVenue("home").withPriority("important").withFavorite(true)
.withStartDate("20/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build();
travel = new EventBuilder().withName("travel").withDate("1/01/2018").withTime(
"").withDescription("To Africa").
withTag("personal").withVenue("Africa").withPriority("important").withFinished(false)
.withStartDate("20/12/2017").withStartTime("").withFavorite(true).withEvent(true).build();
//shopping violates start date constraint
shopping = new EventBuilder().withName("shopping").withDate("1/01/2018").withTime(
"").withDescription("Shopping in Airport").
withTag("personal").withVenue("Airport").withPriority("3").withFavorite(true)
.withStartDate("20/12/2018").withStartTime("").withFinished(false).withEvent(true).build();
} catch (IllegalValueException e) {
throw new IllegalStateException("Unable to build task");
}
}
public static void loadTaskManagerWithSampleData(TaskManager tm) {
for (TestEvent task : new TypicalTestEvents().getTypicalEvents()) {
try {
tm.addTask(new Task(task));
} catch (UniqueTaskList.DuplicateTaskException e) {
assert false : "not possible";
} catch (IllegalValueException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public TestEvent[] getTypicalEvents() {
TestEvent[] events = {gym, gym2, gym3, cs2103, study, assignment, date};
List<TestEvent> listOfEvents = asList(events);
listOfEvents = sort(listOfEvents);
return listOfEvents.toArray(new TestEvent[listOfEvents.size()]);
}
private <T> List<T> asList(T[] objs) {
List<T> list = new ArrayList<>();
for (T obj : objs) {
list.add(obj);
}
return list;
}
private static List<TestEvent> sort(List<TestEvent> list) {
Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getTag().compareTo(t2.getTag()));
Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getName().compareTo(t2.getName()));
Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getTime().compareTo(t2.getTime()));
Collections.sort(list, (TestEvent t1, TestEvent t2) -> -t1.getPriority().compareTo(t2.getPriority()));
Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getDate().compareTo(t2.getDate()));
return list;
}
public TaskManager getTypicalTaskManager() {
TaskManager tm = TaskManager.getStub();
loadTaskManagerWithSampleData(tm);
return tm;
}
}
| CS2103JAN2017-W10-B1/main | src/test/java/seedu/address/testutil/TypicalTestEvents.java | Java | mit | 7,866 |
/*!
* datastructures-js
* priorityQueue
* Copyright(c) 2015 Eyas Ranjous <eyas@eyasranjous.info>
* MIT Licensed
*/
var queue = require('./queue');
function priorityQueue() {
'use strict';
var prototype = queue(), // queue object as the prototype
self = Object.create(prototype);
// determine the top priority element
self.getTopPriorityIndex = function() {
var length = this.elements.length;
if (length > 0) {
var pIndex = 0;
var p = this.elements[0].priority;
for (var i = 1; i < length; i++) {
var priority = this.elements[i].priority;
if (priority < p) {
pIndex = i;
p = priority;
}
}
return pIndex;
}
return -1;
};
self.enqueue = function(el, p) {
p = parseInt(p);
if (isNaN(p)) {
throw {
message: 'priority should be an integer'
};
}
this.elements.push({ // element is pushed as an object with a priority
element: el,
priority: p
});
};
self.dequeue = function() {
var pIndex = self.getTopPriorityIndex();
return pIndex > -1 ? this.elements.splice(pIndex, 1)[0].element : null;
};
self.front = function() {
return !this.isEmpty() ? this.elements[0].element : null;
};
self.back = function() {
return !self.isEmpty() ? this.elements[this.elements.length - 1].element : null;
};
return self;
}
module.exports = priorityQueue; | Bryukh/datastructures-js | lib/priorityQueue.js | JavaScript | mit | 1,632 |
package org.runetranscriber.core;
import java.awt.Font;
/**
* Defines methods required by a rune to font letter transcriber.
*
* @param <R> Rune type parameter.
* @param <F> Font letter type parameter.
*/
public interface FontTranscriber<R extends Rune, F extends FontLetter> extends
Transcriber<RuneList<R>, R, FontLetterList<F>, F>
{
/**
* @return the default font size.
*/
float getDefaultFontSize();
/**
* @return font.
*/
Font getFont();
/**
* @param fontSize Font size.
*
* @return font.
*/
Font getFont(float fontSize);
/**
* @param rune From rune.
* @param fontLetter To font letter.
*/
void put(final R rune, final F fontLetter);
}
| jmthompson2015/runetranscriber | core/src/main/java/org/runetranscriber/core/FontTranscriber.java | Java | mit | 748 |
Minder.run(function($rootScope) {
angular.element("body").fadeIn(300);
// Add runtime tasks here
}); | jeremythuff/minderui | app/config/runTime.js | JavaScript | mit | 107 |
# -*- coding: utf-8 -*-
"""
Setuptools script for the xbee-helper project.
"""
import os
from textwrap import fill, dedent
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
def required(fname):
return open(
os.path.join(
os.path.dirname(__file__), fname
)
).read().split('\n')
setup(
name="xbee-helper",
version="0.0.7",
packages=find_packages(
exclude=[
"*.tests",
"*.tests.*",
"tests.*",
"tests",
"*.ez_setup",
"*.ez_setup.*",
"ez_setup.*",
"ez_setup",
"*.examples",
"*.examples.*",
"examples.*",
"examples"
]
),
scripts=[],
entry_points={},
include_package_data=True,
setup_requires='pytest-runner',
tests_require='pytest',
install_requires=required('requirements.txt'),
test_suite='pytest',
zip_safe=False,
# Metadata for upload to PyPI
author='Ellis Percival',
author_email="xbee-helper@failcode.co.uk",
description=fill(dedent("""\
This project offers a high level API to an XBee device running an
up-to-date version of the ZigBee firmware. It builds upon the existing
XBee project by abstracting more functionality into methods.
""")),
classifiers=[
"Programming Language :: Python",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Topic :: Communications",
"Topic :: Home Automation",
"Topic :: Software Development :: Embedded Systems",
"Topic :: System :: Networking"
],
license="MIT",
keywords="",
url="https://github.com/flyte/xbee-helper"
)
| flyte/xbee-helper | setup.py | Python | mit | 1,972 |
package HealthAndFitnessBlog.bindingModel;
import javax.validation.constraints.NotNull;
public class UserBindingModel {
@NotNull
private String email;
@NotNull
private String fullName;
@NotNull
private String password;
@NotNull
private String confirmPassword;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
}
| HealthAndFitnessBlog/HealthAndFitnessBlog | blog/src/main/java/HealthAndFitnessBlog/bindingModel/UserBindingModel.java | Java | mit | 939 |
<?php
namespace Acf\AdminBundle\Form\Autoinc;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
*
* @author sasedev <seif.salah@gmail.com>
*/
class UpdateTForm extends AbstractType
{
/**
* Form builder
*
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('description', TextareaType::class, array(
'label' => 'Autoinc.description.label',
'required' => false
));
}
/**
*
* @return string
*/
public function getName()
{
return 'AutoincUpdateForm';
}
/**
*
* {@inheritdoc} @see AbstractType::getBlockPrefix()
*/
public function getBlockPrefix()
{
return $this->getName();
}
/**
* get the default options
*
* @return multitype:string multitype:string
*/
public function getDefaultOptions()
{
return array(
'validation_groups' => array(
'Default'
)
);
}
/**
*
* {@inheritdoc} @see AbstractType::configureOptions()
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults($this->getDefaultOptions());
}
}
| sasedev/acf-expert | src/Acf/AdminBundle/Form/Autoinc/UpdateTForm.php | PHP | mit | 1,494 |
package scratchlib.objects;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import scratchlib.project.ScratchProject;
import scratchlib.writer.ScratchOutputStream;
/**
* Maps instances of {@link ScratchObject} to reference IDs, offering insertion,
* lookup and iteration methods.
*/
public class ScratchReferenceTable implements Iterable<ScratchObject>
{
private final List<ScratchObject> references = new ArrayList<>();
/**
* Performs a reference lookup for the given {@link ScratchObject}.
*
* @param object The object to look up.
* @return The object's reference ID, or -1 if not found.
*/
public int lookup(ScratchObject object)
{
int index = references.indexOf(object);
return index == -1 ? index : index + 1;
}
/**
* Performs an object lookup for the given reference ID.
*
* @param referenceID The ID to look up.
* @return The referenced object, or null if not found.
*/
public ScratchObject lookup(int referenceID)
{
if (referenceID < 1 || referenceID > references.size()) {
return null;
}
return references.get(referenceID - 1);
}
/**
* Inserts the given {@link ScratchObject} into this reference table. The ID
* is determined automatically. True is returned if the object was newly
* inserted, false otherwise.
*
* @param object The object to insert.
* @return Whether the element was newly inserted (true), or not (false).
*/
public boolean insert(ScratchObject object)
{
if (references.contains(object)) {
return false;
}
references.add(object);
return true;
}
/**
* @return The number of references stored.
*/
public int size()
{
return references.size();
}
@Override
public Iterator<ScratchObject> iterator()
{
return references.iterator();
}
/**
* Convenience method. If the object is inline, it is written out directly
* via its {@code writeTo(...)} method; otherwise, the reference stored for
* it in this table is written instead.
*
* <p>
* This is useful for fields of other objects.
*
* @param o The object to write.
* @param out The stream to write to.
* @param project The project the object is part of.
* @throws IOException
*/
public void writeField(ScratchObject o, ScratchOutputStream out, ScratchProject project) throws IOException
{
int ref = lookup(o);
if (!(o instanceof IScratchReferenceType) || ref < 1) {
o.writeTo(out, this, project);
return;
}
out.write(99);
out.write24bitUnsignedInt(ref);
}
}
| JangoBrick/scratchlib | src/main/java/scratchlib/objects/ScratchReferenceTable.java | Java | mit | 2,833 |
#include "choice.h"
#include "header.h"
#include "destination.h"
#include <cassert>
#include "parse_tree_visitor.h"
namespace fabula
{
namespace parsing
{
namespace node
{
Choice::Choice(const std::shared_ptr<Header>& header, const std::shared_ptr<Destination>& destination)
: header(header), destination(destination) {}
ParseNode::NodeType Choice::nodeType()
{
return NodeType::Choice;
}
}
}
}
| lightofanima/Fabula | src/ParseNodes/choice.cpp | C++ | mit | 517 |
var Scene = function(gl) {
this.noiseTexture = new Texture2D(gl, "media/lab4_noise.png");
this.brainTexture = new Texture2D(gl, "media/brain-at_1024.jpg");
this.brainTextureHD = new Texture2D(gl, "media/brain-at_4096.jpg");
this.matcapGreen = new Texture2D(gl, "media/Matcap/matcap4.jpg");
this.skyCubeTexture = new
TextureCube(gl, [
"media/posx.jpg",
"media/negx.jpg",
"media/posy.jpg",
"media/negy.jpg",
"media/posz.jpg",
"media/negz.jpg",]
);
this.timeAtLastFrame = new Date().getTime();
this.vsEnvirCube = new Shader(gl, gl.VERTEX_SHADER, "cube_vs.essl");
this.fsEnvirCube = new Shader(gl, gl.FRAGMENT_SHADER, "cube_fs.essl");
this.vsNoiseShader = new Shader(gl, gl.VERTEX_SHADER, "vsNoiseShader.essl");
this.fsNoiseShader = new Shader(gl, gl.FRAGMENT_SHADER, "fsNoiseShader.essl");
this.cubeEnvirProgram = new Program (gl, this.vsEnvirCube, this.fsEnvirCube);
this.noiseProgram = new Program (gl, this.vsNoiseShader, this.fsNoiseShader);
this.quadGeometry = new QuadGeometry(gl);
this.brainMaterial = new Material (gl, this.noiseProgram);
this.brainMaterial.background.set (this.skyCubeTexture);
this.brainMaterial.noiseTexture.set (this.noiseTexture);
this.brainMaterial.brainTex.set (this.brainTextureHD);
//this.brainMaterial.brainTex.set (this.brainTexture);
this.brainMaterial.matcapTex.set (this.matcapGreen);
this.NoiseMaterial = new Material(gl, this.noiseProgram);
this.NoiseMaterial.background.set (this.skyCubeTexture);
this.NoiseMaterial.noiseTexture.set (this.noiseTexture);
this.NoiseMesh = new Mesh (this.quadGeometry, this.brainMaterial);
this.NoiseObj = new GameObject2D(this.NoiseMesh);
this.cubeMaterial = new Material(gl, this.cubeEnvirProgram);
this.cubeMaterial. envMapTexture.set (
this.skyCubeTexture);
this.envirMesh = new Mesh (this.quadGeometry, this.cubeMaterial);
this.environment = new GameObject2D (this.envirMesh);
this.gameObjects = [this.NoiseObj /*, this.environment*/];
this.camera = new PerspectiveCamera();
gl.disable(gl.BLEND);
gl.enable(gl.DEPTH_TEST);
gl.blendFunc(
gl.SRC_ALPHA,
gl.ONE_MINUS_SRC_ALPHA);
this.elapsedTime = 0.0;
this.zSetTime = 0.0;
this.zValue = 0;
};
Scene.prototype.update = function(gl, keysPressed) {
//jshint bitwise:false
//jshint unused:false
var timeAtThisFrame = new Date().getTime();
var dt = (timeAtThisFrame - this.timeAtLastFrame) / 1000.0;
this.elapsedTime += dt;
this.timeAtLastFrame = timeAtThisFrame;
this.zSetTime += dt;
if (this.zSetTime > 0.03)
{
this.zSetTime = 0.0
//this.brainMaterial.z.set (this.zValue);
this.zValue += 1;
}
// clear the screen
gl.clearColor(0.6, 0.0, 0.3, 1.0);
gl.clearDepth(1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
this.camera.move(dt, keysPressed);
for(var i=0; i<this.gameObjects.length; i++) {
this.gameObjects[i].move (dt);
this.gameObjects[i].updateModelTransformation ();
this.gameObjects[i].draw(this.camera);
}
};
Scene.prototype.mouseMove = function(event) {
this.camera.mouseMove(event);
}
Scene.prototype.mouseDown = function(event) {
this.camera.mouseDown(event);
}
Scene.prototype.mouseUp = function(event) {
this.camera.mouseUp(event);
} | RyperHUN/RenderingExamples | RayMarchingVolumetric_Brain/js/Scene.js | JavaScript | mit | 3,266 |
package nsqd
// the core algorithm here was borrowed from:
// Blake Mizerany's `noeqd` https://github.com/bmizerany/noeqd
// and indirectly:
// Twitter's `snowflake` https://github.com/twitter/snowflake
// only minor cleanup and changes to introduce a type, combine the concept
// of workerID + datacenterId into a single identifier, and modify the
// behavior when sequences rollover for our specific implementation needs
import (
"encoding/hex"
"errors"
"time"
)
const (
workerIDBits = uint64(10)
sequenceBits = uint64(12)
workerIDShift = sequenceBits
timestampShift = sequenceBits + workerIDBits
sequenceMask = int64(-1) ^ (int64(-1) << sequenceBits)
// ( 2012-10-28 16:23:42 UTC ).UnixNano() >> 20
twepoch = int64(1288834974288)
)
var ErrTimeBackwards = errors.New("time has gone backwards")
var ErrSequenceExpired = errors.New("sequence expired")
var ErrIDBackwards = errors.New("ID went backward")
type guid int64
type guidFactory struct {
sequence int64
lastTimestamp int64
lastID guid
}
func (f *guidFactory) NewGUID(workerID int64) (guid, error) {
// divide by 1048576, giving pseudo-milliseconds
// ts 是 nano » 20, 也就是 1 ts = 1048576 nano, 而 1 milliseconds = 1000000 nano;
// 这就是注释里说的 “giving pseudo-milliseconds” ,ts 近似等于 1毫秒
ts := time.Now().UnixNano() >> 20
if ts < f.lastTimestamp {
return 0, ErrTimeBackwards
}
if f.lastTimestamp == ts {
f.sequence = (f.sequence + 1) & sequenceMask
if f.sequence == 0 {
return 0, ErrSequenceExpired
}
} else {
f.sequence = 0
}
f.lastTimestamp = ts
// id = [ 37位ts + ?位 workerId + 12位 sequence ]
// workerid 必须 小于 1024, 也就是10位; 而这个是靠启动nsqd的时候检查配置项实现的
id := guid(((ts - twepoch) << timestampShift) |
(workerID << workerIDShift) |
f.sequence)
if id <= f.lastID {
return 0, ErrIDBackwards
}
f.lastID = id
return id, nil
}
func (g guid) Hex() MessageID {
var h MessageID
var b [8]byte
b[0] = byte(g >> 56)
b[1] = byte(g >> 48)
b[2] = byte(g >> 40)
b[3] = byte(g >> 32)
b[4] = byte(g >> 24)
b[5] = byte(g >> 16)
b[6] = byte(g >> 8)
b[7] = byte(g)
hex.Encode(h[:], b[:])
return h
}
| feixiao/nsq-0.3.7 | nsqd/guid.go | GO | mit | 2,223 |
from .base import KaffeError
from .core import GraphBuilder, DataReshaper, NodeMapper
from . import tensorflow
| polltooh/FineGrainedAction | nn/kaffe/__init__.py | Python | mit | 111 |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _imageWriter = require('./image-writer');
var _imageWriter2 = _interopRequireDefault(_imageWriter);
var Message = (function (_DBModel) {
_inherits(Message, _DBModel);
function Message(conf) {
_classCallCheck(this, Message);
_get(Object.getPrototypeOf(Message.prototype), 'constructor', this).call(this);
this.writer = new _imageWriter2['default'](conf.IMAGE_PATH);
}
_createClass(Message, [{
key: 'create',
value: function create(user, text) {
return regeneratorRuntime.async(function create$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.next = 2;
return regeneratorRuntime.awrap(this.query.getOne('createMessage', [user.id, text]));
case 2:
return context$2$0.abrupt('return', context$2$0.sent);
case 3:
case 'end':
return context$2$0.stop();
}
}, null, this);
}
}, {
key: 'createImage',
value: function createImage(user, raw, type) {
var name;
return regeneratorRuntime.async(function createImage$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.next = 2;
return regeneratorRuntime.awrap(this.writer.write(raw, type));
case 2:
name = context$2$0.sent;
context$2$0.next = 5;
return regeneratorRuntime.awrap(this.query.getOne('createImageMessage', [user.id, 'img/' + name]));
case 5:
return context$2$0.abrupt('return', context$2$0.sent);
case 6:
case 'end':
return context$2$0.stop();
}
}, null, this);
}
}, {
key: 'getLatest',
value: function getLatest(id) {
return regeneratorRuntime.async(function getLatest$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
if (!id || id == null || id < 1) id = 999999;
context$2$0.next = 3;
return regeneratorRuntime.awrap(this.query.getAll('getMessageInterval', [id]));
case 3:
return context$2$0.abrupt('return', context$2$0.sent);
case 4:
case 'end':
return context$2$0.stop();
}
}, null, this);
}
}]);
return Message;
})(DBModel);
exports['default'] = Message;
module.exports = exports['default']; | ordinarygithubuser/chat-es7 | server/model/message.js | JavaScript | mit | 4,285 |
require 'test_helper'
class PlatoonsControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:platoons)
end
test "should get new" do
get :new
assert_response :success
end
test "should create platoon" do
assert_difference('Platoon.count') do
post :create, :platoon => { }
end
assert_redirected_to platoon_path(assigns(:platoon))
end
test "should show platoon" do
get :show, :id => platoons(:one).to_param
assert_response :success
end
test "should get edit" do
get :edit, :id => platoons(:one).to_param
assert_response :success
end
test "should update platoon" do
put :update, :id => platoons(:one).to_param, :platoon => { }
assert_redirected_to platoon_path(assigns(:platoon))
end
test "should destroy platoon" do
assert_difference('Platoon.count', -1) do
delete :destroy, :id => platoons(:one).to_param
end
assert_redirected_to platoons_path
end
end
| looloobs/FRGCMS | test/functional/platoons_controller_test.rb | Ruby | mit | 1,040 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RandomFloat = /** @class */ (function () {
function RandomFloat() {
}
RandomFloat.nextFloat = function (min, max) {
if (max === void 0) { max = null; }
if (max == null) {
max = min;
min = 0;
}
if (max - min <= 0)
return min;
return min + Math.random() * (max - min);
};
RandomFloat.updateFloat = function (value, range) {
if (range === void 0) { range = null; }
if (range == null)
range = 0;
range = range == 0 ? 0.1 * value : range;
var minValue = value - range;
var maxValue = value + range;
return RandomFloat.nextFloat(minValue, maxValue);
};
return RandomFloat;
}());
exports.RandomFloat = RandomFloat;
//# sourceMappingURL=RandomFloat.js.map | pip-services/pip-services-commons-node | obj/src/random/RandomFloat.js | JavaScript | mit | 892 |
class AddFleetNameAssetFleets < ActiveRecord::Migration[4.2]
def change
add_column :asset_fleets, :fleet_name, :string, after: :agency_fleet_id
end
end
| camsys/transam_transit | db/migrate/20180124192034_add_fleet_name_asset_fleets.rb | Ruby | mit | 160 |
#!/usr/bin/env python
###
# (C) Copyright (2012-2015) Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import range
from future import standard_library
standard_library.install_aliases()
import sys
PYTHON_VERSION = sys.version_info[:3]
PY2 = (PYTHON_VERSION[0] == 2)
if PY2:
if PYTHON_VERSION < (2, 7, 9):
raise Exception('Must use Python 2.7.9 or later')
elif PYTHON_VERSION < (3, 4):
raise Exception('Must use Python 3.4 or later')
import hpOneView as hpov
from pprint import pprint
def acceptEULA(con):
# See if we need to accept the EULA before we try to log in
con.get_eula_status()
try:
if con.get_eula_status() is True:
print('EULA display needed')
con.set_eula('no')
except Exception as e:
print('EXCEPTION:')
print(e)
def login(con, credential):
# Login with givin credentials
try:
con.login(credential)
except:
print('Login failed')
def add_network_set(net, name, networks, minbw, maxbw):
nset = []
maxbw = int(maxbw * 1000)
minbw = int(minbw * 1000)
if networks:
enets = net.get_enet_networks()
for enet in enets:
if enet['name'] in networks:
nset.append(enet['uri'])
nset = net.create_networkset(name, networkUris=nset,
typicalBandwidth=minbw,
maximumBandwidth=maxbw)
if 'connectionTemplateUri' in nset:
print('\n\nName: ', nset['name'])
print('Type: ', nset['type'])
print('Description: ', nset['description'])
print('State: ', nset['state'])
print('Status: ', nset['status'])
print('Created: ', nset['created'])
print('Uri: ', nset['uri'])
print('networkUris: ')
for net in nset['networkUris']:
print('\t\t', net)
else:
pprint(nset)
def main():
parser = argparse.ArgumentParser(add_help=True,
formatter_class=argparse.RawTextHelpFormatter,
description='''
Define new Network Set
Usage: ''')
parser.add_argument('-a', dest='host', required=True,
help='''
HP OneView Appliance hostname or IP address''')
parser.add_argument('-u', dest='user', required=False,
default='Administrator',
help='''
HP OneView Username''')
parser.add_argument('-p', dest='passwd', required=True,
help='''
HP OneView Password''')
parser.add_argument('-c', dest='cert', required=False,
help='''
Trusted SSL Certificate Bundle in PEM (Base64 Encoded DER) Format''')
parser.add_argument('-y', dest='proxy', required=False,
help='''
Proxy (host:port format''')
parser.add_argument('-j', dest='domain', required=False,
default='Local',
help='''
HP OneView Authorized Login Domain''')
parser.add_argument('-n', dest='network_set_name', required=True,
help='''
Name of the network set''')
parser.add_argument('-l', dest='list_of_networks', required=False,
nargs='+',
help='''
List of network names to add to the network set, seperated by spaces.
For example:
-t "Net One" "Net Two" "Net Three"''')
parser.add_argument('-b', dest='prefered_bandwidth', type=float,
required=False, default=2.5,
help='''
Typical bandwidth between .1 and 20 Gb/s''')
parser.add_argument('-m', dest='max_bandwidth', type=float, required=False,
default=10,
help='''
Maximum bandwidth between .1 and 20 Gb/s''')
args = parser.parse_args()
credential = {'authLoginDomain': args.domain.upper(), 'userName': args.user, 'password': args.passwd}
con = hpov.connection(args.host)
net = hpov.networking(con)
if args.proxy:
con.set_proxy(args.proxy.split(':')[0], args.proxy.split(':')[1])
if args.cert:
con.set_trusted_ssl_bundle(args.cert)
login(con, credential)
acceptEULA(con)
if args.prefered_bandwidth < .1 or args.prefered_bandwidth > 20:
print('Error, prefered bandwidth must be between .1 and 20 Gb/s')
sys.exit()
if args.max_bandwidth < .1 or args.max_bandwidth > 20:
print('Error, max bandwidth must be between .1 and 20 Gb/s')
sys.exit()
if args.prefered_bandwidth > args.max_bandwidth:
print('Error, prefered bandwidth must be less than or equal '
'to the maximum bandwidth')
sys.exit()
add_network_set(net, args.network_set_name, args.list_of_networks,
args.prefered_bandwidth, args.max_bandwidth)
if __name__ == '__main__':
import sys
import argparse
sys.exit(main())
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
| ufcg-lsd/python-hpOneView | examples/scripts/define-network-set.py | Python | mit | 6,316 |
require 'spec_helper'
describe RBattlenet::D3::Act, type: :community do
describe "#find_act" do
it "fetches act data" do
with_connection("d3_act") do
result = RBattlenet::D3::Act.find(1)
expect(result.name).to eq "Act I"
end
end
end
describe "#find_multiple_acts" do
it "fetches act data" do
with_connection("d3_act_multiple") do
collection = RBattlenet::D3::Act.find([1, 2])
expect(collection.results.map(&:name).sort).to eq ["Act I", "Act II"]
end
end
end
describe "#find_all_acts" do
it "fetches all act data" do
with_connection("d3_act_all") do
result = RBattlenet::D3::Act.all
expect(result.acts.size).to be >= 5
end
end
end
end
| wingyu/rbattlenet | spec/lib/d3/act_spec.rb | Ruby | mit | 758 |
<?php
session_start();
require_once ('conn.php');
$action = $_GET['action'];
if ($action == 'login') {
$user = stripslashes(trim($_POST['usrname']));
$pass = stripslashes(trim($_POST['password']));
if (empty ($user)) {
echo '用户名不能为空';
exit;
}
if (empty ($pass)) {
echo '密码不能为空';
exit;
}
$sha1pass = sha1($pass);
$query = mysql_query("select * from user where usrname='$user'");
$us = is_array($row = mysql_fetch_array($query));
$ps = $us ? $sha1pass == $row['passwd'] : FALSE;
if ($ps) {
$_SESSION['usrname'] = $row['usrname'];
$_SESSION['nickname'] = $row['nickname'];
$_SESSION['sex'] = $row['sex'];
$_SESSION['qq'] = $row['qq'];
$_SESSION['tel'] = $row['tel'];
$_SESSION['birth'] = $row['birth'];
$_SESSION['group'] = $row['group'];
$_SESSION['information'] = $row['information'];
$arr['success'] = 1;
$arr['msg'] = '登录成功!';
$arr['user'] = $_SESSION['nickname'];
} else {
$arr['success'] = 0;
$arr['msg'] = '用户名或密码错误!';
}
echo json_encode($arr);
}
elseif($action == 'islogin') {
if($_SESSION['usrname']){
$user = $_SESSION['usrname'];
$query = mysql_query("select * from user where usrname='$user'");
$row = mysql_fetch_array($query);
$_SESSION['nickname'] = $row['nickname'];
$_SESSION['sex'] = $row['sex'];
$_SESSION['qq'] = $row['qq'];
$_SESSION['tel'] = $row['tel'];
$_SESSION['birth'] = $row['birth'];
$_SESSION['group'] = $row['group'];
echo '1';
}
else
echo '0';
}
elseif ($action == 'logout') { //退出
unset($_SESSION);
session_destroy();
echo '1';
}
elseif($action == 'perinfomodify') {
if($_SESSION['usrname'])
{
$user = $_SESSION['usrname'];
$pass = sha1(stripslashes(trim($_POST['password'])));
$nickname = stripslashes(trim($_POST['nickname']));
$sex = stripslashes(trim($_POST['sex']));
$qq = stripslashes(trim($_POST['qq']));
$tel = stripslashes(trim($_POST['tel']));
if($_POST['birth']) $birth = date("Y-m-d",stripslashes(trim($_POST['birth'])));
$group = stripslashes(trim($_POST['group']));
if($_POST['password']) mysql_query("update user set passwd='$pass' where usrname='$user'");
if($_POST['nickname']) mysql_query("update user set nickname='$nickname' where usrname='$user'");
if($_POST['sex']) mysql_query("update user set sex='$sex' where usrname='$user'");
if($_POST['qq']) mysql_query("update user set qq='$qq' where usrname='$user'");
if($_POST['tel']) mysql_query("update user set tel='$tel' where usrname='$user'");
if($_POST['birth']) mysql_query("update user set birth='$birth' where usrname='$user'");
if($_POST['group']) mysql_query("update user set group='$group' where usrname='$user'");
$arr['success'] = 1;
echo json_encode($arr);
}
}
?>
| denghongcai/GyBook | login.php | PHP | mit | 2,757 |
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Wexflow.Tests
{
[TestClass]
public class MessageCorrect
{
[TestInitialize]
public void TestInitialize()
{
}
[TestCleanup]
public void TestCleanup()
{
}
[TestMethod]
public void MessageCorrectTest()
{
Stopwatch stopwatch = Stopwatch.StartNew();
Helper.StartWorkflow(117);
stopwatch.Stop();
Assert.IsTrue(stopwatch.ElapsedMilliseconds > 1000);
}
}
}
| aelassas/Wexflow | src/tests/net/Wexflow.Tests/MessageCorrect.cs | C# | mit | 602 |
! function() {
"use strict";
function t(t, i, n, e) {
function r(t, i) {
for (var n = 0; n < t.length; n++) {
var e = t[n];
i(e, n)
}
}
function a(t) {
s(t), o(t), u(t)
}
function s(t) {
t.addEventListener("mouseover", function(i) {
r(f, function(i, n) {
document.getElementById('now').innerHTML = parseInt(t.getAttribute("data-index")) + 1;
n <= parseInt(t.getAttribute("data-index")) ? i.classList.add("is-active") : i.classList.remove("is-active")
})
})
}
function o(t) {
t.addEventListener("mouseout", function(t) {
document.getElementById('now').innerHTML = i;
-1 === f.indexOf(t.relatedTarget) && c(null, !1)
})
}
function u(t) {
t.addEventListener("click", function(i) {
i.preventDefault(), c(parseInt(t.getAttribute("data-index")) + 1, !0)
})
}
function c(t, a) {
t && 0 > t || t > n || (void 0 === a && (a = !0), i = t || i, r(f, function(t, n) {
i > n ? t.classList.add("is-active") : t.classList.remove("is-active")
}), e && a/* && e(d())*/)
}
function d() {
return i
}
var f = [];
return function() {
if (!t) throw Error("No element supplied.");
if (!n) throw Error("No max rating supplied.");
if (i || (i = 0), 0 > i || i > n) throw Error("Current rating is out of bounds.");
for (var e = 0; n > e; e++) {
var r = document.createElement("li");
r.classList.add("c-rating__item"), r.setAttribute("data-index", e), i > e && r.classList.add("is-active"), t.appendChild(r), f.push(r), a(r)
}
}(), {
setRating: c,
getRating: d
}
}
window.rating = t
}();
| teacher144123/npo_map | server/js/dict/rating.min.js | JavaScript | mit | 1,615 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 FTC team 6460 et. al.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ftc.team6460.javadeck.api.planner;
/**
* Describes a peripheral that can detect imminent obstacles.
*/
public interface ObstacleSensor {
/**
* Determines if there is an obstacle that can be detected by this sensor at this relative position (or closer).
*
* @param pos The relative position to the current physical robot position to check.
* @return True if obstacle detected, false if no obstacle detected, or this position cannot be sensed by this sensor.
*/
boolean checkObstacle(RelativePosition pos);
}
| niskyRobotics/javadeck | src/main/java/ftc/team6460/javadeck/api/planner/ObstacleSensor.java | Java | mit | 1,706 |
<?php
/*
* ServerAuth v3.0 by EvolSoft
* Developer: Flavius12
* Website: https://www.evolsoft.tk
* Copyright (C) 2015-2018 EvolSoft
* Licensed under MIT (https://github.com/EvolSoft/ServerAuth/blob/master/LICENSE)
*/
namespace ServerAuth\Importers;
use pocketmine\command\CommandSender;
use ServerAuth\ServerAuth;
interface Importer {
public function __construct(ServerAuth $plugin);
/**
* Get Importer ID
*
* @return string
*/
public function getId() : string;
/**
* Export data
*
* @param CommandSender $sender
* @param array $params
*/
public function export(CommandSender $sender, array $params = null);
} | EvolSoft/ServerAuth | ServerAuth/src/ServerAuth/Importers/Importer.php | PHP | mit | 726 |