repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
hbaughman/audible-temptations | src/views/HomeView/HomeView.js | 868 | import React from 'react';
import { Link } from 'react-router';
import RaisedButton from 'material-ui/lib/raised-button';
import { OAUTH_REQUEST } from '../../constants';
const Home = () => {
//<Link to="/filterLibrary" style={{padding: "24px"}} >
return (
<div>
<img style={{marginTop: "64px"}} src="/intro.png" />
<div
style={{
position: "fixed",
bottom: 16,
left: 16,
right: 16,
zIndex: 3
}}
>
<RaisedButton
containerElement={<Link to="/manageLocations"/>}
linkButton={true}
fullWidth={true}
label="Continue"
style={{
backgroundColor: "#F7991F",
textAlign: "center"
//margin: "auto 16px 16px 16px"
}}
/>
</div>
</div>
);
}
export default Home;
| mit |
adifaidz/base | config/base.php | 5694 | <?php
/**
* This file is part of AdiFaidz\Base wrapper of Base,
* a role & permission management solution for Laravel.
*
* @license MIT
* @package Base
*/
return [
/*
|--------------------------------------------------------------------------
| Project Name
|--------------------------------------------------------------------------
*/
'name' => 'CHART',
/*
|--------------------------------------------------------------------------
| Project Logo
|--------------------------------------------------------------------------
*/
'logo' => '<i class="fa fa-bell-o" aria-hidden="true"></i>',
/*
|--------------------------------------------------------------------------
| Base App Javascript Path
|
| For generated vue components to be registered in
|--------------------------------------------------------------------------
*/
'app_js_path' => base_path('resources\assets\js\base_app.js'),
/*
|--------------------------------------------------------------------------
| Prefix for all admin routes in admin file
|--------------------------------------------------------------------------
*/
'admin_route_prefix' => 'admin',
/*
|--------------------------------------------------------------------------
| Admin route file path
|--------------------------------------------------------------------------
*/
'admin_route' => base_path('routes/admin.php'),
/*
|--------------------------------------------------------------------------
| Prefix for all admin routes in admin file
|--------------------------------------------------------------------------
*/
'client_route_prefix' => '',
/*
|--------------------------------------------------------------------------
| Client route file path
|--------------------------------------------------------------------------
*/
'client_route' => base_path('routes/client.php'),
/*
|--------------------------------------------------------------------------
| Admin auth guard (If changed, also need to change middleware group array)
|--------------------------------------------------------------------------
*/
'admin_guard' => 'web_admin',
/*
|--------------------------------------------------------------------------
| Client auth guard (If changed, also need to change middleware group array)
|--------------------------------------------------------------------------
*/
'client_guard' => 'web_client',
/*
|--------------------------------------------------------------------------
| Redirect configuration
|--------------------------------------------------------------------------
*/
'redirect' => [
/*
|--------------------------------------------------------------------------
| Default route name for handling unauthorized redirection
|--------------------------------------------------------------------------
*/
'unauth_default' => 'client.login',
/*
|--------------------------------------------------------------------------
| Route name for handling unauthorized redirection for admin side pages
|--------------------------------------------------------------------------
*/
'unauth_admin' => 'admin.login',
/*
|--------------------------------------------------------------------------
| Route name for handling unauthorized redirection for client side pages
|--------------------------------------------------------------------------
*/
'unauth_client' => 'client.login',
/*
|--------------------------------------------------------------------------
| Default route name for handling if authorized redirection
|--------------------------------------------------------------------------
*/
'auth_default' => 'client.home',
/*
|--------------------------------------------------------------------------
| Route name for handling if authorized redirection for admin side pages
|--------------------------------------------------------------------------
*/
'auth_admin' => 'admin.home',
/*
|--------------------------------------------------------------------------
| Route name for handling if authorized redirection for client side pages
|--------------------------------------------------------------------------
*/
'auth_client' => 'client.home',
],
/*
|--------------------------------------------------------------------------
| Base View Stubs
|--------------------------------------------------------------------------
*/
'stubs' => [
/*
| This is the stub folder used for view generation, leave null to use the default views.
*/
'view' => null,
/*
| This is the stub folder used for vue generation, leave null to use the default views.
*/
'vue' => null,
],
/*
|--------------------------------------------------------------------------
| Development environment for provider registration
|--------------------------------------------------------------------------
*/
'dev_env' => 'local',
/*
|--------------------------------------------------------------------------
| Production environment for provider registration
|--------------------------------------------------------------------------
*/
'prod_env' => 'production',
];
| mit |
c0d1ngm0nk3y/pokerhands | src/main/java/examples/pokerhands/valuation/HandRanking.java | 155 | package examples.pokerhands.valuation;
import examples.pokerhands.model.Hand;
public interface HandRanking {
public Valuation evaluate(Hand hand);
}
| mit |
rokde/workload-dashboard | src/Http/Sources/Source.php | 4497 | <?php
namespace WorkloadDashboard\Http\Sources;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Class Source
*
* @package WorkloadDashboard\Http\Sources
*/
abstract class Source
{
/**
* request
*
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* response status
*
* @var int
*/
protected $status = 200;
/**
* response headers
*
* @var array
*/
protected $headers = [];
/**
* http client
*
* @var ClientInterface
*/
private $httpClient;
/**
* constructing Source
*
* @param Request $request
* @param ClientInterface $httpClient
*/
public function __construct($request, ClientInterface $httpClient = null)
{
$this->request = $request;
$this->httpClient = $httpClient ?: new Client();
}
/**
* returns url
*
* @return string
*/
protected function getUrl()
{
return $this->request->get('url');
}
/**
* returns start date for custom url
*
* @return string
*/
abstract protected function getStartDate();
/**
* returns end date for custom url
*
* @return string
*/
abstract protected function getEndDate();
/**
* returns auth settings
*
* @return array|null
*/
protected function getAuth()
{
if ($this->request->has(['auth_type', 'auth_user', 'auth_pass'])) {
return $this->request->only(['auth_type', 'auth_user', 'auth_pass']);
}
if ($this->request->has(['auth_type', 'auth_credentials'])) {
$credentials = $this->request->get('auth_credentials');
if (!empty($credentials)) {
$credentials = base64_decode($credentials);
}
if (empty($credentials) || substr_count($credentials, ':') < 1) {
return null;
}
list($user, $pass) = explode(':', $credentials);
return [
'auth_type' => $this->request->get('auth_type'),
'auth_user' => $user,
'auth_pass' => $pass
];
}
return null;
}
/**
* fetches content
*
* @param string $url
* @param array $auth
* @param string $method
*
* @return \Psr\Http\Message\ResponseInterface
*/
protected function fetch($url, $auth, $method = Request::METHOD_GET)
{
$options = [];
if (!empty($auth)) {
$options['auth'] = [
array_get($auth, 'auth_user'),
array_get($auth, 'auth_pass'),
];
}
if ($method === Request::METHOD_GET) {
return $this->httpClient->get($url, $options);
}
return $this->httpClient->post($url, $options);
}
/**
* resolves the correct source system
*
* only trac for the moment of writing
*
* @param string $sourceString
* @param \Illuminate\Http\Request $request
*
* @return \WorkloadDashboard\Http\Sources\Trac
*/
public static function resolve($sourceString, Request $request)
{
switch ($sourceString) {
case 'trac':
default:
return new Trac($request);
}
}
/**
* returns status
*
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* set status
*
* @param int $status
*
* @return Source
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* returns Headers
*
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* set headers
*
* @param array $headers
*
* @return Source
*/
public function setHeaders($headers)
{
$this->headers = $headers;
return $this;
}
/**
* returns sources data
*
* @return mixed|array|\JsonSerializable
*/
abstract public function getData();
/**
* returns response
*
* @return \Illuminate\Http\JsonResponse
*/
public function getResponse()
{
return new JsonResponse($this->getData(), $this->getStatus(), $this->getHeaders());
}
} | mit |
rmwatson5/Unicorn | src/Unicorn/Logging/WebConsoleLogger.cs | 1131 | using System;
using System.Diagnostics.CodeAnalysis;
using Kamsar.WebConsole;
namespace Unicorn.Logging
{
/// <summary>
/// Logger that writes to a WebConsole.
/// </summary>
[ExcludeFromCodeCoverage]
public class WebConsoleLogger : ILogger
{
private readonly IProgressStatus _progress;
public WebConsoleLogger(IProgressStatus progress)
{
_progress = progress;
}
public void Info(string message)
{
_progress.ReportStatus(message, MessageType.Info);
}
public void Debug(string message)
{
_progress.ReportStatus(message, MessageType.Debug);
}
public void Warn(string message)
{
_progress.ReportStatus(message, MessageType.Warning);
}
public void Error(string message)
{
_progress.ReportStatus(message, MessageType.Error);
}
public void Error(Exception exception)
{
var error = new ExceptionFormatter().FormatExceptionAsHtml(exception);
if(exception is DeserializationSoftFailureAggregateException)
_progress.ReportStatus(error, MessageType.Warning);
else
_progress.ReportStatus(error, MessageType.Error);
}
public void Flush()
{
}
}
}
| mit |
gabrielsimas/SistemasExemplo | DDD/ControleLivros/InterfaceUsuario.Mvc5/App_Start/BundleConfig.cs | 1252 | using System.Web;
using System.Web.Optimization;
namespace InterfaceUsuario.Mvc5
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| mit |
geraldinas/LocalGuide | config/environments/development.rb | 2187 | Rails.application.configure do
config.assets.raise_production_errors = true
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_deliveries = true
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = {host: "localhost", port: 3000}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
user_name: ENV['GMAIL_USERNAME'],
password: ENV['GMAIL_PASSWORD'],
authentication: 'plain',
enable_starttls_auto: true }
end
| mit |
pebblescape/pebblescape | Godeps/_workspace/src/github.com/fsouza/go-dockerclient/tar.go | 3519 | // Copyright 2015 go-dockerclient authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package docker
import (
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/pebblescape/pebblescape/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive"
"github.com/pebblescape/pebblescape/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils"
)
func createTarStream(srcPath, dockerfilePath string) (io.ReadCloser, error) {
excludes, err := parseDockerignore(srcPath)
if err != nil {
return nil, err
}
includes := []string{"."}
// If .dockerignore mentions .dockerignore or the Dockerfile
// then make sure we send both files over to the daemon
// because Dockerfile is, obviously, needed no matter what, and
// .dockerignore is needed to know if either one needs to be
// removed. The deamon will remove them for us, if needed, after it
// parses the Dockerfile.
//
// https://github.com/docker/docker/issues/8330
//
forceIncludeFiles := []string{".dockerignore", dockerfilePath}
for _, includeFile := range forceIncludeFiles {
if includeFile == "" {
continue
}
keepThem, err := fileutils.Matches(includeFile, excludes)
if err != nil {
return nil, fmt.Errorf("cannot match .dockerfile: '%s', error: %s", includeFile, err)
}
if keepThem {
includes = append(includes, includeFile)
}
}
if err := validateContextDirectory(srcPath, excludes); err != nil {
return nil, err
}
tarOpts := &archive.TarOptions{
ExcludePatterns: excludes,
IncludeFiles: includes,
Compression: archive.Uncompressed,
NoLchown: true,
}
return archive.TarWithOptions(srcPath, tarOpts)
}
// validateContextDirectory checks if all the contents of the directory
// can be read and returns an error if some files can't be read.
// Symlinks which point to non-existing files don't trigger an error
func validateContextDirectory(srcPath string, excludes []string) error {
return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
// skip this directory/file if it's not in the path, it won't get added to the context
if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
return err
} else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
return err
} else if skip {
if f.IsDir() {
return filepath.SkipDir
}
return nil
}
if err != nil {
if os.IsPermission(err) {
return fmt.Errorf("can't stat '%s'", filePath)
}
if os.IsNotExist(err) {
return nil
}
return err
}
// skip checking if symlinks point to non-existing files, such symlinks can be useful
// also skip named pipes, because they hanging on open
if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
return nil
}
if !f.IsDir() {
currentFile, err := os.Open(filePath)
if err != nil && os.IsPermission(err) {
return fmt.Errorf("no permission to read from '%s'", filePath)
}
currentFile.Close()
}
return nil
})
}
func parseDockerignore(root string) ([]string, error) {
var excludes []string
ignore, err := ioutil.ReadFile(path.Join(root, ".dockerignore"))
if err != nil && !os.IsNotExist(err) {
return excludes, fmt.Errorf("error reading .dockerignore: '%s'", err)
}
excludes = strings.Split(string(ignore), "\n")
return excludes, nil
}
| mit |
Yortw/Yort.OnlineEftpos | Yort.OnlineEftpos/Properties/AssemblyInfo.cs | 818 | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
// 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("Yort.OnlineEftpos (Portable/Bait library)")]
[assembly: NeutralResourcesLanguage("en")]
// 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: AssemblyFileVersion("2.0.0.0")]
| mit |
jonsequitur/Alluvial | Alluvial.Tests/Infrastructure/Background.cs | 602 | using System;
using System.Reactive.Linq;
namespace Alluvial.Tests
{
public static class Background
{
public static IDisposable Loop(
Action<int> action,
double rateInMilliseconds = 1)
{
var count = 0;
return Observable.Timer(TimeSpan.FromMilliseconds(rateInMilliseconds))
.Repeat()
.Subscribe(i =>
{
count++;
action(count);
});
}
}
} | mit |
dreamtalee/PinterestLikeApp | src/com/dreamtale/pintrestlike/widget/PintrestGridView.java | 528 | package com.dreamtale.pintrestlike.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
public class PintrestGridView extends GridView
{
public PintrestGridView(Context context)
{
super(context);
}
public PintrestGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public PintrestGridView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
}
| mit |
merbjedi/viewfu | lib/view_fu/tag_helper.rb | 6328 | module ViewFu
module TagHelper
# Calls a Merb Partial with a block,
# which you can catch content from
#
# Usage Example:
# <%= partial_block :fieldset, :legend => "Login" do %>
# .. inner partial content
# <% end =%>
#
# Associated Partial (_fieldset.html.erb)
# <fieldset>
# <legend><%= locals[:legend] %></legend>
# <%= catch_content %>
# </fieldset>
def partial_block(template, options={}, &block)
throw_content(:for_layout, block_given? ? capture(&block) : "")
partial(template, options)
end
# Allows Easy Nested Layouts in Merb
#
# Usage Example:
#
# Parent Layout: layout/application.html.erb
# -------
# <html>
# <head>
# <title>Title</title>
# </head>
# <body>
# <%= catch_content %>
# </body>
# </html>
#
# SubLayout: layout/alternate.html.erb
# --------
# <%= parent_layout "application" do %>
# <div class="inner_layout">
# <%= catch_content %>
# </div>
# <% end =%>
#
# Now you can use the alternate layout in any of your views as normal
# and it will reuse the wrapping html on application.html.erb
def parent_layout(layout, &block)
render capture(&block), :layout => layout
end
# Writes a br tag
def br
"<br />"
end
# Writes an hr tag
def hr
"<hr />"
end
# Writes a nonbreaking space
def nbsp
" "
end
# ported from rails
def auto_discovery_link_tag(type = :rss, url = nil, tag_options = {})
# theres gotta be a better way of setting mimetype for a file extensionin Merb..
unless tag_options[:type]
if type.to_s == "rss"
tag_options[:type] = "application/rss+xml"
elsif type.to_s == "atom"
tag_options[:type] = "application/atom+xml"
end
end
tag(:link, :rel => (tag_options[:rel] || "alternate"),
:type => tag_options[:type].to_s,
:title => (tag_options[:title] || type.to_s.upcase),
:href => (url || "#"))
end
# Writes an hr space tag
def space
"<hr class='space' />"
end
# Writes an anchor tag
def anchor(anchor_name, options = {})
tag(:a, options.merge(:name => anchor_name)) do
""
end
end
# Writes a clear tag
def clear_tag(tag, direction = nil)
if tag == :br
"<br class=\"clear#{direction}\" />"
else
"<#{tag} class=\"clear#{direction}\"></#{tag}>"
end
end
def current_year
Time.now.strftime("%Y")
end
# Writes a clear div tag
def clear(direction = nil)
clear_tag(:div, direction)
end
# Return some lorem text
def lorem
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
end
# provides a slick way to add classes inside haml attribute collections
#
# examples:
# %div{add_class("current")}
# #=> adds the "current" class to the div
#
# %div{add_class("current", :if => current?)}
# #=> adds the "current" class to the div if current? method
#
# %div{add_class("highlight", :unless => logged_in?)}
# #=> adds the "highlight" class to the div unless logged_in? method returns true
def add_class(css_class, options = {})
return {} unless css_class
if options.has_key?(:unless) && options[:unless]
return {}
end
if options.has_key?(:if) && options[:if]
return {:class => css_class}
end
if !options.has_key?(:if) and !options.has_key?(:unless)
{:class => css_class}
else
{}
end
end
def add_class_if(css_class, condition)
add_class(css_class, :if => condition)
end
def add_class_unless(css_class, condition)
add_class(css_class, :unless => condition)
end
# Return a hidden attribute hash (useful in Haml tags - %div{hidden})
def hide(options = {})
if options.has_key?(:unless) && options[:unless]
return {}
end
if options.has_key?(:if) && !options[:if]
return {}
end
{:style => "display:none"}
end
alias :hidden :hide
# Return a hidden attribute hash if a condition evaluates to true
def hide_if(condition)
hide(:if => condition)
end
alias :hidden_if :hide_if
alias :show_unless :hide_if
# Return a hidden attribute hash if a condition evaluates to false
def hide_unless(condition)
hide(:unless => condition)
end
alias :hidden_unless :hide_unless
alias :show_if :hide_unless
# Wrap a delete link
def delete_link(*args)
options = {:method => :delete, :confirm => "Are you sure you want to delete this?"}.merge(extract_options_from_args!(args)||{})
args << options
link_to(*args)
end
# Wrap a block with a link
def link_to_block(*args, &block)
content = capture(&block)
return link_to(content, *args)
end
# Check if we're on production environment
def production?
Merb.env?(:production)
end
# Display will_paginate paging links
def paging(page_data, style = :sabros)
return unless page_data.is_a? WillPaginate::Collection
will_paginate(page_data, :class => "pagination #{style}", :inner_window => 3)
end
# clearbit icons
def clearbit_icon(icon, color, options = {})
image_tag "clearbits/#{icon}.gif", {:class => "clearbits #{color}", :alt => icon}.merge(options)
end
# pixel spacing helper
def pixel(options = {})
image_tag "pixel.png", options
end
# check to see if an index is the first item in a collection
def is_first(i)
i.to_i.zero? ? {:class => "first"} : {}
end
end
end | mit |
OrifInformatique/stock | orif/stock/Database/Migrations/restore_CI3_version/2021-06-01-093907_add_item.php | 5850 | <?php
namespace Stock\Database\Migrations;
class Add_Item extends \CodeIgniter\Database\Migration
{
/**
* @inheritDoc
*/
public function up()
{
$this->forge->addField([
'item_id'=>[
'type' => 'INT',
'constraint' => '11',
'null' => false,
'auto_increment' => true,
],
'inventory_prefix'=>[
'type' => 'VARCHAR',
'constraint' => '45',
'null' => true,
'default' => null,
],
'name'=>[
'type' => 'VARCHAR',
'constraint' => '100',
'null' => true,
'default' => null,
],
'description'=>[
'type' => 'text',
'null' => true,
'default' => null,
],
'image'=>[
'type' => 'varchar',
'constraint' => 255,
'null' => true,
'default' => null,
],
'serial_number'=>[
'type' => 'varchar',
'constraint' => 45,
'null' => true,
'default' => null,
],
'buying_price'=>[
'type' => 'float',
'null' => true,
'default' => null,
],
'buying_date'=>[
'type' => 'date',
'null' => true,
'default' => null,
],
'warranty_duration'=>[
'type' => 'int',
'constraint' => 11,
'null' => true,
'default' => null,
],
'remarks'=>[
'type' => 'text',
'null' => true,
'default' => null,
],
'linked_file'=>[
'type' => 'varchar',
'constraint' => 255,
'null' => true,
'default' => null,
],
'supplier_id'=>[
'type' => 'int',
'constraint' => 11,
'null' => true,
'default' => null,
],
'supplier_ref'=>[
'type' => 'varchar',
'constraint' => 45,
'null' => true,
'default' => null,
],
'created_by_user_id'=>[
'type' => 'int',
'constraint' => 11,
'null' => true,
'default' => null,
],
'created_date timestamp DEFAULT CURRENT_TIMESTAMP()',
'modified_by_user_id'=>[
'type' => 'INT',
'constraint' => '11',
'null' => true,
'default' => null,
],
'modified_date'=>[
'type' => 'datetime',
'null' => true,
'default' => null,
],
'checked_by_user_id'=>[
'type' => 'INT',
'constraint' => '11',
'null' => true,
'default' => null,
],
'checked_date'=>[
'type' => 'datetime',
'null' => true,
'default' => null,
],
'stocking_place_id'=>[
'type' => 'INT',
'constraint' => '11',
'null' => true,
'default' => null,
],
'item_condition_id'=>[
'type' => 'INT',
'constraint' => '11',
'null' => true,
'default' => null,
],
'item_group_id'=>[
'type' => 'INT',
'constraint' => '11',
'null' => true,
'default' => null,
],
]);
$this->forge->addKey('item_id', TRUE);
$this->forge->createTable('item', TRUE);
$this->forge->addColumn('item', [
'CONSTRAINT fk_checked_by_user_id FOREIGN KEY (checked_by_user_id) REFERENCES user (user_id)',
'CONSTRAINT fk_created_by_user_id FOREIGN KEY (created_by_user_id) REFERENCES user (user_id)',
'CONSTRAINT fk_modified_by_user_id FOREIGN KEY (modified_by_user_id) REFERENCES user (user_id)',
'CONSTRAINT fk_item_condition_id FOREIGN KEY (item_condition_id) REFERENCES item_condition (item_condition_id)',
'CONSTRAINT fk_item_group_id FOREIGN KEY (item_group_id) REFERENCES item_group (item_group_id)',
'CONSTRAINT fk_supplier_id FOREIGN KEY (supplier_id) REFERENCES supplier (supplier_id)',
'CONSTRAINT fk_stocking_place_id FOREIGN KEY (stocking_place_id) REFERENCES stocking_place (stocking_place_id)'
]);
}
/**
* @inheritDoc
*/
public function down()
{
$this->forge->dropTable('item');
}
} | mit |
Pearson-Higher-Ed/pagination | demo/eventing.js | 337 | import ReactDOM from 'react-dom';
import React from 'react';
import { PaginationContainer } from '../index';
document.body.addEventListener('o.InitPagination', e => {
ReactDOM.render(
React.createElement(PaginationContainer, e.detail.props, e.detail.props.children)
, document.getElementById(e.detail.elementId)
);
});
| mit |
CatalinaTechnology/ctAPIClientExamples | client.orderManagement.maintenance.customerContacts/Web References/ctDynamicsSL.orderManagement.maintenance.customerContacts/Reference.cs | 96185 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by Microsoft.VSDesigner, Version 4.0.30319.42000.
//
#pragma warning disable 1591
namespace client.orderManagement.maintenance.customerContacts.ctDynamicsSL.orderManagement.maintenance.customerContacts {
using System;
using System.Web.Services;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Data;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="customerContactsSoap", Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL")]
public partial class customerContacts : System.Web.Services.Protocols.SoapHttpClientProtocol {
private System.Threading.SendOrPostCallback aboutOperationCompleted;
private ctDynamicsSLHeader ctDynamicsSLHeaderValueField;
private System.Threading.SendOrPostCallback getCustContactsByCustIDOperationCompleted;
private System.Threading.SendOrPostCallback getCustContactsByIDOperationCompleted;
private System.Threading.SendOrPostCallback getCustContactByExactIDOperationCompleted;
private System.Threading.SendOrPostCallback validateCustIDOperationCompleted;
private System.Threading.SendOrPostCallback getScreenByCustIDOperationCompleted;
private System.Threading.SendOrPostCallback getNewscreenOperationCompleted;
private System.Threading.SendOrPostCallback editScreenOperationCompleted;
private System.Threading.SendOrPostCallback editNoteOperationCompleted;
private System.Threading.SendOrPostCallback editNoteAsDataSetOperationCompleted;
private System.Threading.SendOrPostCallback editCustContactOperationCompleted;
private System.Threading.SendOrPostCallback editCustContactAsJSONOperationCompleted;
private System.Threading.SendOrPostCallback editCustContactAsDataSetOperationCompleted;
private System.Threading.SendOrPostCallback editCustContactAsDataSetAsJSONOperationCompleted;
private System.Threading.SendOrPostCallback getNewCustContactOperationCompleted;
private System.Threading.SendOrPostCallback getNewCustContactAsJSONOperationCompleted;
private System.Threading.SendOrPostCallback getCustContactsOperationCompleted;
private System.Threading.SendOrPostCallback getCustContactsAsJSONOperationCompleted;
private System.Threading.SendOrPostCallback getCustContactsAsDataSetOperationCompleted;
private System.Threading.SendOrPostCallback getCustContactsAsDataSetAsJSONOperationCompleted;
private System.Threading.SendOrPostCallback pingOperationCompleted;
private bool useDefaultCredentialsSetExplicitly;
/// <remarks/>
public customerContacts() {
this.Url = global::client.orderManagement.maintenance.customerContacts.Properties.Settings.Default.client_orderManagement_maintenance_customerContacts_ctDynamicsSL_orderManagement_maintenance_customerContacts_customerContacts;
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
public ctDynamicsSLHeader ctDynamicsSLHeaderValue {
get {
return this.ctDynamicsSLHeaderValueField;
}
set {
this.ctDynamicsSLHeaderValueField = value;
}
}
public new string Url {
get {
return base.Url;
}
set {
if ((((this.IsLocalFileSystemWebService(base.Url) == true)
&& (this.useDefaultCredentialsSetExplicitly == false))
&& (this.IsLocalFileSystemWebService(value) == false))) {
base.UseDefaultCredentials = false;
}
base.Url = value;
}
}
public new bool UseDefaultCredentials {
get {
return base.UseDefaultCredentials;
}
set {
base.UseDefaultCredentials = value;
this.useDefaultCredentialsSetExplicitly = true;
}
}
/// <remarks/>
public event aboutCompletedEventHandler aboutCompleted;
/// <remarks/>
public event getCustContactsByCustIDCompletedEventHandler getCustContactsByCustIDCompleted;
/// <remarks/>
public event getCustContactsByIDCompletedEventHandler getCustContactsByIDCompleted;
/// <remarks/>
public event getCustContactByExactIDCompletedEventHandler getCustContactByExactIDCompleted;
/// <remarks/>
public event validateCustIDCompletedEventHandler validateCustIDCompleted;
/// <remarks/>
public event getScreenByCustIDCompletedEventHandler getScreenByCustIDCompleted;
/// <remarks/>
public event getNewscreenCompletedEventHandler getNewscreenCompleted;
/// <remarks/>
public event editScreenCompletedEventHandler editScreenCompleted;
/// <remarks/>
public event editNoteCompletedEventHandler editNoteCompleted;
/// <remarks/>
public event editNoteAsDataSetCompletedEventHandler editNoteAsDataSetCompleted;
/// <remarks/>
public event editCustContactCompletedEventHandler editCustContactCompleted;
/// <remarks/>
public event editCustContactAsJSONCompletedEventHandler editCustContactAsJSONCompleted;
/// <remarks/>
public event editCustContactAsDataSetCompletedEventHandler editCustContactAsDataSetCompleted;
/// <remarks/>
public event editCustContactAsDataSetAsJSONCompletedEventHandler editCustContactAsDataSetAsJSONCompleted;
/// <remarks/>
public event getNewCustContactCompletedEventHandler getNewCustContactCompleted;
/// <remarks/>
public event getNewCustContactAsJSONCompletedEventHandler getNewCustContactAsJSONCompleted;
/// <remarks/>
public event getCustContactsCompletedEventHandler getCustContactsCompleted;
/// <remarks/>
public event getCustContactsAsJSONCompletedEventHandler getCustContactsAsJSONCompleted;
/// <remarks/>
public event getCustContactsAsDataSetCompletedEventHandler getCustContactsAsDataSetCompleted;
/// <remarks/>
public event getCustContactsAsDataSetAsJSONCompletedEventHandler getCustContactsAsDataSetAsJSONCompleted;
/// <remarks/>
public event pingCompletedEventHandler pingCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/about", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string about() {
object[] results = this.Invoke("about", new object[0]);
return ((string)(results[0]));
}
/// <remarks/>
public void aboutAsync() {
this.aboutAsync(null);
}
/// <remarks/>
public void aboutAsync(object userState) {
if ((this.aboutOperationCompleted == null)) {
this.aboutOperationCompleted = new System.Threading.SendOrPostCallback(this.OnaboutOperationCompleted);
}
this.InvokeAsync("about", new object[0], this.aboutOperationCompleted, userState);
}
private void OnaboutOperationCompleted(object arg) {
if ((this.aboutCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.aboutCompleted(this, new aboutCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getCustContactsByCustID", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public CustContact[] getCustContactsByCustID(string custID) {
object[] results = this.Invoke("getCustContactsByCustID", new object[] {
custID});
return ((CustContact[])(results[0]));
}
/// <remarks/>
public void getCustContactsByCustIDAsync(string custID) {
this.getCustContactsByCustIDAsync(custID, null);
}
/// <remarks/>
public void getCustContactsByCustIDAsync(string custID, object userState) {
if ((this.getCustContactsByCustIDOperationCompleted == null)) {
this.getCustContactsByCustIDOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetCustContactsByCustIDOperationCompleted);
}
this.InvokeAsync("getCustContactsByCustID", new object[] {
custID}, this.getCustContactsByCustIDOperationCompleted, userState);
}
private void OngetCustContactsByCustIDOperationCompleted(object arg) {
if ((this.getCustContactsByCustIDCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getCustContactsByCustIDCompleted(this, new getCustContactsByCustIDCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getCustContactsByID", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public CustContact[] getCustContactsByID(string custID, string contactID) {
object[] results = this.Invoke("getCustContactsByID", new object[] {
custID,
contactID});
return ((CustContact[])(results[0]));
}
/// <remarks/>
public void getCustContactsByIDAsync(string custID, string contactID) {
this.getCustContactsByIDAsync(custID, contactID, null);
}
/// <remarks/>
public void getCustContactsByIDAsync(string custID, string contactID, object userState) {
if ((this.getCustContactsByIDOperationCompleted == null)) {
this.getCustContactsByIDOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetCustContactsByIDOperationCompleted);
}
this.InvokeAsync("getCustContactsByID", new object[] {
custID,
contactID}, this.getCustContactsByIDOperationCompleted, userState);
}
private void OngetCustContactsByIDOperationCompleted(object arg) {
if ((this.getCustContactsByIDCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getCustContactsByIDCompleted(this, new getCustContactsByIDCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getCustContactByExactID", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public CustContact getCustContactByExactID(string custID, string contactID) {
object[] results = this.Invoke("getCustContactByExactID", new object[] {
custID,
contactID});
return ((CustContact)(results[0]));
}
/// <remarks/>
public void getCustContactByExactIDAsync(string custID, string contactID) {
this.getCustContactByExactIDAsync(custID, contactID, null);
}
/// <remarks/>
public void getCustContactByExactIDAsync(string custID, string contactID, object userState) {
if ((this.getCustContactByExactIDOperationCompleted == null)) {
this.getCustContactByExactIDOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetCustContactByExactIDOperationCompleted);
}
this.InvokeAsync("getCustContactByExactID", new object[] {
custID,
contactID}, this.getCustContactByExactIDOperationCompleted, userState);
}
private void OngetCustContactByExactIDOperationCompleted(object arg) {
if ((this.getCustContactByExactIDCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getCustContactByExactIDCompleted(this, new getCustContactByExactIDCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/validateCustID", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public genericReturn validateCustID(string custID, bool requireActive) {
object[] results = this.Invoke("validateCustID", new object[] {
custID,
requireActive});
return ((genericReturn)(results[0]));
}
/// <remarks/>
public void validateCustIDAsync(string custID, bool requireActive) {
this.validateCustIDAsync(custID, requireActive, null);
}
/// <remarks/>
public void validateCustIDAsync(string custID, bool requireActive, object userState) {
if ((this.validateCustIDOperationCompleted == null)) {
this.validateCustIDOperationCompleted = new System.Threading.SendOrPostCallback(this.OnvalidateCustIDOperationCompleted);
}
this.InvokeAsync("validateCustID", new object[] {
custID,
requireActive}, this.validateCustIDOperationCompleted, userState);
}
private void OnvalidateCustIDOperationCompleted(object arg) {
if ((this.validateCustIDCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.validateCustIDCompleted(this, new validateCustIDCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getScreenByCustID", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public screen getScreenByCustID(string custID) {
object[] results = this.Invoke("getScreenByCustID", new object[] {
custID});
return ((screen)(results[0]));
}
/// <remarks/>
public void getScreenByCustIDAsync(string custID) {
this.getScreenByCustIDAsync(custID, null);
}
/// <remarks/>
public void getScreenByCustIDAsync(string custID, object userState) {
if ((this.getScreenByCustIDOperationCompleted == null)) {
this.getScreenByCustIDOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetScreenByCustIDOperationCompleted);
}
this.InvokeAsync("getScreenByCustID", new object[] {
custID}, this.getScreenByCustIDOperationCompleted, userState);
}
private void OngetScreenByCustIDOperationCompleted(object arg) {
if ((this.getScreenByCustIDCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getScreenByCustIDCompleted(this, new getScreenByCustIDCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getNewscreen", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public screen getNewscreen(screen inTemplate) {
object[] results = this.Invoke("getNewscreen", new object[] {
inTemplate});
return ((screen)(results[0]));
}
/// <remarks/>
public void getNewscreenAsync(screen inTemplate) {
this.getNewscreenAsync(inTemplate, null);
}
/// <remarks/>
public void getNewscreenAsync(screen inTemplate, object userState) {
if ((this.getNewscreenOperationCompleted == null)) {
this.getNewscreenOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetNewscreenOperationCompleted);
}
this.InvokeAsync("getNewscreen", new object[] {
inTemplate}, this.getNewscreenOperationCompleted, userState);
}
private void OngetNewscreenOperationCompleted(object arg) {
if ((this.getNewscreenCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getNewscreenCompleted(this, new getNewscreenCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/editScreen", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public screen editScreen(string actionType, screen inScreen) {
object[] results = this.Invoke("editScreen", new object[] {
actionType,
inScreen});
return ((screen)(results[0]));
}
/// <remarks/>
public void editScreenAsync(string actionType, screen inScreen) {
this.editScreenAsync(actionType, inScreen, null);
}
/// <remarks/>
public void editScreenAsync(string actionType, screen inScreen, object userState) {
if ((this.editScreenOperationCompleted == null)) {
this.editScreenOperationCompleted = new System.Threading.SendOrPostCallback(this.OneditScreenOperationCompleted);
}
this.InvokeAsync("editScreen", new object[] {
actionType,
inScreen}, this.editScreenOperationCompleted, userState);
}
private void OneditScreenOperationCompleted(object arg) {
if ((this.editScreenCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.editScreenCompleted(this, new editScreenCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/editNote", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public Snote editNote(string actionType, Snote inSnote) {
object[] results = this.Invoke("editNote", new object[] {
actionType,
inSnote});
return ((Snote)(results[0]));
}
/// <remarks/>
public void editNoteAsync(string actionType, Snote inSnote) {
this.editNoteAsync(actionType, inSnote, null);
}
/// <remarks/>
public void editNoteAsync(string actionType, Snote inSnote, object userState) {
if ((this.editNoteOperationCompleted == null)) {
this.editNoteOperationCompleted = new System.Threading.SendOrPostCallback(this.OneditNoteOperationCompleted);
}
this.InvokeAsync("editNote", new object[] {
actionType,
inSnote}, this.editNoteOperationCompleted, userState);
}
private void OneditNoteOperationCompleted(object arg) {
if ((this.editNoteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.editNoteCompleted(this, new editNoteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/editNoteAsDataSet", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet editNoteAsDataSet(string actionType, Snote inSnote) {
object[] results = this.Invoke("editNoteAsDataSet", new object[] {
actionType,
inSnote});
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void editNoteAsDataSetAsync(string actionType, Snote inSnote) {
this.editNoteAsDataSetAsync(actionType, inSnote, null);
}
/// <remarks/>
public void editNoteAsDataSetAsync(string actionType, Snote inSnote, object userState) {
if ((this.editNoteAsDataSetOperationCompleted == null)) {
this.editNoteAsDataSetOperationCompleted = new System.Threading.SendOrPostCallback(this.OneditNoteAsDataSetOperationCompleted);
}
this.InvokeAsync("editNoteAsDataSet", new object[] {
actionType,
inSnote}, this.editNoteAsDataSetOperationCompleted, userState);
}
private void OneditNoteAsDataSetOperationCompleted(object arg) {
if ((this.editNoteAsDataSetCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.editNoteAsDataSetCompleted(this, new editNoteAsDataSetCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/editCustContact", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public CustContact editCustContact(string actionType, CustContact inItem) {
object[] results = this.Invoke("editCustContact", new object[] {
actionType,
inItem});
return ((CustContact)(results[0]));
}
/// <remarks/>
public void editCustContactAsync(string actionType, CustContact inItem) {
this.editCustContactAsync(actionType, inItem, null);
}
/// <remarks/>
public void editCustContactAsync(string actionType, CustContact inItem, object userState) {
if ((this.editCustContactOperationCompleted == null)) {
this.editCustContactOperationCompleted = new System.Threading.SendOrPostCallback(this.OneditCustContactOperationCompleted);
}
this.InvokeAsync("editCustContact", new object[] {
actionType,
inItem}, this.editCustContactOperationCompleted, userState);
}
private void OneditCustContactOperationCompleted(object arg) {
if ((this.editCustContactCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.editCustContactCompleted(this, new editCustContactCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/editCustContactAsJSON", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string editCustContactAsJSON(string actionType, CustContact inItem) {
object[] results = this.Invoke("editCustContactAsJSON", new object[] {
actionType,
inItem});
return ((string)(results[0]));
}
/// <remarks/>
public void editCustContactAsJSONAsync(string actionType, CustContact inItem) {
this.editCustContactAsJSONAsync(actionType, inItem, null);
}
/// <remarks/>
public void editCustContactAsJSONAsync(string actionType, CustContact inItem, object userState) {
if ((this.editCustContactAsJSONOperationCompleted == null)) {
this.editCustContactAsJSONOperationCompleted = new System.Threading.SendOrPostCallback(this.OneditCustContactAsJSONOperationCompleted);
}
this.InvokeAsync("editCustContactAsJSON", new object[] {
actionType,
inItem}, this.editCustContactAsJSONOperationCompleted, userState);
}
private void OneditCustContactAsJSONOperationCompleted(object arg) {
if ((this.editCustContactAsJSONCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.editCustContactAsJSONCompleted(this, new editCustContactAsJSONCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/editCustContactAsDataSet", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet editCustContactAsDataSet(string actionType, CustContact inItem) {
object[] results = this.Invoke("editCustContactAsDataSet", new object[] {
actionType,
inItem});
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void editCustContactAsDataSetAsync(string actionType, CustContact inItem) {
this.editCustContactAsDataSetAsync(actionType, inItem, null);
}
/// <remarks/>
public void editCustContactAsDataSetAsync(string actionType, CustContact inItem, object userState) {
if ((this.editCustContactAsDataSetOperationCompleted == null)) {
this.editCustContactAsDataSetOperationCompleted = new System.Threading.SendOrPostCallback(this.OneditCustContactAsDataSetOperationCompleted);
}
this.InvokeAsync("editCustContactAsDataSet", new object[] {
actionType,
inItem}, this.editCustContactAsDataSetOperationCompleted, userState);
}
private void OneditCustContactAsDataSetOperationCompleted(object arg) {
if ((this.editCustContactAsDataSetCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.editCustContactAsDataSetCompleted(this, new editCustContactAsDataSetCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/editCustContactAsDataSetA" +
"sJSON", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string editCustContactAsDataSetAsJSON(string actionType, CustContact inItem) {
object[] results = this.Invoke("editCustContactAsDataSetAsJSON", new object[] {
actionType,
inItem});
return ((string)(results[0]));
}
/// <remarks/>
public void editCustContactAsDataSetAsJSONAsync(string actionType, CustContact inItem) {
this.editCustContactAsDataSetAsJSONAsync(actionType, inItem, null);
}
/// <remarks/>
public void editCustContactAsDataSetAsJSONAsync(string actionType, CustContact inItem, object userState) {
if ((this.editCustContactAsDataSetAsJSONOperationCompleted == null)) {
this.editCustContactAsDataSetAsJSONOperationCompleted = new System.Threading.SendOrPostCallback(this.OneditCustContactAsDataSetAsJSONOperationCompleted);
}
this.InvokeAsync("editCustContactAsDataSetAsJSON", new object[] {
actionType,
inItem}, this.editCustContactAsDataSetAsJSONOperationCompleted, userState);
}
private void OneditCustContactAsDataSetAsJSONOperationCompleted(object arg) {
if ((this.editCustContactAsDataSetAsJSONCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.editCustContactAsDataSetAsJSONCompleted(this, new editCustContactAsDataSetAsJSONCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getNewCustContact", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public CustContact getNewCustContact(CustContact inTemplate) {
object[] results = this.Invoke("getNewCustContact", new object[] {
inTemplate});
return ((CustContact)(results[0]));
}
/// <remarks/>
public void getNewCustContactAsync(CustContact inTemplate) {
this.getNewCustContactAsync(inTemplate, null);
}
/// <remarks/>
public void getNewCustContactAsync(CustContact inTemplate, object userState) {
if ((this.getNewCustContactOperationCompleted == null)) {
this.getNewCustContactOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetNewCustContactOperationCompleted);
}
this.InvokeAsync("getNewCustContact", new object[] {
inTemplate}, this.getNewCustContactOperationCompleted, userState);
}
private void OngetNewCustContactOperationCompleted(object arg) {
if ((this.getNewCustContactCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getNewCustContactCompleted(this, new getNewCustContactCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getNewCustContactAsJSON", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string getNewCustContactAsJSON(CustContact inTemplate) {
object[] results = this.Invoke("getNewCustContactAsJSON", new object[] {
inTemplate});
return ((string)(results[0]));
}
/// <remarks/>
public void getNewCustContactAsJSONAsync(CustContact inTemplate) {
this.getNewCustContactAsJSONAsync(inTemplate, null);
}
/// <remarks/>
public void getNewCustContactAsJSONAsync(CustContact inTemplate, object userState) {
if ((this.getNewCustContactAsJSONOperationCompleted == null)) {
this.getNewCustContactAsJSONOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetNewCustContactAsJSONOperationCompleted);
}
this.InvokeAsync("getNewCustContactAsJSON", new object[] {
inTemplate}, this.getNewCustContactAsJSONOperationCompleted, userState);
}
private void OngetNewCustContactAsJSONOperationCompleted(object arg) {
if ((this.getNewCustContactAsJSONCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getNewCustContactAsJSONCompleted(this, new getNewCustContactAsJSONCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getCustContacts", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public CustContact[] getCustContacts(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
object[] results = this.Invoke("getCustContacts", new object[] {
currentPageNumber,
pageSize,
parms});
return ((CustContact[])(results[0]));
}
/// <remarks/>
public void getCustContactsAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
this.getCustContactsAsync(currentPageNumber, pageSize, parms, null);
}
/// <remarks/>
public void getCustContactsAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms, object userState) {
if ((this.getCustContactsOperationCompleted == null)) {
this.getCustContactsOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetCustContactsOperationCompleted);
}
this.InvokeAsync("getCustContacts", new object[] {
currentPageNumber,
pageSize,
parms}, this.getCustContactsOperationCompleted, userState);
}
private void OngetCustContactsOperationCompleted(object arg) {
if ((this.getCustContactsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getCustContactsCompleted(this, new getCustContactsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getCustContactsAsJSON", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void getCustContactsAsJSON(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
this.Invoke("getCustContactsAsJSON", new object[] {
currentPageNumber,
pageSize,
parms});
}
/// <remarks/>
public void getCustContactsAsJSONAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
this.getCustContactsAsJSONAsync(currentPageNumber, pageSize, parms, null);
}
/// <remarks/>
public void getCustContactsAsJSONAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms, object userState) {
if ((this.getCustContactsAsJSONOperationCompleted == null)) {
this.getCustContactsAsJSONOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetCustContactsAsJSONOperationCompleted);
}
this.InvokeAsync("getCustContactsAsJSON", new object[] {
currentPageNumber,
pageSize,
parms}, this.getCustContactsAsJSONOperationCompleted, userState);
}
private void OngetCustContactsAsJSONOperationCompleted(object arg) {
if ((this.getCustContactsAsJSONCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getCustContactsAsJSONCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ctDynamicsSLHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getCustContactsAsDataSet", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet getCustContactsAsDataSet(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
object[] results = this.Invoke("getCustContactsAsDataSet", new object[] {
currentPageNumber,
pageSize,
parms});
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void getCustContactsAsDataSetAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
this.getCustContactsAsDataSetAsync(currentPageNumber, pageSize, parms, null);
}
/// <remarks/>
public void getCustContactsAsDataSetAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms, object userState) {
if ((this.getCustContactsAsDataSetOperationCompleted == null)) {
this.getCustContactsAsDataSetOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetCustContactsAsDataSetOperationCompleted);
}
this.InvokeAsync("getCustContactsAsDataSet", new object[] {
currentPageNumber,
pageSize,
parms}, this.getCustContactsAsDataSetOperationCompleted, userState);
}
private void OngetCustContactsAsDataSetOperationCompleted(object arg) {
if ((this.getCustContactsAsDataSetCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getCustContactsAsDataSetCompleted(this, new getCustContactsAsDataSetCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/getCustContactsAsDataSetA" +
"sJSON", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void getCustContactsAsDataSetAsJSON(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
this.Invoke("getCustContactsAsDataSetAsJSON", new object[] {
currentPageNumber,
pageSize,
parms});
}
/// <remarks/>
public void getCustContactsAsDataSetAsJSONAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms) {
this.getCustContactsAsDataSetAsJSONAsync(currentPageNumber, pageSize, parms, null);
}
/// <remarks/>
public void getCustContactsAsDataSetAsJSONAsync(int currentPageNumber, int pageSize, nameValuePairs[] parms, object userState) {
if ((this.getCustContactsAsDataSetAsJSONOperationCompleted == null)) {
this.getCustContactsAsDataSetAsJSONOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetCustContactsAsDataSetAsJSONOperationCompleted);
}
this.InvokeAsync("getCustContactsAsDataSetAsJSON", new object[] {
currentPageNumber,
pageSize,
parms}, this.getCustContactsAsDataSetAsJSONOperationCompleted, userState);
}
private void OngetCustContactsAsDataSetAsJSONOperationCompleted(object arg) {
if ((this.getCustContactsAsDataSetAsJSONCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getCustContactsAsDataSetAsJSONCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.catalinatechnology.com/services/ctDynamicsSL/ping", RequestNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", ResponseNamespace="http://www.catalinatechnology.com/services/ctDynamicsSL", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public System.Data.DataSet ping(string pingType, string siteID, string siteKey, string licenseKey, string licenseName, string licenseExpiration, string softwareName) {
object[] results = this.Invoke("ping", new object[] {
pingType,
siteID,
siteKey,
licenseKey,
licenseName,
licenseExpiration,
softwareName});
return ((System.Data.DataSet)(results[0]));
}
/// <remarks/>
public void pingAsync(string pingType, string siteID, string siteKey, string licenseKey, string licenseName, string licenseExpiration, string softwareName) {
this.pingAsync(pingType, siteID, siteKey, licenseKey, licenseName, licenseExpiration, softwareName, null);
}
/// <remarks/>
public void pingAsync(string pingType, string siteID, string siteKey, string licenseKey, string licenseName, string licenseExpiration, string softwareName, object userState) {
if ((this.pingOperationCompleted == null)) {
this.pingOperationCompleted = new System.Threading.SendOrPostCallback(this.OnpingOperationCompleted);
}
this.InvokeAsync("ping", new object[] {
pingType,
siteID,
siteKey,
licenseKey,
licenseName,
licenseExpiration,
softwareName}, this.pingOperationCompleted, userState);
}
private void OnpingOperationCompleted(object arg) {
if ((this.pingCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.pingCompleted(this, new pingCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
private bool IsLocalFileSystemWebService(string url) {
if (((url == null)
|| (url == string.Empty))) {
return false;
}
System.Uri wsUri = new System.Uri(url);
if (((wsUri.Port >= 1024)
&& (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) {
return true;
}
return false;
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL", IsNullable=false)]
public partial class ctDynamicsSLHeader : System.Web.Services.Protocols.SoapHeader {
private string licenseKeyField;
private string licenseNameField;
private string licenseExpirationField;
private string softwareNameField;
private string siteIDField;
private string siteKeyField;
private string userNameField;
private string cpnyIDField;
private System.Xml.XmlAttribute[] anyAttrField;
/// <remarks/>
public string licenseKey {
get {
return this.licenseKeyField;
}
set {
this.licenseKeyField = value;
}
}
/// <remarks/>
public string licenseName {
get {
return this.licenseNameField;
}
set {
this.licenseNameField = value;
}
}
/// <remarks/>
public string licenseExpiration {
get {
return this.licenseExpirationField;
}
set {
this.licenseExpirationField = value;
}
}
/// <remarks/>
public string softwareName {
get {
return this.softwareNameField;
}
set {
this.softwareNameField = value;
}
}
/// <remarks/>
public string siteID {
get {
return this.siteIDField;
}
set {
this.siteIDField = value;
}
}
/// <remarks/>
public string siteKey {
get {
return this.siteKeyField;
}
set {
this.siteKeyField = value;
}
}
/// <remarks/>
public string userName {
get {
return this.userNameField;
}
set {
this.userNameField = value;
}
}
/// <remarks/>
public string cpnyID {
get {
return this.cpnyIDField;
}
set {
this.cpnyIDField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr {
get {
return this.anyAttrField;
}
set {
this.anyAttrField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL")]
public partial class nameValuePairs {
private string nameField;
private string valueField;
/// <remarks/>
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
public string value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL")]
public partial class Snote {
private string errorMessageField;
private string notesField;
private int resultCodeField;
private System.DateTime dtRevisedDateField;
private int nIDField;
private string sLevelNameField;
private string sTableNameField;
private string sNoteTextField;
/// <remarks/>
public string errorMessage {
get {
return this.errorMessageField;
}
set {
this.errorMessageField = value;
}
}
/// <remarks/>
public string notes {
get {
return this.notesField;
}
set {
this.notesField = value;
}
}
/// <remarks/>
public int resultCode {
get {
return this.resultCodeField;
}
set {
this.resultCodeField = value;
}
}
/// <remarks/>
public System.DateTime dtRevisedDate {
get {
return this.dtRevisedDateField;
}
set {
this.dtRevisedDateField = value;
}
}
/// <remarks/>
public int nID {
get {
return this.nIDField;
}
set {
this.nIDField = value;
}
}
/// <remarks/>
public string sLevelName {
get {
return this.sLevelNameField;
}
set {
this.sLevelNameField = value;
}
}
/// <remarks/>
public string sTableName {
get {
return this.sTableNameField;
}
set {
this.sTableNameField = value;
}
}
/// <remarks/>
public string sNoteText {
get {
return this.sNoteTextField;
}
set {
this.sNoteTextField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL")]
public partial class screen {
private string myCustIDField;
private CustContact[] myCustContactsField;
private string errorMessageField;
/// <remarks/>
public string myCustID {
get {
return this.myCustIDField;
}
set {
this.myCustIDField = value;
}
}
/// <remarks/>
public CustContact[] myCustContacts {
get {
return this.myCustContactsField;
}
set {
this.myCustContactsField = value;
}
}
/// <remarks/>
public string errorMessage {
get {
return this.errorMessageField;
}
set {
this.errorMessageField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL")]
public partial class CustContact {
private string errorMessageField;
private string notesField;
private int resultCodeField;
private string addr1Field;
private string addr2Field;
private string cityField;
private string contactIDField;
private string countryField;
private System.DateTime crtd_DateTimeField;
private string crtd_ProgField;
private string crtd_UserField;
private string custIDField;
private string emailAddrField;
private string faxField;
private System.DateTime lUpd_DateTimeField;
private string lUpd_ProgField;
private string lUpd_UserField;
private string nameField;
private int noteIDField;
private double orderLimitField;
private string phoneField;
private double pOReqdAmtField;
private string s4Future01Field;
private string s4Future02Field;
private double s4Future03Field;
private double s4Future04Field;
private double s4Future05Field;
private double s4Future06Field;
private System.DateTime s4Future07Field;
private System.DateTime s4Future08Field;
private int s4Future09Field;
private int s4Future10Field;
private string s4Future11Field;
private string s4Future12Field;
private string salutField;
private string stateField;
private string typeField;
private string user1Field;
private System.DateTime user10Field;
private string user2Field;
private string user3Field;
private string user4Field;
private double user5Field;
private double user6Field;
private string user7Field;
private string user8Field;
private System.DateTime user9Field;
private string webSiteField;
private string zipField;
/// <remarks/>
public string errorMessage {
get {
return this.errorMessageField;
}
set {
this.errorMessageField = value;
}
}
/// <remarks/>
public string notes {
get {
return this.notesField;
}
set {
this.notesField = value;
}
}
/// <remarks/>
public int resultCode {
get {
return this.resultCodeField;
}
set {
this.resultCodeField = value;
}
}
/// <remarks/>
public string Addr1 {
get {
return this.addr1Field;
}
set {
this.addr1Field = value;
}
}
/// <remarks/>
public string Addr2 {
get {
return this.addr2Field;
}
set {
this.addr2Field = value;
}
}
/// <remarks/>
public string City {
get {
return this.cityField;
}
set {
this.cityField = value;
}
}
/// <remarks/>
public string ContactID {
get {
return this.contactIDField;
}
set {
this.contactIDField = value;
}
}
/// <remarks/>
public string Country {
get {
return this.countryField;
}
set {
this.countryField = value;
}
}
/// <remarks/>
public System.DateTime Crtd_DateTime {
get {
return this.crtd_DateTimeField;
}
set {
this.crtd_DateTimeField = value;
}
}
/// <remarks/>
public string Crtd_Prog {
get {
return this.crtd_ProgField;
}
set {
this.crtd_ProgField = value;
}
}
/// <remarks/>
public string Crtd_User {
get {
return this.crtd_UserField;
}
set {
this.crtd_UserField = value;
}
}
/// <remarks/>
public string CustID {
get {
return this.custIDField;
}
set {
this.custIDField = value;
}
}
/// <remarks/>
public string EmailAddr {
get {
return this.emailAddrField;
}
set {
this.emailAddrField = value;
}
}
/// <remarks/>
public string Fax {
get {
return this.faxField;
}
set {
this.faxField = value;
}
}
/// <remarks/>
public System.DateTime LUpd_DateTime {
get {
return this.lUpd_DateTimeField;
}
set {
this.lUpd_DateTimeField = value;
}
}
/// <remarks/>
public string LUpd_Prog {
get {
return this.lUpd_ProgField;
}
set {
this.lUpd_ProgField = value;
}
}
/// <remarks/>
public string LUpd_User {
get {
return this.lUpd_UserField;
}
set {
this.lUpd_UserField = value;
}
}
/// <remarks/>
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
public int NoteID {
get {
return this.noteIDField;
}
set {
this.noteIDField = value;
}
}
/// <remarks/>
public double OrderLimit {
get {
return this.orderLimitField;
}
set {
this.orderLimitField = value;
}
}
/// <remarks/>
public string Phone {
get {
return this.phoneField;
}
set {
this.phoneField = value;
}
}
/// <remarks/>
public double POReqdAmt {
get {
return this.pOReqdAmtField;
}
set {
this.pOReqdAmtField = value;
}
}
/// <remarks/>
public string S4Future01 {
get {
return this.s4Future01Field;
}
set {
this.s4Future01Field = value;
}
}
/// <remarks/>
public string S4Future02 {
get {
return this.s4Future02Field;
}
set {
this.s4Future02Field = value;
}
}
/// <remarks/>
public double S4Future03 {
get {
return this.s4Future03Field;
}
set {
this.s4Future03Field = value;
}
}
/// <remarks/>
public double S4Future04 {
get {
return this.s4Future04Field;
}
set {
this.s4Future04Field = value;
}
}
/// <remarks/>
public double S4Future05 {
get {
return this.s4Future05Field;
}
set {
this.s4Future05Field = value;
}
}
/// <remarks/>
public double S4Future06 {
get {
return this.s4Future06Field;
}
set {
this.s4Future06Field = value;
}
}
/// <remarks/>
public System.DateTime S4Future07 {
get {
return this.s4Future07Field;
}
set {
this.s4Future07Field = value;
}
}
/// <remarks/>
public System.DateTime S4Future08 {
get {
return this.s4Future08Field;
}
set {
this.s4Future08Field = value;
}
}
/// <remarks/>
public int S4Future09 {
get {
return this.s4Future09Field;
}
set {
this.s4Future09Field = value;
}
}
/// <remarks/>
public int S4Future10 {
get {
return this.s4Future10Field;
}
set {
this.s4Future10Field = value;
}
}
/// <remarks/>
public string S4Future11 {
get {
return this.s4Future11Field;
}
set {
this.s4Future11Field = value;
}
}
/// <remarks/>
public string S4Future12 {
get {
return this.s4Future12Field;
}
set {
this.s4Future12Field = value;
}
}
/// <remarks/>
public string Salut {
get {
return this.salutField;
}
set {
this.salutField = value;
}
}
/// <remarks/>
public string State {
get {
return this.stateField;
}
set {
this.stateField = value;
}
}
/// <remarks/>
public string Type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
/// <remarks/>
public string User1 {
get {
return this.user1Field;
}
set {
this.user1Field = value;
}
}
/// <remarks/>
public System.DateTime User10 {
get {
return this.user10Field;
}
set {
this.user10Field = value;
}
}
/// <remarks/>
public string User2 {
get {
return this.user2Field;
}
set {
this.user2Field = value;
}
}
/// <remarks/>
public string User3 {
get {
return this.user3Field;
}
set {
this.user3Field = value;
}
}
/// <remarks/>
public string User4 {
get {
return this.user4Field;
}
set {
this.user4Field = value;
}
}
/// <remarks/>
public double User5 {
get {
return this.user5Field;
}
set {
this.user5Field = value;
}
}
/// <remarks/>
public double User6 {
get {
return this.user6Field;
}
set {
this.user6Field = value;
}
}
/// <remarks/>
public string User7 {
get {
return this.user7Field;
}
set {
this.user7Field = value;
}
}
/// <remarks/>
public string User8 {
get {
return this.user8Field;
}
set {
this.user8Field = value;
}
}
/// <remarks/>
public System.DateTime User9 {
get {
return this.user9Field;
}
set {
this.user9Field = value;
}
}
/// <remarks/>
public string WebSite {
get {
return this.webSiteField;
}
set {
this.webSiteField = value;
}
}
/// <remarks/>
public string Zip {
get {
return this.zipField;
}
set {
this.zipField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.catalinatechnology.com/services/ctDynamicsSL")]
public partial class genericReturn {
private int errorCodeField;
private string errorMessageField;
/// <remarks/>
public int errorCode {
get {
return this.errorCodeField;
}
set {
this.errorCodeField = value;
}
}
/// <remarks/>
public string errorMessage {
get {
return this.errorMessageField;
}
set {
this.errorMessageField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void aboutCompletedEventHandler(object sender, aboutCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class aboutCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal aboutCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getCustContactsByCustIDCompletedEventHandler(object sender, getCustContactsByCustIDCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getCustContactsByCustIDCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getCustContactsByCustIDCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public CustContact[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((CustContact[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getCustContactsByIDCompletedEventHandler(object sender, getCustContactsByIDCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getCustContactsByIDCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getCustContactsByIDCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public CustContact[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((CustContact[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getCustContactByExactIDCompletedEventHandler(object sender, getCustContactByExactIDCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getCustContactByExactIDCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getCustContactByExactIDCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public CustContact Result {
get {
this.RaiseExceptionIfNecessary();
return ((CustContact)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void validateCustIDCompletedEventHandler(object sender, validateCustIDCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class validateCustIDCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal validateCustIDCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public genericReturn Result {
get {
this.RaiseExceptionIfNecessary();
return ((genericReturn)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getScreenByCustIDCompletedEventHandler(object sender, getScreenByCustIDCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getScreenByCustIDCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getScreenByCustIDCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public screen Result {
get {
this.RaiseExceptionIfNecessary();
return ((screen)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getNewscreenCompletedEventHandler(object sender, getNewscreenCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getNewscreenCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getNewscreenCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public screen Result {
get {
this.RaiseExceptionIfNecessary();
return ((screen)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void editScreenCompletedEventHandler(object sender, editScreenCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class editScreenCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal editScreenCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public screen Result {
get {
this.RaiseExceptionIfNecessary();
return ((screen)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void editNoteCompletedEventHandler(object sender, editNoteCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class editNoteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal editNoteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public Snote Result {
get {
this.RaiseExceptionIfNecessary();
return ((Snote)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void editNoteAsDataSetCompletedEventHandler(object sender, editNoteAsDataSetCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class editNoteAsDataSetCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal editNoteAsDataSetCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void editCustContactCompletedEventHandler(object sender, editCustContactCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class editCustContactCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal editCustContactCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public CustContact Result {
get {
this.RaiseExceptionIfNecessary();
return ((CustContact)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void editCustContactAsJSONCompletedEventHandler(object sender, editCustContactAsJSONCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class editCustContactAsJSONCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal editCustContactAsJSONCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void editCustContactAsDataSetCompletedEventHandler(object sender, editCustContactAsDataSetCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class editCustContactAsDataSetCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal editCustContactAsDataSetCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void editCustContactAsDataSetAsJSONCompletedEventHandler(object sender, editCustContactAsDataSetAsJSONCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class editCustContactAsDataSetAsJSONCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal editCustContactAsDataSetAsJSONCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getNewCustContactCompletedEventHandler(object sender, getNewCustContactCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getNewCustContactCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getNewCustContactCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public CustContact Result {
get {
this.RaiseExceptionIfNecessary();
return ((CustContact)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getNewCustContactAsJSONCompletedEventHandler(object sender, getNewCustContactAsJSONCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getNewCustContactAsJSONCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getNewCustContactAsJSONCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getCustContactsCompletedEventHandler(object sender, getCustContactsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getCustContactsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getCustContactsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public CustContact[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((CustContact[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getCustContactsAsJSONCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getCustContactsAsDataSetCompletedEventHandler(object sender, getCustContactsAsDataSetCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getCustContactsAsDataSetCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getCustContactsAsDataSetCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void getCustContactsAsDataSetAsJSONCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
public delegate void pingCompletedEventHandler(object sender, pingCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1586.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class pingCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal pingCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public System.Data.DataSet Result {
get {
this.RaiseExceptionIfNecessary();
return ((System.Data.DataSet)(this.results[0]));
}
}
}
}
#pragma warning restore 1591 | mit |
SebSept/onemorelaravelblog | app/database/seeds/TagsTableSeeder.php | 324 | <?php
class TagsTableSeeder extends Seeder {
public function run()
{
$faker = Faker\Factory::create('fr_FR');
$tags = [];
$count = 0;
while($count++ < 7) {
$title = $faker->word;
$tags[] = [
'title' => $title
];
}
DB::table('tags')->truncate();
DB::table('tags')->insert($tags);
}
}
| mit |
tomwalker/glasgow_parking | test/karma.conf.js | 690 | module.exports = function(config){
config.set({
basePath : '../',
files : [
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/js/*.js',
'test/unit/*.js',
{pattern: 'test/mocks/*.json',}
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Firefox'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
| mit |
aaldaber/owid-grapher | grapher_admin/migrations/0017_auto_20170915_1024.py | 488 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-09-15 10:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grapher_admin', '0016_remove_old_axis_labels_20170915_0430'),
]
operations = [
migrations.AlterField(
model_name='chartdimension',
name='conversionFactor',
field=models.FloatField(null=True),
),
]
| mit |
markoa/audiogara | features/step_definitions/user_steps.rb | 1067 | Given /^I am logged in as "([^"]*)"$/ do |username|
@user = Factory(:user, :lastfm_username => username)
steps %Q{
Given I am on the home page
And I fill in "user_lastfm_username" with "#{username}"
And I press "Show me"
}
end
Given /^I have a recommendation "([^"]*)" \- "([^"]*)"$/ do |artist_name, album_name|
tmp = Artist.where(:name => artist_name).first
if tmp.present?
artist = tmp
else
artist = Factory(:artist, :name => artist_name)
end
interest = @user.interests.where(:artist_name => artist_name).first
if interest.nil?
@user.interests.create(:artist => artist,
:artist_name => artist_name,
:score => 0.7)
end
Factory(:torrent,
:artist => artist,
:artist_name => artist_name,
:album_name => album_name,
:title => "#{artist_name} - #{album_name}")
end
Given "I am in" do
visit("/")
end
Given /^I wait for (\d+) seconds$/ do |sec|
sleep(sec.to_i)
end
When /^I reload the page$/ do
visit(current_path)
end
| mit |
tetra5/telegooby | telegooby/__init__.py | 35 | __version__ = ('2016', '07', '14')
| mit |
strongcoins/strongcoin | src/qt/guiutil.cpp | 13519 | #include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include "base58.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("StrongCoin"))
return false;
// check if the address is valid
CBitcoinAddress addressFromUri(uri.path().toStdString());
if (!addressFromUri.IsValid())
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert StrongCoin:// to StrongCoin:
//
// Cannot handle this later, because StrongCoin:// will cause Qt to see the part after // as host,
// which will lowercase it (and thus invalidate the address).
if(uri.startsWith("StrongCoin://"))
{
uri.replace(0, 11, "StrongCoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "StrongCoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for StrongCoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "StrongCoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a StrongCoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=StrongCoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("StrongCoin-qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" StrongCoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("StrongCoin-qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stderr, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
| mit |
Alex-B09/Tostitos | Tostitos/threading/callstack.cpp | 2195 | #include "callstack.h"
#include <algorithm>
using namespace Threading::impl;
using namespace TosLang;
////////// Stack Frame //////////
size_t StackFrame::mCount = 0;
void StackFrame::AddOrUpdateSymbolValue(const FrontEnd::Symbol* sym, const InterpretedValue& value)
{
mCurrentSymbolVals[sym] = value;
}
void StackFrame::SetExprValue(const TosLang::FrontEnd::ASTNode* expr, const InterpretedValue& value)
{
mExprVals[expr] = value;
}
bool StackFrame::TryGetSymbolValue(const FrontEnd::Symbol* sym, InterpretedValue& value)
{
auto valIt = mCurrentSymbolVals.find(sym);
const bool found = valIt != mCurrentSymbolVals.end();
if (found)
value = valIt->second;
return found;
}
bool StackFrame::TryGetExprValue(const FrontEnd::ASTNode* expr, InterpretedValue& value)
{
auto valIt = mExprVals.find(expr);
const bool found = valIt != mExprVals.end();
if (found)
value = valIt->second;
return found;
}
////////// Call Stack //////////
void CallStack::AddOrUpdateSymbolValue(const FrontEnd::Symbol* sym, const InterpretedValue& value, bool isGlobalSymol)
{
if (isGlobalSymol)
mFrames.front().AddOrUpdateSymbolValue(sym, value);
else
mFrames.back().AddOrUpdateSymbolValue(sym, value);
}
void CallStack::SetExprValue(const TosLang::FrontEnd::ASTNode* expr, const InterpretedValue& value, size_t frameID)
{
auto foundIt = std::find_if(mFrames.begin(), mFrames.end(), [&frameID](const StackFrame& frame) { return frameID == frame.GetID(); });
if (foundIt != mFrames.end())
foundIt->SetExprValue(expr, value);
}
void CallStack::PushFrame(const StackFrame& frame)
{
mFrames.push_back(frame);
}
void CallStack::PushFrame(StackFrame&& frame)
{
mFrames.emplace_back(frame);
}
bool CallStack::TryGetSymbolValue(const FrontEnd::Symbol* sym, InterpretedValue& value, bool isGlobalSymol)
{
if (isGlobalSymol)
return mFrames.front().TryGetSymbolValue(sym, value);
else
return mFrames.back().TryGetSymbolValue(sym, value);
}
bool CallStack::TryGetExprValue(const FrontEnd::ASTNode* expr, InterpretedValue& value)
{
return mFrames.back().TryGetExprValue(expr, value);
}
| mit |
eaigner/shield | shield.go | 3312 | package shield
import (
"math"
)
const defaultProb float64 = 1e-11
type shield struct {
tokenizer Tokenizer
store Store
}
func New(t Tokenizer, s Store) Shield {
return &shield{
tokenizer: t,
store: s,
}
}
func (sh *shield) Learn(class, text string) (err error) {
return sh.increment(class, text, 1)
}
func (sh *shield) BulkLearn(sets []Set) (err error) {
return sh.bulkIncrement(sets, 1)
}
func (sh *shield) Forget(class, text string) (err error) {
return sh.increment(class, text, -1)
}
func (sh *shield) increment(class, text string, sign int64) (err error) {
if len(class) == 0 {
panic("invalid class")
}
if len(text) == 0 {
panic("invalid text")
}
return sh.bulkIncrement([]Set{Set{Class: class, Text: text}}, sign)
}
func (sh *shield) bulkIncrement(sets []Set, sign int64) (err error) {
if len(sets) == 0 {
panic("invalid data set")
}
m := make(map[string]map[string]int64)
for _, set := range sets {
tokens := sh.tokenizer.Tokenize(set.Text)
for k, _ := range tokens {
tokens[k] *= sign
}
if w, ok := m[set.Class]; ok {
for word, count := range tokens {
w[word] += count
}
} else {
m[set.Class] = tokens
}
}
for class, _ := range m {
if err = sh.store.AddClass(class); err != nil {
return
}
}
return sh.store.IncrementClassWordCounts(m)
}
func getKeys(m map[string]int64) []string {
keys := make([]string, 0, len(m))
for k, _ := range m {
keys = append(keys, k)
}
return keys
}
func (s *shield) Score(text string) (scores map[string]float64, err error) {
// Get total class word counts
totals, err := s.store.TotalClassWordCounts()
if err != nil {
return
}
classes := getKeys(totals)
// Tokenize text
wordFreqs := s.tokenizer.Tokenize(text)
words := getKeys(wordFreqs)
// Get word frequencies for each class
classFreqs := make(map[string]map[string]int64)
for _, class := range classes {
freqs, err2 := s.store.ClassWordCounts(class, words)
if err2 != nil {
err = err2
return
}
classFreqs[class] = freqs
}
// Calculate log scores for each class
logScores := make(map[string]float64, len(classes))
for _, class := range classes {
freqs := classFreqs[class]
total := totals[class]
// Because this classifier is not biased, we don't use prior probabilities
score := float64(0)
for _, word := range words {
// Compute the probability that this word belongs to that class
wordProb := float64(freqs[word]) / float64(total)
if wordProb == 0 {
wordProb = defaultProb
}
score += math.Log(wordProb)
}
logScores[class] = score
}
// Normalize the scores
var min = math.MaxFloat64
var max = -math.MaxFloat64
for _, score := range logScores {
if score > max {
max = score
}
if score < min {
min = score
}
}
r := max - min
scores = make(map[string]float64, len(classes))
for class, score := range logScores {
if r == 0 {
scores[class] = 1
} else {
scores[class] = (score - min) / r
}
}
return
}
func (s *shield) Classify(text string) (class string, err error) {
scores, err := s.Score(text)
if err != nil {
return
}
// Select class with highes prob
var score float64
for k, v := range scores {
if v > score {
class, score = k, v
}
}
return
}
func (sh *shield) Reset() error {
return sh.store.Reset()
}
| mit |
abkfenris/knowhow | knowhow/__init__.py | 518 | """
App builder.
"""
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
bootstrap.init_app(app)
db.init_app(app)
from knowhow.main import main, views, errors # noqa
app.register_blueprint(main)
from knowhow.admin import admin
admin.init_app(app)
return app
| mit |
Miragecoder/Urbanization | src/Mirage.Urbanization.Resources/BitmapExtensions.cs | 1318 | using System;
using System.Collections.Generic;
using SixLabors.ImageSharp;
using System.Linq;
using SixLabors.Primitives;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace Mirage.Urbanization.Tilesets
{
public static class ImageExtensions
{
public static Image RotateImage(this Image bmp, float angle) => bmp.Clone(x => x.Rotate(angle));
public static IEnumerable<KeyValuePair<Point, Image>> GetSegments(this Image image, int multiplier)
{
static Image GetImageSegment(Image image, int x, int y, int multiplier)
{
// Clone a portion of the Image object.
Rectangle cloneRect = new Rectangle(
x: (x * multiplier),
y: (y * multiplier),
width: 1 * multiplier,
height: 1 * multiplier
);
return image.Clone(x => x.Crop(cloneRect));
}
return
from x in Enumerable.Range(0, image.Width / multiplier)
from y in Enumerable.Range(0, image.Height / multiplier)
select new KeyValuePair<Point, Image>(new Point(x, y), GetImageSegment(image, x, y, multiplier));
}
}
} | mit |
rebus007/BaseRecyclerView | library/src/main/java/com/raphaelbussa/baserecyclerview/StaticViewHolder.java | 325 | package com.raphaelbussa.baserecyclerview;
import android.view.View;
/**
* Created by rebus007 on 04/09/17.
*/
class StaticViewHolder extends BaseViewHolder {
StaticViewHolder(View itemView) {
super(itemView);
}
@Override
public void onBindViewHolder(Object data) {
//not used
}
}
| mit |
aliyun/fc-java-sdk | src/main/java/com/aliyuncs/fc/http/HttpRequest.java | 2781 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.aliyuncs.fc.http;
import com.aliyuncs.fc.constants.Const;
import com.aliyuncs.fc.exceptions.ClientException;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public abstract class HttpRequest {
protected Map<String, String> headers;
public HttpRequest() {
headers = new HashMap<String, String>();
}
public abstract String getPath();
public abstract void validate() throws ClientException;
public HttpURLConnection getHttpConnection(String urls, String method)
throws IOException {
String strUrl = urls;
if (null == strUrl || null == method) {
return null;
}
URL url = new URL(strUrl);
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod(method);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
httpConn.setConnectTimeout(Const.CONNECT_TIMEOUT);
httpConn.setReadTimeout(Const.READ_TIMEOUT);
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpConn.setRequestProperty(entry.getKey(), entry.getValue());
}
return httpConn;
}
public void setHeader(String key, String value) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(key), "Header key cannot be blank");
Preconditions.checkArgument(!Strings.isNullOrEmpty(value), "Header value cannot be blank");
headers.put(key, value);
}
public byte[] getPayload() {
return null;
}
public Map<String, String> getQueryParams() {
return null;
}
public Map<String, String> getHeaders() {
return headers;
}
}
| mit |
happy-coin/test-coin | src/qt/sendcoinsentry.cpp | 4617 | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a HappyCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
| mit |
Leanty/tree-gateway | src/utils/time-intervals.ts | 1110 | 'use strict';
import * as _ from 'lodash';
const humanInterval = require('human-interval');
humanInterval.languageMap['eleven'] = 11;
humanInterval.languageMap['twelve'] = 12;
humanInterval.languageMap['thirteen'] = 13;
humanInterval.languageMap['fourteen'] = 14;
humanInterval.languageMap['fifteen'] = 15;
humanInterval.languageMap['sixteen'] = 16;
humanInterval.languageMap['seventeen'] = 17;
humanInterval.languageMap['eighteen'] = 18;
humanInterval.languageMap['nineteen'] = 19;
humanInterval.languageMap['twenty'] = 20;
humanInterval.languageMap['thirty'] = 30;
humanInterval.languageMap['fourty'] = 40;
humanInterval.languageMap['fifty'] = 50;
humanInterval.languageMap['sixty'] = 60;
humanInterval.languageMap['seventy'] = 70;
humanInterval.languageMap['eighty'] = 80;
humanInterval.languageMap['ninety'] = 90;
humanInterval.languageMap['hundred'] = 100;
export function getMilisecondsInterval(value: string | number | undefined, defaultValue?: number) {
if (!value) {
return defaultValue;
}
if (_.isNumber(value)) {
return value;
}
return humanInterval(value);
}
| mit |
malero/simple-ts-models | src/fields/EmailField.ts | 435 | import { Field } from "./Field";
export class EmailField extends Field {
_emailRegex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
validate() {
super.validate();
if(this._value != null && !this._emailRegex.test(this._value))
this._errors.push('Please enter a valid email address');
return this._errors;
}
}
| mit |
Irraquated/old-Irraquated.github.io | Resources/main.js | 344 | var red = [0, 100, 63];
var orange = [40, 100, 60];
var green = [75, 100, 40];
var blue = [196, 77, 55];
var purple = [280, 50, 60];
var myName = "Irraquated";
letterColors = [red, orange, green, blue, purple]
if(10 < 200) {
bubbleShape = "circle";
}
else {
bubbleShape = "square";
}
drawName(myName, letterColors);
bounceBubbles() | mit |
dbachrach/skinner | src/skinner/core/intervals.js | 1644 | define (["lib/lodash"], function (_) {
"use strict";
// TODO: Use pegjs
var ONE_SECOND = 1000;
var ONE_MINUTE = 60 * ONE_SECOND;
var ONE_HOUR = 60 * ONE_MINUTE;
var ONE_DAY = 24 * ONE_HOUR;
var ONE_YEAR = 365 * ONE_DAY;
/**
* Parses a string for a timer interval.
* For example "2 minutes" returns a time interval of 120,000 milliseconds.
* @param interval The string that represents a time interval.
* @returns The time interval in milliseconds. Returns `undefined` if parsing fails.
*/
function parseTimeInterval(interval) {
if (_.isUndefined(interval)) {
return undefined;
}
var matches = interval.match(/^([+-]?\d+) *(.*)$/);
if (!matches) {
return undefined;
}
var number = parseInt(matches[1], 10);
var word = matches[2].toLowerCase();
var timeUnits = [
{ "words": ["sec", "secs", "second", "seconds"], "unit": ONE_SECOND },
{ "words": ["min", "mins", "minute", "minutes"], "unit": ONE_MINUTE },
{ "words": ["hr", "hrs", "hour", "hours"], "unit": ONE_HOUR },
{ "words": ["day", "days"], "unit": ONE_DAY },
{ "words": ["yr", "yrs", "year", "years"], "unit": ONE_YEAR }
];
var found = _.find(timeUnits, function (timeUnit) {
return _.contains(timeUnit.words, word);
});
if (!found) {
return undefined;
}
return number * found.unit;
}
return {
"parseTimeInterval": parseTimeInterval
};
});
| mit |
Comp4711CILab3/comp4711-lab3-starter-gallery | application/controllers/Gallery.php | 1145 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Gallery extends Application
{
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/
* - or -
* http://example.com/welcome/index
*
* So any other public methods not prefixed with an underscore will
* map to /welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$pix = $this->images->all();
foreach ($pix as $picture) {
$cells[] = $this->parser->parse('_cell', (array) $picture, true);
}
$this->load->library('table');
$params = array(
'table_open' => '<table class="gallery">',
'cell_start' => '<td class="oneimage">',
'cell_alt_start' => '<td class="oneimage">'
);
$this->table->set_template($params);
$rows = $this->table->make_columns($cells, 3);
$this->data['thetable'] = $this->table->generate($rows);
$this->data['pagebody'] = 'gallery';
$this->render();
}
}
| mit |
jacks205/Beyond45Game | Assets/MainMenu/Scripts/ButtonScript.cs | 504 | using UnityEngine;
using System.Collections;
public class ButtonScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void StartGameOnClick()
{
Debug.Log("Start");
Application.LoadLevel("Level1");
}
public void ContinueOnClick()
{
Debug.Log("Continue");
}
public void QuitOnClick()
{
Debug.Log("Quit");
Application.Quit();
}
}
| mit |
pshynin/JavaRushTasks | 1.JavaSyntax/src/com/javarush/task/task04/task0419/Solution.java | 752 | package com.javarush.task.task04.task0419;
/*
Максимум четырех чисел
*/
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
//напишите тут ваш код
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int d = scanner.nextInt();
if (Math.max(a, b) > Math.max(c, d)) {
System.out.println(Math.max(a, b));
} else if (Math.max(a, b) < Math.max(c, d)) {
System.out.println(Math.max(c, d));
} else if (Math.max(a, b) == Math.max(c, d)) {
System.out.println(a);
}
}
}
| mit |
ThirdPartyNinjas/NinjaParty | Test/Tests/Facebook.hpp | 1202 | #include <functional>
#include <memory>
#include <NinjaParty/FacebookManager.hpp>
#include <NinjaParty/Game.hpp>
namespace Tests
{
class TestGame : public NinjaParty::Game
{
public:
TestGame(int screenWidth, int screenHeight)
: NinjaParty::Game(screenWidth, screenHeight)
{
}
void Update(float deltaSeconds)
{
}
void Draw()
{
if(facebookManager.IsLoggedIn())
ClearScreen(NinjaParty::Color::CornflowerBlue);
else
ClearScreen(NinjaParty::Color::Red);
}
void TouchBegan(void *touchHandle, int tapCount, int x, int y)
{
if(x < GetScreenWidth() / 2)
{
if(facebookManager.IsLoggedIn())
facebookManager.RequestInfo();
else
facebookManager.Login();
}
else
{
if(facebookManager.IsLoggedIn())
facebookManager.Logout();
else
facebookManager.Login();
}
}
void FacebookLogin(bool success, const std::string &accessToken)
{
facebookManager.InjectLogin(success, accessToken);
}
void FacebookLogout()
{
facebookManager.InjectLogout();
}
private:
NinjaParty::FacebookManager facebookManager;
};
}
| mit |
cryptix/talebay | modules_basic/like.js | 2254 |
var h = require('hyperscript')
var u = require('../util')
var pull = require('pull-stream')
var plugs = require('../plugs')
//var message_confirm = plugs.first(exports.message_confirm = [])
//var message_link = plugs.first(exports.message_link = [])
//var sbot_links = plugs.first(exports.sbot_links = [])
exports.needs = {
avatar_name: 'first',
message_confirm: 'first',
message_link: 'first',
sbot_links: 'first'
}
exports.gives = {
message_content: true,
message_content_mini: true,
message_meta: true,
message_action: true
}
exports.create = function (api) {
var exports = {}
exports.message_content =
exports.message_content_mini = function (msg, sbot) {
if(msg.value.content.type !== 'vote') return
var link = msg.value.content.vote.link
return [
msg.value.content.vote.value > 0 ? 'dug' : 'undug',
' ', api.message_link(link)
]
}
exports.message_meta = function (msg, sbot) {
var digs = h('a')
var votes = []
for(var k in CACHE) {
if(CACHE[k].content.type == 'vote' &&
(CACHE[k].content.vote == msg.key ||
CACHE[k].content.vote.link == msg.key
))
votes.push({source: CACHE[k].author, dest: k, rel: 'vote'})
}
if(votes.length === 1)
digs.textContent = ' 1 Dig'
else if(votes.length > 1)
digs.textContent = ' ' + votes.length + ' Digs'
pull(
pull.values(votes.map(vote => {
return api.avatar_name(vote.source)
})),
pull.collect(function (err, ary) {
digs.title = ary.map(x => x.innerHTML).join(" ")
})
)
return digs
}
exports.message_action = function (msg, sbot) {
if(msg.value.content.type !== 'vote')
return h('div.skill_object.dig.black', {href: '#', onclick: function () {
var dig = {
type: 'vote',
vote: { link: msg.key, value: 1, expression: 'Dig' }
}
if(msg.value.content.recps) {
dig.recps = msg.value.content.recps.map(function (e) {
return e && typeof e !== 'string' ? e.link : e
})
dig.private = true
}
//TODO: actually publish...
api.message_confirm(dig)
}}, 'Dig')
}
return exports
}
| mit |
SlavaBogu1/xvi | xvi_clAbsModule.php | 708 | <?php
/** @file xvi_clAbsModule.php
* This is abstract class describing third party modules.
* Each customized module must implement it.
* XVI also support function plugins .. to be removed soon.
* @todo Finalize module interface (either class or function or both)
\addtogroup Modules
@{
*/
/** @class cXVI_AbsModule Abstarct class describing interfaces
* @param Register - to register all supported placeholders and functions
* @param Call - simple call a function associated with placeholder
*/
abstract class cXVI_AbsModule {
abstract public static function Register();
abstract public static function Call($placeholder_id);
}
/*@}*/
?>
| mit |
yatanokarasu/jsf-practice | sample04/src/main/java/sample/MeiboBean.java | 1882 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Yusuke TAKEI.
*
* 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 sample;
import javax.faces.bean.ManagedBean;
/**
*
*/
@ManagedBean(name="meibo")
public class MeiboBean {
private String name = "default";
private int number = 0;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the number
*/
public int getNumber() {
return number;
}
/**
* @param name the name to set
*/
public void setName(final String name) {
this.name = name;
}
/**
* @param number the number to set
*/
public void setNumber(final int number) {
this.number = number;
}
public String next() {
return "output.xhtml";
}
}
| mit |
bouzuya/node-jenking | lib/index.js | 1217 | var express = require('express');
var request = require('request');
var TimeBomb = require('./time-bomb').TimeBomb;
var PORT = parseInt((process.env.PORT || '3000'), 10);
var TIMEOUT = parseInt((process.env.JENKING_TIMEOUT || '10000'), 10);
var CALLBACK = JSON.parse(process.env.JENKING_CALLBACK || '""');
if (isNaN(PORT))
throw new Error('invalid port : ' + process.env.PORT);
if (isNaN(TIMEOUT))
throw new Error('invalid timeout : ' + process.env.JENKING_TIMEOUT);
if (!CALLBACK)
throw new Error('invalid callback : ' + process.env.JENKING_CALLBACK);
var bomb = new TimeBomb({
bomb: function() {
console.log('bomb at ' + new Date().toISOString());
console.log(CALLBACK);
request(CALLBACK);
bomb.start();
},
timeout: TIMEOUT
});
var app = express();
app.get('/', function(req, res) {
var message = 'reset at ' + new Date().toISOString();
console.log(message);
bomb.reset();
res.json({ message: message });
});
app.get('/ping', function(req, res) {
console.log('ping');
res.json({ message: 'pong' });
});
app.listen(PORT, function() {
console.log('listening : ' + PORT);
console.log('start at ' + new Date().toISOString());
bomb.start();
});
module.exports = app;
| mit |
adamos42/ionize | themes/admin/javascript/mootools_locale/eu.js | 327 | /*
---
name: Locale.EU.Number
description: Number messages for Europe.
license: MIT-style license
authors:
- Arian Stolwijk
requires:
- /Locale
provides: [Locale.EU.Number]
...
*/
Locale.define('EU', 'Number', {
decimal: ',',
group: '.',
currency: {
prefix: '€ '
}
}); | mit |
cachilders/backpat | src/helpers.test.js | 11130 | import chai, { expect } from 'chai';
import chaiSpies from 'chai-spies';
import {
NpmConfig,
readPackageJson,
readYarnLock,
rootDir,
instantiateDependencies,
fetchEachDependency,
fetchDependency,
resolveDependency,
addNode,
nodeDetails,
chopDependencies
} from './helpers';
import { getNpmData } from './utilities';
chai.use(chaiSpies);
describe('Helpers', function() {
describe('rootDir', () => {
it('should be a string', () => {
expect(rootDir).to.be.a('string');
});
});
describe('nodeDetails', () => {
it('should be an object', () => {
expect(nodeDetails).to.be.an('object');
});
});
describe('readPackageJson', () => {
it('should be a function that accepts two optional arguments', () => {
expect(readPackageJson).to.be.a('function');
expect(readPackageJson.length).to.equal(0);
});
it('should throw TypeError when passed argument that is not a string', () => {
expect(() => readPackageJson(42)).to.throw(TypeError);
});
it('should return a promise object', () => {
expect(() => readPackageJson().to.be.an.instanceof(Promise));
});
it('should return a simple, name-only object when path does not exist', (done) => {
readPackageJson('/', 'abroxia').then((pkg) => {
expect(pkg).to.be.an('object');
expect(pkg).to.contain.only.keys('name');
});
done();
});
it('should return project\'s parsed package.json', (done) => {
readPackageJson().then((pkg) => {
expect(pkg).to.be.an('object');
expect(pkg).to.contain.all.keys('name', 'description');
expect(pkg).to.have.any.keys(
'version',
'main',
'scripts',
'author',
'license',
'dependencies',
'devDependencies'
);
});
done();
});
});
describe('readYarnLock', () => {
it('should be a function that accepts two optional arguments', () => {
expect(readYarnLock).to.be.a('function');
expect(readYarnLock.length).to.equal(0);
});
it('should throw TypeError when passed argument that is not a string', () => {
expect(() => readYarnLock(42)).to.throw(TypeError);
});
it('should return a promise object', () => {
expect(() => readYarnLock().to.be.an.instanceof(Promise));
});
it('should return a hollow object when path does not exist', (done) => {
readYarnLock('/', 'abroxia').then((yarnDeps) => {
expect(yarnDeps).to.be.an('object');
expect(yarnDeps).to.contain.only.keys('yarnDependencies');
});
done();
});
it('should return project\'s parsed yarn.lock', (done) => {
readYarnLock().then((lock) => {
expect(lock).to.be.an('object');
expect(lock).to.contain.only.keys('yarnDependencies');
});
done();
});
});
describe('instantiateDependencies', () => {
const deps = {
dependencies: {
flashy: '^3.5.0', stuff: '^0.7.1'
}
};
const devDeps = {
devDependencies: {
chai: '^3.5.0', coveralls: '^2.11.15'
}
};
it('should be a function', () => {
expect(instantiateDependencies).to.be.a('function');
});
it('should return a promise when passed an object', () => {
expect(instantiateDependencies(deps)).to.be.an.instanceof(Promise);
});
it('returned promise should eventually resolve into an object', (done) => {
instantiateDependencies({})
.then((result) => expect(result).to.be.an('object'));
done();
});
it('resolved promise should be an empty object when provided no \'dependencies\' or \'devDependencies\' keys', (done) => {
instantiateDependencies({})
.then((result) => expect(result).to.have.all.keys([]));
done();
});
it('resolved promise should be an object when given only \'dependencies\'', (done) => {
instantiateDependencies(deps)
.then((result) => expect(result).to.have.all.keys(['flashy', 'stuff']));
done();
});
it('resolved promise should be an object when given only \'devDependencies\'', (done) => {
instantiateDependencies(devDeps)
.then((result) => expect(result).to.have.all.keys(['chai', 'coveralls']));
done();
});
it('resolved promise should be an object when given both \'dependencies\' and \'devDependencies\'', (done) => {
instantiateDependencies(Object.assign(deps, devDeps))
.then((result) => expect(result).to.have.all.keys(['flashy', 'stuff', 'chai', 'coveralls']));
done();
});
});
const deps = {
"lodash": { version: "4.17.2" },
"ramda": { version: "0.22.1" }
};
describe('NpmConfig', () => {
it('should be a factory that returns an array of config objects', () => {
expect(NpmConfig).to.be.a('function');
const result = NpmConfig(deps);
expect(result).to.be.an('array');
expect(result).to.deep.equal([{
hostname: 'api.npmjs.org',
path: '/downloads/point/last-month/lodash,ramda',
method: 'GET',
headers: {
'User-Agent': 'cachilders/backpat'
}
}]);
});
});
describe('chopDependencies', () => {
it('should be a function', () => {
expect(chopDependencies).to.be.a('function');
});
it('should be a return an array of strings', () => {
const result = chopDependencies(new Array(400).fill('a'));
expect(result).to.be.an('array');
expect(result.length).to.equal(4);
expect(result[0]).to.be.a('string');
expect(result[0].match(/,/g).length).to.equal(99);
});
});
describe('getNpmData', () => {
it('should be a function', () => {
expect(getNpmData).to.be.a('function');
});
it('should return a promise object', () => {
expect(getNpmData(deps)).to.be.an.instanceof(Promise);
});
it('should make an https GET request', (done) => {
// const config = NpmConfig(deps);
getNpmData(deps).then( (result) => {
expect(result).to.be.an('object');
expect(result.lodash).to.have.any.keys('downloads');
expect(result.ramda).to.have.any.keys('downloads');
});
done();
});
});
describe('fetchEachDependency', () => {
const deps = {
"lodash": { version: "4.17.2" },
"ramda": { version: "0.22.1" }
};
it('should be a function', () => {
expect(fetchEachDependency).to.be.a('function');
});
it('should accept an object as its single parameter', () => {
expect(fetchEachDependency).to.have.length(1);
expect(() => fetchEachDependency(deps)).to.not.throw(TypeError);
});
it('should throw TypeError when not passed object', () => {
expect(() => fetchEachDependency('this is a string')).to.throw(TypeError);
expect(() => fetchEachDependency(42)).to.throw(TypeError);
expect(() => fetchEachDependency(true)).to.throw(TypeError);
});
it('should throw TypeError when passed an array', () => {
expect(() => fetchEachDependency([])).to.throw(TypeError);
});
it('should handle multiple dependencies', () => {
expect(fetchEachDependency(deps)).to.be.ok;
});
// TODO:
// it('should invoke readPackageJson for each dependency', () => {
//
// });
it('should return a promise object', () => {
expect(fetchEachDependency(deps)).to.be.an.instanceof(Promise);
});
it('should eventually return an object', (done) => {
fetchEachDependency(deps).then((dependencies) => {
expect(dependencies).to.be.an('object');
});
done();
});
it('should eventually map dependencies to objects', (done) => {
fetchEachDependency(deps).then((dependencies) => {
expect(Object.keys(dependencies)).to.have.length(2);
});
done();
});
});
describe('fetchDependency', () => {
it('should return a promise object', () => {
expect(fetchDependency('ramda')).to.be.an.instanceof(Promise);
});
it('should accept an string as its single parameter', () => {
expect(fetchDependency).to.have.length(1);
expect(() => fetchDependency('ramda')).to.not.throw(TypeError);
});
it('should fail when passed an argument that is not a string', () => {
expect(fetchDependency).to.throw(TypeError);
expect(() => fetchDependency([])).to.throw(TypeError);
expect(() => fetchDependency({})).to.throw(TypeError);
});
it('should eventually resolve to a dependency\'s package', (done) => {
fetchDependency('ramda').then((result) => {
expect(result).to.be.an('object');
});
done();
});
});
describe('resolveDependency', () => {
const dependency1 = {
name: 'lodash',
repository: {url: 'https://lodash.com/'},
description: 'Lodash modular utilities.',
};
const dependency2 = {
name: 'style-loader',
repository: {url: 'ssh://[email protected]/webpack/style-loader.git'},
description: 'file loader module for webpack',
};
const dependency3 = {
name: 'shrg',
repository: {url: 'shrg.biz'},
description: 'shrug it off',
};
const dependency4 = {
name: 'sass-loader',
repository: {url: 'git://github.com/jtangelder/sass-loader.git'},
description: 'Sass loader for webpack',
};
const dependency5 = {
name: 'doubleshrg',
description: 'nope.nope',
};
it('should return a promise', () => {
expect(resolveDependency).to.be.a('function');
expect(resolveDependency(dependency1)).to.be.an.instanceof(Promise);
});
it('should eventually return the correct output', (done) => {
resolveDependency(dependency1).then((result) => {
expect(result).to.have.all.keys('name', 'url', 'description');
});
done();
});
it('should adequately process standard URL patterns', (done) => {
resolveDependency(dependency1).then((result) => {
expect(result.url).to.equal('https://lodash.com/');
});
done();
});
it('should adequately process ssh URL patterns', (done) => {
resolveDependency(dependency2).then((result) => {
expect(result.url).to.equal('https://github.com/webpack/style-loader');
});
done();
});
it('should adequately process minimal URL patterns', (done) => {
resolveDependency(dependency3).then((result) => {
expect(result.url).to.equal('https://shrg.biz');
});
done();
});
it('should adequately process git URL patterns', (done) => {
resolveDependency(dependency4).then((result) => {
expect(result.url).to.equal('https://github.com/jtangelder/sass-loader');
});
done();
});
it('should return blank URL value in absence of URL string', (done) => {
resolveDependency(dependency5).then((result) => {
expect(result.url).to.equal('');
});
done();
});
});
describe('addNode', () => {
it('should be a function', () => {
expect(addNode).to.be.a('function');
});
});
});
| mit |
stefan-lehmann/atomatic | app/scripts/services/StructureService.js | 4913 | import Vue from 'vue';
class StructureService {
constructor(sections, maxLevel = 2) {
this.maxLevel = maxLevel;
this.sections = sections;
this.urls = sections.reduce(this.generateSectionStructure.bind(this), {});
}
static hasSiblings(file, index, files) {
const siblings = files
.filter((otherFile, otherIndex) => index !== otherIndex)
.filter((otherFile) => otherFile.path === file.path);
return siblings.length > 0;
}
static sortByOrderValue(a, b) {
const
valueA = a.orderValue ? a.orderValue.toLowerCase() : '',
valueB = b.orderValue ? b.orderValue.toLowerCase() : '',
titleA = a.title ? a.title.toLowerCase() : '',
titleB = b.title ? b.title.toLowerCase() : '';
return valueA === valueB ? titleA < titleB ? -1 : 1 : valueA < valueB ? -1 : 1;
}
static capitalizeString(str) {
return str.toLowerCase()
.replace(/\b\w/g, (matches) => matches.toUpperCase());
}
static getTitleFromName(str) {
return self.capitalizeString(str)
.replace(/\d{2,}-|\-|_/g, ' ')
.trim();
}
generateSectionStructure(urls, section) {
const
{maxLevel} = this,
{files = [], url: basePath} = section;
files
.sort(self.sortByOrderValue)
.map((file, index) => {
const
splittedPath = file.path.split('/'),
hasSiblings = self.hasSiblings(file, index, files);
splittedPath
.slice(0, maxLevel)
.reduce((current, name, index, array) => {
const
{urls: currentUrls = []} = current,
index1 = index + 1,
lastIndex = index1 === array.length,
getItemFunction = lastIndex ? this.getRealItem : this.getVirtualItem,
pathFragments = index1 === maxLevel ? splittedPath : splittedPath.slice(0, index1),
itemPath = pathFragments.join('/'),
url = [basePath, itemPath].filter(item => item)
.join('/'),
redundantIndex = currentUrls.findIndex((item) => item.url === url);
if (!lastIndex && redundantIndex > -1) {
return current.urls[redundantIndex];
}
const item = getItemFunction({name, url, file, current});
urls[item.baseUrl] = Object.assign({}, item);
if (lastIndex && hasSiblings && redundantIndex > -1) {
current = current.urls[redundantIndex];
current.grouped.push(item);
current.grouped.sort(self.sortByOrderValue);
return item;
}
else {
urls[url] = item;
}
if (current.urls === undefined) {
current.urls = [];
}
current.urls.push(item);
current.urls.sort(self.sortByOrderValue);
if (lastIndex && hasSiblings) {
if (item.grouped === undefined) {
item.grouped = [Vue.util.extend({}, item)];
item.title = self.getTitleFromName(item.name);
item.orderValue = item.name;
}
else {
item.grouped.push(Vue.util.extend({}, item));
item.grouped.sort(self.sortByOrderValue);
}
}
return item;
}, section);
});
return urls;
}
getVirtualItem(options) {
const
{name, url, file} = options,
{path, ext, collector, componentName} = file;
return {
name,
url,
collector,
filename: `index.${ext}`,
title: self.getTitleFromName(name),
orderValue: path
};
}
getRealItem(options) {
const
{name, url, file, current} = options,
{url: fileUrl, title, path, orderValue, collector, asyncContentUrls, componentName} = file,
{title: pageTitle} = current;
return {
name,
componentName,
url,
fileUrl,
asyncContentUrls,
collector,
title,
pageTitle,
orderValue: orderValue || path,
baseUrl: fileUrl.split('.').slice(0, -1).join('.')
};
}
static filteredStructure(structure, search='atoms') {
if (search.length < 3){
return null;
}
return Object.values(structure).reduce((carray, item) => {
return StructureService.filter(carray, search, item);
}, []);
}
static filter(carry, search, file) {
if (file.urls) {
file.urls.forEach((item) => StructureService.filter(carry, search, item));
return carry;
}
if (file.grouped) {
file.grouped.forEach((item) => StructureService.filter(carry, search, item));
return carry;
}
if (file.componentName && file.componentName.indexOf(search) !== -1) {
carry.push(Object.assign({}, file, {title: file.componentName}));
}
return carry;
}
}
const self = StructureService;
export default StructureService;
| mit |
avijit1258/OnlineBusTicket | database/migrations/2016_03_19_154658_create_companies_table.php | 716 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCompaniesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('company_name');
$table->unique('company_name');
$table->text('user_name');
$table->text('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('companies');
}
}
| mit |
usamec/CR-index | benchmark/test_cr_index.cpp | 2491 | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <chrono>
#include <boost/algorithm/string.hpp>
#include <malloc.h>
#include "cr_index.hpp"
using namespace std;
bool is_memory_mapping(const string &line) {
istringstream s(line);
s.exceptions(istream::failbit | istream::badbit);
try {
// Try reading the fields to verify format.
string buf;
s >> buf; // address range
s >> buf; // permissions
s >> buf; // offset
s >> buf; // device major:minor
size_t inode;
s >> inode;
if (inode == 0) {
return true;
}
} catch (std::ios_base::failure &e) { }
return false;
}
size_t get_field_value(const string &line) {
istringstream s(line);
size_t result;
string buf;
s >> buf >> result;
return result;
}
size_t get_referenced_memory_size() {
ifstream smaps("/proc/self/smaps");
smaps.exceptions(istream::failbit | istream::badbit);
string line;
size_t result = 0;
try {
while (1) {
while (!is_memory_mapping(line)) {
getline(smaps, line);
}
while (!(line.substr(0, 11) == "Referenced:")) {
getline(smaps, line);
}
result += get_field_value(line);
}
} catch (std::ios_base::failure &e) { }
return result;
}
void go(string index_filename) {
cout << "Building CRIndex ... " << endl;
CRIndex *rm = CRIndex::LoadFromFile(index_filename);
cout << "Referenced memory: " << get_referenced_memory_size() << "kB" << endl;
malloc_trim(42);
cout << "Referenced memory: " << get_referenced_memory_size() << "kB" << endl;
vector<int> res = rm->find_indexes("CCATCTT");
cout << "Referenced memory: " << get_referenced_memory_size() << "kB" << endl;
cout << res.size() << endl;
cout << "Referenced memory: " << get_referenced_memory_size() << "kB" << endl;
}
int main(int argc, char** argv) {
if (argc < 2) {
cerr << "Usage: " << argv[0] << " <filename>" << endl;
cerr << "Examples: " << endl;
cerr << " Read index file and construct CR-index" << endl;
cerr << " " << argv[0] << " index.data" << endl;
exit(1);
}
try {
go(argv[1]);
} catch(exception &e) {
cerr << "Error: " << e.what() << endl;
exit(1);
}
return 0;
}
| mit |
windy/wblog | db/migrate/20210614151102_create_administrators.rb | 253 | class CreateAdministrators < ActiveRecord::Migration[6.1]
def change
create_table :administrators do |t|
t.string :name
t.string :password_digest
t.timestamps
end
add_index :administrators, :name, unique: true
end
end
| mit |
collegepulse/material-react-components | src/Tabs/index.js | 70 | export {default} from './Tabs';
export {default as Tab} from './Tab';
| mit |
ddqd/zvonok | app/src/main/java/org/cryptocommune/zvonok/di/ApplicationComponent.java | 768 | package org.cryptocommune.zvonok.di;
import android.content.Context;
import com.cryptocommune.domain.repository.ZvonokRepository;
import com.cryptocommune.domain.schedulers.ObserveOn;
import com.cryptocommune.domain.schedulers.SubscribeOn;
import org.cryptocommune.zvonok.MainActivity;
import org.cryptocommune.zvonok.ZvonokFragment;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by Dema on 24.09.2016.
*/
@Singleton
@Component(modules = {ApplicationModule.class, RepositoryModule.class})
public interface ApplicationComponent {
void inject(MainActivity activity);
void inject(ZvonokFragment fragment);
Context context();
SubscribeOn subscribeOn();
ObserveOn observeOn();
ZvonokRepository zvonokRepository();
} | mit |
ivayloilievv/Issue-Tracking-System | app/notify/notify-services.js | 1657 | 'use strict';
angular.module('issueTrackingSystem.notify-factory', [])
.factory('notifyService',
function () {
return {
showInfo: function(msg) {
noty({
text: msg,
type: 'info',
layout: 'topCenter',
timeout: 1000}
);
},
showError: function(msg, serverError) {
// Collect errors to display from the server response
var errors = [];
if (serverError && serverError.error_description) {
errors.push(serverError.error_description);
}
if (serverError && serverError.modelState) {
var modelStateErrors = serverError.modelState;
for (var propertyName in modelStateErrors) {
var errorMessages = modelStateErrors[propertyName];
var trimmedName = propertyName.substr(propertyName.indexOf('.') + 1);
for (var i = 0; i < errorMessages.length; i++) {
var currentError = errorMessages[i];
errors.push(trimmedName + ' - ' + currentError);
}
}
}
if (errors.length > 0) {
msg = msg + ":<br>" + errors.join("<br>");
}
noty({
text: msg,
type: 'error',
layout: 'topCenter',
timeout: 5000}
);
}
}
}
);
| mit |
cesvald/lbm | db/migrate/20170629223345_add_currency_to_project.rb | 176 | class AddCurrencyToProject < ActiveRecord::Migration
def change
add_column :projects, :currency_id, :integer, default: 1
add_index :projects, :currency_id
end
end
| mit |
cuckata23/wurfl-data | data/blackberry9380_ver1.php | 2412 | <?php
return array (
'id' => 'blackberry9380_ver1',
'fallback' => 'blackberry_generic_ver7',
'capabilities' =>
array (
'uaprof' => 'http://www.blackberry.net/go/mobile/profiles/uaprof/9380_umts/7.0.0.rdf',
'model_name' => 'BlackBerry 9380',
'uaprof2' => 'http://www.blackberry.net/go/mobile/profiles/uaprof/9380_edge/7.0.0.rdf',
'uaprof3' => 'http://www.blackberry.net/go/mobile/profiles/uaprof/9380_gprs/7.0.0.rdf',
'brand_name' => 'RIM',
'marketing_name' => 'Blackberry 9380 Curve',
'release_date' => '2012_february',
'table_support' => 'true',
'wml_1_1' => 'true',
'wml_1_2' => 'true',
'wml_1_3' => 'true',
'physical_screen_height' => '66',
'columns' => '36',
'dual_orientation' => 'true',
'physical_screen_width' => '50',
'max_image_width' => '320',
'rows' => '32',
'resolution_width' => '360',
'resolution_height' => '480',
'jpg' => 'true',
'gif' => 'true',
'bmp' => 'true',
'wbmp' => 'true',
'svgt_1_1' => 'true',
'png' => 'true',
'colors' => '16777216',
'max_deck_size' => '32768',
'streaming_vcodec_h263_0' => '10',
'streaming_vcodec_h264_bp' => '1',
'streaming_vcodec_mpeg4_sp' => '0',
'connectionless_service_load' => 'true',
'connectionless_cache_operation' => 'true',
'connectionless_service_indication' => 'true',
'wap_push_support' => 'true',
'j2me_cldc_1_0' => 'true',
'j2me_midp_1_0' => 'true',
'mms_png' => 'true',
'mms_3gpp' => 'true',
'mms_max_size' => '614400',
'mms_max_width' => '1600',
'sender' => 'true',
'mms_wml' => 'true',
'mms_spmidi' => 'true',
'mms_max_height' => '1600',
'mms_gif_static' => 'true',
'mms_wav' => 'true',
'mms_video' => 'true',
'mms_vcard' => 'true',
'mms_midi_polyphonic' => 'true',
'mms_jad' => 'true',
'mms_midi_monophonic' => 'true',
'mms_wmlc' => 'true',
'mms_bmp' => 'true',
'receiver' => 'true',
'mms_wbmp' => 'true',
'mms_vcalendar' => 'true',
'mms_mp3' => 'true',
'mms_jar' => 'true',
'mms_amr' => 'true',
'mms_mp4' => 'true',
'mms_jpeg_baseline' => 'true',
'mms_gif_animated' => 'true',
'wav' => 'true',
'sp_midi' => 'true',
'aac' => 'true',
'mp3' => 'true',
'amr' => 'true',
'midi_monophonic' => 'true',
'midi_polyphonic' => 'true',
'nfc_support' => 'true',
),
);
| mit |
Stonekity/ShopManager | ShopManager-app/src/main/java/com/stone/shopmanager/model/hbut/BXTNews.java | 1672 | package com.stone.shopmanager.model.hbut;
import cn.bmob.v3.BmobObject;
/**
* 博学堂讲座实体类
* @date 2014-5-10
* @author Stone
*/
public class BXTNews extends BmobObject{
//private String id;
private String title; //标题
private String topic; //讲座主题
private String speaker; //主 讲 人
private String time; //讲座时间
private String location; //讲座地点
private String holder1; //主办单位
private String holder2; //承办单位
private String points; //主讲内容提要
private String speakerinfo; //主讲人简介
public String getTitle() {
return title;
}
public String getTopic() {
return topic;
}
public String getSpeaker() {
return speaker;
}
public String getTime() {
return time;
}
public String getLocation() {
return location;
}
public String getHolder1() {
return holder1;
}
public String getHolder2() {
return holder2;
}
public String getPoints() {
return points;
}
public String getSpeakerinfo() {
return speakerinfo;
}
public void setTitle(String title) {
this.title = title;
}
public void setTopic(String topic) {
this.topic = topic;
}
public void setSpeaker(String speaker) {
this.speaker = speaker;
}
public void setTime(String time) {
this.time = time;
}
public void setLocation(String location) {
this.location = location;
}
public void setHolder1(String holder1) {
this.holder1 = holder1;
}
public void setHolder2(String holder2) {
this.holder2 = holder2;
}
public void setPoints(String points) {
this.points = points;
}
public void setSpeakerinfo(String speakerinfo) {
this.speakerinfo = speakerinfo;
}
}
| mit |
Adonga/Dumbazells | Dumbazells/src/Player.java | 3827 |
import org.lwjgl.input.Controller;
import org.lwjgl.input.Controllers;
import org.newdawn.slick.*;
import org.newdawn.slick.geom.Circle;
public class Player {
static private final float cursorSpeed = 0.03f;
static private final float controllerDeadZone = 0.2f;
static private final float PLAYER_SCALE = 0.004f;
private Circle paintCircle = new Circle(8.0f, 4.5f, 0.4f);
private CommandType nextCommandType;
private int controllerIndex;
private Controller controller = null;
int i=0;
Image[] playerImages;
Player(int controllerIndex) {
this.controllerIndex = controllerIndex;
// Find controllerIndex'th xbox controller
int foundXboxControllerCount = 0;
for(int i = 0; i < Controllers.getControllerCount(); ++i) {
if(Controllers.getController(i).getName().toLowerCase().contains("xbox")) {
if(foundXboxControllerCount == controllerIndex) {
controller = Controllers.getController(i);
controller.setXAxisDeadZone(controllerDeadZone);
controller.setYAxisDeadZone(controllerDeadZone);
}
++foundXboxControllerCount;
}
}
try {
playerImages = new Image[] {
new Image("images/player_circle.png"),
new Image("images/player_raute.png"),
new Image("images/player_square.png"),
new Image("images/player_triangle.png")
};
} catch (SlickException e) {
e.printStackTrace();
}
}
public void setCursorStartPosition(Basis base) {
paintCircle.setCenterX(base.getPosition().getX());
paintCircle.setCenterY(base.getPosition().getY());
}
public void update(Input input) {
float movementY = 0.0f;
float movementX = 0.0f;
nextCommandType = null;
// Extra controls
switch(controllerIndex) {
case 0:
if(input.isKeyDown(Input.KEY_1)) {
nextCommandType = CommandType.NOTHING;
} else if(input.isKeyDown(Input.KEY_2)) {
nextCommandType = CommandType.RUN;
} else if(input.isKeyDown(Input.KEY_3)) {
nextCommandType = CommandType.CATCH;
} else if(input.isKeyDown(Input.KEY_4)) {
nextCommandType = CommandType.ATTACK;
}
movementY += input.isKeyDown(Input.KEY_DOWN) ? cursorSpeed : 0.0f;
movementY -= input.isKeyDown(Input.KEY_UP) ? cursorSpeed : 0.0f;
movementX += input.isKeyDown(Input.KEY_RIGHT) ? cursorSpeed : 0.0f;
movementX -= input.isKeyDown(Input.KEY_LEFT) ? cursorSpeed : 0.0f;
break;
}
if(controller != null && controller.getAxisCount() >= 2) {
if(controller.isButtonPressed(3)) {
nextCommandType = CommandType.NOTHING;
} else if(controller.isButtonPressed(2)) {
nextCommandType = CommandType.RUN;
} else if(controller.isButtonPressed(0)) {
nextCommandType = CommandType.CATCH;
} else if(controller.isButtonPressed(1)) {
nextCommandType = CommandType.ATTACK;
}
movementX += controller.getXAxisValue() * cursorSpeed;
movementY += controller.getYAxisValue() * cursorSpeed;
}
// Double speed if player does not draw.
if(nextCommandType == null) {
movementX *= 2.0f;
movementY *= 2.0f;
}
if(paintCircle.getCenterX() + movementX >= 0 && paintCircle.getCenterX() + movementX <= 16 )
paintCircle.setCenterX(paintCircle.getCenterX() + movementX);
if(paintCircle.getCenterY() + movementY >= 0 && paintCircle.getCenterY() + movementY <= 9 )
paintCircle.setCenterY(paintCircle.getCenterY() + movementY);
}
public void render(CommandMap commandMap, Graphics g) {
g.setColor(Color.white);
playerImages[controllerIndex].draw(paintCircle.getCenterX() - playerImages[controllerIndex].getWidth() * PLAYER_SCALE * 0.5f,
paintCircle.getCenterY() - playerImages[controllerIndex].getHeight() * PLAYER_SCALE * 0.5f, PLAYER_SCALE);
if(nextCommandType != null) {
commandMap.paint(paintCircle, nextCommandType);
}
}
public int getControlerIndex() {
return controllerIndex;
}
}
| mit |
u9520107/component-react-bootstrap | react-bootstrap/transpiled/OverlayTrigger.js | 5683 | "use strict";
/** @jsx React.DOM */
var React = require("./react-es6")["default"];
var cloneWithProps = require("./react-es6/lib/cloneWithProps")["default"];
var merge = require("./react-es6/lib/merge")["default"];
var OverlayMixin = require("./OverlayMixin")["default"];
var domUtils = require("./domUtils")["default"];
var utils = require("./utils")["default"];
/**
* Check if value one is inside or equal to the of value
*
* @param {string} one
* @param {string|array} of
* @returns {boolean}
*/
function isOneOf(one, of) {
if (Array.isArray(of)) {
return of.indexOf(one) >= 0;
}
return one === of;
}
var OverlayTrigger = React.createClass({displayName: 'OverlayTrigger',
mixins: [OverlayMixin],
propTypes: {
trigger: React.PropTypes.oneOfType([
React.PropTypes.oneOf(['manual', 'click', 'hover', 'focus']),
React.PropTypes.arrayOf(React.PropTypes.oneOf(['click', 'hover', 'focus']))
]),
placement: React.PropTypes.oneOf(['top','right', 'bottom', 'left']),
delay: React.PropTypes.number,
delayShow: React.PropTypes.number,
delayHide: React.PropTypes.number,
defaultOverlayShown: React.PropTypes.bool,
overlay: React.PropTypes.renderable.isRequired
},
getDefaultProps: function () {
return {
placement: 'right',
trigger: ['hover', 'focus']
};
},
getInitialState: function () {
return {
isOverlayShown: this.props.defaultOverlayShown == null ?
false : this.props.defaultOverlayShown,
overlayLeft: null,
overlayTop: null
};
},
show: function () {
this.setState({
isOverlayShown: true
}, function() {
this.updateOverlayPosition();
});
},
hide: function () {
this.setState({
isOverlayShown: false
});
},
toggle: function () {
this.state.isOverlayShown ?
this.hide() : this.show();
},
renderOverlay: function () {
if (!this.state.isOverlayShown) {
return React.DOM.span(null );
}
return cloneWithProps(
this.props.overlay,
{
onRequestHide: this.hide,
placement: this.props.placement,
positionLeft: this.state.overlayLeft,
positionTop: this.state.overlayTop
}
);
},
render: function () {
var props = {};
if (isOneOf('click', this.props.trigger)) {
props.onClick = utils.createChainedFunction(this.toggle, this.props.onClick);
}
if (isOneOf('hover', this.props.trigger)) {
props.onMouseOver = utils.createChainedFunction(this.handleDelayedShow, this.props.onMouseOver);
props.onMouseOut = utils.createChainedFunction(this.handleDelayedHide, this.props.onMouseOut);
}
if (isOneOf('focus', this.props.trigger)) {
props.onFocus = utils.createChainedFunction(this.handleDelayedShow, this.props.onFocus);
props.onBlur = utils.createChainedFunction(this.handleDelayedHide, this.props.onBlur);
}
return cloneWithProps(
React.Children.only(this.props.children),
props
);
},
componentWillUnmount: function() {
clearTimeout(this._hoverDelay);
},
handleDelayedShow: function () {
if (this._hoverDelay != null) {
clearTimeout(this._hoverDelay);
this._hoverDelay = null;
return;
}
var delay = this.props.delayShow != null ?
this.props.delayShow : this.props.delay;
if (!delay) {
this.show();
return;
}
this._hoverDelay = setTimeout(function() {
this._hoverDelay = null;
this.show();
}.bind(this), delay);
},
handleDelayedHide: function () {
if (this._hoverDelay != null) {
clearTimeout(this._hoverDelay);
this._hoverDelay = null;
return;
}
var delay = this.props.delayHide != null ?
this.props.delayHide : this.props.delay;
if (!delay) {
this.hide();
return;
}
this._hoverDelay = setTimeout(function() {
this._hoverDelay = null;
this.hide();
}.bind(this), delay);
},
updateOverlayPosition: function () {
if (!this.isMounted()) {
return;
}
var pos = this.calcOverlayPosition();
this.setState({
overlayLeft: pos.left,
overlayTop: pos.top
});
},
calcOverlayPosition: function () {
var childOffset = this.getPosition();
var overlayNode = this.getOverlayDOMNode();
var overlayHeight = overlayNode.offsetHeight;
var overlayWidth = overlayNode.offsetWidth;
switch (this.props.placement) {
case 'right':
return {
top: childOffset.top + childOffset.height / 2 - overlayHeight / 2,
left: childOffset.left + childOffset.width
};
case 'left':
return {
top: childOffset.top + childOffset.height / 2 - overlayHeight / 2,
left: childOffset.left - overlayWidth
};
case 'top':
return {
top: childOffset.top - overlayHeight,
left: childOffset.left + childOffset.width / 2 - overlayWidth / 2
};
case 'bottom':
return {
top: childOffset.top + childOffset.height,
left: childOffset.left + childOffset.width / 2 - overlayWidth / 2
};
default:
throw new Error('calcOverlayPosition(): No such placement of "' + this.props.placement + '" found.');
}
},
getPosition: function () {
var node = this.getDOMNode();
var container = this.getContainerDOMNode();
var offset = container.tagName == 'BODY' ?
domUtils.getOffset(node) : domUtils.getPosition(node, container);
return merge(offset, {
height: node.offsetHeight,
width: node.offsetWidth
});
}
});
exports["default"] = OverlayTrigger; | mit |
agorf/feed2email | spec/feed2email/email_spec.rb | 2119 | require 'spec_helper'
require 'feed2email/email'
require 'feed2email/version'
describe Feed2Email::Email do
subject(:email) do
described_class.new(
from: from,
to: to,
subject: email_subject,
html_body: html_body,
)
end
let(:from) { '[email protected]' }
let(:to) { '[email protected]' }
let(:email_subject) { 'This is a subject' }
let(:html_body) { '<p>This is the <strong>body</strong>.</p>' }
describe '#deliver!' do
it 'sends email' do
expect { subject.deliver! }.to change {
Mail::TestMailer.deliveries.size }.from(0).to(1)
end
describe 'sent email' do
subject(:delivery) { Mail::TestMailer.deliveries.first }
before do
email.deliver!
end
it 'has the right sender' do
expect(subject.from).to eq [from]
end
it 'has the right recipient' do
expect(subject.to).to eq [to]
end
it 'has the right subject' do
expect(subject.subject).to eq email_subject
end
it 'is multipart' do
expect(subject).to be_multipart
end
it 'has two parts' do
expect(subject.parts.size).to eq 2
end
describe 'HTML part body' do
subject do
delivery.parts.find {|p| p.content_type['text/html'] }.body.raw_source
end
it 'contains the passed HTML body' do
expect(subject).to match(/#{Regexp.escape(html_body)}/)
end
it 'mentions feed2email' do
expect(subject).to match(
/feed2email\s+#{Regexp.escape(Feed2Email::VERSION)}/)
end
end
describe 'text part body' do
subject do
delivery.parts.find {|p| p.content_type['text/plain'] }.body.raw_source
end
it 'contains the passed HTML body as Markdown' do
expect(subject).to match(/#{Regexp.escape('This is the **body**.')}/)
end
it 'mentions feed2email' do
expect(subject).to match(
/feed2email\s+#{Regexp.escape(Feed2Email::VERSION)}/)
end
end
end
end
end
| mit |
MsrButterfly/OpenGLLearning | OpenGLLearning/2_Hello_dot_.hpp | 2085 | #ifndef _2_HELLO_DOT__HPP_INCLUDED
#define _2_HELLO_DOT__HPP_INCLUDED
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
namespace _2_Hello_dot_ {
const char *title = "Hello dot!";
static void errorCallback(int error, const char *description) {
std::cerr << description << std::endl;
}
static void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
static int main(int argc, const char *argv[]) {
glfwSetErrorCallback(errorCallback);
if (!glfwInit()) {
std::cerr << glewGetErrorString(glGetError()) << std::endl;
return EXIT_FAILURE;
}
GLFWwindow *window = glfwCreateWindow(1024, 768, title, nullptr, nullptr);
if (!window) {
glfwTerminate();
return EXIT_FAILURE;
}
glfwSetWindowPos(window, 100, 100);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwSetKeyCallback(window, keyCallback);
if (glewInit() != GLEW_OK) {
std::cerr << glewGetErrorString(glGetError()) << std::endl;
}
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
using namespace glm;
vec3 vertex(0.0f, 0.0f, 0.0f);
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), &vertex, GL_STATIC_DRAW);
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_POINTS, 0, 1);
glDisableVertexAttribArray(0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return EXIT_SUCCESS;
}
}
#endif
| mit |
lechkulina/CosmicRiverInsanity | Include/Common/Keywords.hpp | 1211 | /*
* Keywords.hpp
*
* Created on: 29 maj 2014
* Author: Lech Kulina
* E-Mail: [email protected]
*/
#ifndef KEYWORDS_HPP_
#define KEYWORDS_HPP_
#include <boost/parameter.hpp>
namespace Cosmic {
namespace Core {
namespace Keywords {
BOOST_PARAMETER_NAME((name, Tags) name)
BOOST_PARAMETER_NAME((path, Tags) path)
BOOST_PARAMETER_NAME((signalsQueue, Tags) signalsQueue)
BOOST_PARAMETER_NAME((ignoreInvalid, Tags) ignoreInvalid)
BOOST_PARAMETER_NAME((ignoreDuplicates, Tags) ignoreDuplicates)
BOOST_PARAMETER_NAME((frequency, Tags) frequency)
BOOST_PARAMETER_NAME((format, Tags) format)
BOOST_PARAMETER_NAME((channels, Tags) channels)
BOOST_PARAMETER_NAME((chunkSize, Tags) chunkSize)
BOOST_PARAMETER_NAME((rotationSize, Tags) rotationSize)
BOOST_PARAMETER_NAME((videoContext, Tags) videoContext)
BOOST_PARAMETER_NAME((windowTitle, Tags) windowTitle)
BOOST_PARAMETER_NAME((windowGeometry, Tags) windowGeometry)
BOOST_PARAMETER_NAME((disableScreenSaver, Tags) disableScreenSaver)
BOOST_PARAMETER_NAME((hideCursor, Tags) hideCursor)
}
}
}
#endif /* KEYWORDS_HPP_ */
| mit |
hubuk/Binary | src/LeetABit.Binary/Backups/Bits/Int16ArrayBinaryReader.cs | 3679 | //-----------------------------------------------------------------------
// <copyright file="Int16ArrayBinaryReader.cs" company="Leet">
// Copyright © by Hubert Bukowski. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Leet.Binary
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// A class that represents a binary reader which underlying data is an <see cref="Int16"/> array.
/// </summary>
internal sealed class Int16ArrayBinaryReader : ArrayBinaryReader<Int16>
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Int16ArrayBinaryReader"/> class with
/// a bit array,
/// a bit offset value and
/// a bit count.
/// </summary>
/// <param name="bits">
/// An array which contains reader bits.
/// </param>
/// <param name="bitOffset">
/// An array bit index at which the reading shall begin.
/// </param>
/// <param name="bitLength">
/// Number of bits available for the reader.
/// </param>
internal Int16ArrayBinaryReader(short[] bits, long bitOffset, long bitLength)
: base(bits, bitOffset, bitLength)
{
Contract.Requires(bits != null);
Contract.Requires(bitOffset >= 0);
Contract.Requires(bitLength >= 0);
Contract.Ensures(this.Length.HasValue);
Contract.Ensures(this.Length.Value == bitLength);
Contract.Ensures(this.BitsArray == bits);
Contract.Ensures(this.BitOffset == bitOffset);
}
#endregion
#region Methods
/// <summary>
/// Reads specified numbers of bits towards the end of the bitwise readable object starting at the specified offset.
/// </summary>
/// <param name="offset">
/// Offset at which the read shall begin.
/// </param>
/// <param name="count">
/// Number of bits to read.
/// </param>
/// <param name="valueOffset">
/// Returns the offset within the result value at which the left-most bit read is located.
/// </param>
/// <param name="bitsRead">
/// Returns the number of bits read.
/// </param>
/// <returns>
/// A value that contains the bits read.
/// </returns>
public override long ReadBits(long offset, long count, out int valueOffset, out int bitsRead)
{
long totalOffset = this.BitOffset + offset;
long elementIndex = (totalOffset + BitString.Int16BitSize - 1) / BitString.Int16BitSize;
long lastBitTotalOffset = this.BitOffset + offset + count;
long lastBitElementIndex = (lastBitTotalOffset + BitString.Int16BitSize - 1) / BitString.Int16BitSize;
if (lastBitElementIndex > elementIndex)
{
valueOffset = 48 + (int)(totalOffset % BitString.Int16BitSize);
bitsRead = 64 - valueOffset;
return this.BitsArray[elementIndex];
}
else
{
valueOffset = 48 + (int)(totalOffset % BitString.Int16BitSize);
bitsRead = (int)(this.BitOffset - offset - count);
return this.BitsArray[elementIndex];
}
}
#endregion
}
}
| mit |
qianlifeng/Wox | Wox/App.xaml.cs | 7306 | using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
using CommandLine;
using NLog;
using Wox.Core;
using Wox.Core.Configuration;
using Wox.Core.Plugin;
using Wox.Core.Resource;
using Wox.Helper;
using Wox.Infrastructure;
using Wox.Infrastructure.Http;
using Wox.Image;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure.UserSettings;
using Wox.ViewModel;
using Stopwatch = Wox.Infrastructure.Stopwatch;
using Wox.Infrastructure.Exception;
using Sentry;
namespace Wox
{
public partial class App : IDisposable, ISingleInstanceApp
{
public static PublicAPIInstance API { get; private set; }
private const string Unique = "Wox_Unique_Application_Mutex";
private static bool _disposed;
private MainViewModel _mainVM;
private SettingWindowViewModel _settingsVM;
private readonly Portable _portable = new Portable();
private StringMatcher _stringMatcher;
private static string _systemLanguage;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private class Options
{
[Option('q', "query", Required = false, HelpText = "Specify text to query on startup.")]
public string QueryText { get; set; }
}
private void ParseCommandLineArgs(IList<string> args)
{
if (args == null)
return;
Parser.Default.ParseArguments<Options>(args)
.WithParsed(o =>
{
if (o.QueryText != null && _mainVM != null)
_mainVM.ChangeQueryText(o.QueryText);
});
}
[STAThread]
public static void Main()
{
_systemLanguage = CultureInfo.CurrentUICulture.Name;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
using (ErrorReporting.InitializedSentry(_systemLanguage))
{
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
using (var application = new App())
{
application.InitializeComponent();
application.Run();
}
}
}
}
private void OnStartup(object sender, StartupEventArgs e)
{
Logger.StopWatchNormal("Startup cost", () =>
{
RegisterAppDomainExceptions();
RegisterDispatcherUnhandledException();
Logger.WoxInfo("Begin Wox startup----------------------------------------------------");
Settings.Initialize();
ExceptionFormatter.Initialize(_systemLanguage, Settings.Instance.Language);
InsertWoxLanguageIntoLog();
Logger.WoxInfo(ExceptionFormatter.RuntimeInfo());
_portable.PreStartCleanUpAfterPortabilityUpdate();
ImageLoader.Initialize();
_settingsVM = new SettingWindowViewModel(_portable);
_stringMatcher = new StringMatcher();
StringMatcher.Instance = _stringMatcher;
_stringMatcher.UserSettingSearchPrecision = Settings.Instance.QuerySearchPrecision;
PluginManager.LoadPlugins(Settings.Instance.PluginSettings);
_mainVM = new MainViewModel();
var window = new MainWindow(_mainVM);
API = new PublicAPIInstance(_settingsVM, _mainVM);
PluginManager.InitializePlugins(API);
Current.MainWindow = window;
Current.MainWindow.Title = Constant.Wox;
// todo temp fix for instance code logic
// load plugin before change language, because plugin language also needs be changed
InternationalizationManager.Instance.Settings = Settings.Instance;
InternationalizationManager.Instance.ChangeLanguage(Settings.Instance.Language);
// main windows needs initialized before theme change because of blur settigns
ThemeManager.Instance.ChangeTheme(Settings.Instance.Theme);
Http.Proxy = Settings.Instance.Proxy;
RegisterExitEvents();
AutoStartup();
ParseCommandLineArgs(SingleInstance<App>.CommandLineArgs);
_mainVM.MainWindowVisibility = Settings.Instance.HideOnStartup ? Visibility.Hidden : Visibility.Visible;
Logger.WoxInfo($"SDK Info: {ExceptionFormatter.SDKInfo()}");
Logger.WoxInfo("End Wox startup ---------------------------------------------------- ");
});
}
private static void InsertWoxLanguageIntoLog()
{
Log.updateSettingsInfo(Settings.Instance.Language);
Settings.Instance.PropertyChanged += (s, ev) =>
{
if (ev.PropertyName == nameof(Settings.Instance.Language))
{
Log.updateSettingsInfo(Settings.Instance.Language);
}
};
}
private void AutoStartup()
{
if (Settings.Instance.StartWoxOnSystemStartup)
{
if (!SettingWindow.StartupSet())
{
SettingWindow.SetStartup();
}
}
}
private void RegisterExitEvents()
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => Dispose();
Current.Exit += (s, e) => Dispose();
Current.SessionEnding += (s, e) => Dispose();
}
/// <summary>
/// let exception throw as normal is better for Debug
/// </summary>
//[Conditional("RELEASE")]
private void RegisterDispatcherUnhandledException()
{
DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
}
/// <summary>
/// let exception throw as normal is better for Debug
/// </summary>
//[Conditional("RELEASE")]
private static void RegisterAppDomainExceptions()
{
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandleMain;
}
public void Dispose()
{
Logger.WoxInfo("Wox Start Displose");
// if sessionending is called, exit proverbially be called when log off / shutdown
// but if sessionending is not called, exit won't be called when log off / shutdown
if (!_disposed)
{
API?.SaveAppAllSettings();
_disposed = true;
// todo temp fix to exist application
// should notify child thread programmaly
Environment.Exit(0);
}
Logger.WoxInfo("Wox End Displose");
}
public void OnSecondAppStarted(IList<string> args)
{
ParseCommandLineArgs(args);
Current.MainWindow.Visibility = Visibility.Visible;
}
}
} | mit |
giftcards/Encryption | Tests/CipherText/Serializer/ContainerAwareChainSerializerDeserializerTest.php | 1096 | <?php
/**
* Created by PhpStorm.
* User: jderay
* Date: 8/24/15
* Time: 7:16 PM
*/
namespace Giftcards\Encryption\Tests\CipherText\Serializer;
use Giftcards\Encryption\CipherText\Serializer\ContainerAwareChainSerializerDeserializer;
use Symfony\Component\DependencyInjection\Container;
class ContainerAwareChainSerializerDeserializerTest extends ChainSerializerDeserializerTest
{
protected $container;
public function setUp() : void
{
parent::setUp();
$this->container = new Container();
$this->container->set('deserializer2', $this->deserializer2);
$this->container->set('serializer2', $this->serializer2);
$this->chain = new ContainerAwareChainSerializerDeserializer($this->container);
$this->chain
->addSerializer($this->serializer1)
->addSerializerServiceId('serializer2')
->addSerializer($this->serializer3)
->addDeserializer($this->deserializer1)
->addDeserializerServiceId('deserializer2')
->addDeserializer($this->deserializer3)
;
}
}
| mit |
plouc/nivo | packages/bar/src/ResponsiveBar.tsx | 391 | import { Bar } from './Bar'
import { BarDatum, BarSvgProps } from './types'
import { ResponsiveWrapper } from '@nivo/core'
export const ResponsiveBar = <RawDatum extends BarDatum>(
props: Omit<BarSvgProps<RawDatum>, 'height' | 'width'>
) => (
<ResponsiveWrapper>
{({ width, height }) => <Bar<RawDatum> width={width} height={height} {...props} />}
</ResponsiveWrapper>
)
| mit |
bkahlert/seqan-research | raw/pmsb13/pmsb13-data-20130530/sources/21gbd4mgnulhm130/2013-04-12T11-39-35.840+0200/sandbox/olfrik/apps/t5Graphs/t5Graphs.cpp | 4329 | // ==========================================================================
// t5Graphs
// ==========================================================================
// Copyright (c) 2006-2012, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ====
// ======================================================================
// Author: Your Name <[email protected]>
// ==========================================================================
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/arg_parse.h>
#include <iostream>
#include <seqan/graph_types.h>
#include <seqan/graph_algorithms.h>
using namespace seqan;
int digraph ()
{
typedef unsigned int TCargo;
typedef Graph<Directed<TCargo> > TGraph;
typedef VertexDescriptor<TGraph>::Type TVertexDescriptor;
TGraph g;
TVertexDescriptor vertices[] = {1,0, 0,4, 2,1, 4,1, 5,1, 6,2, 3,2, 2,3, 7,3, 5,4, 6,5, 5,6, 7,6, 7,7};
int size = (sizeof( vertices)/sizeof(TVertexDescriptor))/2;
std::cout << "sizeof " << size << std::endl;
addEdges(g, vertices, size);
FILE* strmWrite = fopen("graph.dot", "w");
write(strmWrite, g, DotDrawing());
fclose(strmWrite);
std::cout << g << ::std::endl;
return 0;
}
template <typename TAlphabet>
int hmmGraph(TAlphabet const &){
typedef unsigned int TCargo;
typedef Graph<Hmm<Dna,TCargo> > TGraph;
typedef VertexDescriptor<TGraph>::Type TVertexDescriptor;
typedef double TProb;
typedef typename Size<TAlphabet>::Type TSize;
TGraph g;
TVertexDescriptor exonState, spliceState, intronState, startState, endState;
addVertex(g, exonState);
addVertex(g, spliceState);
addVertex(g, intronState);
addVertex(g, startState);
addVertex(g, endState);
/*
A C G T
exon state 0.25 0.25 0.25 0.25
splice state 0.05 0.0 0.95 0.0
intron state 0.4 0.1 0.1 0.4
*
*
*/
TSize alphSize = ValueSize<TAlphabet>::VALUE;
TProb emmission_table[3][4] = {
{.25,.25,.25,.25},
{.05,.0,.95,.0},
{.4,.1,.1,.1}
};
std::cout << Dna << std::endl;
return 0;
//assignEmissionProbability(g, exonState, );
assignTransitionProbability(g,startState, exonState, 1.0);
assignTransitionProbability(g,exonState,exonState, 0.9);
assignTransitionProbability(g,exonState,spliceState,0.1);
assignTransitionProbability(g,spliceState, intronState, 1.0);
assignTransitionProbability(g,intronState, intronState, 0.9);
assignTransitionProbability(g,intronState, endState, 0.1);
assignBeginState(g, startState);
// assignEndState(g, intronState);
return 0;
}
int main(){
return hmmGraph(Dna());
}
| mit |
macpczone/codeigniter-datatables-example | application/views/example_form.php | 2427 | <!doctype html>
<html>
<head>
<title>harviacode.com - codeigniter crud generator</title>
<link rel="stylesheet" href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css') ?>"/>
<style>
body{
padding: 15px;
}
</style>
</head>
<body>
<h2 style="margin-top:0px">People <?php echo $button ?></h2>
<form action="<?php echo $action; ?>" method="post">
<div class="form-group">
<label for="varchar">firstname <?php echo form_error('firstname') ?></label>
<input type="text" class="form-control" name="firstname" id="firstname" placeholder="firstname" value="<?php echo $firstname; ?>" />
</div>
<div class="form-group">
<label for="varchar">lastname <?php echo form_error('lastname') ?></label>
<input type="text" class="form-control" name="lastname" id="lastname" placeholder="lastname" value="<?php echo $lastname; ?>" />
</div>
<div class="form-group">
<label for="varchar">address <?php echo form_error('address') ?></label>
<input type="text" class="form-control" name="address" id="address" placeholder="address" value="<?php echo $address; ?>" />
</div>
<div class="form-group">
<label for="varchar">area <?php echo form_error('area') ?></label>
<input type="text" class="form-control" name="area" id="area" placeholder="area" value="<?php echo $area; ?>" />
</div>
<div class="form-group">
<label for="varchar">postcode <?php echo form_error('postcode') ?></label>
<input type="text" class="form-control" name="postcode" id="postcode" placeholder="postcode" value="<?php echo $postcode; ?>" />
</div>
<div class="form-group">
<label for="tinyint">age <?php echo form_error('age') ?></label>
<input type="text" class="form-control" name="age" id="age" placeholder="age" value="<?php echo $age; ?>" />
</div>
<?php if ($id != NULL) {; ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<?php } ?>
<button type="submit" class="btn btn-primary"><?php echo $button ?></button>
<a href="<?php echo site_url('example') ?>" class="btn btn-default">Cancel</a>
</form>
</body>
</html>
| mit |
icebreaker/dotfiles | gnome/gnome2/gedit/plugins.symlink/ViGedit/bindings/yank.py | 1003 | from base import VIG_ModeBase
class Mode(VIG_ModeBase):
def setup(self, act):
self.reg(None, act.gtk.keysyms.a)
self.reg(self.nop, act.gtk.keysyms.B, after=(act.modes.block, ["yank", "numLines"]))
self.reg(self.nop, act.gtk.keysyms.t, after=(act.modes.t, ["yank", "numLines", "f"]))
self.reg(act.text.yank_Line, act.gtk.keysyms.y, pos=True, after=act.modes.command, **self.fr)
self.reg(act.text.yank_TillEndOfWord, act.gtk.keysyms.w, pos=True, after=act.modes.command, **self.fr)
self.reg(act.text.yank_NextWord, act.gtk.keysyms.w, pos=True, after=act.modes.command,
stack="a", **self.fr)
self.reg(act.text.yank_ToLineEnd, act.gtk.keysyms.dollar, pos=True, after=act.modes.command, **self.fr)
| mit |
immissile/angular.js | src/auto/injector.js | 28209 | 'use strict';
/**
* @ngdoc function
* @module ng
* @name angular.injector
* @kind function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link auto.$injector $injector}.
*
* @example
* Typical usage
* ```js
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* ```
*
* Sometimes you want to get access to the injector of a currently running Angular app
* from outside Angular. Perhaps, you want to inject and compile some markup after the
* application has been bootstrapped. You can do this using the extra `injector()` added
* to JQuery/jqLite elements. See {@link angular.element}.
*
* *This is fairly rare but could be the case if a third party library is injecting the
* markup.*
*
* In the following example a new block of HTML containing a `ng-controller`
* directive is added to the end of the document body by JQuery. We then compile and link
* it into the current AngularJS scope.
*
* ```js
* var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
* $(document.body).append($div);
*
* angular.element(document).injector().invoke(function($compile) {
* var scope = angular.element($div).scope();
* $compile($div)(scope);
* });
* ```
*/
/**
* @ngdoc module
* @name auto
* @description
*
* Implicit module which gets automatically added to each {@link auto.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function anonFn(fn) {
// For anonymous functions, showing at the very least the function signature can help in
// debugging.
var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
args = fnText.match(FN_ARGS);
if (args) {
return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
}
return 'fn';
}
function annotate(fn, strictDi, name) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi',
'{0} is not using explicit annotation and cannot be invoked in strict mode', name);
}
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc service
* @name $injector
* @kind function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link auto.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* ```js
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* ```
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* ```js
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* ```
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition
* can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
* minification, and obfuscation tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding an `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name $injector#get
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name $injector#invoke
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!Function} fn The function to invoke. Function parameters are injected according to the
* {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name $injector#has
*
* @description
* Allows the user to query if the particular service exists.
*
* @param {string} Name of the service to query.
* @returns {boolean} returns true if injector has given service.
*/
/**
* @ngdoc method
* @name $injector#instantiate
* @description
* Create a new instance of JS type. The method takes a constructor function, invokes the new
* operator, and supplies all of the arguments to the constructor function as specified by the
* constructor annotation.
*
* @param {Function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name $injector#annotate
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is
* used by the injector to determine which services need to be injected into the function when the
* function is invoked. There are three ways in which the function can be annotated with the needed
* dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done
* by converting the function into a string using `toString()` method and extracting the argument
* names.
* ```js
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* This method does not work with code minification / obfuscation. For this reason the following
* annotation strategies are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings
* represent names of services to be injected into the function.
* ```js
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController['$inject'] = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property
* is very inconvenient. In these situations using the array notation to specify the dependencies in
* a way that survives minification is a better choice:
*
* ```js
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* ```
*
* @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
* be retrieved as described above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc service
* @name $provide
*
* @description
*
* The {@link auto.$provide $provide} service has a number of methods for registering components
* with the {@link auto.$injector $injector}. Many of these functions are also exposed on
* {@link angular.Module}.
*
* An Angular **service** is a singleton object created by a **service factory**. These **service
* factories** are functions which, in turn, are created by a **service provider**.
* The **service providers** are constructor functions. When instantiated they must contain a
* property called `$get`, which holds the **service factory** function.
*
* When you request a service, the {@link auto.$injector $injector} is responsible for finding the
* correct **service provider**, instantiating it and then calling its `$get` **service factory**
* function to get the instance of the **service**.
*
* Often services have no configuration options and there is no need to add methods to the service
* provider. The provider will be no more than a constructor function with a `$get` property. For
* these cases the {@link auto.$provide $provide} service has additional helper methods to register
* services without specifying a provider.
*
* * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
* {@link auto.$injector $injector}
* * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
* providers and services.
* * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
* services, not providers.
* * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
* that will be wrapped in a **service provider** object, whose `$get` property will contain the
* given factory function.
* * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate
* a new object using the given constructor function.
*
* See the individual methods for more information and examples.
*/
/**
* @ngdoc method
* @name $provide#provider
* @description
*
* Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
* are constructor functions, whose instances are responsible for "providing" a factory for a
* service.
*
* Service provider names start with the name of the service they provide followed by `Provider`.
* For example, the {@link ng.$log $log} service has a provider called
* {@link ng.$logProvider $logProvider}.
*
* Service provider objects can have additional methods which allow configuration of the provider
* and its service. Importantly, you can configure what kind of service is created by the `$get`
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
* method {@link ng.$logProvider#debugEnabled debugEnabled}
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
* console or not.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name +
'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
* @example
*
* The following example shows how to create a simple event tracking service and register it using
* {@link auto.$provide#provider $provide.provider()}.
*
* ```js
* // Define the eventTracker provider
* function EventTrackerProvider() {
* var trackingUrl = '/track';
*
* // A provider method for configuring where the tracked events should been saved
* this.setTrackingUrl = function(url) {
* trackingUrl = url;
* };
*
* // The service factory function
* this.$get = ['$http', function($http) {
* var trackedEvents = {};
* return {
* // Call this to track an event
* event: function(event) {
* var count = trackedEvents[event] || 0;
* count += 1;
* trackedEvents[event] = count;
* return count;
* },
* // Call this to save the tracked events to the trackingUrl
* save: function() {
* $http.post(trackingUrl, trackedEvents);
* }
* };
* }];
* }
*
* describe('eventTracker', function() {
* var postSpy;
*
* beforeEach(module(function($provide) {
* // Register the eventTracker provider
* $provide.provider('eventTracker', EventTrackerProvider);
* }));
*
* beforeEach(module(function(eventTrackerProvider) {
* // Configure eventTracker provider
* eventTrackerProvider.setTrackingUrl('/custom-track');
* }));
*
* it('tracks events', inject(function(eventTracker) {
* expect(eventTracker.event('login')).toEqual(1);
* expect(eventTracker.event('login')).toEqual(2);
* }));
*
* it('saves to the tracking url', inject(function(eventTracker, $http) {
* postSpy = spyOn($http, 'post');
* eventTracker.event('login');
* eventTracker.save();
* expect(postSpy).toHaveBeenCalled();
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
* }));
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#factory
* @description
*
* Register a **service factory**, which will be called to return the service instance.
* This is short for registering a service where its provider consists of only a `$get` property,
* which is the given service factory function.
* You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
* configure your service in a provider.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
* for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service
* ```js
* $provide.factory('ping', ['$http', function($http) {
* return function ping() {
* return $http.send('/ping');
* };
* }]);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#service
* @description
*
* Register a **service constructor**, which will be invoked with `new` to create the service
* instance.
* This is short for registering a service where its provider's `$get` property is the service
* constructor function that will be used to instantiate the service instance.
*
* You should use {@link auto.$provide#service $provide.service(class)} if you define your service
* as a type/class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service using
* {@link auto.$provide#service $provide.service(class)}.
* ```js
* var Ping = function($http) {
* this.$http = $http;
* };
*
* Ping.$inject = ['$http'];
*
* Ping.prototype.send = function() {
* return this.$http.get('/ping');
* };
* $provide.service('ping', Ping);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping.send();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#value
* @description
*
* Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
* number, an array, an object or a function. This is short for registering a service where its
* provider's `$get` property is a factory function that takes no arguments and returns the **value
* service**.
*
* Value services are similar to constant services, except that they cannot be injected into a
* module configuration function (see {@link angular.Module#config}) but they can be overridden by
* an Angular
* {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*
* @example
* Here are some examples of creating value services.
* ```js
* $provide.value('ADMIN_USER', 'admin');
*
* $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
*
* $provide.value('halfOf', function(value) {
* return value / 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#constant
* @description
*
* Register a **constant service**, such as a string, a number, an array, an object or a function,
* with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot
* be overridden by an Angular {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*
* @example
* Here a some examples of creating constants:
* ```js
* $provide.constant('SHARD_HEIGHT', 306);
*
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
*
* $provide.constant('double', function(value) {
* return value * 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#decorator
* @description
*
* Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
* intercepts the creation of a service, allowing it to override or modify the behaviour of the
* service. The object returned by the decorator may be the original service, or a new service
* object which replaces or wraps and delegates to the original service.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance. The function is called using
* the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
* Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*
* @example
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
* calls to {@link ng.$log#error $log.warn()}.
* ```js
* $provide.decorator('$log', ['$delegate', function($delegate) {
* $delegate.warn = $delegate.error;
* return $delegate;
* }]);
* ```
*/
function createInjector(modulesToLoad, strictDi) {
strictDi = (strictDi === true);
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap([], true),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function() {
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
}, strictDi)),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider, undefined, servicename);
}, strictDi));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
};
}
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, val) { return factory(name, valueFn(val)); }
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [], moduleFn, invokeQueue;
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
function runInvokeQueue(queue) {
var i, ii;
for(i = 0, ii = queue.length; i < ii; i++) {
var invokeArgs = queue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
}
try {
if (isString(module)) {
moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
runInvokeQueue(moduleFn._invokeQueue);
runInvokeQueue(moduleFn._configBlocks);
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
// Safari & FF's stack traces don't contain error.message content
// unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
/* jshint -W022 */
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals, serviceName){
if (typeof locals === 'string') {
serviceName = locals;
locals = null;
}
var args = [],
$inject = annotate(fn, strictDi, serviceName),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn',
'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// http://jsperf.com/angularjs-invoke-apply-vs-switch
// #5388
return fn.apply(self, args);
}
function instantiate(Type, locals, serviceName) {
var Constructor = function() {},
instance, returnedValue;
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals, serviceName);
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
createInjector.$$annotate = annotate;
| mit |
goodzsq/xyj | src/shared/utils/behavior/decorator/Inverter.ts | 536 | import {Decorator, Tick, State} from '../BaseNode'
export class Inverter extends Decorator {
tick(tick: Tick) {
if (!this.child) return State.FAILURE
var status = this.child.execute(tick)
if (status === State.SUCCESS) {
return State.FAILURE
} else if (status === State.FAILURE) {
return State.SUCCESS
}
return status
}
serialize(): IDataBehaviorNode {
var data = super.serialize()
data.nodeType = 'Inverter'
return data
}
} | mit |
cpsoinos/fb_error_machine | spec/fb_error_machine_spec.rb | 225 | require "spec_helper"
describe FbErrorMachine do
# it "has a version number" do
# expect(FbErrorMachine::VERSION).not_to be nil
# end
#
# it "does something useful" do
# expect(false).to eq(true)
# end
end
| mit |
webbestmaster/ae3 | www/js/component/game/model/bot.js | 14134 | // @flow
import type {MapType, MapUserType, UnitType} from '../../../maps/type';
import type {GameDataType, UnitActionMoveType, UnitActionsMapType, UnitActionType} from './unit/unit';
import {Unit} from './unit/unit';
import {rateBotResultActionData} from './bot-helper';
import {Building} from './building/building';
import {isCommanderLive} from './helper';
import * as serverApi from '../../../module/server-api';
import {messageConst} from '../../../lib/local-server/room/message-const';
import type {UnitTypeCommanderType, UnitTypeCommonType} from './unit/unit-guide';
import {unitGuideData} from './unit/unit-guide';
function getUnitListByPlayerId(gameData: GameDataType, activeUserId: string): Array<Unit> {
return gameData.unitList.filter((unit: Unit): boolean => unit.getUserId() === activeUserId);
}
function getEnemyUnitListForPlayerId(gameData: GameDataType, activeUserId: string): Array<Unit> {
const playerData =
gameData.userList.find((userData: MapUserType): boolean => userData.userId === activeUserId) || null;
if (playerData === null) {
console.error('can not find user by id', activeUserId);
return [];
}
const {teamId} = playerData;
const enemyPlayerDataList = gameData.userList.filter(
(userData: MapUserType): boolean => userData.teamId !== teamId
);
const enemyPlayerIdList = enemyPlayerDataList.map((userData: MapUserType): string => userData.userId);
return gameData.unitList.filter((unit: Unit): boolean => enemyPlayerIdList.includes(unit.getUserId()));
}
function getActionByName(actionMap: UnitActionsMapType, actionType: string | null): Array<UnitActionType> {
const moveActionList = [];
actionMap.forEach((actionListList: Array<Array<UnitActionType>>) => {
actionListList.forEach((actionList: Array<UnitActionType>) => {
actionList.forEach((action: UnitActionType) => {
if (actionType === null || actionType === action.type) {
moveActionList.push(action);
}
});
});
});
return moveActionList;
}
function getMoveActionList(actionMap: UnitActionsMapType): Array<UnitActionMoveType> {
const moveActionList = [];
actionMap.forEach((actionListList: Array<Array<UnitActionType>>) => {
actionListList.forEach((actionList: Array<UnitActionType>) => {
actionList.forEach((action: UnitActionType) => {
if (action.type !== 'move') {
return;
}
moveActionList.push(action);
});
});
});
return moveActionList;
}
function getActionMapAfterMove(
unit: Unit,
actionMove: UnitActionMoveType,
gameData: GameDataType
): UnitActionsMapType | null {
const beforeUnitAttr = unit.getAttr();
const moveUnitAttr = unit.getAttr();
moveUnitAttr.x = actionMove.to.x;
moveUnitAttr.y = actionMove.to.y;
unit.setAttr(moveUnitAttr);
unit.setDidMove(true);
const actionMap = unit.getActions(gameData);
unit.setAttr(beforeUnitAttr);
return actionMap;
}
type UnitAvailableActionsMapType = {|
+moveAction: {|
+action: UnitActionMoveType | null,
+actionsMap: UnitActionsMapType | null,
|},
+actionsMap: UnitActionsMapType | null,
|};
function getUnitAvailableActionsMapList(unit: Unit, gameData: GameDataType): Array<UnitAvailableActionsMapType> | null {
const actionsMap = unit.getActions(gameData);
if (actionsMap === null) {
return null;
}
const actionMapList = [
{
moveAction: {
action: null,
actionsMap: null,
},
actionsMap,
},
];
getMoveActionList(actionsMap).forEach((actionMove: UnitActionMoveType) => {
actionMapList.push({
moveAction: {
action: actionMove,
actionsMap,
},
actionsMap: null,
});
const actionMapAfterMove = getActionMapAfterMove(unit, actionMove, gameData);
if (actionMapAfterMove === null) {
return;
}
actionMapList.push({
moveAction: {
action: actionMove,
actionsMap,
},
actionsMap: actionMapAfterMove,
});
});
return actionMapList;
}
// eslint-disable-next-line id-length
function getEnemyUnitAvailableActionsMapList(
unit: Unit,
gameData: GameDataType
): Array<UnitAvailableActionsMapType> | null {
return getUnitAvailableActionsMapList(unit, {...gameData, unitList: [unit]});
}
export type BotResultActionDataType = {|
+unit: Unit,
+moveAction: {|
+action: UnitActionMoveType | null,
+actionsMap: UnitActionsMapType | null,
|},
+unitAction: UnitActionType | null,
+armorMap: {|
+walk: Array<Array<number>>,
+flow: Array<Array<number>>,
+fly: Array<Array<number>>,
|},
|};
type UnitAllAvailableActionsMapType = {|
+unit: Unit,
+availableActionsMapList: Array<UnitAvailableActionsMapType> | null,
|};
export type EnemyUnitAllAvailableActionsMapType = {|
+unit: Unit,
+availableActionsMapList: Array<UnitAvailableActionsMapType> | null,
+damageMap: Array<Array<number | null>>,
|};
function getBotActionDataList(
unitAllActionsMapList: Array<UnitAllAvailableActionsMapType>,
enemyUnitAllActionsMapList: Array<EnemyUnitAllAvailableActionsMapType>,
gameData: GameDataType
): Array<BotResultActionDataType> {
const botResultActionDataList = [];
const {armorMap} = gameData;
unitAllActionsMapList.forEach((unitAllActionsMap: UnitAllAvailableActionsMapType) => {
const {unit, availableActionsMapList} = unitAllActionsMap;
if (availableActionsMapList === null) {
return;
}
availableActionsMapList.forEach((unitActionsMap: UnitAvailableActionsMapType) => {
const {actionsMap, moveAction} = unitActionsMap;
botResultActionDataList.push({unit, moveAction, unitAction: null, armorMap});
if (actionsMap === null) {
return;
}
getActionByName(actionsMap, null).forEach((unitAction: UnitActionType) => {
// no need to open store
if (unitAction.type === 'open-store') {
return;
}
// no need to move, moveAction exists in botActionData yet
if (unitAction.type === 'move') {
return;
}
botResultActionDataList.push({unit, moveAction, unitAction, armorMap});
});
});
});
return botResultActionDataList.sort(
(botResultA: BotResultActionDataType, botResultB: BotResultActionDataType): number => {
return (
rateBotResultActionData(botResultB, enemyUnitAllActionsMapList, gameData) -
rateBotResultActionData(botResultA, enemyUnitAllActionsMapList, gameData)
);
}
);
}
// TODO: get enemy unit available path (remove self unit from map for this)
// TODO: and make available path map and available attack map
export function getBotTurnDataList(map: MapType, gameData: GameDataType): Array<BotResultActionDataType> | null {
console.log('getBotTurnData map', map);
const enemyUnitList = getEnemyUnitListForPlayerId(gameData, map.activeUserId);
console.log('getBotTurnData enemyUnitList', enemyUnitList);
const enemyUnitAllActionsMapList = enemyUnitList.map(
(unit: Unit): EnemyUnitAllAvailableActionsMapType => {
const availableActionsMapList = getEnemyUnitAvailableActionsMapList(unit, gameData);
const damageMap = unit.getAvailableDamageMap({...gameData, unitList: [unit]});
return {unit, availableActionsMapList, damageMap};
}
);
console.log('getBotTurnData enemyUnitAllActionsMapList', enemyUnitAllActionsMapList);
const unitList = getUnitListByPlayerId(gameData, map.activeUserId);
console.log('getBotTurnData unitList', unitList);
const unitAllActionsMapList = unitList.map(
(unit: Unit): UnitAllAvailableActionsMapType => ({
unit,
availableActionsMapList: getUnitAvailableActionsMapList(unit, gameData),
})
);
console.log('getBotTurnData unitAllActionsMapList', unitAllActionsMapList);
const bestBotActionDataList = getBotActionDataList(unitAllActionsMapList, enemyUnitAllActionsMapList, gameData);
if (bestBotActionDataList.length > 0) {
return bestBotActionDataList;
}
return null;
}
function getStoreList(activeUserId: string, gameData: GameDataType): Array<Building> | null {
const castleList = gameData.buildingList.filter(
(buildingInList: Building): boolean => {
const buildingInListAttr = buildingInList.attr;
if (buildingInListAttr.type !== 'castle') {
return false;
}
if (buildingInListAttr.userId !== activeUserId) {
return false;
}
const unitOnStore =
gameData.unitList.find(
(unitInList: Unit): boolean => {
return unitInList.attr.x === buildingInListAttr.x && unitInList.attr.y === buildingInListAttr.y;
}
) || null;
// if on store stay NO unit - buy unit
return unitOnStore === null;
}
);
return castleList.length === 0 ? null : castleList;
}
function getStoreToBuyUnit(activeUserId: string, gameData: GameDataType): Building | null {
const storeList = getStoreList(activeUserId, gameData);
if (storeList === null) {
return null;
}
return storeList.sort((): number => Math.random() - 0.5)[0];
}
// eslint-disable-next-line complexity
function getUnitTypeToBuy(
activeUserId: string,
gameData: GameDataType,
mapState: MapType
): UnitTypeCommonType | UnitTypeCommanderType | null {
const playerData =
gameData.userList.find((userInList: MapUserType): boolean => userInList.userId === activeUserId) || null;
if (playerData === null) {
console.error('getUnitTypeToBuy - can not find user with id:', activeUserId, gameData);
return null;
}
const hasCommander = isCommanderLive(playerData.userId, mapState);
if (hasCommander === false) {
// return playerData.commander ? playerData.commander.type : 'galamar';
return playerData.commander.type;
}
const soldierList = gameData.unitList.filter(
(unitInList: Unit): boolean => {
const {userId, type} = unitInList.attr;
return type === 'soldier' && userId === activeUserId;
}
);
if (soldierList.length < 2) {
return 'soldier';
}
const archerList = gameData.unitList.filter(
(unitInList: Unit): boolean => {
const {userId, type} = unitInList.attr;
return type === 'archer' && userId === activeUserId;
}
);
if (archerList.length < 2) {
return 'archer';
}
return ['sorceress', 'golem', 'catapult', 'dire-wolf', 'wisp'].sort((): number => Math.random() - 0.5)[0];
}
export function canPlayerBuyUnit(activeUserId: string, gameData: GameDataType): boolean {
// get players castle list
// get castle list to open
// check unit limit
const playerData =
gameData.userList.find((userInList: MapUserType): boolean => userInList.userId === activeUserId) || null;
if (playerData === null) {
console.error('canPlayerBuyUnit - can not find user with id:', activeUserId, gameData);
return false;
}
if (getStoreList(activeUserId, gameData) === null) {
return false;
}
const playerUnitList = gameData.unitList.filter(
(unitInList: Unit): boolean => unitInList.attr.userId === activeUserId
);
return playerUnitList.length < gameData.unitLimit;
}
// eslint-disable-next-line complexity
export async function botBuyUnit(
activeUserId: string,
gameData: GameDataType,
mapState: MapType,
roomId: string
): Promise<UnitType | Error | null> {
const newMapState: MapType = JSON.parse(JSON.stringify(mapState));
const playerData =
newMapState.userList.find((userInList: MapUserType): boolean => userInList.userId === activeUserId) || null;
if (playerData === null) {
console.error('botBuyUnit - can not find user with id:', activeUserId, gameData);
return null;
}
const storeToBuyUnit = getStoreToBuyUnit(activeUserId, gameData);
if (storeToBuyUnit === null) {
return null;
}
const newUnitX = storeToBuyUnit.attr.x;
const newUnitY = storeToBuyUnit.attr.y;
const newUnitType = getUnitTypeToBuy(activeUserId, gameData, newMapState);
if (newUnitType === null) {
return null;
}
const unitData = unitGuideData[newUnitType];
if (playerData.money < unitData.cost) {
return null;
}
playerData.money -= unitData.cost;
const newMapUnitData: UnitType = {
type: newUnitType,
x: newUnitX,
y: newUnitY,
userId: activeUserId,
id: [newUnitX, newUnitY, Math.random()].join('-'),
};
newMapState.units.push(newMapUnitData);
return serverApi
.pushState(roomId, activeUserId, {
type: messageConst.type.pushState,
state: {
type: 'buy-unit',
newMapUnit: newMapUnitData,
map: newMapState,
activeUserId,
},
})
.then(
(response: mixed): UnitType => {
console.log('---> user action buy unit', response);
return newMapUnitData;
}
)
.catch(
(error: Error): Error => {
console.error('store-push-state error');
console.log(error);
return error;
}
);
}
| mit |
andela-iokonkwo/zucy | spec/spec_helper.rb | 298 | require "simplecov"
SimpleCov.start
require "codeclimate-test-reporter"
require "test_reporter_helper"
CodeClimate::TestReporter.start
require "rspec"
require "rack/test"
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "todolist/config/application.rb"
ENV["RACK_ENV"] = "test"
| mit |
vileopratama/vitech | new-addons/reporting-engine-10.0/report_custom_filename/__manifest__.py | 1567 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Custom report filenames",
"summary": "Configure the filename to use when downloading a report",
"version": "8.0.1.0.0",
"author": "Therp BV,Odoo Community Association (OCA)",
"license": "AGPL-3",
"complexity": "normal",
"category": "Reporting",
"depends": [
'web',
'email_template',
],
"data": [
"view/ir_actions_report_xml.xml",
],
"test": [
],
"auto_install": False,
'installable': False,
"application": False,
"external_dependencies": {
'python': ['jinja2'],
},
}
| mit |
paulohp/ango | slushfile.js | 2632 | /*
* slush-go
* https://github.com/paulohp/slush-go
*
* Copyright (c) 2014, Paulo Pires
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = require('gulp-rename'),
_ = require('underscore.string'),
inquirer = require('inquirer');
function format(string) {
var username = string.toLowerCase();
return username.replace(/\s/g, '');
}
var defaults = (function () {
var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
workingDirName = process.cwd().split('/').pop().split('\\').pop(),
osUserName = homeDir && homeDir.split('/').pop() || 'root',
configFile = homeDir + '/.gitconfig',
user = {};
if (require('fs').existsSync(configFile)) {
user = require('iniparser').parseSync(configFile).user;
}
return {
appName: workingDirName,
userName: format(user.name) || osUserName,
authorEmail: user.email || ''
};
})();
gulp.task('default', function (done) {
var prompts = [{
name: 'appName',
message: 'What is the name of your project?',
default: defaults.appName
}, {
name: 'appDescription',
message: 'What is the description?'
}, {
name: 'appVersion',
message: 'What is the version of your project?',
default: '0.1.0'
}, {
name: 'authorName',
message: 'What is the author name?',
}, {
name: 'authorEmail',
message: 'What is the author email?',
default: defaults.authorEmail
}, {
name: 'userName',
message: 'What is the github username?',
default: defaults.userName
}, {
type: 'confirm',
name: 'moveon',
message: 'Continue?'
}];
//Ask
inquirer.prompt(prompts,
function (answers) {
if (!answers.moveon) {
return done();
}
answers.appNameSlug = _.slugify(answers.appName);
gulp.src(__dirname + '/templates/**')
.pipe(template(answers))
.pipe(rename(function (file) {
if (file.basename[0] === '_') {
file.basename = '.' + file.basename.slice(1);
}
}))
.pipe(conflict('./'))
.pipe(gulp.dest('./'))
.pipe(install())
.on('end', function () {
done();
});
});
});
| mit |
xdimedrolx/omnipay-yandex-kassa-mws | src/Message/RepeatCardPaymentRequest.php | 1453 | <?php
namespace Omnipay\YandexKassaMws\Message;
class RepeatCardPaymentRequest extends AbstractRequest
{
public function getClientOrderId()
{
return $this->getParameter('clientOrderId');
}
public function setClientOrderId($clientOrderId)
{
return $this->setParameter('clientOrderId', $clientOrderId);
}
public function getInvoiceId()
{
return $this->getParameter('invoiceId');
}
public function setInvoiceId($invoiceId)
{
return $this->setParameter('invoiceId', $invoiceId);
}
public function getOrderNumber()
{
return $this->getParameter('orderNumber');
}
public function setOrderNumber($orderNumber)
{
return $this->setParameter('orderNumber', $orderNumber);
}
public function getCVV()
{
return $this->getParameter('cvv');
}
public function setCVV($cvv)
{
return $this->setParameter('cvv', $cvv);
}
public function getData()
{
$this->validate('clientOrderId', 'invoiceId', 'amount', 'orderNumber');
$data = array();
$data['amount'] = $this->getAmount();
$data['clientOrderId'] = $this->getClientOrderId();
$data['invoiceId'] = $this->getInvoiceId();
$data['orderNumber'] = $this->getOrderNumber();
if (!empty($this->getCVV())) {
$data['cvv'] = $this->getCVV();
}
return $data;
}
public function sendData($data)
{
$httpResponse = $this->sendRequest('repeatCardPayment', $data);
return $this->response = new RepeatCardPaymentResponse($this, $httpResponse->xml());
}
} | mit |
nwoeanhinnogaehr/flow-synth | src/gui/geom.rs | 4926 | use std::ops::{Add, Div, Mul, Neg, Sub};
#[derive(Copy, Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct Pt2 {
pub x: f32,
pub y: f32,
}
impl Pt2 {
pub fn new(x: f32, y: f32) -> Pt2 {
Pt2 {
x,
y,
}
}
pub fn zero() -> Pt2 {
0.0.into()
}
pub fn with_z(self, z: f32) -> Pt3 {
Pt3::new(self.x, self.y, z)
}
}
impl From<Pt2> for [f32; 2] {
fn from(val: Pt2) -> [f32; 2] {
[val.x, val.y]
}
}
impl From<f32> for Pt2 {
fn from(val: f32) -> Pt2 {
Pt2::new(val, val)
}
}
macro_rules! impl_binop_pt2 {
($op:ident, $fn:ident) => {
impl $op for Pt2 {
type Output = Pt2;
#[inline(always)]
fn $fn(self, other: Pt2) -> Pt2 {
Pt2::new(self.x.$fn(other.x), self.y.$fn(other.y))
}
}
impl $op<f32> for Pt2 {
type Output = Pt2;
#[inline(always)]
fn $fn(self, other: f32) -> Pt2 {
Pt2::new(self.x.$fn(other), self.y.$fn(other))
}
}
};
}
macro_rules! impl_uniop_pt2 {
($op:ty, $fn:ident) => {
impl $op for Pt2 {
type Output = Pt2;
#[inline(always)]
fn $fn(self) -> Pt2 {
Pt2::new((self.x).$fn(), (self.y).$fn())
}
}
};
}
impl_binop_pt2!(Add, add);
impl_binop_pt2!(Sub, sub);
impl_binop_pt2!(Mul, mul);
impl_binop_pt2!(Div, div);
impl_uniop_pt2!(Neg, neg);
#[derive(Copy, Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct Pt3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl Pt3 {
pub fn new(x: f32, y: f32, z: f32) -> Pt3 {
Pt3 {
x,
y,
z,
}
}
pub fn zero() -> Pt3 {
0.0.into()
}
pub fn drop_z(self) -> Pt2 {
Pt2::new(self.x, self.y)
}
pub fn with_z(self, z: f32) -> Pt3 {
Pt3::new(self.x, self.y, z)
}
}
impl From<Pt3> for [f32; 3] {
fn from(val: Pt3) -> [f32; 3] {
[val.x, val.y, val.z]
}
}
impl From<f32> for Pt3 {
fn from(val: f32) -> Pt3 {
Pt3::new(val, val, val)
}
}
macro_rules! impl_binop_pt3 {
($op:ident, $fn:ident) => {
impl $op for Pt3 {
type Output = Pt3;
#[inline(always)]
fn $fn(self, other: Pt3) -> Pt3 {
Pt3::new(
self.x.$fn(other.x),
self.y.$fn(other.y),
self.z.$fn(other.z),
)
}
}
impl $op<f32> for Pt3 {
type Output = Pt3;
#[inline(always)]
fn $fn(self, other: f32) -> Pt3 {
Pt3::new(self.x.$fn(other), self.y.$fn(other), self.z.$fn(other))
}
}
};
}
macro_rules! impl_uniop_pt3 {
($op:ty, $fn:ident) => {
impl $op for Pt3 {
type Output = Pt3;
#[inline(always)]
fn $fn(self) -> Pt3 {
Pt3::new((self.x).$fn(), (self.y).$fn(), (self.z).$fn())
}
}
};
}
impl_binop_pt3!(Add, add);
impl_binop_pt3!(Sub, sub);
impl_binop_pt3!(Mul, mul);
impl_binop_pt3!(Div, div);
impl_uniop_pt3!(Neg, neg);
#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize)]
pub struct Rect2 {
pub pos: Pt2,
pub size: Pt2,
}
impl Rect2 {
pub fn new(pos: Pt2, size: Pt2) -> Rect2 {
Rect2 {
pos,
size,
}
}
pub fn with_z(self, z: f32) -> Rect3 {
Rect3 {
pos: Pt3::new(self.pos.x, self.pos.y, z),
size: self.size,
}
}
/// upgrade to rect3 with z from other
pub fn with_z_from(self, other: &Rect3) -> Rect3 {
Rect3 {
pos: Pt3::new(self.pos.x, self.pos.y, other.pos.z),
size: self.size,
}
}
pub fn intersect(&self, pt: Pt2) -> bool {
pt.x > self.pos.x
&& pt.x < self.pos.x + self.size.x
&& pt.y > self.pos.y
&& pt.y < self.pos.y + self.size.y
}
pub fn offset(self, other: Rect2) -> Rect2 {
Rect2::new(self.pos + other.pos, self.size)
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Rect3 {
pub pos: Pt3,
pub size: Pt2,
}
impl Rect3 {
pub fn new(pos: Pt3, size: Pt2) -> Rect3 {
Rect3 {
pos,
size,
}
}
pub fn drop_z(self) -> Rect2 {
Rect2::new(self.pos.drop_z(), self.size)
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Box3 {
pub pos: Pt3,
pub size: Pt3,
}
impl Box3 {
pub fn new(pos: Pt3, size: Pt3) -> Box3 {
Box3 {
pos,
size,
}
}
pub fn flatten(self) -> Rect3 {
Rect3::new(self.pos, self.size.drop_z())
}
}
| mit |
marcosriso/QuickPHP | App/Views/Crud/listing.blade.php | 8946 | @extends('Layout.admin_layout')
@section('content')
<div class="listing_wrapper" ng-controller="getList" ng-init="init('/{{ $table }}',0)">
<div class="row">
<div class="col-lg-12">
@if(isset($tbldetails->display_name))
<h2>{{ $tbldetails->display_name }}</h2>
<a class="btn btn-success" href="/insert/{{ $table }}"><i class="fa fa-plus"></i> Add {{ $tbldetails->display_name }}</a>
@else
<p><i class="glyphicon glyphicon-remove-circle"></i> There is an error in your table configuration. Please check the table comment JSON</p>
@endif
<div class="sm-marg"></div>
<div id="scrolltop"></div>
@if(isset($tbldetails->filter))
<div class="filter">
<div class="row">
<div class="col-xs-12">
<h4>Filtro</h4>
<form class="form-inline" action="/admsearch" method="post">
@foreach($tableObj['fields'] as $field)
@if(in_array($field->Field, $tbldetails->filter))
<?php
$info = \Library\Utils\DataUtilities::deSerializeJson($field->Comment);
$info->isfilter = true;
$info->readonly = false;
$info->required = false;
if(isset($info->link_fk)){
$link = \Library\DAO\Tables::getLinkObjects($info->link_fk);
$link->details = \Library\DAO\Tables::getTableDetails($tableObj, $info->link_fk);
}
?>
<div class="form-group">
@include('Components.'.$info->DOM)
</div>
@endif
@endforeach
<input type="hidden" id="table" name="table" value="{{ $table }}">
<button type="submit" class="btn btn-default">Filter</button>
</form>
</div>
</div>
</div>
<div class="margin-bottom"></div><br>
@endif
<div class="table-responsive">
<table class="table table-bordered table-striped table-condensed" ng-cloak>
<tr>
<th class="text-center">Options</th>
<th ng-repeat="h in obj.headers" >@{{ h }}</th>
</tr>
<tr ng-show="obj.collection | isEmpty" ><td colspan="@{{ obj.colspan }}">There is no records.</td></tr>
<tr ng-repeat="item in obj.collection" >
<td class="min-width">
<p>
<a class="btn-sm btn-primary" ng-href="/editing/{{ $table }}/@{{ item.id }}"><i class="glyphicon glyphicon-edit"></i></a>
<a class="btn-sm btn-danger pointer" ng-href="" ng-click="showModal(item.id)"><i class="glyphicon glyphicon-remove"></i></a>
</td>
<td class="max-width" ng-repeat="(key, col) in item" ng-if="obj.fieldsObj[key]" ng-switch="getTypeOf(col)">
<span ng-switch-when="string">
<span ng-if="obj.fieldsObj[key].DOM == 'upload'"><img ng-src="/@{{ col }}" class="little-thumb" /></span>
<span ng-if="obj.fieldsObj[key].DOM != 'upload' && key != 'totalvalue'" ng-bind-html="trustme(col)">@{{ col }}</span>
<span ng-if="key == 'totalvalue'">@{{ col | currency }}</span>
</span>
<span ng-if="obj.fieldsObj[key].DOM == 'checkbox' && col ==1">Yes</span>
<span ng-if="obj.fieldsObj[key].DOM == 'checkbox' && col ==0">No</span>
<span ng-switch-when="number" ng-if="obj.fieldsObj[key].DOM != 'checkbox'">@{{ col }}</span>
<span ng-switch-when="object">
<span ng-repeat="coln in col">@{{ coln.id }} - @{{ coln.display_field }}<br/></span>
</span>
<span ng-switch-default>@{{ col }}</span>
</td>
</tr>
</table>
<div>
<!-- Pagination -->
<nav ng-show="obj.links.total > obj.links.per_page" ng-cloak>
<ul class="pagination">
<li>
<a href="" ng-click="init(obj.links.prev_page_url)" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li ng-repeat="a in range(obj.links.last_page) track by $index"><a href="" ng-click="init('/{{ $table }}?page='+($index+1), 0)">@{{ $index + 1 }}</a></li>
<li>
<a href="" ng-click="init(obj.links.next_page_url)" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div class="sm-marg"></div>
<div class="alert alert-danger alert-dismissible hidden" id="alertd" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Error!</strong> Unknow error.
</div>
<div class="alert alert-success alert-dismissible hidden" id="alerts" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Success!</strong> Record deleted.
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this record ?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="exclui-btn" ng-click="deleteobj('{{ $table }}')" class="btn btn-primary">Delete</button>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('js')
<script src="/public/bower_components/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
$(function(){
$('.select2').select2({ });
$( ".datepicker" ).datepicker({
dateFormat: "dd/mm/yy",
dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
nextText: 'Próximo',
prevText: 'Anterior',
changeMonth: true,
changeYear: true,
yearRange: "-110:+15",
//minDate: '0'
});
tinymce.init({
selector: '.text_advanced',
plugins: "code"
});
});
</script>
@endsection | mit |
RufusMbugua/nqcl | application/core/MY_Controller.php | 304 | <?php
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
require_once('REST_Controller.php');
// error_reporting(1);
class MY_Controller extends REST_Controller{
var $fractal;
public function __construct()
{
$this->fractal = new Manager();
parent::__construct();
}
}
| mit |
txstate-etc/attendance | test/unit/grade_settings_test.rb | 127 | require 'test_helper'
class GradeSettingsTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| mit |
mirkhamidov/yii2-mail | migrations/m161113_061932_create_mail_table.php | 1100 | <?php
use yii\db\Migration;
/**
* Handles the creation of table `mail`.
*/
class m161113_061932_create_mail_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('mail', [
'id' => $this->primaryKey(),
'alias' => $this->string()->unique()->comment('Mail Template Alias'),
'is_active' => $this->boolean()->defaultValue(true)->comment('Is this item active?'),
'name' => $this->string()->notNull()->comment('Arbitrary name'),
'subject' => $this->string()->notNull()->comment('E-mail subject'),
'content_text' => $this->string()->notNull()->comment('Alias for text message representation'),
'content_html' => $this->string()->notNull()->comment('Alias for html message representation'),
'created_at' => $this->timestamp()->defaultValue(null),
'updated_at' => $this->timestamp()->defaultValue(null),
]);
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('mail');
}
}
| mit |
dyoub/app | src/Dyoub.Test/Contexts/Inventory/PurchaseOrders/DeletePurchaseOrderContext.cs | 1148 | // Copyright (c) Dyoub Applications. All rights reserved.
// Licensed under MIT (https://github.com/dyoub/app/blob/master/LICENSE).
using Dyoub.App.Models.EntityModel;
using Dyoub.App.Models.EntityModel.Account.Tenants;
using Dyoub.App.Models.EntityModel.Inventory.PurchaseOrders;
using Dyoub.App.Models.EntityModel.Manage.Stores;
using Dyoub.Test.Factories.Account;
using Dyoub.Test.Factories.Inventory;
using Dyoub.Test.Factories.Manage;
using Effort;
using System.Linq;
namespace Dyoub.Test.Contexts.Inventory.PurchaseOrders
{
public class DeletePurchaseOrderContext : TenantContext
{
public PurchaseOrder PurchaseOrder { get; private set; }
public DeletePurchaseOrderContext() : base(1, DbConnectionFactory.CreateTransient())
{
Tenant tenant = Tenants.Add(TenantFactory.Tenant());
Store store = Stores.Add(StoreFactory.Store(tenant));
PurchaseOrder = PurchaseOrders.Add(PurchaseOrderFactory.PurchaseOrder(store));
SaveChanges();
}
public bool PurchaseOrderWasDeleted()
{
return !PurchaseOrders.Any();
}
}
}
| mit |
cogliaWho/romec | application/controllers/Slideshows.php | 4644 | <?php
class Slideshows extends MY_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('slideshows_model');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function index()
{
if ( ! file_exists(APPPATH.'/views/pagesMember/slideshows.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = 'Upload Slide:'; // Capitalize the first letter
$data['error'] = '';
$data['hasSlide'] = FALSE;
$this->load->view('templates/header', $data);
$this->load->view('pagesMember/slideshows', $data);
$this->load->view('templates/footer', $data);
}
public function remove($slideID)
{
$this->slideshows_model->remove_slide($slideID);
$data['title'] = 'Upload Slide:'; // Capitalize the first letter
$data['error'] = '';
$data['slideshows'] = $this->slideshows_model->get_slideshows();
$data['slides'] = $this->slideshows_model->get_slides();
$this->load->view('templates/header', $data);
$this->load->view('pagesMember/slideupload', $data);
$this->load->view('templates/footer', $data);
}
public function create()
{
$this->form_validation->set_rules('slideshow', 'Slideshow Name', 'trim|required');
if ($this->form_validation->run() !== FALSE)
{
$ss_exist = $this->slideshows_model->slideshow_exists($this->input->post('slideshow'));
if(!$ss_exist){
$this->slideshows_model->set_slideshow();
}
}
$data['title'] = 'Upload Slide:'; // Capitalize the first letter
$data['error'] = '';
$data['slideshows'] = $this->slideshows_model->get_slideshows();
$data['slides'] = $this->slideshows_model->get_slides();
$this->load->view('templates/header', $data);
$this->load->view('pagesMember/slideupload', $data);
$this->load->view('templates/footer', $data);
}
public function upload()
{
$this->form_validation->set_rules('slideshow', 'Slideshow Name', 'trim|required');
$this->form_validation->set_rules('position', 'Position', 'trim|required');
$this->form_validation->set_rules('visible', 'Visible', 'trim|required');
if (empty($_FILES['image']['name']))
{
$this->form_validation->set_rules('image', 'Image', 'required');
}
if ($this->form_validation->run() === FALSE)
{
$data['title'] = 'Upload Slide:'; // Capitalize the first letter
$data['error'] = '';
$data['slideshows'] = $this->slideshows_model->get_slideshows();
$data['slides'] = $this->slideshows_model->get_slides();
$this->load->view('templates/header', $data);
$this->load->view('pagesMember/slideupload', $data);
$this->load->view('templates/footer', $data);
}
else
{
$this->slideshows_model->set_slide();
if( is_dir('./resources/slideshows/'.$this->input->post('slideshow')) === false )
{
mkdir('./resources/slideshows/'.$this->input->post('slideshow'));
}
$config = array(
'upload_path' => './resources/slideshows/'.$this->input->post('slideshow').'/',
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "1536",
'max_width' => "2048"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('image'))
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('templates/header', $data);
$this->load->view('pagesMember/success', $data);
$this->load->view('templates/footer');
}
else
{
$data['error'] = $this->upload->display_errors();
$data['title'] = 'Upload ERROR';
$data['slideshows'] = $this->slideshows_model->get_slideshows();
$data['slides'] = $this->slideshows_model->get_slides();
$this->load->view('templates/header', $data);
$this->load->view('pagesMember/slideupload', $data);
$this->load->view('templates/footer');
}
}
}
} | mit |
svenkreiss/databench | databench/tests/analyses/simple1_py/analysis.py | 829 | import datetime
import time
import databench_py
import databench_py.singlethread
class Simple1_Py(databench_py.Analysis):
def on_connect(self):
"""Run as soon as a browser connects to this."""
time.sleep(1)
formatted_time = datetime.datetime.now().isoformat()
self.data['status'] = 'ready since {}'.format(formatted_time)
def on_ack(self, msg):
"""process 'ack' action"""
time.sleep(1)
self.data['status'] = 'acknowledged'
def on_test_fn(self, first_param, second_param=100):
"""Echo params."""
self.emit('test_fn', {
'first_param': first_param,
'second_param': second_param,
})
if __name__ == "__main__":
analysis = databench_py.singlethread.Meta('simple1_py', Simple1_Py)
analysis.event_loop()
| mit |
anudeepsharma/azure-sdk-for-java | azure-mgmt-servicebus/src/main/java/com/microsoft/azure/management/servicebus/implementation/QueuesImpl.java | 4267 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.servicebus.implementation;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.azure.management.servicebus.ServiceBusNamespace;
import com.microsoft.azure.management.servicebus.Queue;
import com.microsoft.azure.management.servicebus.Queues;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import rx.Completable;
import rx.Observable;
/**
* Implementation for Queues.
*/
class QueuesImpl
extends ServiceBusChildResourcesImpl<
Queue,
QueueImpl,
QueueInner,
QueuesInner,
ServiceBusManager,
ServiceBusNamespace>
implements Queues {
private final String resourceGroupName;
private final String namespaceName;
private final Region region;
QueuesImpl(String resourceGroupName, String namespaceName, Region region, ServiceBusManager manager) {
super(manager.inner().queues(), manager);
this.resourceGroupName = resourceGroupName;
this.namespaceName = namespaceName;
this.region = region;
}
@Override
public QueueImpl define(String name) {
return wrapModel(name);
}
@Override
public Completable deleteByNameAsync(String name) {
return this.inner().deleteAsync(this.resourceGroupName,
this.namespaceName,
name).toCompletable();
}
@Override
public ServiceFuture<Void> deleteByNameAsync(String name, ServiceCallback<Void> callback) {
return this.inner().deleteAsync(this.resourceGroupName,
this.namespaceName,
name,
callback);
}
@Override
protected Observable<QueueInner> getInnerByNameAsync(String name) {
return this.inner().getAsync(this.resourceGroupName, this.namespaceName, name);
}
@Override
protected Observable<ServiceResponse<Page<QueueInner>>> listInnerAsync() {
return this.inner().listByNamespaceWithServiceResponseAsync(this.resourceGroupName, this.namespaceName);
}
@Override
protected PagedList<QueueInner> listInner() {
return this.inner().listByNamespace(this.resourceGroupName,
this.namespaceName);
}
@Override
protected QueueImpl wrapModel(String name) {
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
name,
this.region,
new QueueInner(),
this.manager());
}
@Override
protected QueueImpl wrapModel(QueueInner inner) {
return new QueueImpl(this.resourceGroupName,
this.namespaceName,
inner.name(),
this.region,
inner,
this.manager());
}
@Override
public PagedList<Queue> listByParent(String resourceGroupName, String parentName) {
// 'IndependentChildResourcesImpl' will be refactoring to remove all 'ByParent' methods
// This method is not exposed to end user from any of the derived types of IndependentChildResourcesImpl
//
throw new UnsupportedOperationException();
}
@Override
public Completable deleteByParentAsync(String groupName, String parentName, String name) {
// 'IndependentChildResourcesImpl' will be refactoring to remove all 'ByParent' methods
// This method is not exposed to end user from any of the derived types of IndependentChildResourcesImpl
//
throw new UnsupportedOperationException();
}
@Override
public Observable<Queue> getByParentAsync(String resourceGroup, String parentName, String name) {
// 'IndependentChildResourcesImpl' will be refactoring to remove all 'ByParent' methods
// This method is not exposed to end user from any of the derived types of IndependentChildResourcesImpl
//
throw new UnsupportedOperationException();
}
} | mit |
kahliloppenheimer/Naive-Bayes-Classifier | test_classifier.py | 2166 | # -*- mode: Python; coding: utf-8 -*-
from classifier import Classifier
from document import Document
from cStringIO import StringIO
from unittest import TestCase, main
class TrivialDocument(Document):
"""A document whose sole feature is its identity."""
def features(self):
return [id(self)]
class TrivialClassifier(Classifier):
"""A classifier that classifies based on exact feature matches."""
def __init__(self, model={}):
super(TrivialClassifier, self).__init__(model)
def get_model(self): return self.seen
def set_model(self, model): self.seen = model
model = property(get_model, set_model)
def train(self, instances):
"""Remember the labels associated with the features of instances."""
for instance in instances:
for feature in instance.features():
self.seen[feature] = instance.label
def classify(self, instance):
"""Classify an instance using the features seen during training."""
for feature in instance.features():
if feature in self.seen:
return self.seen[feature]
class ClassifierTest(TestCase):
def test_save_load(self):
"""Save and load a trivial model"""
foo = TrivialDocument("foo", True)
c1 = TrivialClassifier()
c1.train([foo])
model = c1.model
stream = StringIO()
c1.save(stream)
self.assertGreater(len(stream.getvalue()), 0)
c2 = TrivialClassifier()
c2.load(StringIO(stream.getvalue()))
self.assertEquals(c2.model, model)
self.assertTrue(c2.classify(foo))
def test_trivial_classifier(self):
"""Classify instances as seen or unseen"""
corpus = [TrivialDocument(x, True) for x in ("foo", "bar", "baz")]
classifier = TrivialClassifier()
classifier.train(corpus)
for x in corpus:
self.assertTrue(classifier.classify(x))
for y in [TrivialDocument(x) for x in ("foobar", "quux")]:
self.assertFalse(classifier.classify(y))
if __name__ == '__main__':
# Run all of the tests, print the results, and exit.
main()
| mit |
miuramo/AnchorGarden | src/jaist/css/covis/filefilter/NullFileFilter.java | 873 | package jaist.css.covis.filefilter;
import java.io.File;
/**
* JavaÌt@C_CAOiJFileChooserjÅCÁèÌg£qÌt@CÌÝð
* IñÅ\¦µ½¢Æ«ÉCp¢éD
*
* g£qªðRXgN^ÅwèÅ«é½ßC»ÝàgpD
*
* @author miuramo
*
*/
public class NullFileFilter extends javax.swing.filechooser.FileFilter implements
java.io.FilenameFilter {
String suffix;
/**
* RXgN^
* @param s g£q̶ñ(áCtxt)
*/
public NullFileFilter(String s) {
suffix = s;
}
public boolean accept(File dir) {
String name = dir.getName();
if (name.endsWith(suffix) || dir.isDirectory()) {
return true;
} else {
return false;
}
}
public boolean accept(File dir, String name) {
if (name.endsWith(suffix)) {
return true;
} else {
return false;
}
}
public String getDescription() {
return suffix;
}
}
| mit |
monkdaf/skuter77-opencart | catalog/controller/module/full_screen_background_slider.php | 899 | <?php
/*
Version: 1.0
Author: Artur Sułkowski
Website: http://artursulkowski.pl
*/
class ControllerModuleFullScreenBackgroundSlider extends Controller {
public function index($setting) {
// Ładowanie modelu Full screen background slider
$this->load->model('slider/full_screen_background_slider');
// Pobranie slideru z modelu
$data['slider'] = $this->model_slider_full_screen_background_slider->getSlider($setting['slider_id']);
$data['language_id'] = $this->config->get('config_language_id');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/full_screen_background_slider.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/module/full_screen_background_slider.tpl', $data);
} else {
return $this->load->view('default/template/module/full_screen_background_slider.tpl', $data);
}
}
}
?> | mit |
alycit/javascript_skeleton | src/sample.js | 50 | function add(num1, num2) {
return num1 + num2;
} | mit |
nurulazradm/dice | spec/dice_spec.rb | 403 | require 'dice'
describe Dice do
dice = Dice.new
it "has 6 faces" do
expect(dice.faces.count).to eql(6)
end
describe ".roll" do
it "return any number between 1 to 6" do
last_roll = dice.roll
expect(%w(1 2 3 4 5 6)).to include(last_roll)
end
it "has last roll recorded" do
last_roll = dice.roll
expect(dice.last_roll).to eq(last_roll)
end
end
end
| mit |
guillermo/ginst | lib/ginst/template.rb | 858 |
module Ginst::Template
require('templater')
extend Templater::Manifold
class GinstData < Templater::Generator
desc 'Ginst data directory generator'
def self.source_root
File.join(File.dirname(__FILE__), 'ginst_template')
end
template :database, 'database.yml'
template :config, 'webserver.yml'
empty_directory :log, "log"
empty_directory :projects, "projects"
empty_directory :tmp, "tmp"
empty_directory :plugins, "plugins"
end
class PluginData < Templater::Generator
def self.source_root
File.join(File.dirname(__FILE__), 'ginst_template/plugins')
end
glob!
end
add :base, GinstData
add :plugins, PluginData
def self.install_to(dir)
run_cli(dir, 'base', '0.0', ['base'])
run_cli(dir+'/plugins', 'plugins', '0.0', ['plugins'])
end
end
| mit |
thofis/hangularman | app/lib/angular/i18n/angular-locale_en-bm.js | 3276 | angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-bm",
"pluralCat": function(n) {
if (n == 1) {
return PLURAL_CATEGORY.ONE;
}
return PLURAL_CATEGORY.OTHER;
}
});
}]); | mit |
DnDGen/CharacterGen | CharacterGen.Tests.Integration.Tables/Abilities/Ages/VenerableAbilityAdjustmentsTests.cs | 1400 | using CharacterGen.Abilities;
using CharacterGen.Domain.Tables;
using CharacterGen.Races;
using NUnit.Framework;
namespace CharacterGen.Tests.Integration.Tables.Abilities.Ages
{
[TestFixture]
public class VenerableAbilityAdjustmentsTests : AdjustmentsTests
{
protected override string tableName
{
get
{
return string.Format(TableNameConstants.Formattable.Adjustments.AGEAbilityAdjustments, RaceConstants.Ages.Venerable);
}
}
public override void CollectionNames()
{
var names = new[]
{
AbilityConstants.Charisma,
AbilityConstants.Constitution,
AbilityConstants.Dexterity,
AbilityConstants.Intelligence,
AbilityConstants.Strength,
AbilityConstants.Wisdom
};
AssertCollectionNames(names);
}
[TestCase(AbilityConstants.Charisma, 3)]
[TestCase(AbilityConstants.Constitution, -6)]
[TestCase(AbilityConstants.Dexterity, -6)]
[TestCase(AbilityConstants.Intelligence, 3)]
[TestCase(AbilityConstants.Strength, -6)]
[TestCase(AbilityConstants.Wisdom, 3)]
public override void Adjustment(string name, int adjustment)
{
base.Adjustment(name, adjustment);
}
}
}
| mit |
cityway-soft/atlas | lib/atlas/geocoding.rb | 5504 | module Atlas
class Geocoding
extend ActiveSupport::Memoizable
include Benchmarking
@@default_location_index = nil
cattr_accessor :default_location_index
attr_accessor :timeout
attr_reader :input_string
attr_reader :location_index
def initialize(input_string, options = {})
options = { :location_index => (Geocoding.default_location_index or LocationIndex.new),
:timeout => 0 }.update(options)
@input_string = input_string
@location_index = options[:location_index]
@timeout = options[:timeout]
@score_board = ScoreBoard.new
end
def locations_limit
10
end
def input_tokens
Token.tokenize(input_string)
end
memoize :input_tokens
def last_token
input_tokens.last
end
memoize :last_token
def input_words
input_string.to_words.tap do |words|
words.shift if street_number
end
end
memoize :input_words
def input_phonetics
Phonetic.phonetics(input_words).delete_if { |p| p.size <= 1 }
end
memoize :input_phonetics
def street_number
unless input_tokens.empty?
value_of_first_token = input_tokens.first.to_s.to_i
value_of_first_token unless value_of_first_token.zero?
end
end
memoize :street_number
def locations
score_board.first(locations_limit).collect!(&:location)
end
memoize :locations
def references
locations.collect(&:reference)
end
def suggestions
used_words = score_board.collect(&:location).collect!(&:words).flatten
most_used_words = used_words.inject({}) do |words_count, word|
words_count[word] = ((words_count[word] or 0) + 1)
words_count
end.sort_by(&:last).select { |word, score| score > 1 }.collect!(&:first).reverse
(most_used_words - input_tokens).each do |word|
Suggestion.new word
end
end
memoize :suggestions
def score_board
load
@score_board
end
def load
return if @score_board_loaded
@score_board_loaded = true
benchmark("run all tasks") do
Timeout.new(timeout).tap do |timeout|
timeout.each(tasks) do |task|
unless task.cost > 3000 or (task.cost > 500 and top_score > 1)
task.run(timeout)
end
end
Atlas.logger.debug "stop on timeout" if timeout.timeout?
end
end
end
class Timeout
def initialize(time_length = nil)
unless time_length.nil? or time_length.zero?
@stop_at = time_length.from_now
end
end
def timeout?
Time.now >= @stop_at if @stop_at
end
def timeout!
if timeout?
Atlas.logger.debug "raise error"
raise Error
end
end
def each(elements)
pending_elements = elements.dup
until pending_elements.empty? or timeout?
yield pending_elements.shift
end
end
def to_s
if @stop_at
"timeout in #{(@stop_at - Time.now) * 1000} ms"
else
"no timeout"
end
end
class Error < Interrupt
end
end
def tasks
return [] if input_tokens.empty?
tasks = [].tap do |tasks|
input_words.each do |word|
tasks << Task.new(self, word)
end
input_words.each do |word|
tasks << Task.new(self, word, :match => :begin)
end
# tasks << Task.new(self, last_token, :match => :begin)
input_phonetics.each do |phonetic|
tasks << Task.new(self, phonetic, :index => :phonetic)
end
input_phonetics.each do |phonetic|
tasks << Task.new(self, phonetic, :match => :begin, :index => :phonetic)
end
end
benchmark("sort all tasks") do
tasks = tasks.sort_by(&:cost)
end
tasks
end
memoize :tasks
class Task
extend ActiveSupport::Memoizable
include Benchmarking
attr_reader :geocoding, :input, :options
def initialize(geocoding, input, options = {})
@geocoding, @input, @options =
geocoding, input, options
end
delegate :location_index, :score, :to => :geocoding
def locations
location_index.find(input, options) or []
end
memoize :locations
def cost
location_index.count(input, options)
end
def run(timeout = Timeout.new)
Atlas.logger.debug "scoring #{locations.size} locations for #{input} (#{options.inspect}) ..."
benchmark("scored #{locations.size} locations for #{input} (#{options.inspect})") do
timeout.each(locations) do |location|
score location
end
end
end
end
def top_ten_score
top_ten = @score_board.first(10)
unless top_ten.empty?
top_ten.find_all { |s| s.score > 0 }.sum(&:score) / top_ten.size.to_f
else
0
end
end
def top_score
if top_scoring = @score_board.first
top_scoring.score
else
0
end
end
def score(location)
unless @score_board.include?(location)
@score_board.push new_scoring(location)
end
end
def new_scoring(location)
Scoring.new(location).tap do |scoring|
scoring.score =
WordSetMatcher.new(input_words, scoring.location).score
end
end
end
end
| mit |
PurplePenguin4102/ConnectFour | ConnectFour/ConnectFourTests/TextParserTests/ParseTokens.cs | 2066 | using Microsoft.VisualStudio.TestTools.UnitTesting;
using ConnectFour;
using System;
using System.Linq;
using ConnectFour.Exceptions;
namespace ConnectFourTests.TextParserTests
{
[TestClass]
public class ParseTokens
{
[TestMethod]
public void TokensAreIntegers()
{
string[] tokens = new string[] { "1", "2", "3" };
int[] output = new int[] { 1, 2, 3};
var rules = new TextParser();
Assert.IsTrue(rules.ParseTokens(tokens).SequenceEqual(output));
}
[TestMethod]
public void TokensAreNotIntegers()
{
string[] tokens = new string[] { "qasd", "2", "3" };
var rules = new TextParser();
Assert.ThrowsException<UserInputException>(() => rules.ParseTokens(tokens));
}
[TestMethod]
public void TokensAreNegativeIntegers()
{
string[] tokens = new string[] { "-1", "2", "3" };
int[] output = new int[] { -1, 2, 3 };
var rules = new TextParser();
Assert.IsTrue(rules.ParseTokens(tokens).SequenceEqual(output));
}
[TestMethod]
public void TokensAreFloats()
{
string[] tokens = new string[] { "1", "2.2", "3" };
var rules = new TextParser();
Assert.ThrowsException<UserInputException>(() => rules.ParseTokens(tokens));
}
[TestMethod]
public void TokensContainZero()
{
string[] tokens = new string[] { "0", "2", "3" };
int[] output = new int[] { 0, 2, 3 };
var rules = new TextParser();
Assert.IsTrue(rules.ParseTokens(tokens).SequenceEqual(output));
}
[TestMethod]
public void TokensContainWhitespace()
{
string[] tokens = new string[] { "1 ", " 2", "\t3" };
int[] output = new int[] { 1, 2, 3 };
var rules = new TextParser();
Assert.IsTrue(rules.ParseTokens(tokens).SequenceEqual(output));
}
}
}
| mit |
mtils/php-ems | src/Ems/Core/Exceptions/UnConfiguredException.php | 273 | <?php
namespace Ems\Core\Exceptions;
use RuntimeException;
use Ems\Contracts\Core\Errors\ConfigurationError;
/**
* Throw a UnConfiguredException if an object was not configured
**/
class UnConfiguredException extends RuntimeException implements ConfigurationError
{
}
| mit |
rodromart/angular-phonecat | test/unit/filtersSpec.js | 404 | 'use strict';
/* jasmine specs for filters go here */
describe('filter', function() {
beforeEach(module('phonecatFilters'));
describe('checkmarks', function(){
it('should convert boolean values to unicode checkmarks or cross',
inject(function(checkmarkFilter){
expect(checkmarkFilter(true)).toBe('\u2713');
expect(checkmarkFilter(false)).toBe('\u2718');
}));
});
});
| mit |
stuppy/beethoven | src/beethoven/Play.java | 3386 | package beethoven;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
/**
* Play test case that "beats" the Classic Pro level.
*/
public class Play extends UiAutomatorTestCase {
/**
* For the purposes of white vs. black tile, this is "black."
*/
private static final int BLACK = Color.rgb(32, 32, 32);
/**
* Click row.
*/
private static final int Y = 700;
/**
* Test!
*
* <p>This one uses screenshots to pinpoint the location of the next tile!
*/
public void testClassicPro() throws Exception {
UiObject tile = new UiObject(
new UiSelector()
.packageName("com.umonistudio.tile")
.className(android.view.View.class));
assertTrue(tile.exists());
X x = new X(50);
while (x.hasNext()) {
getUiDevice().click(x.next(), Y);
}
}
/**
* Iterates through the X values to click on at the {@link #Y} row.
*/
private class X implements Iterator<Integer> {
private final int length;
private int count = 0;
private Bitmap bmp;
private X(int length) {
this.length = length;
}
public boolean hasNext() {
return count < length;
}
public Integer next() {
int mod = count % 3;
if (mod == 0) {
bmp = takeScreenshot();
}
int y = Y - mod * 300;
count++;
for (int x = 90; x <= 720; x += 180) {
int pixel = bmp.getPixel(x, y);
if (pixel == BLACK) {
return x;
}
}
// Delay until needed.
StringBuilder colors = new StringBuilder();
for (int x = 90; x <= 720; x += 180) {
int pixel = bmp.getPixel(x, y);
colors.append(Utils.color(pixel)).append(";");
}
throw new AssertionError("No BLACK @ y=" + y + "! " + colors);
}
public void remove() {
throw new UnsupportedOperationException("Not supported!");
}
}
/**
* Takes a screenshot in ~ 16ms (basically, one frame).
*
* <p>The basic call chain is:
* UiDevice.getInstance().getAutomatorBridge().mUiAutomation.takeScreenshot()
*
* <p>This is a super hack that uses private/hidden methods to avoid creating a file, which is
* slow (300+ ms).
*/
private Bitmap takeScreenshot() {
try {
UiDevice device = UiDevice.getInstance();
Method getAutomatorBridge = device.getClass().getDeclaredMethod("getAutomatorBridge");
getAutomatorBridge.setAccessible(true);
Object automatorBridge = getAutomatorBridge.invoke(device);
// UiAutomatorBridge is abstract, so use the super class (UiAutomatorBridge).
Field mUiAutomation =
automatorBridge.getClass().getSuperclass().getDeclaredField("mUiAutomation");
mUiAutomation.setAccessible(true);
Object uiAutomation = mUiAutomation.get(automatorBridge);
Method takeScreenshot = uiAutomation.getClass().getDeclaredMethod("takeScreenshot");
takeScreenshot.setAccessible(true);
return (Bitmap) takeScreenshot.invoke(uiAutomation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| mit |
computerundsound/cuLibrary | db/CuDBResult.php | 581 | <?php
declare(strict_types=1);
/**
* Copyright by Jörg Wrase - www.Computer-Und-Sound.de
* Hire me! [email protected]
*
*/
namespace computerundsound\culibrary\db;
/**
* Class CuDBResult
*/
interface CuDBResult
{
/**
* @return mixed
*/
public function getLastInsertId();
/**
* @param mixed $lastInsertId
*/
public function setLastInsertId($lastInsertId);
public function getMessage(): string;
public function setMessage(string $message);
public function getQuery(): string;
public function setQuery(string $query);
}
| mit |
mrwest808/slam | react-js/src/store/modules/__tests__/games.selectors.spec.js | 1106 | import { values } from 'ramda';
import gamesReducer, {
FETCH_GAMES_FOR_TEAM_SUCCESS,
selectGameListForTeam,
} from '../games';
const action = {
type: FETCH_GAMES_FOR_TEAM_SUCCESS,
payload: {
teamId: 'knicks',
games: {
'knicks-at-cavs': { eventStartDateTime: '2017-02-24T23:00:00.000Z' },
'knicks-vs-lakers': { eventStartDateTime: '2017-02-26T21:00:00.000Z' },
},
},
};
const gamesState = gamesReducer(undefined, action);
const state = { games: gamesState };
it('selectGameListForTeam returns expected', () => {
const knicksGameList = selectGameListForTeam(state, { teamId: 'knicks' });
const cavsGameList = selectGameListForTeam(state, { teamId: 'cavs' });
const expectedGames = action.payload.games;
expect(knicksGameList).toBeValidGameList();
expect(knicksGameList.games).toEqual(expectedGames);
expect(values(knicksGameList.gamesByDate)).toEqual(values(expectedGames));
expect(cavsGameList).toBe(undefined);
});
it('selectors are memoized', () => {
const props = { teamId: 'knicks' };
expect(selectGameListForTeam).toBeMemoized(state, props);
});
| mit |
ragingwind/got-github-blob-cli | .tmp/app.js | 3484 | /*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(document) {
'use strict';
// Grab a reference to our auto-binding template
// and give it some initial binding values
// Learn more about auto-binding templates at http://goo.gl/Dx1u2g
var app = document.querySelector('#app');
// Sets app default base URL
app.baseUrl = '/app';
if (window.location.port === '') { // if production
// Uncomment app.baseURL below and
// set app.baseURL to '/your-pathname/' if running from folder in production
// app.baseUrl = '/polymer-starter-kit/';
}
app.displayInstalledToast = function() {
// Check to make sure caching is actually enabled—it won't be in the dev environment.
if (!Polymer.dom(document).querySelector('platinum-sw-cache').disabled) {
Polymer.dom(document).querySelector('#caching-complete').show();
}
};
// Listen for template bound event to know when bindings
// have resolved and content has been stamped to the page
app.addEventListener('dom-change', function() {
console.log('Our app is ready to rock!');
});
// See https://github.com/Polymer/polymer/issues/1381
window.addEventListener('WebComponentsReady', function() {
// imports are loaded and elements have been registered
});
// Main area's paper-scroll-header-panel custom condensing transformation of
// the appName in the middle-container and the bottom title in the bottom-container.
// The appName is moved to top and shrunk on condensing. The bottom sub title
// is shrunk to nothing on condensing.
window.addEventListener('paper-header-transform', function(e) {
var appName = Polymer.dom(document).querySelector('#mainToolbar .app-name');
var middleContainer = Polymer.dom(document).querySelector('#mainToolbar .middle-container');
var bottomContainer = Polymer.dom(document).querySelector('#mainToolbar .bottom-container');
var detail = e.detail;
var heightDiff = detail.height - detail.condensedHeight;
var yRatio = Math.min(1, detail.y / heightDiff);
// appName max size when condensed. The smaller the number the smaller the condensed size.
var maxMiddleScale = 0.50;
var auxHeight = heightDiff - detail.y;
var auxScale = heightDiff / (1 - maxMiddleScale);
var scaleMiddle = Math.max(maxMiddleScale, auxHeight / auxScale + maxMiddleScale);
var scaleBottom = 1 - yRatio;
// Move/translate middleContainer
Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);
// Scale bottomContainer and bottom sub title to nothing and back
Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);
// Scale middleContainer appName
Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
});
// Scroll page to top and expand header
app.scrollPageToTop = function() {
app.$.headerPanelMain.scrollToTop(true);
};
app.closeDrawer = function() {
app.$.paperDrawerPanel.closeDrawer();
};
})(document);
| mit |
mximos/openproject-heroku | db/migrate/20130807081927_move_journals_to_legacy_journals.rb | 1391 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2013 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
class MoveJournalsToLegacyJournals < ActiveRecord::Migration
def up
rename_table :journals, :legacy_journals
end
def down
rename_table :legacy_journals, :journals
end
end
| mit |
fayfox/fayfox | application/blog/configs/exts.php | 165 | <?php
/**
* 所有数组项均会被转为正则表达式进行匹配,转换规则
* / => \/
* * => .*
*/
return array(
'/'=>array('work', 'post'),
); | mit |
Pouf/CodingCompetition | CiO/clock-angle.py | 158 | def clock_angle(time):
h, m = [int(i) for i in time.split(':')]
h = (h%12)*30
m = m*5.5
return abs(h-m)//180 and 180-abs(h-m)%180 or abs(h-m)
| mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.